From 90d4f56fe46140f9e97e2fa72698f98b57447fe5 Mon Sep 17 00:00:00 2001 From: Aryeh Gregor Date: Sun, 29 Jul 2018 15:24:54 +0300 Subject: [PATCH] Mass conversion of $wgContLang to service Brought to you by vim macros. Bug: T200246 Change-Id: I79e919f4553e3bd3eb714073fed7a43051b4fb2a --- includes/CategoryViewer.php | 15 ++---- includes/CommentStore.php | 7 +-- includes/CommentStoreComment.php | 6 +-- includes/EditPage.php | 19 ++++--- includes/GlobalFunctions.php | 6 +-- includes/Html.php | 9 ++-- includes/Linker.php | 21 ++++---- includes/MWGrants.php | 4 +- includes/MediaWiki.php | 9 ++-- includes/Message.php | 12 +++-- includes/OutputPage.php | 36 ++++++------- includes/Preferences.php | 4 +- includes/PrefixSearch.php | 24 ++++----- includes/Storage/DerivedPageDataUpdater.php | 10 ++-- includes/Title.php | 51 ++++++++----------- includes/WebRequest.php | 18 +++---- includes/WebRequestUpload.php | 5 +- includes/Xml.php | 11 ++-- includes/actions/Action.php | 5 +- includes/actions/HistoryAction.php | 9 ++-- includes/actions/InfoAction.php | 4 +- includes/actions/RevertAction.php | 9 ++-- includes/api/ApiBase.php | 4 +- includes/api/ApiHelp.php | 8 +-- includes/api/ApiMain.php | 6 +-- includes/api/ApiPageSet.php | 14 +++-- includes/api/ApiQueryAllMessages.php | 6 +-- includes/api/ApiQueryImageInfo.php | 11 ++-- includes/api/ApiQueryInfo.php | 8 +-- includes/api/ApiQueryLangLinks.php | 5 +- includes/api/ApiQuerySearch.php | 6 ++- includes/api/ApiQuerySiteinfo.php | 42 +++++++-------- includes/api/ApiResult.php | 6 +-- includes/auth/AuthManager.php | 10 ++-- includes/cache/HTMLFileCache.php | 8 +-- includes/cache/LinkBatch.php | 3 +- includes/cache/MessageCache.php | 36 ++++++------- includes/collation/Collation.php | 7 +-- includes/collation/IdentityCollation.php | 5 +- .../collation/NumericUppercaseCollation.php | 4 +- includes/content/ContentHandler.php | 7 +-- includes/content/TextContent.php | 15 +++--- includes/context/RequestContext.php | 4 +- includes/db/DatabaseOracle.php | 25 +++++---- includes/deferred/LinksUpdate.php | 5 +- includes/deferred/SearchUpdate.php | 13 ++--- includes/diff/DifferenceEngine.php | 9 ++-- includes/export/XmlDumpWriter.php | 17 ++++--- includes/filerepo/FileRepo.php | 5 +- includes/filerepo/LocalRepo.php | 4 +- includes/filerepo/file/ForeignAPIFile.php | 5 +- includes/gallery/ImageGalleryBase.php | 5 +- includes/gallery/TraditionalImageGallery.php | 4 +- .../htmlform/fields/HTMLTitleTextField.php | 5 +- includes/import/WikiImporter.php | 7 +-- includes/installer/CliInstaller.php | 6 ++- includes/installer/MysqlUpdater.php | 5 +- includes/installer/WebInstaller.php | 6 ++- includes/installer/WebInstallerName.php | 5 +- includes/interwiki/ClassicInterwikiLookup.php | 10 ++-- includes/logging/LogFormatter.php | 12 ++--- includes/logging/LogPage.php | 4 +- includes/logging/ProtectLogFormatter.php | 7 +-- includes/logging/RightsLogFormatter.php | 7 ++- includes/mail/EmailNotification.php | 14 ++--- includes/media/FormatMetadata.php | 13 ++--- includes/page/ImageHistoryList.php | 9 ++-- includes/page/WikiPage.php | 25 +++++---- includes/parser/DateFormatter.php | 6 ++- includes/parser/Parser.php | 1 - includes/parser/ParserOptions.php | 14 ++--- includes/parser/Sanitizer.php | 5 +- includes/password/PasswordPolicyChecks.php | 7 ++- .../preferences/DefaultPreferencesFactory.php | 2 +- .../resourceloader/ResourceLoaderModule.php | 5 +- .../ResourceLoaderStartUpModule.php | 12 +++-- includes/search/SearchEngine.php | 17 +++---- includes/search/SearchHighlighter.php | 24 +++++---- includes/search/SearchMssql.php | 5 +- includes/search/SearchMySQL.php | 19 +++---- includes/search/SearchOracle.php | 9 ++-- includes/search/SearchSqlite.php | 18 +++---- includes/skins/Skin.php | 7 +-- includes/skins/SkinTemplate.php | 13 +++-- includes/specialpage/PageQueryPage.php | 6 +-- includes/specialpage/QueryPage.php | 5 +- includes/specialpage/SpecialPage.php | 10 ++-- includes/specialpage/SpecialPageFactory.php | 21 ++++---- includes/specials/SpecialAncientpages.php | 7 +-- includes/specials/SpecialBooksources.php | 6 +-- includes/specials/SpecialEditWatchlist.php | 5 +- includes/specials/SpecialExport.php | 10 ++-- includes/specials/SpecialFewestrevisions.php | 7 +-- .../specials/SpecialFileDuplicateSearch.php | 4 +- includes/specials/SpecialListgrouprights.php | 6 ++- includes/specials/SpecialLockdb.php | 9 ++-- includes/specials/SpecialMIMEsearch.php | 6 +-- .../specials/SpecialMostlinkedcategories.php | 5 +- includes/specials/SpecialNewimages.php | 10 ++-- includes/specials/SpecialPrefixindex.php | 8 +-- includes/specials/SpecialRandompage.php | 13 ++--- includes/specials/SpecialRecentchanges.php | 9 ++-- includes/specials/SpecialSearch.php | 5 +- includes/specials/SpecialUnwatchedpages.php | 6 +-- includes/specials/SpecialWantedcategories.php | 6 +-- includes/specials/formfields/Licenses.php | 7 +-- includes/specials/forms/UploadForm.php | 5 +- .../specials/pagers/AllMessagesTablePager.php | 10 ++-- includes/title/NaiveForeignTitleFactory.php | 11 ++-- includes/title/NaiveImportTitleFactory.php | 7 +-- includes/user/User.php | 30 ++++++----- .../search/BasicSearchResultSetWidget.php | 10 ++-- includes/widget/search/SearchFormWidget.php | 11 ++-- languages/Language.php | 4 +- languages/LanguageConverter.php | 7 ++- maintenance/benchmarks/benchmarkTidy.php | 12 ++--- maintenance/cleanupCaps.php | 10 ++-- maintenance/cleanupImages.php | 10 ++-- maintenance/cleanupTitles.php | 3 +- maintenance/cleanupWatchlist.php | 5 +- maintenance/convertLinks.php | 7 +-- maintenance/deleteEqualMessages.php | 17 ++++--- maintenance/dumpTextPass.php | 9 ++-- maintenance/generateSitemap.php | 12 +++-- maintenance/importDump.php | 8 +-- maintenance/language/dumpMessages.php | 2 +- maintenance/namespaceDupes.php | 25 ++++----- maintenance/orphans.php | 8 +-- maintenance/preprocessorFuzzTest.php | 5 +- maintenance/rebuildImages.php | 6 +-- tests/phpunit/MediaWikiLangTestCase.php | 11 ++-- tests/phpunit/includes/CommentStoreTest.php | 4 +- tests/phpunit/includes/EditPageTest.php | 5 ++ tests/phpunit/includes/ExportTest.php | 6 ++- .../Storage/DerivedPageDataUpdaterTest.php | 5 +- tests/phpunit/includes/TimeAdjustTest.php | 7 +-- .../phpunit/includes/TitlePermissionTest.php | 11 ++-- tests/phpunit/includes/TitleTest.php | 2 +- .../includes/cache/MessageCacheTest.php | 11 ++-- .../includes/content/TextContentTest.php | 11 ++-- .../content/WikitextContentHandlerTest.php | 3 +- .../includes/parser/ParserOptionsTest.php | 11 ++-- .../includes/parser/ParserPreloadTest.php | 8 +-- .../includes/parser/PreprocessorTest.php | 6 ++- .../phpunit/includes/parser/TagHooksTest.php | 4 +- .../specialpage/SpecialPageFactoryTest.php | 5 +- .../languages/LanguageConverterTest.php | 12 ++--- tests/phpunit/maintenance/backup_LogTest.php | 15 +++--- 148 files changed, 730 insertions(+), 712 deletions(-) diff --git a/includes/CategoryViewer.php b/includes/CategoryViewer.php index 79ab8b4463..46a1473a91 100644 --- a/includes/CategoryViewer.php +++ b/includes/CategoryViewer.php @@ -221,8 +221,6 @@ class CategoryViewer extends ContextSource { * @return string */ function getSubcategorySortChar( $title, $sortkey ) { - global $wgContLang; - if ( $title->getPrefixedText() == $sortkey ) { $word = $title->getDBkey(); } else { @@ -231,7 +229,7 @@ class CategoryViewer extends ContextSource { $firstChar = $this->collation->getFirstLetter( $word ); - return $wgContLang->convert( $firstChar ); + return MediaWikiServices::getInstance()->getContentLanguage()->convert( $firstChar ); } /** @@ -242,7 +240,6 @@ class CategoryViewer extends ContextSource { * @param bool $isRedirect */ function addImage( Title $title, $sortkey, $pageLength, $isRedirect = false ) { - global $wgContLang; if ( $this->showGallery ) { $flip = $this->flip['file']; if ( $flip ) { @@ -253,8 +250,8 @@ class CategoryViewer extends ContextSource { } else { $this->imgsNoGallery[] = $this->generateLink( 'image', $title, $isRedirect ); - $this->imgsNoGallery_start_char[] = $wgContLang->convert( - $this->collation->getFirstLetter( $sortkey ) ); + $this->imgsNoGallery_start_char[] = MediaWikiServices::getInstance()-> + getContentLanguage()->convert( $this->collation->getFirstLetter( $sortkey ) ); } } @@ -266,12 +263,10 @@ class CategoryViewer extends ContextSource { * @param bool $isRedirect */ function addPage( $title, $sortkey, $pageLength, $isRedirect = false ) { - global $wgContLang; - $this->articles[] = $this->generateLink( 'page', $title, $isRedirect ); - $this->articles_start_char[] = $wgContLang->convert( - $this->collation->getFirstLetter( $sortkey ) ); + $this->articles_start_char[] = MediaWikiServices::getInstance()-> + getContentLanguage()->convert( $this->collation->getFirstLetter( $sortkey ) ); } function finaliseCategoryState() { diff --git a/includes/CommentStore.php b/includes/CommentStore.php index d03a00eb1f..bf3e3d6608 100644 --- a/includes/CommentStore.php +++ b/includes/CommentStore.php @@ -98,7 +98,7 @@ class CommentStore { /** * @param Language $lang Language to use for comment truncation. Defaults - * to $wgContLang. + * to content language. * @param int $migrationStage One of the MIGRATION_* constants */ public function __construct( Language $lang, $migrationStage ) { @@ -114,10 +114,11 @@ class CommentStore { * @return CommentStore */ public static function newKey( $key ) { - global $wgCommentTableSchemaMigrationStage, $wgContLang; + global $wgCommentTableSchemaMigrationStage; // TODO uncomment once not used in extensions // wfDeprecated( __METHOD__, '1.31' ); - $store = new CommentStore( $wgContLang, $wgCommentTableSchemaMigrationStage ); + $store = new CommentStore( MediaWikiServices::getInstance()->getContentLanguage(), + $wgCommentTableSchemaMigrationStage ); $store->key = $key; return $store; } diff --git a/includes/CommentStoreComment.php b/includes/CommentStoreComment.php index 7ed86d66c7..af866cdce7 100644 --- a/includes/CommentStoreComment.php +++ b/includes/CommentStoreComment.php @@ -19,6 +19,7 @@ * * @file */ +use MediaWiki\MediaWikiServices; /** * CommentStoreComment represents a comment stored by CommentStore. The fields @@ -63,8 +64,6 @@ class CommentStoreComment { * @return CommentStoreComment */ public static function newUnsavedComment( $comment, array $data = null ) { - global $wgContLang; - if ( $comment instanceof CommentStoreComment ) { return $comment; } @@ -79,7 +78,8 @@ class CommentStoreComment { if ( $comment instanceof Message ) { $message = clone $comment; - $text = $message->inLanguage( $wgContLang ) // Avoid $wgForceUIMsgAsContentMsg + // Avoid $wgForceUIMsgAsContentMsg + $text = $message->inLanguage( MediaWikiServices::getInstance()->getContentLanguage() ) ->setInterfaceMessageFlag( true ) ->text(); return new CommentStoreComment( null, $text, $message, $data ); diff --git a/includes/EditPage.php b/includes/EditPage.php index 5f9ce0b60f..61e0dd0962 100644 --- a/includes/EditPage.php +++ b/includes/EditPage.php @@ -1171,8 +1171,6 @@ class EditPage { * @since 1.21 */ protected function getContentObject( $def_content = null ) { - global $wgContLang; - $content = false; $user = $this->context->getUser(); @@ -1235,7 +1233,8 @@ class EditPage { if ( $undoMsg === null ) { $oldContent = $this->page->getContent( Revision::RAW ); - $popts = ParserOptions::newFromUserAndLang( $user, $wgContLang ); + $popts = ParserOptions::newFromUserAndLang( + $user, MediaWikiServices::getInstance()->getContentLanguage() ); $newContent = $content->preSaveTransform( $this->mTitle, $user, $popts ); if ( $newContent->getModel() !== $oldContent->getModel() ) { // The undo may change content @@ -3461,8 +3460,6 @@ ERROR; * save and then make a comparison. */ public function showDiff() { - global $wgContLang; - $oldtitlemsg = 'currentrev'; # if message does not exist, show diff against the preloaded default if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && !$this->mTitle->exists() ) { @@ -3492,7 +3489,8 @@ ERROR; Hooks::run( 'EditPageGetDiffContent', [ $this, &$newContent ] ); $user = $this->context->getUser(); - $popts = ParserOptions::newFromUserAndLang( $user, $wgContLang ); + $popts = ParserOptions::newFromUserAndLang( $user, + MediaWikiServices::getInstance()->getContentLanguage() ); $newContent = $newContent->preSaveTransform( $this->mTitle, $user, $popts ); } @@ -4047,8 +4045,7 @@ ERROR; * @return string */ public static function getEditToolbar( $title = null ) { - global $wgContLang, $wgOut; - global $wgEnableUploads, $wgForeignFileRepos; + global $wgOut, $wgEnableUploads, $wgForeignFileRepos; $imagesAvailable = $wgEnableUploads || count( $wgForeignFileRepos ); $showSignature = true; @@ -4056,6 +4053,8 @@ ERROR; $showSignature = MWNamespace::wantSignatures( $title->getNamespace() ); } + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); + /** * $toolarray is an array of arrays each of which includes the * opening tag, the closing tag, optionally a sample text that is @@ -4103,14 +4102,14 @@ ERROR; ], $imagesAvailable ? [ 'id' => 'mw-editbutton-image', - 'open' => '[[' . $wgContLang->getNsText( NS_FILE ) . ':', + 'open' => '[[' . $contLang->getNsText( NS_FILE ) . ':', 'close' => ']]', 'sample' => wfMessage( 'image_sample' )->text(), 'tip' => wfMessage( 'image_tip' )->text(), ] : false, $imagesAvailable ? [ 'id' => 'mw-editbutton-media', - 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA ) . ':', + 'open' => '[[' . $contLang->getNsText( NS_MEDIA ) . ':', 'close' => ']]', 'sample' => wfMessage( 'media_sample' )->text(), 'tip' => wfMessage( 'media_tip' )->text(), diff --git a/includes/GlobalFunctions.php b/includes/GlobalFunctions.php index 4a09b9c6a1..567db853ee 100644 --- a/includes/GlobalFunctions.php +++ b/includes/GlobalFunctions.php @@ -1308,11 +1308,11 @@ function wfGetLangObj( $langcode = false ) { return $langcode; } - global $wgContLang, $wgLanguageCode; + global $wgLanguageCode; if ( $langcode === true || $langcode === $wgLanguageCode ) { # $langcode is the language code of the wikis content language object. # or it is a boolean and value is true - return $wgContLang; + return MediaWikiServices::getInstance()->getContentLanguage(); } global $wgLang; @@ -1330,7 +1330,7 @@ function wfGetLangObj( $langcode = false ) { # $langcode is a string, but not a valid language code; use content language. wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" ); - return $wgContLang; + return MediaWikiServices::getInstance()->getContentLanguage(); } /** diff --git a/includes/Html.php b/includes/Html.php index ad0130bf8f..32375c1f57 100644 --- a/includes/Html.php +++ b/includes/Html.php @@ -22,6 +22,7 @@ * * @file */ +use MediaWiki\MediaWikiServices; /** * This class is a collection of static functions that serve two purposes: @@ -824,8 +825,6 @@ class Html { * @return array */ public static function namespaceSelectorOptions( array $params = [] ) { - global $wgContLang; - $options = []; if ( !isset( $params['exclude'] ) || !is_array( $params['exclude'] ) ) { @@ -838,7 +837,8 @@ class Html { $options[$params['all']] = wfMessage( 'namespacesall' )->text(); } // Add all namespaces as options (in the content language) - $options += $wgContLang->getFormattedNamespaces(); + $options += + MediaWikiServices::getInstance()->getContentLanguage()->getFormattedNamespaces(); $optionsOut = []; // Filter out namespaces below 0 and massage labels @@ -851,7 +851,8 @@ class Html { // main we don't use "" but the user message describing it (e.g. "(Main)" or "(Article)") $nsName = wfMessage( 'blanknamespace' )->text(); } elseif ( is_int( $nsId ) ) { - $nsName = $wgContLang->convertNamespace( $nsId ); + $nsName = MediaWikiServices::getInstance()->getContentLanguage()-> + convertNamespace( $nsId ); } $optionsOut[$nsId] = $nsName; } diff --git a/includes/Linker.php b/includes/Linker.php index f160fd67fa..56e377d838 100644 --- a/includes/Linker.php +++ b/includes/Linker.php @@ -184,14 +184,13 @@ class Linker { * @return string */ public static function getInvalidTitleDescription( IContextSource $context, $namespace, $title ) { - global $wgContLang; - // First we check whether the namespace exists or not. if ( MWNamespace::exists( $namespace ) ) { if ( $namespace == NS_MAIN ) { $name = $context->msg( 'blanknamespace' )->text(); } else { - $name = $wgContLang->getFormattedNsText( $namespace ); + $name = MediaWikiServices::getInstance()->getContentLanguage()-> + getFormattedNsText( $namespace ); } return $context->msg( 'invalidtitle-knownnamespace', $namespace, $name, $title )->text(); } else { @@ -1227,10 +1226,11 @@ class Linker { ([^[]*) # 3. link trail (the text up until the next link) /x', function ( $match ) use ( $title, $local, $wikiId ) { - global $wgContLang; - $medians = '(?:' . preg_quote( MWNamespace::getCanonicalName( NS_MEDIA ), '/' ) . '|'; - $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA ), '/' ) . '):'; + $medians .= preg_quote( + MediaWikiServices::getInstance()->getContentLanguage()->getNsText( NS_MEDIA ), + '/' + ) . '):'; $comment = $match[0]; @@ -1264,7 +1264,11 @@ class Linker { $match[1] = substr( $match[1], 1 ); } if ( $match[1] !== false && $match[1] !== '' ) { - if ( preg_match( $wgContLang->linkTrail(), $match[3], $submatch ) ) { + if ( preg_match( + MediaWikiServices::getInstance()->getContentLanguage()->linkTrail(), + $match[3], + $submatch + ) ) { $trail = $submatch[1]; } else { $trail = ""; @@ -1655,8 +1659,7 @@ class Linker { * @return array */ static function splitTrail( $trail ) { - global $wgContLang; - $regex = $wgContLang->linkTrail(); + $regex = MediaWikiServices::getInstance()->getContentLanguage()->linkTrail(); $inside = ''; if ( $trail !== '' ) { $m = []; diff --git a/includes/MWGrants.php b/includes/MWGrants.php index 769e5b4da4..3079c65512 100644 --- a/includes/MWGrants.php +++ b/includes/MWGrants.php @@ -193,12 +193,10 @@ class MWGrants { * @return string Wikitext */ public static function getGrantsWikiText( $grantsFilter, $lang = null ) { - global $wgContLang; - if ( is_string( $lang ) ) { $lang = Language::factory( $lang ); } elseif ( $lang === null ) { - $lang = $wgContLang; + $lang = MediaWikiServices::getInstance()->getContentLanguage(); } $s = ''; diff --git a/includes/MediaWiki.php b/includes/MediaWiki.php index a67cb9bf47..36200476df 100644 --- a/includes/MediaWiki.php +++ b/includes/MediaWiki.php @@ -66,8 +66,6 @@ class MediaWiki { * @return Title Title object to be $wgTitle */ private function parseTitle() { - global $wgContLang; - $request = $this->context->getRequest(); $curid = $request->getInt( 'curid' ); $title = $request->getVal( 'title' ); @@ -88,12 +86,13 @@ class MediaWiki { if ( !is_null( $ret ) && $ret->getNamespace() == NS_MEDIA ) { $ret = Title::makeTitle( NS_FILE, $ret->getDBkey() ); } + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); // Check variant links so that interwiki links don't have to worry // about the possible different language variants - if ( $wgContLang->hasVariants() - && !is_null( $ret ) && $ret->getArticleID() == 0 + if ( + $contLang->hasVariants() && !is_null( $ret ) && $ret->getArticleID() == 0 ) { - $wgContLang->findVariantLink( $title, $ret ); + $contLang->findVariantLink( $title, $ret ); } } diff --git a/includes/Message.php b/includes/Message.php index 5ca0942291..e2fe254f60 100644 --- a/includes/Message.php +++ b/includes/Message.php @@ -20,6 +20,7 @@ * @file * @author Niklas Laxström */ +use MediaWiki\MediaWikiServices; /** * The Message class provides methods which fulfil two basic services: @@ -469,18 +470,20 @@ class Message implements MessageSpecifier, Serializable { * @since 1.26 */ public function getTitle() { - global $wgContLang, $wgForceUIMsgAsContentMsg; + global $wgForceUIMsgAsContentMsg; + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); $title = $this->key; if ( - !$this->language->equals( $wgContLang ) + !$this->language->equals( $contLang ) && in_array( $this->key, (array)$wgForceUIMsgAsContentMsg ) ) { $code = $this->language->getCode(); $title .= '/' . $code; } - return Title::makeTitle( NS_MEDIAWIKI, $wgContLang->ucfirst( strtr( $title, ' ', '_' ) ) ); + return Title::makeTitle( + NS_MEDIAWIKI, $contLang->ucfirst( strtr( $title, ' ', '_' ) ) ); } /** @@ -766,8 +769,7 @@ class Message implements MessageSpecifier, Serializable { return $this; } - global $wgContLang; - $this->inLanguage( $wgContLang ); + $this->inLanguage( MediaWikiServices::getInstance()->getContentLanguage() ); return $this; } diff --git a/includes/OutputPage.php b/includes/OutputPage.php index be5da53fcf..92f5760314 100644 --- a/includes/OutputPage.php +++ b/includes/OutputPage.php @@ -1245,8 +1245,6 @@ class OutputPage extends ContextSource { * @param array $categories Mapping category name => sort key */ public function addCategoryLinks( array $categories ) { - global $wgContLang; - if ( !$categories ) { return; } @@ -1270,7 +1268,8 @@ class OutputPage extends ContextSource { 'OutputPageMakeCategoryLinks', [ &$outputPage, $categories, &$this->mCategoryLinks ] ) ) { - $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer(); + $services = MediaWikiServices::getInstance(); + $linkRenderer = $services->getLinkRenderer(); foreach ( $categories as $category => $type ) { // array keys will cast numeric category names to ints, so cast back to string $category = (string)$category; @@ -1279,11 +1278,11 @@ class OutputPage extends ContextSource { if ( !$title ) { continue; } - $wgContLang->findVariantLink( $category, $title, true ); + $services->getContentLanguage()->findVariantLink( $category, $title, true ); if ( $category != $origcategory && array_key_exists( $category, $categories ) ) { continue; } - $text = $wgContLang->convertHtml( $title->getText() ); + $text = $services->getContentLanguage()->convertHtml( $title->getText() ); $this->mCategories[$type][] = $title->getText(); $this->mCategoryLinks[$type][] = $linkRenderer->makeLink( $title, new HtmlArmor( $text ) ); } @@ -1881,9 +1880,9 @@ class OutputPage extends ContextSource { * * @param string $text * @param bool $linestart Is this the start of a line? - * @param bool $interface Use interface language ($wgLang instead of - * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL. - * This also disables LanguageConverter. + * @param bool $interface Use interface language (instead of content language) while parsing + * language sensitive magic words like GRAMMAR and PLURAL. This also disables + * LanguageConverter. * @param Language|null $language Target language object, will override $interface * @throws MWException * @return string HTML @@ -1925,9 +1924,8 @@ class OutputPage extends ContextSource { * * @param string $text * @param bool $linestart Is this the start of a line? - * @param bool $interface Use interface language ($wgLang instead of - * $wgContLang) while parsing language sensitive magic - * words like GRAMMAR and PLURAL + * @param bool $interface Use interface language (instead of content language) while parsing + * language sensitive magic words like GRAMMAR and PLURAL * @return string HTML */ public function parseInline( $text, $linestart = true, $interface = false ) { @@ -2315,8 +2313,6 @@ class OutputPage extends ContextSource { * @throws MWException */ public function output( $return = false ) { - global $wgContLang; - if ( $this->mDoNothing ) { return $return ? '' : null; } @@ -2363,7 +2359,8 @@ class OutputPage extends ContextSource { ob_start(); $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' ); - $response->header( 'Content-language: ' . $wgContLang->getHtmlCode() ); + $response->header( 'Content-language: ' . + MediaWikiServices::getInstance()->getContentLanguage()->getHtmlCode() ); if ( !$this->mArticleBodyOnly ) { $sk = $this->getSkin(); @@ -2861,10 +2858,8 @@ class OutputPage extends ContextSource { * @return string The doctype, opening "", and head element. */ public function headElement( Skin $sk, $includeStyle = true ) { - global $wgContLang; - $userdir = $this->getLanguage()->getDir(); - $sitedir = $wgContLang->getDir(); + $sitedir = MediaWikiServices::getInstance()->getContentLanguage()->getDir(); $pieces = []; $pieces[] = Html::htmlHeader( Sanitizer::mergeAttributes( @@ -3062,8 +3057,6 @@ class OutputPage extends ContextSource { * @return array */ public function getJSVars() { - global $wgContLang; - $curRevisionId = 0; $articleId = 0; $canonicalSpecialPageName = false; # T23115 @@ -3147,8 +3140,9 @@ class OutputPage extends ContextSource { $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId(); } - if ( $wgContLang->hasVariants() ) { - $vars['wgUserVariant'] = $wgContLang->getPreferredVariant(); + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); + if ( $contLang->hasVariants() ) { + $vars['wgUserVariant'] = $contLang->getPreferredVariant(); } // Same test as SkinTemplate $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user ) diff --git a/includes/Preferences.php b/includes/Preferences.php index a8a312c3bd..d66da930b1 100644 --- a/includes/Preferences.php +++ b/includes/Preferences.php @@ -35,12 +35,12 @@ class Preferences { * @return DefaultPreferencesFactory */ protected static function getDefaultPreferencesFactory() { - global $wgContLang; $authManager = AuthManager::singleton(); $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer(); $config = MediaWikiServices::getInstance()->getMainConfig(); $preferencesFactory = new DefaultPreferencesFactory( - $config, $wgContLang, $authManager, $linkRenderer + $config, MediaWikiServices::getInstance()->getContentLanguage(), $authManager, + $linkRenderer ); return $preferencesFactory; } diff --git a/includes/PrefixSearch.php b/includes/PrefixSearch.php index 63a4d9c620..e32b439755 100644 --- a/includes/PrefixSearch.php +++ b/includes/PrefixSearch.php @@ -20,6 +20,8 @@ * @file */ +use MediaWiki\MediaWikiServices; + /** * Handles searching prefixes of titles and finding any page * names that match. Used largely by the OpenSearch implementation. @@ -81,9 +83,8 @@ abstract class PrefixSearch { // if the content language has variants, try to retrieve fallback results $fallbackLimit = $limit - count( $searches ); if ( $fallbackLimit > 0 ) { - global $wgContLang; - - $fallbackSearches = $wgContLang->autoConvertToAllVariants( $search ); + $fallbackSearches = MediaWikiServices::getInstance()->getContentLanguage()-> + autoConvertToAllVariants( $search ); $fallbackSearches = array_diff( array_unique( $fallbackSearches ), [ $search ] ); foreach ( $fallbackSearches as $fbs ) { @@ -167,8 +168,6 @@ abstract class PrefixSearch { * @return array */ protected function specialSearch( $search, $limit, $offset ) { - global $wgContLang; - $searchParts = explode( '/', $search, 2 ); $searchKey = $searchParts[0]; $subpageSearch = $searchParts[1] ?? null; @@ -192,23 +191,24 @@ abstract class PrefixSearch { } # normalize searchKey, so aliases with spaces can be found - T27675 + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); $searchKey = str_replace( ' ', '_', $searchKey ); - $searchKey = $wgContLang->caseFold( $searchKey ); + $searchKey = $contLang->caseFold( $searchKey ); // Unlike SpecialPage itself, we want the canonical forms of both // canonical and alias title forms... $keys = []; foreach ( SpecialPageFactory::getNames() as $page ) { - $keys[$wgContLang->caseFold( $page )] = [ 'page' => $page, 'rank' => 0 ]; + $keys[$contLang->caseFold( $page )] = [ 'page' => $page, 'rank' => 0 ]; } - foreach ( $wgContLang->getSpecialPageAliases() as $page => $aliases ) { + foreach ( $contLang->getSpecialPageAliases() as $page => $aliases ) { if ( !in_array( $page, SpecialPageFactory::getNames() ) ) {# T22885 continue; } foreach ( $aliases as $key => $alias ) { - $keys[$wgContLang->caseFold( $alias )] = [ 'page' => $alias, 'rank' => $key ]; + $keys[$contLang->caseFold( $alias )] = [ 'page' => $alias, 'rank' => $key ]; } } ksort( $keys ); @@ -307,10 +307,8 @@ abstract class PrefixSearch { * @return array (default: contains only NS_MAIN) */ protected function validateNamespaces( $namespaces ) { - global $wgContLang; - - // We will look at each given namespace against wgContLang namespaces - $validNamespaces = $wgContLang->getNamespaces(); + // We will look at each given namespace against content language namespaces + $validNamespaces = MediaWikiServices::getInstance()->getContentLanguage()->getNamespaces(); if ( is_array( $namespaces ) && count( $namespaces ) > 0 ) { $valid = []; foreach ( $namespaces as $ns ) { diff --git a/includes/Storage/DerivedPageDataUpdater.php b/includes/Storage/DerivedPageDataUpdater.php index 8c304ea271..a00766fa74 100644 --- a/includes/Storage/DerivedPageDataUpdater.php +++ b/includes/Storage/DerivedPageDataUpdater.php @@ -110,7 +110,7 @@ class DerivedPageDataUpdater implements IDBAccessObject { /** * @var Language */ - private $contentLanguage; + private $contLang; /** * @var LoggerInterface @@ -251,7 +251,7 @@ class DerivedPageDataUpdater implements IDBAccessObject { * @param ParserCache $parserCache * @param JobQueueGroup $jobQueueGroup * @param MessageCache $messageCache - * @param Language $contentLanguage + * @param Language $contLang * @param LoggerInterface|null $saveParseLogger */ public function __construct( @@ -260,7 +260,7 @@ class DerivedPageDataUpdater implements IDBAccessObject { ParserCache $parserCache, JobQueueGroup $jobQueueGroup, MessageCache $messageCache, - Language $contentLanguage, + Language $contLang, LoggerInterface $saveParseLogger = null ) { $this->wikiPage = $wikiPage; @@ -269,7 +269,7 @@ class DerivedPageDataUpdater implements IDBAccessObject { $this->revisionStore = $revisionStore; $this->jobQueueGroup = $jobQueueGroup; $this->messageCache = $messageCache; - $this->contentLanguage = $contentLanguage; + $this->contLang = $contLang; // XXX: replace all wfDebug calls with a Logger. Do we nede more than one logger here? $this->saveParseLogger = $saveParseLogger ?: new NullLogger(); @@ -762,7 +762,7 @@ class DerivedPageDataUpdater implements IDBAccessObject { $this->canonicalParserOutput = $output; } - $userPopts = ParserOptions::newFromUserAndLang( $user, $this->contentLanguage ); + $userPopts = ParserOptions::newFromUserAndLang( $user, $this->contLang ); Hooks::run( 'ArticlePrepareTextForEdit', [ $wikiPage, $userPopts ] ); $this->user = $user; diff --git a/includes/Title.php b/includes/Title.php index cc7d722fba..f2c6adb669 100644 --- a/includes/Title.php +++ b/includes/Title.php @@ -745,12 +745,10 @@ class Title implements LinkTarget { public static function makeName( $ns, $title, $fragment = '', $interwiki = '', $canonicalNamespace = false ) { - global $wgContLang; - if ( $canonicalNamespace ) { $namespace = MWNamespace::getCanonicalName( $ns ); } else { - $namespace = $wgContLang->getNsText( $ns ); + $namespace = MediaWikiServices::getInstance()->getContentLanguage()->getNsText( $ns ); } $name = $namespace == '' ? $title : "$namespace:$title"; if ( strval( $interwiki ) != '' ) { @@ -1051,8 +1049,8 @@ class Title implements LinkTarget { * @return string Namespace text */ public function getSubjectNsText() { - global $wgContLang; - return $wgContLang->getNsText( MWNamespace::getSubject( $this->mNamespace ) ); + return MediaWikiServices::getInstance()->getContentLanguage()-> + getNsText( MWNamespace::getSubject( $this->mNamespace ) ); } /** @@ -1061,8 +1059,8 @@ class Title implements LinkTarget { * @return string Namespace text */ public function getTalkNsText() { - global $wgContLang; - return $wgContLang->getNsText( MWNamespace::getTalk( $this->mNamespace ) ); + return MediaWikiServices::getInstance()->getContentLanguage()-> + getNsText( MWNamespace::getTalk( $this->mNamespace ) ); } /** @@ -1632,8 +1630,6 @@ class Title implements LinkTarget { * @return string The prefixed text */ private function prefix( $name ) { - global $wgContLang; - $p = ''; if ( $this->isExternal() ) { $p = $this->mInterwiki . ':'; @@ -1644,7 +1640,8 @@ class Title implements LinkTarget { if ( $nsText === false ) { // See T165149. Awkward, but better than erroneously linking to the main namespace. - $nsText = $wgContLang->getNsText( NS_SPECIAL ) . ":Badtitle/NS{$this->mNamespace}"; + $nsText = MediaWikiServices::getInstance()->getContentLanguage()-> + getNsText( NS_SPECIAL ) . ":Badtitle/NS{$this->mNamespace}"; } $p .= $nsText . ':'; @@ -1979,7 +1976,7 @@ class Title implements LinkTarget { $titleRef = $this; Hooks::run( 'GetLocalURL::Article', [ &$titleRef, &$url ] ); } else { - global $wgVariantArticlePath, $wgActionPaths, $wgContLang; + global $wgVariantArticlePath, $wgActionPaths; $url = false; $matches = []; @@ -2002,7 +1999,8 @@ class Title implements LinkTarget { if ( $url === false && $wgVariantArticlePath && preg_match( '/^variant=([^&]*)$/', $query, $matches ) - && $this->getPageLanguage()->equals( $wgContLang ) + && $this->getPageLanguage()->equals( + MediaWikiServices::getInstance()->getContentLanguage() ) && $this->getPageLanguage()->hasVariants() ) { $variant = urldecode( $matches[1] ); @@ -3677,10 +3675,8 @@ class Title implements LinkTarget { * @return string Containing capitalized title */ public static function capitalize( $text, $ns = NS_MAIN ) { - global $wgContLang; - if ( MWNamespace::isCapitalized( $ns ) ) { - return $wgContLang->ucfirst( $text ); + return MediaWikiServices::getInstance()->getContentLanguage()->ucfirst( $text ); } else { return $text; } @@ -4227,8 +4223,6 @@ class Title implements LinkTarget { * $parent => $currentarticle */ public function getParentCategories() { - global $wgContLang; - $data = []; $titleKey = $this->getArticleID(); @@ -4247,9 +4241,11 @@ class Title implements LinkTarget { ); if ( $res->numRows() > 0 ) { + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); foreach ( $res as $row ) { - // $data[] = Title::newFromText($wgContLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to); - $data[$wgContLang->getNsText( NS_CATEGORY ) . ':' . $row->cl_to] = $this->getFullText(); + // $data[] = Title::newFromText( $contLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to); + $data[$contLang->getNsText( NS_CATEGORY ) . ':' . $row->cl_to] = + $this->getFullText(); } } return $data; @@ -4733,11 +4729,11 @@ class Title implements LinkTarget { // message content will be displayed, same for language subpages- // Use always content language to avoid loading hundreds of languages // to get the link color. - global $wgContLang; + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); list( $name, ) = MessageCache::singleton()->figureMessage( - $wgContLang->lcfirst( $this->getText() ) + $contLang->lcfirst( $this->getText() ) ); - $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false ); + $message = wfMessage( $name )->inLanguage( $contLang )->useDatabase( false ); return $message->exists(); } @@ -4750,14 +4746,12 @@ class Title implements LinkTarget { * @return string|bool */ public function getDefaultMessageText() { - global $wgContLang; - if ( $this->getNamespace() != NS_MEDIAWIKI ) { // Just in case return false; } list( $name, $lang ) = MessageCache::singleton()->figureMessage( - $wgContLang->lcfirst( $this->getText() ) + MediaWikiServices::getInstance()->getContentLanguage()->lcfirst( $this->getText() ) ); $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false ); @@ -4884,7 +4878,6 @@ class Title implements LinkTarget { * @return string XML 'id' name */ public function getNamespaceKey( $prepend = 'nstab-' ) { - global $wgContLang; // Gets the subject namespace of this title $subjectNS = MWNamespace::getSubject( $this->getNamespace() ); // Prefer canonical namespace name for HTML IDs @@ -4894,7 +4887,7 @@ class Title implements LinkTarget { $namespaceKey = $this->getSubjectNsText(); } // Makes namespace key lowercase - $namespaceKey = $wgContLang->lc( $namespaceKey ); + $namespaceKey = MediaWikiServices::getInstance()->getContentLanguage()->lc( $namespaceKey ); // Uses main if ( $namespaceKey == '' ) { $namespaceKey = 'main'; @@ -5043,7 +5036,7 @@ class Title implements LinkTarget { /** * Get the language in which the content of this page is written in - * wikitext. Defaults to $wgContLang, but in certain cases it can be + * wikitext. Defaults to content language, but in certain cases it can be * e.g. $wgLang (such as special pages, which are in the user language). * * @since 1.18 @@ -5081,7 +5074,7 @@ class Title implements LinkTarget { /** * Get the language in which the content of this page is written when - * viewed by user. Defaults to $wgContLang, but in certain cases it can be + * viewed by user. Defaults to content language, but in certain cases it can be * e.g. $wgLang (such as special pages, which are in the user language). * * @since 1.20 diff --git a/includes/WebRequest.php b/includes/WebRequest.php index e31d3f9c77..327dd54c0d 100644 --- a/includes/WebRequest.php +++ b/includes/WebRequest.php @@ -162,11 +162,12 @@ class WebRequest { $router->add( $wgActionPaths, [ 'action' => '$key' ] ); } - global $wgVariantArticlePath, $wgContLang; + global $wgVariantArticlePath; if ( $wgVariantArticlePath ) { $router->add( $wgVariantArticlePath, [ 'variant' => '$2' ], - [ '$2' => $wgContLang->getVariants() ] + [ '$2' => MediaWikiServices::getInstance()->getContentLanguage()-> + getVariants() ] ); } @@ -306,7 +307,7 @@ class WebRequest { /** * Check for title, action, and/or variant data in the URL * and interpolate it into the GET variables. - * This should only be run after $wgContLang is available, + * This should only be run after the content language is available, * as we may need the list of language variants to determine * available variant URLs. */ @@ -364,9 +365,8 @@ class WebRequest { $data[$key] = $this->normalizeUnicode( $val ); } } else { - global $wgContLang; - $data = isset( $wgContLang ) ? - $wgContLang->normalize( $data ) : + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); + $data = $contLang ? $contLang->normalize( $data ) : UtfNormal\Validator::cleanUp( $data ); } return $data; @@ -386,12 +386,12 @@ class WebRequest { # Work around PHP *feature* to avoid *bugs* elsewhere. $name = strtr( $name, '.', '_' ); if ( isset( $arr[$name] ) ) { - global $wgContLang; $data = $arr[$name]; if ( isset( $_GET[$name] ) && !is_array( $data ) ) { # Check for alternate/legacy character encoding. - if ( isset( $wgContLang ) ) { - $data = $wgContLang->checkTitleEncoding( $data ); + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); + if ( $contLang ) { + $data = $contLang->checkTitleEncoding( $data ); } } $data = $this->normalizeUnicode( $data ); diff --git a/includes/WebRequestUpload.php b/includes/WebRequestUpload.php index 916a10c9f0..34c606204c 100644 --- a/includes/WebRequestUpload.php +++ b/includes/WebRequestUpload.php @@ -20,6 +20,8 @@ * @file */ +use MediaWiki\MediaWikiServices; + /** * Object to access the $_FILES array * @@ -63,13 +65,12 @@ class WebRequestUpload { return null; } - global $wgContLang; $name = $this->fileInfo['name']; # Safari sends filenames in HTML-encoded Unicode form D... # Horrid and evil! Let's try to make some kind of sense of it. $name = Sanitizer::decodeCharReferences( $name ); - $name = $wgContLang->normalize( $name ); + $name = MediaWikiServices::getInstance()->getContentLanguage()->normalize( $name ); wfDebug( __METHOD__ . ": {$this->fileInfo['name']} normalized to '$name'\n" ); return $name; } diff --git a/includes/Xml.php b/includes/Xml.php index 8c65461680..9744aeefcc 100644 --- a/includes/Xml.php +++ b/includes/Xml.php @@ -20,6 +20,8 @@ * @file */ +use MediaWiki\MediaWikiServices; + /** * Module of static functions for generating XML */ @@ -79,9 +81,8 @@ class Xml { } /** - * Format an XML element as with self::element(), but run text through the - * $wgContLang->normalize() validator first to ensure that no invalid UTF-8 - * is passed. + * Format an XML element as with self::element(), but run text through the content language's + * normalize() validator first to ensure that no invalid UTF-8 is passed. * * @param string $element * @param array $attribs Name=>value pairs. Values will be escaped. @@ -89,12 +90,12 @@ class Xml { * @return string */ public static function elementClean( $element, $attribs = [], $contents = '' ) { - global $wgContLang; if ( $attribs ) { $attribs = array_map( [ 'UtfNormal\Validator', 'cleanUp' ], $attribs ); } if ( $contents ) { - $contents = $wgContLang->normalize( $contents ); + $contents = + MediaWikiServices::getInstance()->getContentLanguage()->normalize( $contents ); } return self::element( $element, $attribs, $contents ); } diff --git a/includes/actions/Action.php b/includes/actions/Action.php index fb22445410..66f4d590c8 100644 --- a/includes/actions/Action.php +++ b/includes/actions/Action.php @@ -19,6 +19,8 @@ * @file */ +use MediaWiki\MediaWikiServices; + /** * @defgroup Actions Action done on pages */ @@ -386,8 +388,7 @@ abstract class Action implements MessageLocalizer { * @since 1.25 */ public function addHelpLink( $to, $overrideBaseUrl = false ) { - global $wgContLang; - $msg = wfMessage( $wgContLang->lc( + $msg = wfMessage( MediaWikiServices::getInstance()->getContentLanguage()->lc( self::getActionName( $this->getContext() ) ) . '-helppage' ); diff --git a/includes/actions/HistoryAction.php b/includes/actions/HistoryAction.php index 1a15fc0179..2778a1d91f 100644 --- a/includes/actions/HistoryAction.php +++ b/includes/actions/HistoryAction.php @@ -358,12 +358,13 @@ class HistoryAction extends FormlessAction { $rev->getComment() ); if ( $rev->getComment() == '' ) { - global $wgContLang; + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); $title = $this->msg( 'history-feed-item-nocomment', $rev->getUserText(), - $wgContLang->timeanddate( $rev->getTimestamp() ), - $wgContLang->date( $rev->getTimestamp() ), - $wgContLang->time( $rev->getTimestamp() ) )->inContentLanguage()->text(); + $contLang->timeanddate( $rev->getTimestamp() ), + $contLang->date( $rev->getTimestamp() ), + $contLang->time( $rev->getTimestamp() ) + )->inContentLanguage()->text(); } else { $title = $rev->getUserText() . $this->msg( 'colon-separator' )->inContentLanguage()->text() . diff --git a/includes/actions/InfoAction.php b/includes/actions/InfoAction.php index e77cdf77c8..dc661aa63c 100644 --- a/includes/actions/InfoAction.php +++ b/includes/actions/InfoAction.php @@ -207,8 +207,6 @@ class InfoAction extends FormlessAction { * @return array */ protected function pageInfo() { - global $wgContLang; - $services = MediaWikiServices::getInstance(); $user = $this->getUser(); @@ -607,7 +605,7 @@ class InfoAction extends FormlessAction { $wordIDs = $magicWords->names; // Array of IDs => localized magic words - $localizedWords = $wgContLang->getMagicWords(); + $localizedWords = $services->getContentLanguage()->getMagicWords(); $listItems = []; foreach ( $pageProperties as $property => $value ) { diff --git a/includes/actions/RevertAction.php b/includes/actions/RevertAction.php index a914c9b2b3..68a032573a 100644 --- a/includes/actions/RevertAction.php +++ b/includes/actions/RevertAction.php @@ -23,6 +23,8 @@ * @author Rob Church */ +use MediaWiki\MediaWikiServices; + /** * File reversion user interface * @@ -78,8 +80,6 @@ class RevertAction extends FormAction { } protected function getFormFields() { - global $wgContLang; - $timestamp = $this->oldFile->getTimestamp(); $user = $this->getUser(); @@ -88,8 +88,9 @@ class RevertAction extends FormAction { $userTime = $lang->userTime( $timestamp, $user ); $siteTs = MWTimestamp::getLocalInstance( $timestamp ); $ts = $siteTs->format( 'YmdHis' ); - $siteDate = $wgContLang->date( $ts, false, false ); - $siteTime = $wgContLang->time( $ts, false, false ); + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); + $siteDate = $contLang->date( $ts, false, false ); + $siteTime = $contLang->time( $ts, false, false ); $tzMsg = $siteTs->getTimezoneMessage()->inContentLanguage()->text(); return [ diff --git a/includes/api/ApiBase.php b/includes/api/ApiBase.php index e546c4aca5..ac07eebe3b 100644 --- a/includes/api/ApiBase.php +++ b/includes/api/ApiBase.php @@ -1246,8 +1246,8 @@ abstract class ApiBase extends ContextSource { // Preserve U+001F for self::parseMultiValue(), or error out if that won't be called if ( isset( $value ) && substr( $rawValue, 0, 1 ) === "\x1f" ) { if ( $multi ) { - // This loses the potential $wgContLang->checkTitleEncoding() transformation - // done by WebRequest for $_GET. Let's call that a feature. + // This loses the potential checkTitleEncoding() transformation done by + // WebRequest for $_GET. Let's call that a feature. $value = implode( "\x1f", $request->normalizeUnicode( explode( "\x1f", $rawValue ) ) ); } else { $this->dieWithError( 'apierror-badvalue-notmultivalue', 'badvalue_notmultivalue' ); diff --git a/includes/api/ApiHelp.php b/includes/api/ApiHelp.php index 041b02479b..72509c233e 100644 --- a/includes/api/ApiHelp.php +++ b/includes/api/ApiHelp.php @@ -91,8 +91,6 @@ class ApiHelp extends ApiBase { * @param array $options Formatting options (described above) */ public static function getHelp( IContextSource $context, $modules, array $options ) { - global $wgContLang; - if ( !is_array( $modules ) ) { $modules = [ $modules ]; } @@ -108,10 +106,12 @@ class ApiHelp extends ApiBase { } $out->setPageTitle( $context->msg( 'api-help-title' ) ); - $cache = MediaWikiServices::getInstance()->getMainWANObjectCache(); + $services = MediaWikiServices::getInstance(); + $cache = $services->getMainWANObjectCache(); $cacheKey = null; if ( count( $modules ) == 1 && $modules[0] instanceof ApiMain && - $options['recursivesubmodules'] && $context->getLanguage() === $wgContLang + $options['recursivesubmodules'] && + $context->getLanguage()->equals( $services->getContentLanguage() ) ) { $cacheHelpTimeout = $context->getConfig()->get( 'APICacheHelpTimeout' ); if ( $cacheHelpTimeout > 0 ) { diff --git a/includes/api/ApiMain.php b/includes/api/ApiMain.php index e5e384c0f1..672ec8f352 100644 --- a/includes/api/ApiMain.php +++ b/includes/api/ApiMain.php @@ -244,8 +244,7 @@ class ApiMain extends ApiBase { // for uselang=user (see T85635). } else { if ( $uselang === 'content' ) { - global $wgContLang; - $uselang = $wgContLang->getCode(); + $uselang = MediaWikiServices::getInstance()->getContentLanguage()->getCode(); } $code = RequestContext::sanitizeLangCode( $uselang ); $this->getContext()->setLanguage( $code ); @@ -265,8 +264,7 @@ class ApiMain extends ApiBase { if ( $errorLangCode === 'uselang' ) { $errorLang = $this->getLanguage(); } elseif ( $errorLangCode === 'content' ) { - global $wgContLang; - $errorLang = $wgContLang; + $errorLang = MediaWikiServices::getInstance()->getContentLanguage(); } else { $errorLangCode = RequestContext::sanitizeLangCode( $errorLangCode ); $errorLang = Language::factory( $errorLangCode ); diff --git a/includes/api/ApiPageSet.php b/includes/api/ApiPageSet.php index ea2a85fb1e..19629dae09 100644 --- a/includes/api/ApiPageSet.php +++ b/includes/api/ApiPageSet.php @@ -512,11 +512,10 @@ class ApiPageSet extends ApiBase { * @since 1.21 */ public function getNormalizedTitlesAsResult( $result = null ) { - global $wgContLang; - $values = []; + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); foreach ( $this->getNormalizedTitles() as $rawTitleStr => $titleStr ) { - $encode = ( $wgContLang->normalize( $rawTitleStr ) !== $rawTitleStr ); + $encode = $contLang->normalize( $rawTitleStr ) !== $rawTitleStr; $values[] = [ 'fromencoded' => $encode, 'from' => $encode ? rawurlencode( $rawTitleStr ) : $rawTitleStr, @@ -1198,15 +1197,14 @@ class ApiPageSet extends ApiBase { $this->mInterwikiTitles[$unconvertedTitle] = $titleObj->getInterwiki(); } else { // Variants checking - global $wgContLang; - if ( $this->mConvertTitles && - $wgContLang->hasVariants() && - !$titleObj->exists() + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); + if ( + $this->mConvertTitles && $contLang->hasVariants() && !$titleObj->exists() ) { // Language::findVariantLink will modify titleText and titleObj into // the canonical variant if possible $titleText = is_string( $title ) ? $title : $titleObj->getPrefixedText(); - $wgContLang->findVariantLink( $titleText, $titleObj ); + $contLang->findVariantLink( $titleText, $titleObj ); $titleWasConverted = $unconvertedTitle !== $titleObj->getPrefixedText(); } diff --git a/includes/api/ApiQueryAllMessages.php b/includes/api/ApiQueryAllMessages.php index 40abcaf2d2..1d57c3c47a 100644 --- a/includes/api/ApiQueryAllMessages.php +++ b/includes/api/ApiQueryAllMessages.php @@ -20,6 +20,8 @@ * @file */ +use MediaWiki\MediaWikiServices; + /** * A query action to return messages from site message cache * @@ -110,15 +112,13 @@ class ApiQueryAllMessages extends ApiQueryBase { // Whether we have any sort of message customisation filtering $customiseFilterEnabled = $params['customised'] !== 'all'; if ( $customiseFilterEnabled ) { - global $wgContLang; - $customisedMessages = AllMessagesTablePager::getCustomisedStatuses( array_map( [ $langObj, 'ucfirst' ], $messages_target ), $langObj->getCode(), - !$langObj->equals( $wgContLang ) + !$langObj->equals( MediaWikiServices::getInstance()->getContentLanguage() ) ); $customised = $params['customised'] === 'modified'; diff --git a/includes/api/ApiQueryImageInfo.php b/includes/api/ApiQueryImageInfo.php index 8994e0638c..18d2804c2f 100644 --- a/includes/api/ApiQueryImageInfo.php +++ b/includes/api/ApiQueryImageInfo.php @@ -20,6 +20,8 @@ * @file */ +use MediaWiki\MediaWikiServices; + /** * A query action to get image information and upload history. * @@ -369,14 +371,12 @@ class ApiQueryImageInfo extends ApiQueryBase { * @return array Result array */ public static function getInfo( $file, $prop, $result, $thumbParams = null, $opts = false ) { - global $wgContLang; - $anyHidden = false; if ( !$opts || is_string( $opts ) ) { $opts = [ 'version' => $opts ?: 'latest', - 'language' => $wgContLang, + 'language' => MediaWikiServices::getInstance()->getContentLanguage(), 'multilang' => false, 'extmetadatafilter' => [], 'revdelUser' => null, @@ -650,8 +650,6 @@ class ApiQueryImageInfo extends ApiQueryBase { } public function getAllowedParams() { - global $wgContLang; - return [ 'prop' => [ ApiBase::PARAM_ISMULTI => true, @@ -690,7 +688,8 @@ class ApiQueryImageInfo extends ApiQueryBase { ], 'extmetadatalanguage' => [ ApiBase::PARAM_TYPE => 'string', - ApiBase::PARAM_DFLT => $wgContLang->getCode(), + ApiBase::PARAM_DFLT => + MediaWikiServices::getInstance()->getContentLanguage()->getCode(), ], 'extmetadatamultilang' => [ ApiBase::PARAM_TYPE => 'boolean', diff --git a/includes/api/ApiQueryInfo.php b/includes/api/ApiQueryInfo.php index 1d3c110c3a..0cf6b04c82 100644 --- a/includes/api/ApiQueryInfo.php +++ b/includes/api/ApiQueryInfo.php @@ -764,12 +764,12 @@ class ApiQueryInfo extends ApiQueryBase { } private function getAllVariants( $text, $ns = NS_MAIN ) { - global $wgContLang; $result = []; - foreach ( $wgContLang->getVariants() as $variant ) { - $convertTitle = $wgContLang->autoConvert( $text, $variant ); + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); + foreach ( $contLang->getVariants() as $variant ) { + $convertTitle = $contLang->autoConvert( $text, $variant ); if ( $ns !== NS_MAIN ) { - $convertNs = $wgContLang->convertNamespace( $ns, $variant ); + $convertNs = $contLang->convertNamespace( $ns, $variant ); $convertTitle = $convertNs . ':' . $convertTitle; } $result[$variant] = $convertTitle; diff --git a/includes/api/ApiQueryLangLinks.php b/includes/api/ApiQueryLangLinks.php index 2d8e44cda5..f33a67fe96 100644 --- a/includes/api/ApiQueryLangLinks.php +++ b/includes/api/ApiQueryLangLinks.php @@ -20,6 +20,8 @@ * @file */ +use MediaWiki\MediaWikiServices; + /** * A query module to list all langlinks (links to corresponding foreign language pages). * @@ -140,7 +142,6 @@ class ApiQueryLangLinks extends ApiQueryBase { } public function getAllowedParams() { - global $wgContLang; return [ 'prop' => [ ApiBase::PARAM_ISMULTI => true, @@ -160,7 +161,7 @@ class ApiQueryLangLinks extends ApiQueryBase { 'descending' ] ], - 'inlanguagecode' => $wgContLang->getCode(), + 'inlanguagecode' => MediaWikiServices::getInstance()->getContentLanguage()->getCode(), 'limit' => [ ApiBase::PARAM_DFLT => 10, ApiBase::PARAM_TYPE => 'limit', diff --git a/includes/api/ApiQuerySearch.php b/includes/api/ApiQuerySearch.php index f5461e0ace..d4f0396c93 100644 --- a/includes/api/ApiQuerySearch.php +++ b/includes/api/ApiQuerySearch.php @@ -20,6 +20,8 @@ * @file */ +use MediaWiki\MediaWikiServices; + /** * Query module to perform full text search within wiki titles and content * @@ -48,7 +50,6 @@ class ApiQuerySearch extends ApiQueryGeneratorBase { * @return void */ private function run( $resultPageSet = null ) { - global $wgContLang; $params = $this->extractRequestParams(); // Extract parameters @@ -152,7 +153,8 @@ class ApiQuerySearch extends ApiQueryGeneratorBase { } // Add the search results to the result - $terms = $wgContLang->convertForSearchResult( $matches->termMatches() ); + $terms = MediaWikiServices::getInstance()->getContentLanguage()-> + convertForSearchResult( $matches->termMatches() ); $titles = []; $count = 0; $limit = $params['limit']; diff --git a/includes/api/ApiQuerySiteinfo.php b/includes/api/ApiQuerySiteinfo.php index c65dfa543a..c26bb625d2 100644 --- a/includes/api/ApiQuerySiteinfo.php +++ b/includes/api/ApiQuerySiteinfo.php @@ -125,8 +125,6 @@ class ApiQuerySiteinfo extends ApiQueryBase { } protected function appendGeneralInfo( $property ) { - global $wgContLang; - $config = $this->getConfig(); $data = []; @@ -164,8 +162,9 @@ class ApiQuerySiteinfo extends ApiQueryBase { $data['langconversion'] = !$config->get( 'DisableLangConversion' ); $data['titleconversion'] = !$config->get( 'DisableTitleConversion' ); - if ( $wgContLang->linkPrefixExtension() ) { - $linkPrefixCharset = $wgContLang->linkPrefixCharset(); + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); + if ( $contLang->linkPrefixExtension() ) { + $linkPrefixCharset = $contLang->linkPrefixCharset(); $data['linkprefixcharset'] = $linkPrefixCharset; // For backwards compatibility $data['linkprefix'] = "/^((?>.*[^$linkPrefixCharset]|))(.+)$/sDu"; @@ -174,7 +173,7 @@ class ApiQuerySiteinfo extends ApiQueryBase { $data['linkprefix'] = ''; } - $linktrail = $wgContLang->linkTrail(); + $linktrail = $contLang->linkTrail(); $data['linktrail'] = $linktrail ?: ''; $data['legaltitlechars'] = Title::legalChars(); @@ -197,26 +196,26 @@ class ApiQuerySiteinfo extends ApiQueryBase { $data['lang'] = $config->get( 'LanguageCode' ); $fallbacks = []; - foreach ( $wgContLang->getFallbackLanguages() as $code ) { + foreach ( $contLang->getFallbackLanguages() as $code ) { $fallbacks[] = [ 'code' => $code ]; } $data['fallback'] = $fallbacks; ApiResult::setIndexedTagName( $data['fallback'], 'lang' ); - if ( $wgContLang->hasVariants() ) { + if ( $contLang->hasVariants() ) { $variants = []; - foreach ( $wgContLang->getVariants() as $code ) { + foreach ( $contLang->getVariants() as $code ) { $variants[] = [ 'code' => $code, - 'name' => $wgContLang->getVariantname( $code ), + 'name' => $contLang->getVariantname( $code ), ]; } $data['variants'] = $variants; ApiResult::setIndexedTagName( $data['variants'], 'lang' ); } - $data['rtl'] = $wgContLang->isRTL(); - $data['fallback8bitEncoding'] = $wgContLang->fallback8bitEncoding(); + $data['rtl'] = $contLang->isRTL(); + $data['fallback8bitEncoding'] = $contLang->fallback8bitEncoding(); $data['readonly'] = wfReadOnly(); if ( $data['readonly'] ) { @@ -280,11 +279,13 @@ class ApiQuerySiteinfo extends ApiQueryBase { } protected function appendNamespaces( $property ) { - global $wgContLang; $data = [ ApiResult::META_TYPE => 'assoc', ]; - foreach ( $wgContLang->getFormattedNamespaces() as $ns => $title ) { + foreach ( + MediaWikiServices::getInstance()->getContentLanguage()->getFormattedNamespaces() + as $ns => $title + ) { $data[$ns] = [ 'id' => intval( $ns ), 'case' => MWNamespace::isCapitalized( $ns ) ? 'first-letter' : 'case-sensitive', @@ -314,10 +315,10 @@ class ApiQuerySiteinfo extends ApiQueryBase { } protected function appendNamespaceAliases( $property ) { - global $wgContLang; + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); $aliases = array_merge( $this->getConfig()->get( 'NamespaceAliases' ), - $wgContLang->getNamespaceAliases() ); - $namespaces = $wgContLang->getNamespaces(); + $contLang->getNamespaceAliases() ); + $namespaces = $contLang->getNamespaces(); $data = []; foreach ( $aliases as $title => $ns ) { if ( $namespaces[$ns] == $title ) { @@ -339,9 +340,8 @@ class ApiQuerySiteinfo extends ApiQueryBase { } protected function appendSpecialPageAliases( $property ) { - global $wgContLang; $data = []; - $aliases = $wgContLang->getSpecialPageAliases(); + $aliases = MediaWikiServices::getInstance()->getContentLanguage()->getSpecialPageAliases(); foreach ( SpecialPageFactory::getNames() as $specialpage ) { if ( isset( $aliases[$specialpage] ) ) { $arr = [ 'realname' => $specialpage, 'aliases' => $aliases[$specialpage] ]; @@ -355,9 +355,11 @@ class ApiQuerySiteinfo extends ApiQueryBase { } protected function appendMagicWords( $property ) { - global $wgContLang; $data = []; - foreach ( $wgContLang->getMagicWords() as $magicword => $aliases ) { + foreach ( + MediaWikiServices::getInstance()->getContentLanguage()->getMagicWords() + as $magicword => $aliases + ) { $caseSensitive = array_shift( $aliases ); $arr = [ 'name' => $magicword, 'aliases' => $aliases ]; $arr['case-sensitive'] = (bool)$caseSensitive; diff --git a/includes/api/ApiResult.php b/includes/api/ApiResult.php index 3b7c181fa7..c4a31c7845 100644 --- a/includes/api/ApiResult.php +++ b/includes/api/ApiResult.php @@ -18,6 +18,8 @@ * @file */ +use MediaWiki\MediaWikiServices; + /** * This class represents the result of the API operations. * It simply wraps a nested array structure, adding some functions to simplify @@ -330,8 +332,6 @@ class ApiResult implements ApiSerializable { * @return array|mixed|string */ private static function validateValue( $value ) { - global $wgContLang; - if ( is_object( $value ) ) { // Note we use is_callable() here instead of instanceof because // ApiSerializable is an informal protocol (see docs there for details). @@ -374,7 +374,7 @@ class ApiResult implements ApiSerializable { } elseif ( is_float( $value ) && !is_finite( $value ) ) { throw new InvalidArgumentException( 'Cannot add non-finite floats to ApiResult' ); } elseif ( is_string( $value ) ) { - $value = $wgContLang->normalize( $value ); + $value = MediaWikiServices::getInstance()->getContentLanguage()->normalize( $value ); } elseif ( $value !== null && !is_scalar( $value ) ) { $type = gettype( $value ); if ( is_resource( $value ) ) { diff --git a/includes/auth/AuthManager.php b/includes/auth/AuthManager.php index d3fd5fcb0f..ab7ba0fb8c 100644 --- a/includes/auth/AuthManager.php +++ b/includes/auth/AuthManager.php @@ -2408,15 +2408,15 @@ class AuthManager implements LoggerAwareInterface { * @param bool $useContextLang Use 'uselang' to set the user's language */ private function setDefaultUserOptions( User $user, $useContextLang ) { - global $wgContLang; - $user->setToken(); - $lang = $useContextLang ? \RequestContext::getMain()->getLanguage() : $wgContLang; + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); + + $lang = $useContextLang ? \RequestContext::getMain()->getLanguage() : $contLang; $user->setOption( 'language', $lang->getPreferredVariant() ); - if ( $wgContLang->hasVariants() ) { - $user->setOption( 'variant', $wgContLang->getPreferredVariant() ); + if ( $contLang->hasVariants() ) { + $user->setOption( 'variant', $contLang->getPreferredVariant() ); } } diff --git a/includes/cache/HTMLFileCache.php b/includes/cache/HTMLFileCache.php index f8cd754a06..3a89066f8c 100644 --- a/includes/cache/HTMLFileCache.php +++ b/includes/cache/HTMLFileCache.php @@ -91,7 +91,6 @@ class HTMLFileCache extends FileCacheBase { * @return bool */ public static function useFileCache( IContextSource $context, $mode = self::MODE_NORMAL ) { - global $wgContLang; $config = MediaWikiServices::getInstance()->getMainConfig(); if ( !$config->get( 'UseFileCache' ) && $mode !== self::MODE_REBUILD ) { @@ -124,7 +123,8 @@ class HTMLFileCache extends FileCacheBase { $ulang = $context->getLanguage(); // Check that there are no other sources of variation - if ( $user->getId() || !$ulang->equals( $wgContLang ) ) { + if ( $user->getId() || + !$ulang->equals( MediaWikiServices::getInstance()->getContentLanguage() ) ) { return false; } @@ -145,7 +145,6 @@ class HTMLFileCache extends FileCacheBase { * @return void */ public function loadFromFileCache( IContextSource $context, $mode = self::MODE_NORMAL ) { - global $wgContLang; $config = MediaWikiServices::getInstance()->getMainConfig(); wfDebug( __METHOD__ . "()\n" ); @@ -158,7 +157,8 @@ class HTMLFileCache extends FileCacheBase { $context->getOutput()->sendCacheControl(); header( "Content-Type: {$config->get( 'MimeType' )}; charset=UTF-8" ); - header( "Content-Language: {$wgContLang->getHtmlCode()}" ); + header( 'Content-Language: ' . + MediaWikiServices::getInstance()->getContentLanguage()->getHtmlCode() ); if ( $this->useGzip() ) { if ( wfClientAcceptsGzip() ) { header( 'Content-Encoding: gzip' ); diff --git a/includes/cache/LinkBatch.php b/includes/cache/LinkBatch.php index 30d105b212..c1aef59be4 100644 --- a/includes/cache/LinkBatch.php +++ b/includes/cache/LinkBatch.php @@ -222,8 +222,7 @@ class LinkBatch { return false; } - global $wgContLang; - if ( !$wgContLang->needsGenderDistinction() ) { + if ( !MediaWikiServices::getInstance()->getContentLanguage()->needsGenderDistinction() ) { return false; } diff --git a/includes/cache/MessageCache.php b/includes/cache/MessageCache.php index 7a172bead8..5c14818a52 100644 --- a/includes/cache/MessageCache.php +++ b/includes/cache/MessageCache.php @@ -88,6 +88,8 @@ class MessageCache { protected $clusterCache; /** @var BagOStuff */ protected $srvCache; + /** @var Language */ + protected $contLang; /** * Singleton instance @@ -112,7 +114,8 @@ class MessageCache { ? MediaWikiServices::getInstance()->getLocalServerObjectCache() : new EmptyBagOStuff(), $wgUseDatabaseMessages, - $wgMsgCacheExpiry + $wgMsgCacheExpiry, + MediaWikiServices::getInstance()->getContentLanguage() ); } @@ -135,13 +138,11 @@ class MessageCache { * @return string Normalized message key */ public static function normalizeKey( $key ) { - global $wgContLang; - $lckey = strtr( $key, ' ', '_' ); if ( ord( $lckey ) < 128 ) { $lckey[0] = strtolower( $lckey[0] ); } else { - $lckey = $wgContLang->lcfirst( $lckey ); + $lckey = MediaWikiServices::getInstance()->getContentLanguage()->lcfirst( $lckey ); } return $lckey; @@ -153,13 +154,15 @@ class MessageCache { * @param BagOStuff $serverCache * @param bool $useDB Whether to look for message overrides (e.g. MediaWiki: pages) * @param int $expiry Lifetime for cache. @see $mExpiry. + * @param Language|null $contLang Content language of site */ public function __construct( WANObjectCache $wanCache, BagOStuff $clusterCache, BagOStuff $serverCache, $useDB, - $expiry + $expiry, + Language $contLang = null ) { $this->wanCache = $wanCache; $this->clusterCache = $clusterCache; @@ -169,6 +172,7 @@ class MessageCache { $this->mDisable = !$useDB; $this->mExpiry = $expiry; + $this->contLang = $contLang ?? MediaWikiServices::getInstance()->getContentLanguage(); } /** @@ -581,7 +585,7 @@ class MessageCache { // (b) Update the shared caches in a deferred update with a fresh DB snapshot DeferredUpdates::addCallableUpdate( function () use ( $title, $msg, $code ) { - global $wgContLang, $wgMaxMsgCacheEntrySize; + global $wgMaxMsgCacheEntrySize; // Allow one caller at a time to avoid race conditions $scopedLock = $this->getReentrantScopedLock( $this->clusterCache->makeKey( 'messages', $code ) @@ -627,7 +631,7 @@ class MessageCache { // Purge the message in the message blob store $resourceloader = RequestContext::getMain()->getOutput()->getResourceLoader(); $blobStore = $resourceloader->getMessageBlobStore(); - $blobStore->updateMessage( $wgContLang->lcfirst( $msg ) ); + $blobStore->updateMessage( $this->contLang->lcfirst( $msg ) ); Hooks::run( 'MessageCacheReplace', [ $title, $text ] ); }, @@ -860,8 +864,6 @@ class MessageCache { * @return string|bool The message, or false if not found */ protected function getMessageFromFallbackChain( $lang, $lckey, $useDB ) { - global $wgContLang; - $alreadyTried = []; // First try the requested language. @@ -871,7 +873,7 @@ class MessageCache { } // Now try checking the site language. - $message = $this->getMessageForLang( $wgContLang, $lckey, $useDB, $alreadyTried ); + $message = $this->getMessageForLang( $this->contLang, $lckey, $useDB, $alreadyTried ); return $message; } @@ -886,13 +888,11 @@ class MessageCache { * @return string|bool The message, or false if not found */ private function getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried ) { - global $wgContLang; - $langcode = $lang->getCode(); // Try checking the database for the requested language if ( $useDB ) { - $uckey = $wgContLang->ucfirst( $lckey ); + $uckey = $this->contLang->ucfirst( $lckey ); if ( !isset( $alreadyTried[$langcode] ) ) { $message = $this->getMsgFromNamespace( @@ -1241,8 +1241,6 @@ class MessageCache { * @return array Array of message keys (strings) */ public function getAllMessageKeys( $code ) { - global $wgContLang; - $this->load( $code ); if ( !$this->cache->has( $code ) ) { // Apparently load() failed @@ -1257,7 +1255,7 @@ class MessageCache { $cache = array_diff( $cache, [ '!NONEXISTENT' ] ); // Keys may appear with a capital first letter. lcfirst them. - return array_map( [ $wgContLang, 'lcfirst' ], array_keys( $cache ) ); + return array_map( [ $this->contLang, 'lcfirst' ], array_keys( $cache ) ); } /** @@ -1268,8 +1266,6 @@ class MessageCache { * @since 1.29 */ public function updateMessageOverride( Title $title, Content $content = null ) { - global $wgContLang; - $msgText = $this->getMessageTextFromContent( $content ); if ( $msgText === null ) { $msgText = false; // treat as not existing @@ -1277,8 +1273,8 @@ class MessageCache { $this->replace( $title->getDBkey(), $msgText ); - if ( $wgContLang->hasVariants() ) { - $wgContLang->updateConversionTable( $title ); + if ( $this->contLang->hasVariants() ) { + $this->contLang->updateConversionTable( $title ); } } diff --git a/includes/collation/Collation.php b/includes/collation/Collation.php index b1ccdc20a3..25b3d94574 100644 --- a/includes/collation/Collation.php +++ b/includes/collation/Collation.php @@ -20,6 +20,8 @@ * @file */ +use MediaWiki\MediaWikiServices; + /** * @since 1.16.3 * @author Tim Starling @@ -46,13 +48,12 @@ abstract class Collation { * @return Collation */ public static function factory( $collationName ) { - global $wgContLang; - switch ( $collationName ) { case 'uppercase': return new UppercaseCollation; case 'numeric': - return new NumericUppercaseCollation( $wgContLang ); + return new NumericUppercaseCollation( + MediaWikiServices::getInstance()->getContentLanguage() ); case 'identity': return new IdentityCollation; case 'uca-default': diff --git a/includes/collation/IdentityCollation.php b/includes/collation/IdentityCollation.php index 46e7f38f5b..8e5871bf43 100644 --- a/includes/collation/IdentityCollation.php +++ b/includes/collation/IdentityCollation.php @@ -18,6 +18,8 @@ * @file */ +use MediaWiki\MediaWikiServices; + /** * Collation class that's essentially a no-op. * @@ -33,12 +35,11 @@ class IdentityCollation extends Collation { } public function getFirstLetter( $string ) { - global $wgContLang; // Copied from UppercaseCollation. // I'm kind of unclear on when this could happen... if ( $string[0] == "\0" ) { $string = substr( $string, 1 ); } - return $wgContLang->firstChar( $string ); + return MediaWikiServices::getInstance()->getContentLanguage()->firstChar( $string ); } } diff --git a/includes/collation/NumericUppercaseCollation.php b/includes/collation/NumericUppercaseCollation.php index 4a2d776f67..d2496402fd 100644 --- a/includes/collation/NumericUppercaseCollation.php +++ b/includes/collation/NumericUppercaseCollation.php @@ -35,7 +35,7 @@ class NumericUppercaseCollation extends UppercaseCollation { /** - * @var $digitTransformLang Language How to convert digits (usually $wgContLang) + * @var $digitTransformLang Language How to convert digits (usually the content language) */ private $digitTransformLang; @@ -43,7 +43,7 @@ class NumericUppercaseCollation extends UppercaseCollation { * @param Language $lang How to convert digits. * For example, if given language "my" than ၇ is treated like 7. * - * It is expected that usually this is given $wgContLang. + * It is expected that usually this is given the content language. */ public function __construct( Language $lang ) { $this->digitTransformLang = $lang; diff --git a/includes/content/ContentHandler.php b/includes/content/ContentHandler.php index 79bbba8b0f..004e38a5ef 100644 --- a/includes/content/ContentHandler.php +++ b/includes/content/ContentHandler.php @@ -1,5 +1,6 @@ getContentLanguage(); if ( $title->getNamespace() == NS_MEDIAWIKI ) { // Parse mediawiki messages with correct target language diff --git a/includes/content/TextContent.php b/includes/content/TextContent.php index c0582962b5..20bce3701a 100644 --- a/includes/content/TextContent.php +++ b/includes/content/TextContent.php @@ -25,6 +25,8 @@ * @author Daniel Kinzler */ +use MediaWiki\MediaWikiServices; + /** * Content object implementation for representing flat text. * @@ -71,13 +73,10 @@ class TextContent extends AbstractContent { } public function getTextForSummary( $maxlength = 250 ) { - global $wgContLang; - $text = $this->getNativeData(); - $truncatedtext = $wgContLang->truncateForDatabase( - preg_replace( "/[\n\r]/", ' ', $text ), - max( 0, $maxlength ) ); + $truncatedtext = MediaWikiServices::getInstance()->getContentLanguage()-> + truncateForDatabase( preg_replace( "/[\n\r]/", ' ', $text ), max( 0, $maxlength ) ); return $truncatedtext; } @@ -195,20 +194,18 @@ class TextContent extends AbstractContent { * * @param Content $that The other content object to compare this content object to. * @param Language|null $lang The language object to use for text segmentation. - * If not given, $wgContentLang is used. + * If not given, the content language is used. * * @return Diff A diff representing the changes that would have to be * made to this content object to make it equal to $that. */ public function diff( Content $that, Language $lang = null ) { - global $wgContLang; - $this->checkModelID( $that->getModel() ); // @todo could implement this in DifferenceEngine and just delegate here? if ( !$lang ) { - $lang = $wgContLang; + $lang = MediaWikiServices::getInstance()->getContentLanguage(); } $otext = $this->getNativeData(); diff --git a/includes/context/RequestContext.php b/includes/context/RequestContext.php index 7563330697..16c304c015 100644 --- a/includes/context/RequestContext.php +++ b/includes/context/RequestContext.php @@ -325,8 +325,6 @@ class RequestContext implements IContextSource, MutableContext { } elseif ( $this->lang === null ) { $this->recursion = true; - global $wgContLang; - try { $request = $this->getRequest(); $user = $this->getUser(); @@ -340,7 +338,7 @@ class RequestContext implements IContextSource, MutableContext { Hooks::run( 'UserGetLanguageObject', [ $user, &$code, $this ] ); if ( $code === $this->getConfig()->get( 'LanguageCode' ) ) { - $this->lang = $wgContLang; + $this->lang = MediaWikiServices::getInstance()->getContentLanguage(); } else { $obj = Language::factory( $code ); $this->lang = $obj; diff --git a/includes/db/DatabaseOracle.php b/includes/db/DatabaseOracle.php index f4f04f1ff9..49777627af 100644 --- a/includes/db/DatabaseOracle.php +++ b/includes/db/DatabaseOracle.php @@ -21,6 +21,7 @@ * @ingroup Database */ +use MediaWiki\MediaWikiServices; use Wikimedia\Rdbms\Database; use Wikimedia\Rdbms\Blob; use Wikimedia\Rdbms\ResultWrapper; @@ -446,8 +447,6 @@ class DatabaseOracle extends Database { * @throws DBUnexpectedError */ private function insertOneRow( $table, $row, $fname ) { - global $wgContLang; - $table = $this->tableName( $table ); // "INSERT INTO tables (a, b, c)" $sql = "INSERT INTO " . $table . " (" . implode( ',', array_keys( $row ) ) . ')'; @@ -493,7 +492,8 @@ class DatabaseOracle extends Database { $val = $this->getInfinity(); } - $val = ( $wgContLang != null ) ? $wgContLang->checkTitleEncoding( $val ) : $val; + $val = MediaWikiServices::getInstance()->getContentLanguage()-> + checkTitleEncoding( $val ); if ( oci_bind_by_name( $stmt, ":$col", $val, -1, SQLT_CHR ) === false ) { $e = oci_error( $stmt ); $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ ); @@ -1067,9 +1067,9 @@ class DatabaseOracle extends Database { } function addQuotes( $s ) { - global $wgContLang; - if ( isset( $wgContLang->mLoaded ) && $wgContLang->mLoaded ) { - $s = $wgContLang->checkTitleEncoding( $s ); + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); + if ( isset( $contLang->mLoaded ) && $contLang->mLoaded ) { + $s = $contLang->checkTitleEncoding( $s ); } return "'" . $this->strencode( $s ) . "'"; @@ -1092,15 +1092,15 @@ class DatabaseOracle extends Database { } private function wrapFieldForWhere( $table, &$col, &$val ) { - global $wgContLang; - $col_info = $this->fieldInfoMulti( $table, $col ); $col_type = $col_info != false ? $col_info->type() : 'CONSTANT'; if ( $col_type == 'CLOB' ) { $col = 'TO_CHAR(' . $col . ')'; - $val = $wgContLang->checkTitleEncoding( $val ); + $val = + MediaWikiServices::getInstance()->getContentLanguage()->checkTitleEncoding( $val ); } elseif ( $col_type == 'VARCHAR2' ) { - $val = $wgContLang->checkTitleEncoding( $val ); + $val = + MediaWikiServices::getInstance()->getContentLanguage()->checkTitleEncoding( $val ); } } @@ -1225,8 +1225,6 @@ class DatabaseOracle extends Database { * @throws DBUnexpectedError */ function update( $table, $values, $conds, $fname = __METHOD__, $options = [] ) { - global $wgContLang; - $table = $this->tableName( $table ); $opts = $this->makeUpdateOptions( $options ); $sql = "UPDATE $opts $table SET "; @@ -1270,7 +1268,8 @@ class DatabaseOracle extends Database { $val = '31-12-2030 12:00:00.000000'; } - $val = ( $wgContLang != null ) ? $wgContLang->checkTitleEncoding( $val ) : $val; + $val = MediaWikiServices::getInstance()->getContentLanguage()-> + checkTitleEncoding( $val ); if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) { $e = oci_error( $stmt ); $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ ); diff --git a/includes/deferred/LinksUpdate.php b/includes/deferred/LinksUpdate.php index 141888cda6..ae3c66008c 100644 --- a/includes/deferred/LinksUpdate.php +++ b/includes/deferred/LinksUpdate.php @@ -581,12 +581,13 @@ class LinksUpdate extends DataUpdate implements EnqueueableDataUpdate { * @return array */ private function getCategoryInsertions( $existing = [] ) { - global $wgContLang, $wgCategoryCollation; + global $wgCategoryCollation; $diffs = array_diff_assoc( $this->mCategories, $existing ); $arr = []; foreach ( $diffs as $name => $prefix ) { $nt = Title::makeTitleSafe( NS_CATEGORY, $name ); - $wgContLang->findVariantLink( $name, $nt, true ); + MediaWikiServices::getInstance()->getContentLanguage()-> + findVariantLink( $name, $nt, true ); $type = MWNamespace::getCategoryLinkType( $this->mTitle->getNamespace() ); diff --git a/includes/deferred/SearchUpdate.php b/includes/deferred/SearchUpdate.php index 0d1de1a4a9..105877bd35 100644 --- a/includes/deferred/SearchUpdate.php +++ b/includes/deferred/SearchUpdate.php @@ -117,15 +117,14 @@ class SearchUpdate implements DeferrableUpdate { * @return string */ public function updateText( $text, SearchEngine $se = null ) { - global $wgContLang; - # Language-specific strip/conversion - $text = $wgContLang->normalizeForSearch( $text ); + $text = MediaWikiServices::getInstance()->getContentLanguage()->normalizeForSearch( $text ); $se = $se ?: MediaWikiServices::getInstance()->newSearchEngine(); $lc = $se->legalSearchChars() . '&#;'; + # Strip HTML markup $text = preg_replace( "/<\\/?\\s*[A-Za-z][^>]*?>/", - ' ', $wgContLang->lc( " " . $text . " " ) ); # Strip HTML markup + ' ', MediaWikiServices::getInstance()->getContentLanguage()->lc( " " . $text . " " ) ); $text = preg_replace( "/(^|\\n)==\\s*([^\\n]+)\\s*==(\\s)/sD", "\\1\\2 \\2 \\2\\3", $text ); # Emphasize headings @@ -200,15 +199,13 @@ class SearchUpdate implements DeferrableUpdate { * @return string A stripped-down title string ready for the search index */ private function getNormalizedTitle( SearchEngine $search ) { - global $wgContLang; - $ns = $this->title->getNamespace(); $title = $this->title->getText(); $lc = $search->legalSearchChars() . '&#;'; - $t = $wgContLang->normalizeForSearch( $title ); + $t = MediaWikiServices::getInstance()->getContentLanguage()->normalizeForSearch( $title ); $t = preg_replace( "/[^{$lc}]+/", ' ', $t ); - $t = $wgContLang->lc( $t ); + $t = MediaWikiServices::getInstance()->getContentLanguage()->lc( $t ); # Handle 's, s' $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t ); diff --git a/includes/diff/DifferenceEngine.php b/includes/diff/DifferenceEngine.php index aa0a1f782f..5138655763 100644 --- a/includes/diff/DifferenceEngine.php +++ b/includes/diff/DifferenceEngine.php @@ -992,8 +992,6 @@ class DifferenceEngine extends ContextSource { * @return bool|string */ protected function textDiff( $otext, $ntext ) { - global $wgContLang; - $otext = str_replace( "\r\n", "\n", $otext ); $ntext = str_replace( "\r\n", "\n", $ntext ); @@ -1067,11 +1065,12 @@ class DifferenceEngine extends ContextSource { } # Native PHP diff - $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) ); - $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) ); + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); + $ota = explode( "\n", $contLang->segmentForDiff( $otext ) ); + $nta = explode( "\n", $contLang->segmentForDiff( $ntext ) ); $diffs = new Diff( $ota, $nta ); $formatter = new TableDiffFormatter(); - $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ); + $difftext = $contLang->unsegmentForDiff( $formatter->format( $diffs ) ); $difftext .= $this->debug( 'native PHP' ); return $difftext; diff --git a/includes/export/XmlDumpWriter.php b/includes/export/XmlDumpWriter.php index e1c12de1b9..e6f1fd76f9 100644 --- a/includes/export/XmlDumpWriter.php +++ b/includes/export/XmlDumpWriter.php @@ -23,6 +23,8 @@ * @file */ +use MediaWiki\MediaWikiServices; + /** * @ingroup Dump */ @@ -38,7 +40,6 @@ class XmlDumpWriter { * @return string */ function openStream() { - global $wgContLang; $ver = WikiExporter::schemaVersion(); return Xml::element( 'mediawiki', [ 'xmlns' => "http://www.mediawiki.org/xml/export-$ver/", @@ -55,8 +56,8 @@ class XmlDumpWriter { */ 'xsi:schemaLocation' => "http://www.mediawiki.org/xml/export-$ver/ " . "http://www.mediawiki.org/xml/export-$ver.xsd", - 'version' => $ver, - 'xml:lang' => $wgContLang->getHtmlCode() ], + 'version' => $ver, + 'xml:lang' => MediaWikiServices::getInstance()->getContentLanguage()->getHtmlCode() ], null ) . "\n" . $this->siteInfo(); @@ -123,9 +124,11 @@ class XmlDumpWriter { * @return string */ function namespaces() { - global $wgContLang; $spaces = "\n"; - foreach ( $wgContLang->getFormattedNamespaces() as $ns => $title ) { + foreach ( + MediaWikiServices::getInstance()->getContentLanguage()->getFormattedNamespaces() + as $ns => $title + ) { $spaces .= ' ' . Xml::element( 'namespace', [ @@ -434,8 +437,8 @@ class XmlDumpWriter { return $title->getPrefixedText(); } - global $wgContLang; - $prefix = $wgContLang->getFormattedNsText( $title->getNamespace() ); + $prefix = MediaWikiServices::getInstance()->getContentLanguage()-> + getFormattedNsText( $title->getNamespace() ); // @todo Emit some kind of warning to the user if $title->getNamespace() !== // NS_MAIN and $prefix === '' (viz. pages in an unregistered namespace) diff --git a/includes/filerepo/FileRepo.php b/includes/filerepo/FileRepo.php index a39529011b..858e124af4 100644 --- a/includes/filerepo/FileRepo.php +++ b/includes/filerepo/FileRepo.php @@ -7,6 +7,8 @@ * @details */ +use MediaWiki\MediaWikiServices; + /** * Base code for file repositories. * @@ -638,11 +640,10 @@ class FileRepo { * @return string */ public function getNameFromTitle( Title $title ) { - global $wgContLang; if ( $this->initialCapital != MWNamespace::isCapitalized( NS_FILE ) ) { $name = $title->getUserCaseDBKey(); if ( $this->initialCapital ) { - $name = $wgContLang->ucfirst( $name ); + $name = MediaWikiServices::getInstance()->getContentLanguage()->ucfirst( $name ); } } else { $name = $title->getDBkey(); diff --git a/includes/filerepo/LocalRepo.php b/includes/filerepo/LocalRepo.php index 9a6ef22f17..789ed4c0a6 100644 --- a/includes/filerepo/LocalRepo.php +++ b/includes/filerepo/LocalRepo.php @@ -278,7 +278,6 @@ class LocalRepo extends FileRepo { $applyMatchingFiles = function ( ResultWrapper $res, &$searchSet, &$finalFiles ) use ( $fileMatchesSearch, $flags ) { - global $wgContLang; $info = $this->getInfo(); foreach ( $res as $row ) { $file = $this->newFileFromRow( $row ); @@ -287,7 +286,8 @@ class LocalRepo extends FileRepo { $dbKeysLook = [ strtr( $file->getName(), ' ', '_' ) ]; if ( !empty( $info['initialCapital'] ) ) { // Search keys for "hi.png" and "Hi.png" should use the "Hi.png file" - $dbKeysLook[] = $wgContLang->lcfirst( $file->getName() ); + $dbKeysLook[] = MediaWikiServices::getInstance()->getContentLanguage()-> + lcfirst( $file->getName() ); } foreach ( $dbKeysLook as $dbKey ) { if ( isset( $searchSet[$dbKey] ) diff --git a/includes/filerepo/file/ForeignAPIFile.php b/includes/filerepo/file/ForeignAPIFile.php index 0e48195c6e..2ed4853f17 100644 --- a/includes/filerepo/file/ForeignAPIFile.php +++ b/includes/filerepo/file/ForeignAPIFile.php @@ -355,9 +355,8 @@ class ForeignAPIFile extends File { } function purgeDescriptionPage() { - global $wgContLang; - - $url = $this->repo->getDescriptionRenderUrl( $this->getName(), $wgContLang->getCode() ); + $url = $this->repo->getDescriptionRenderUrl( + $this->getName(), MediaWikiServices::getInstance()->getContentLanguage()->getCode() ); $key = $this->repo->getLocalCacheKey( 'RemoteFileDescription', 'url', md5( $url ) ); MediaWikiServices::getInstance()->getMainWANObjectCache()->delete( $key ); diff --git a/includes/gallery/ImageGalleryBase.php b/includes/gallery/ImageGalleryBase.php index 09e40a2821..6e8c8c9ab7 100644 --- a/includes/gallery/ImageGalleryBase.php +++ b/includes/gallery/ImageGalleryBase.php @@ -20,6 +20,8 @@ * @file */ +use MediaWiki\MediaWikiServices; + /** * Image gallery * @@ -99,7 +101,6 @@ abstract class ImageGalleryBase extends ContextSource { * @throws MWException */ static function factory( $mode = false, IContextSource $context = null ) { - global $wgContLang; self::loadModes(); if ( !$context ) { $context = RequestContext::getMainAndWarn( __METHOD__ ); @@ -109,7 +110,7 @@ abstract class ImageGalleryBase extends ContextSource { $mode = $galleryOptions['mode']; } - $mode = $wgContLang->lc( $mode ); + $mode = MediaWikiServices::getInstance()->getContentLanguage()->lc( $mode ); if ( isset( self::$modeMapping[$mode] ) ) { $class = self::$modeMapping[$mode]; diff --git a/includes/gallery/TraditionalImageGallery.php b/includes/gallery/TraditionalImageGallery.php index 479ca5d9bd..5ede631aa3 100644 --- a/includes/gallery/TraditionalImageGallery.php +++ b/includes/gallery/TraditionalImageGallery.php @@ -170,8 +170,8 @@ class TraditionalImageGallery extends ImageGalleryBase { } // @todo Code is incomplete. - // $linkTarget = Title::newFromText( $wgContLang->getNsText( MWNamespace::getUser() ) . - // ":{$ut}" ); + // $linkTarget = Title::newFromText( MediaWikiServices::getInstance()-> + // getContentLanguage()->getNsText( MWNamespace::getUser() ) . ":{$ut}" ); // $ul = Linker::link( $linkTarget, $ut ); $meta = []; diff --git a/includes/htmlform/fields/HTMLTitleTextField.php b/includes/htmlform/fields/HTMLTitleTextField.php index 0ad41d43bd..93d09e7f14 100644 --- a/includes/htmlform/fields/HTMLTitleTextField.php +++ b/includes/htmlform/fields/HTMLTitleTextField.php @@ -1,5 +1,6 @@ getNsText( $this->mParams['namespace'] ); + $namespaceName = MediaWikiServices::getInstance()->getContentLanguage()-> + getNsText( $this->mParams['namespace'] ); $title = Title::newFromTextThrow( $namespaceName . ':' . $value ); } } catch ( MalformedTitleException $e ) { diff --git a/includes/import/WikiImporter.php b/includes/import/WikiImporter.php index e5dacd70bc..00a7b52992 100644 --- a/includes/import/WikiImporter.php +++ b/includes/import/WikiImporter.php @@ -24,6 +24,8 @@ * @ingroup SpecialPage */ +use MediaWiki\MediaWikiServices; + /** * XML file reader for the page data importer. * @@ -286,11 +288,10 @@ class WikiImporter { $status->fatal( 'import-rootpage-invalid' ); } else { if ( !MWNamespace::hasSubpages( $title->getNamespace() ) ) { - global $wgContLang; - $displayNSText = $title->getNamespace() == NS_MAIN ? wfMessage( 'blanknamespace' )->text() - : $wgContLang->getNsText( $title->getNamespace() ); + : MediaWikiServices::getInstance()->getContentLanguage()-> + getNsText( $title->getNamespace() ); $status->fatal( 'import-rootpage-nosubpage', $displayNSText ); } else { // set namespace to 'all', so the namespace check in processTitle() can pass diff --git a/includes/installer/CliInstaller.php b/includes/installer/CliInstaller.php index 4f531dae52..aee51e78cd 100644 --- a/includes/installer/CliInstaller.php +++ b/includes/installer/CliInstaller.php @@ -21,6 +21,8 @@ * @ingroup Deployment */ +use MediaWiki\MediaWikiServices; + /** * Class for the core installer command line interface. * @@ -69,9 +71,9 @@ class CliInstaller extends Installer { if ( isset( $option['lang'] ) ) { global $wgLang, $wgLanguageCode; $this->setVar( '_UserLang', $option['lang'] ); - $wgContLang = Language::factory( $option['lang'] ); - $wgLang = Language::factory( $option['lang'] ); $wgLanguageCode = $option['lang']; + $wgContLang = MediaWikiServices::getInstance()->getContentLanguage(); + $wgLang = Language::factory( $option['lang'] ); RequestContext::getMain()->setLanguage( $wgLang ); } diff --git a/includes/installer/MysqlUpdater.php b/includes/installer/MysqlUpdater.php index 99d6b35bd9..ac0a520435 100644 --- a/includes/installer/MysqlUpdater.php +++ b/includes/installer/MysqlUpdater.php @@ -756,8 +756,9 @@ class MysqlUpdater extends DatabaseUpdater { 'Converting links and brokenlinks tables to pagelinks' ); - global $wgContLang; - foreach ( $wgContLang->getNamespaces() as $ns => $name ) { + foreach ( + MediaWikiServices::getInstance()->getContentLanguage()->getNamespaces() as $ns => $name + ) { if ( $ns == 0 ) { continue; } diff --git a/includes/installer/WebInstaller.php b/includes/installer/WebInstaller.php index 739d9f21cf..d8281b015e 100644 --- a/includes/installer/WebInstaller.php +++ b/includes/installer/WebInstaller.php @@ -21,6 +21,8 @@ * @ingroup Deployment */ +use MediaWiki\MediaWikiServices; + /** * Class for the core installer web interface. * @@ -500,14 +502,14 @@ class WebInstaller extends Installer { if ( $this->getSession( 'test' ) === null && !$this->request->wasPosted() ) { $wgLanguageCode = $this->getAcceptLanguage(); - $wgLang = $wgContLang = Language::factory( $wgLanguageCode ); + $wgLang = Language::factory( $wgLanguageCode ); RequestContext::getMain()->setLanguage( $wgLang ); $this->setVar( 'wgLanguageCode', $wgLanguageCode ); $this->setVar( '_UserLang', $wgLanguageCode ); } else { $wgLanguageCode = $this->getVar( 'wgLanguageCode' ); - $wgContLang = Language::factory( $wgLanguageCode ); } + $wgContLang = MediaWikiServices::getInstance()->getContentLanguage(); } /** diff --git a/includes/installer/WebInstallerName.php b/includes/installer/WebInstallerName.php index 09fc0f37c7..8314fd2803 100644 --- a/includes/installer/WebInstallerName.php +++ b/includes/installer/WebInstallerName.php @@ -19,6 +19,8 @@ * @ingroup Deployment */ +use MediaWiki\MediaWikiServices; + class WebInstallerName extends WebInstallerPage { /** @@ -186,8 +188,7 @@ class WebInstallerName extends WebInstallerPage { } // Make sure it won't conflict with any existing namespaces - global $wgContLang; - $nsIndex = $wgContLang->getNsIndex( $name ); + $nsIndex = MediaWikiServices::getInstance()->getContentLanguage()->getNsIndex( $name ); if ( $nsIndex !== false && $nsIndex !== NS_PROJECT ) { $this->parent->showError( 'config-ns-conflict', $name ); $retVal = false; diff --git a/includes/interwiki/ClassicInterwikiLookup.php b/includes/interwiki/ClassicInterwikiLookup.php index eada9d40ca..05cf933345 100644 --- a/includes/interwiki/ClassicInterwikiLookup.php +++ b/includes/interwiki/ClassicInterwikiLookup.php @@ -53,7 +53,7 @@ class ClassicInterwikiLookup implements InterwikiLookup { /** * @var Language */ - private $contentLanguage; + private $contLang; /** * @var WANObjectCache @@ -91,7 +91,7 @@ class ClassicInterwikiLookup implements InterwikiLookup { private $thisSite = null; /** - * @param Language $contentLanguage Language object used to convert prefixes to lower case + * @param Language $contLang Language object used to convert prefixes to lower case * @param WANObjectCache $objectCache Cache for interwiki info retrieved from the database * @param int $objectCacheExpiry Expiry time for $objectCache, in seconds * @param bool|array|string $cdbData The path of a CDB file, or @@ -104,7 +104,7 @@ class ClassicInterwikiLookup implements InterwikiLookup { * @param string $fallbackSite The code to assume for the local site, */ function __construct( - Language $contentLanguage, + Language $contLang, WANObjectCache $objectCache, $objectCacheExpiry, $cdbData, @@ -113,7 +113,7 @@ class ClassicInterwikiLookup implements InterwikiLookup { ) { $this->localCache = new MapCacheLRU( 100 ); - $this->contentLanguage = $contentLanguage; + $this->contLang = $contLang; $this->objectCache = $objectCache; $this->objectCacheExpiry = $objectCacheExpiry; $this->cdbData = $cdbData; @@ -144,7 +144,7 @@ class ClassicInterwikiLookup implements InterwikiLookup { return null; } - $prefix = $this->contentLanguage->lc( $prefix ); + $prefix = $this->contLang->lc( $prefix ); if ( $this->localCache->has( $prefix ) ) { return $this->localCache->get( $prefix ); } diff --git a/includes/logging/LogFormatter.php b/includes/logging/LogFormatter.php index 0e39b7ac97..e14c485147 100644 --- a/includes/logging/LogFormatter.php +++ b/includes/logging/LogFormatter.php @@ -227,8 +227,6 @@ class LogFormatter { * @return string Text */ public function getIRCActionText() { - global $wgContLang; - $this->plaintext = true; $this->irctext = true; @@ -238,6 +236,7 @@ class LogFormatter { // Text of title the action is aimed at. $target = $entry->getTarget()->getPrefixedText(); $text = null; + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); switch ( $entry->getType() ) { case 'move': switch ( $entry->getSubtype() ) { @@ -383,12 +382,12 @@ class LogFormatter { $rawDuration = $parameters['5::duration']; $rawFlags = $parameters['6::flags']; } - $duration = $wgContLang->translateBlockExpiry( + $duration = $contLang->translateBlockExpiry( $rawDuration, null, wfTimestamp( TS_UNIX, $entry->getTimestamp() ) ); - $flags = BlockLogFormatter::formatBlockFlags( $rawFlags, $wgContLang ); + $flags = BlockLogFormatter::formatBlockFlags( $rawFlags, $contLang ); $text = wfMessage( 'blocklogentry' ) ->rawParams( $target, $duration, $flags )->inContentLanguage()->escaped(); break; @@ -397,12 +396,13 @@ class LogFormatter { ->rawParams( $target )->inContentLanguage()->escaped(); break; case 'reblock': - $duration = $wgContLang->translateBlockExpiry( + $duration = $contLang->translateBlockExpiry( $parameters['5::duration'], null, wfTimestamp( TS_UNIX, $entry->getTimestamp() ) ); - $flags = BlockLogFormatter::formatBlockFlags( $parameters['6::flags'], $wgContLang ); + $flags = BlockLogFormatter::formatBlockFlags( $parameters['6::flags'], + $contLang ); $text = wfMessage( 'reblock-logentry' ) ->rawParams( $target, $duration, $flags )->inContentLanguage()->escaped(); break; diff --git a/includes/logging/LogPage.php b/includes/logging/LogPage.php index 265a41cdaf..673c9292fa 100644 --- a/includes/logging/LogPage.php +++ b/includes/logging/LogPage.php @@ -223,10 +223,10 @@ class LogPage { public static function actionText( $type, $action, $title = null, $skin = null, $params = [], $filterWikilinks = false ) { - global $wgLang, $wgContLang, $wgLogActions; + global $wgLang, $wgLogActions; if ( is_null( $skin ) ) { - $langObj = $wgContLang; + $langObj = MediaWikiServices::getInstance()->getContentLanguage(); $langObjOrNull = null; } else { $langObj = $wgLang; diff --git a/includes/logging/ProtectLogFormatter.php b/includes/logging/ProtectLogFormatter.php index 931829ab20..02a6972003 100644 --- a/includes/logging/ProtectLogFormatter.php +++ b/includes/logging/ProtectLogFormatter.php @@ -22,6 +22,8 @@ * @since 1.26 */ +use MediaWiki\MediaWikiServices; + /** * This class formats protect log entries. * @@ -146,13 +148,12 @@ class ProtectLogFormatter extends LogFormatter { } public function formatParametersForApi() { - global $wgContLang; - $ret = parent::formatParametersForApi(); if ( isset( $ret['details'] ) && is_array( $ret['details'] ) ) { foreach ( $ret['details'] as &$detail ) { if ( isset( $detail['expiry'] ) ) { - $detail['expiry'] = $wgContLang->formatExpiry( $detail['expiry'], TS_ISO_8601, 'infinite' ); + $detail['expiry'] = MediaWikiServices::getInstance()->getContentLanguage()-> + formatExpiry( $detail['expiry'], TS_ISO_8601, 'infinite' ); } } } diff --git a/includes/logging/RightsLogFormatter.php b/includes/logging/RightsLogFormatter.php index 6e527e8487..c958947b01 100644 --- a/includes/logging/RightsLogFormatter.php +++ b/includes/logging/RightsLogFormatter.php @@ -23,6 +23,8 @@ * @since 1.22 */ +use MediaWiki\MediaWikiServices; + /** * This class formats rights log entries. * @@ -30,10 +32,11 @@ */ class RightsLogFormatter extends LogFormatter { protected function makePageLink( Title $title = null, $parameters = [], $html = null ) { - global $wgContLang, $wgUserrightsInterwikiDelimiter; + global $wgUserrightsInterwikiDelimiter; if ( !$this->plaintext ) { - $text = $wgContLang->ucfirst( $title->getDBkey() ); + $text = MediaWikiServices::getInstance()->getContentLanguage()-> + ucfirst( $title->getDBkey() ); $parts = explode( $wgUserrightsInterwikiDelimiter, $text, 2 ); if ( count( $parts ) === 2 ) { diff --git a/includes/mail/EmailNotification.php b/includes/mail/EmailNotification.php index 67b7142a07..314450470e 100644 --- a/includes/mail/EmailNotification.php +++ b/includes/mail/EmailNotification.php @@ -452,7 +452,7 @@ class EmailNotification { * @private */ function sendPersonalised( $watchingUser, $source ) { - global $wgContLang, $wgEnotifUseRealName; + global $wgEnotifUseRealName; // From the PHP manual: // Note: The to parameter cannot be an address in the form of // "Something ". The mail command will not parse @@ -462,14 +462,15 @@ class EmailNotification { # $PAGEEDITDATE is the time and date of the page change # expressed in terms of individual local time of the notification # recipient, i.e. watching user + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); $body = str_replace( [ '$WATCHINGUSERNAME', '$PAGEEDITDATE', '$PAGEEDITTIME' ], [ $wgEnotifUseRealName && $watchingUser->getRealName() !== '' ? $watchingUser->getRealName() : $watchingUser->getName(), - $wgContLang->userDate( $this->timestamp, $watchingUser ), - $wgContLang->userTime( $this->timestamp, $watchingUser ) ], + $contLang->userDate( $this->timestamp, $watchingUser ), + $contLang->userTime( $this->timestamp, $watchingUser ) ], $this->body ); $headers = []; @@ -490,19 +491,18 @@ class EmailNotification { * @return Status|null */ function sendImpersonal( $addresses ) { - global $wgContLang; - if ( empty( $addresses ) ) { return null; } + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); $body = str_replace( [ '$WATCHINGUSERNAME', '$PAGEEDITDATE', '$PAGEEDITTIME' ], [ wfMessage( 'enotif_impersonal_salutation' )->inContentLanguage()->text(), - $wgContLang->date( $this->timestamp, false, false ), - $wgContLang->time( $this->timestamp, false, false ) ], + $contLang->date( $this->timestamp, false, false ), + $contLang->time( $this->timestamp, false, false ) ], $this->body ); return UserMailer::send( $addresses, $this->from, $this->subject, $body, [ diff --git a/includes/media/FormatMetadata.php b/includes/media/FormatMetadata.php index f647a9dd79..345b3cb60f 100644 --- a/includes/media/FormatMetadata.php +++ b/includes/media/FormatMetadata.php @@ -1003,13 +1003,12 @@ class FormatMetadata extends ContextSource { public static function flattenArrayContentLang( $vals, $type = 'ul', $noHtml = false, $context = false ) { - global $wgContLang; $obj = new FormatMetadata; if ( $context ) { $obj->setContext( $context ); } $context = new DerivativeContext( $obj->getContext() ); - $context->setLanguage( $wgContLang ); + $context->setLanguage( MediaWikiServices::getInstance()->getContentLanguage() ); $obj->setContext( $context ); return $obj->flattenArrayReal( $vals, $type, $noHtml ); @@ -1056,7 +1055,7 @@ class FormatMetadata extends ContextSource { */ switch ( $type ) { case 'lang': - // Display default, followed by ContLang, + // Display default, followed by ContentLanguage, // followed by the rest in no particular // order. @@ -1218,13 +1217,15 @@ class FormatMetadata extends ContextSource { * @return string The text content of "exif-$tag-$val" message in lower case */ private function exifMsg( $tag, $val, $arg = null, $arg2 = null ) { - global $wgContLang; - if ( $val === '' ) { $val = 'value'; } - return $this->msg( $wgContLang->lc( "exif-$tag-$val" ), $arg, $arg2 )->text(); + return $this->msg( + MediaWikiServices::getInstance()->getContentLanguage()->lc( "exif-$tag-$val" ), + $arg, + $arg2 + )->text(); } /** diff --git a/includes/page/ImageHistoryList.php b/includes/page/ImageHistoryList.php index bb8ed2420b..1f87d93360 100644 --- a/includes/page/ImageHistoryList.php +++ b/includes/page/ImageHistoryList.php @@ -18,6 +18,8 @@ * @file */ +use MediaWiki\MediaWikiServices; + /** * Builds the image revision log shown on image pages * @@ -111,8 +113,6 @@ class ImageHistoryList extends ContextSource { * @return string */ public function imageHistoryLine( $iscur, $file ) { - global $wgContLang; - $user = $this->getUser(); $lang = $this->getLanguage(); $timestamp = wfTimestamp( TS_MW, $file->getTimestamp() ); @@ -264,8 +264,9 @@ class ImageHistoryList extends ContextSource { $row .= '' . $this->msg( 'rev-deleted-comment' )->escaped() . ''; } else { - $row .= '' . - Linker::formatComment( $description, $this->title ) . ''; + $row .= + '' . Linker::formatComment( $description, $this->title ) . ''; } $rowClass = null; diff --git a/includes/page/WikiPage.php b/includes/page/WikiPage.php index a1b2e574d1..661faa7a02 100644 --- a/includes/page/WikiPage.php +++ b/includes/page/WikiPage.php @@ -1625,7 +1625,7 @@ class WikiPage implements Page, IDBAccessObject { * @return DerivedPageDataUpdater */ private function newDerivedDataUpdater() { - global $wgContLang, $wgRCWatchCategoryMembership, $wgArticleCountMethod; + global $wgRCWatchCategoryMembership, $wgArticleCountMethod; $derivedDataUpdater = new DerivedPageDataUpdater( $this, // NOTE: eventually, PageUpdater should not know about WikiPage @@ -1633,7 +1633,7 @@ class WikiPage implements Page, IDBAccessObject { $this->getParserCache(), JobQueueGroup::singleton(), MessageCache::singleton(), - $wgContLang, + MediaWikiServices::getInstance()->getContentLanguage(), LoggerFactory::getInstance( 'SaveParse' ) ); @@ -2301,14 +2301,13 @@ class WikiPage implements Page, IDBAccessObject { * @return string */ protected function formatExpiry( $expiry ) { - global $wgContLang; - if ( $expiry != 'infinity' ) { + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); return wfMessage( 'protect-expiring', - $wgContLang->timeanddate( $expiry, false, false ), - $wgContLang->date( $expiry, false, false ), - $wgContLang->time( $expiry, false, false ) + $contLang->timeanddate( $expiry, false, false ), + $contLang->date( $expiry, false, false ), + $contLang->time( $expiry, false, false ) )->inContentLanguage()->text(); } else { return wfMessage( 'protect-expiry-indefinite' ) @@ -2366,13 +2365,12 @@ class WikiPage implements Page, IDBAccessObject { * @return string */ public function protectDescriptionLog( array $limit, array $expiry ) { - global $wgContLang; - $protectDescriptionLog = ''; foreach ( array_filter( $limit ) as $action => $restrictions ) { $expiryText = $this->formatExpiry( $expiry[$action] ); - $protectDescriptionLog .= $wgContLang->getDirMark() . + $protectDescriptionLog .= + MediaWikiServices::getInstance()->getContentLanguage()->getDirMark() . "[$action=$restrictions] ($expiryText)"; } @@ -2841,7 +2839,7 @@ class WikiPage implements Page, IDBAccessObject { public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User $guser, $tags = null ) { - global $wgUseRCPatrol, $wgContLang; + global $wgUseRCPatrol; $dbw = wfGetDB( DB_MASTER ); @@ -2922,13 +2920,14 @@ class WikiPage implements Page, IDBAccessObject { $targetEditorForPublic = $target->getUser( RevisionRecord::FOR_PUBLIC ); // Allow the custom summary to use the same args as the default message + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); $args = [ $targetEditorForPublic ? $targetEditorForPublic->getName() : null, $currentEditorForPublic ? $currentEditorForPublic->getName() : null, $s->rev_id, - $wgContLang->timeanddate( wfTimestamp( TS_MW, $s->rev_timestamp ) ), + $contLang->timeanddate( wfTimestamp( TS_MW, $s->rev_timestamp ) ), $current->getId(), - $wgContLang->timeanddate( $current->getTimestamp() ) + $contLang->timeanddate( $current->getTimestamp() ) ]; if ( $summary instanceof Message ) { $summary = $summary->params( $args )->inContentLanguage()->text(); diff --git a/includes/parser/DateFormatter.php b/includes/parser/DateFormatter.php index 2aefc0396f..3be4353e29 100644 --- a/includes/parser/DateFormatter.php +++ b/includes/parser/DateFormatter.php @@ -21,6 +21,8 @@ * @ingroup Parser */ +use MediaWiki\MediaWikiServices; + /** * Date formatter, recognises dates in plain text and formats them according to user preferences. * @todo preferences, OutputPage @@ -131,9 +133,9 @@ class DateFormatter { * @return DateFormatter */ public static function getInstance( Language $lang = null ) { - global $wgContLang, $wgMainCacheType; + global $wgMainCacheType; - $lang = $lang ?: $wgContLang; + $lang = $lang ?: MediaWikiServices::getInstance()->getContentLanguage(); $cache = ObjectCache::getLocalServerInstance( $wgMainCacheType ); static $dateFormatter = false; diff --git a/includes/parser/Parser.php b/includes/parser/Parser.php index 7599a1f1cf..96bf89270b 100644 --- a/includes/parser/Parser.php +++ b/includes/parser/Parser.php @@ -5750,7 +5750,6 @@ class Parser { # to other users, and potentially even used inside links and such, # it needs to be consistent for all visitors. $this->mRevisionTimestamp = $this->contLang->userAdjust( $timestamp, '' ); - } return $this->mRevisionTimestamp; } diff --git a/includes/parser/ParserOptions.php b/includes/parser/ParserOptions.php index e4b064e0ca..b30c1163b8 100644 --- a/includes/parser/ParserOptions.php +++ b/includes/parser/ParserOptions.php @@ -968,8 +968,8 @@ class ParserOptions { * @return ParserOptions */ public static function newFromAnon() { - global $wgContLang; - return new ParserOptions( new User, $wgContLang ); + return new ParserOptions( new User, + MediaWikiServices::getInstance()->getContentLanguage() ); } /** @@ -1021,7 +1021,7 @@ class ParserOptions { * @param IContextSource|string|User|null $context * - If an IContextSource, the options are initialized based on the source's User and Language. * - If the string 'canonical', the options are initialized with an anonymous user and - * $wgContLang. + * the content language. * - If a User or null, the options are initialized for that User (or $wgUser if null). * 'userlang' is taken from the $userLang parameter, defaulting to $wgLang if that is null. * @param Language|StubObject|null $userLang (see above) @@ -1061,7 +1061,7 @@ class ParserOptions { $wgMaxArticleSize, $wgMaxPPNodeCount, $wgMaxTemplateDepth, $wgMaxPPExpandDepth, $wgCleanSignatures, $wgExternalLinkTarget, $wgExpensiveParserFunctionLimit, $wgMaxGeneratedPPNodeCount, $wgDisableLangConversion, $wgDisableTitleConversion, - $wgEnableMagicLinks, $wgContLang; + $wgEnableMagicLinks; if ( self::$defaults === null ) { // *UPDATE* ParserOptions::matches() if any of this changes as needed @@ -1115,7 +1115,7 @@ class ParserOptions { 'numberheadings' => User::getDefaultOption( 'numberheadings' ), 'thumbsize' => User::getDefaultOption( 'thumbsize' ), 'stubthreshold' => 0, - 'userlang' => $wgContLang, + 'userlang' => MediaWikiServices::getInstance()->getContentLanguage(), ]; } @@ -1329,8 +1329,8 @@ class ParserOptions { if ( !is_null( $title ) ) { $confstr .= $title->getPageLanguage()->getExtraHashOptions(); } else { - global $wgContLang; - $confstr .= $wgContLang->getExtraHashOptions(); + $confstr .= + MediaWikiServices::getInstance()->getContentLanguage()->getExtraHashOptions(); } $confstr .= $wgRenderHashAppend; diff --git a/includes/parser/Sanitizer.php b/includes/parser/Sanitizer.php index 461440228c..d885e24c25 100644 --- a/includes/parser/Sanitizer.php +++ b/includes/parser/Sanitizer.php @@ -24,6 +24,8 @@ * @ingroup Parser */ +use MediaWiki\MediaWikiServices; + /** * HTML sanitizer for MediaWiki * @ingroup Parser @@ -1657,7 +1659,6 @@ class Sanitizer { * @return string Still normalized, without entities */ public static function decodeCharReferencesAndNormalize( $text ) { - global $wgContLang; $text = preg_replace_callback( self::CHAR_REFS_REGEX, [ self::class, 'decodeCharReferencesCallback' ], @@ -1667,7 +1668,7 @@ class Sanitizer { ); if ( $count ) { - return $wgContLang->normalize( $text ); + return MediaWikiServices::getInstance()->getContentLanguage()->normalize( $text ); } else { return $text; } diff --git a/includes/password/PasswordPolicyChecks.php b/includes/password/PasswordPolicyChecks.php index 502f1e024c..837e959780 100644 --- a/includes/password/PasswordPolicyChecks.php +++ b/includes/password/PasswordPolicyChecks.php @@ -21,6 +21,7 @@ */ use Cdb\Reader as CdbReader; +use MediaWiki\MediaWikiServices; /** * Functions to check passwords against a policy requirement @@ -81,10 +82,12 @@ class PasswordPolicyChecks { * @return Status error if username and password match, and policy is true */ public static function checkPasswordCannotMatchUsername( $policyVal, User $user, $password ) { - global $wgContLang; $status = Status::newGood(); $username = $user->getName(); - if ( $policyVal && $wgContLang->lc( $password ) === $wgContLang->lc( $username ) ) { + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); + if ( + $policyVal && $contLang->lc( $password ) === $contLang->lc( $username ) + ) { $status->error( 'password-name-match' ); } return $status; diff --git a/includes/preferences/DefaultPreferencesFactory.php b/includes/preferences/DefaultPreferencesFactory.php index 830da0653d..07d8b0b840 100644 --- a/includes/preferences/DefaultPreferencesFactory.php +++ b/includes/preferences/DefaultPreferencesFactory.php @@ -66,7 +66,7 @@ class DefaultPreferencesFactory implements PreferencesFactory { /** @var Config */ protected $config; - /** @var Language The wiki's content language, equivalent to $wgContLang. */ + /** @var Language The wiki's content language. */ protected $contLang; /** @var AuthManager */ diff --git a/includes/resourceloader/ResourceLoaderModule.php b/includes/resourceloader/ResourceLoaderModule.php index 7018f16564..3bf309d9ea 100644 --- a/includes/resourceloader/ResourceLoaderModule.php +++ b/includes/resourceloader/ResourceLoaderModule.php @@ -129,9 +129,8 @@ abstract class ResourceLoaderModule implements LoggerAwareInterface { * @return bool */ public function getFlip( $context ) { - global $wgContLang; - - return $wgContLang->getDir() !== $context->getDirection(); + return MediaWikiServices::getInstance()->getContentLanguage()->getDir() !== + $context->getDirection(); } /** diff --git a/includes/resourceloader/ResourceLoaderStartUpModule.php b/includes/resourceloader/ResourceLoaderStartUpModule.php index 53c10df4b1..2457fe8c72 100644 --- a/includes/resourceloader/ResourceLoaderStartUpModule.php +++ b/includes/resourceloader/ResourceLoaderStartUpModule.php @@ -20,6 +20,8 @@ * @author Roan Kattouw */ +use MediaWiki\MediaWikiServices; + /** * Module for ResourceLoader initialization. * @@ -53,7 +55,6 @@ class ResourceLoaderStartUpModule extends ResourceLoaderModule { return $this->configVars[$hash]; } - global $wgContLang; $conf = $this->getConfig(); // We can't use Title::newMainPage() if 'mainpage' is in @@ -71,10 +72,11 @@ class ResourceLoaderStartUpModule extends ResourceLoaderModule { * - wgNamespaceIds: Key-value pairs of all localized, canonical and aliases for namespaces. * - wgCaseSensitiveNamespaces: Array of namespaces that are case-sensitive. */ - $namespaceIds = $wgContLang->getNamespaceIds(); + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); + $namespaceIds = $contLang->getNamespaceIds(); $caseSensitiveNamespaces = []; foreach ( MWNamespace::getCanonicalNamespaces() as $index => $name ) { - $namespaceIds[$wgContLang->lc( $name )] = $index; + $namespaceIds[$contLang->lc( $name )] = $index; if ( !MWNamespace::isCapitalized( $index ) ) { $caseSensitiveNamespaces[] = $index; } @@ -101,13 +103,13 @@ class ResourceLoaderStartUpModule extends ResourceLoaderModule { 'wgServer' => $conf->get( 'Server' ), 'wgServerName' => $conf->get( 'ServerName' ), 'wgUserLanguage' => $context->getLanguage(), - 'wgContentLanguage' => $wgContLang->getCode(), + 'wgContentLanguage' => $contLang->getCode(), 'wgTranslateNumerals' => $conf->get( 'TranslateNumerals' ), 'wgVersion' => $conf->get( 'Version' ), 'wgEnableAPI' => true, // Deprecated since MW 1.32 'wgEnableWriteAPI' => true, // Deprecated since MW 1.32 'wgMainPageTitle' => $mainPage->getPrefixedText(), - 'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(), + 'wgFormattedNamespaces' => $contLang->getFormattedNamespaces(), 'wgNamespaceIds' => $namespaceIds, 'wgContentNamespaces' => MWNamespace::getContentNamespaces(), 'wgSiteName' => $conf->get( 'Sitename' ), diff --git a/includes/search/SearchEngine.php b/includes/search/SearchEngine.php index 30c2271916..e3088c1a80 100644 --- a/includes/search/SearchEngine.php +++ b/includes/search/SearchEngine.php @@ -232,10 +232,8 @@ abstract class SearchEngine { * @return string */ public function normalizeText( $string ) { - global $wgContLang; - // Some languages such as Chinese require word segmentation - return $wgContLang->segmentByWord( $string ); + return MediaWikiServices::getInstance()->getContentLanguage()->segmentByWord( $string ); } /** @@ -257,8 +255,8 @@ abstract class SearchEngine { * @return SearchNearMatcher */ public function getNearMatcher( Config $config ) { - global $wgContLang; - return new SearchNearMatcher( $config, $wgContLang ); + return new SearchNearMatcher( $config, + MediaWikiServices::getInstance()->getContentLanguage() ); } /** @@ -415,8 +413,6 @@ abstract class SearchEngine { $withAllKeyword = true, $withPrefixSearchExtractNamespaceHook = false ) { - global $wgContLang; - $parsed = $query; if ( strpos( $query, ':' ) === false ) { // nothing to do return false; @@ -445,7 +441,7 @@ abstract class SearchEngine { if ( !$allQuery && strpos( $query, ':' ) !== false ) { $prefix = str_replace( ' ', '_', substr( $query, 0, strpos( $query, ':' ) ) ); - $index = $wgContLang->getNsIndex( $prefix ); + $index = MediaWikiServices::getInstance()->getContentLanguage()->getNsIndex( $prefix ); if ( $index !== false ) { $extractedNamespace = [ $index ]; $parsed = substr( $query, strlen( $prefix ) + 1 ); @@ -625,9 +621,8 @@ abstract class SearchEngine { $results = $this->completionSearchBackendOverfetch( $search ); $fallbackLimit = 1 + $this->limit - $results->getSize(); if ( $fallbackLimit > 0 ) { - global $wgContLang; - - $fallbackSearches = $wgContLang->autoConvertToAllVariants( $search ); + $fallbackSearches = MediaWikiServices::getInstance()->getContentLanguage()-> + autoConvertToAllVariants( $search ); $fallbackSearches = array_diff( array_unique( $fallbackSearches ), [ $search ] ); foreach ( $fallbackSearches as $fbs ) { diff --git a/includes/search/SearchHighlighter.php b/includes/search/SearchHighlighter.php index 2cec241e40..5dfc4dfe40 100644 --- a/includes/search/SearchHighlighter.php +++ b/includes/search/SearchHighlighter.php @@ -21,6 +21,8 @@ * @ingroup Search */ +use MediaWiki\MediaWikiServices; + /** * Highlight bits of wikitext * @@ -49,7 +51,7 @@ class SearchHighlighter { * @return string */ public function highlightText( $text, $terms, $contextlines, $contextchars ) { - global $wgContLang, $wgSearchHighlightBoundaries; + global $wgSearchHighlightBoundaries; if ( $text == '' ) { return ''; @@ -84,7 +86,10 @@ class SearchHighlighter { if ( $key == 2 ) { // see if this is an image link $ns = substr( $val[0], 2, -1 ); - if ( $wgContLang->getNsIndex( $ns ) != NS_FILE ) { + if ( + MediaWikiServices::getInstance()->getContentLanguage()-> + getNsIndex( $ns ) != NS_FILE + ) { break; } @@ -313,9 +318,10 @@ class SearchHighlighter { * @return string */ function caseCallback( $matches ) { - global $wgContLang; if ( strlen( $matches[0] ) > 1 ) { - return '[' . $wgContLang->lc( $matches[0] ) . $wgContLang->uc( $matches[0] ) . ']'; + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); + return '[' . $contLang->lc( $matches[0] ) . + $contLang->uc( $matches[0] ) . ']'; } else { return $matches[0]; } @@ -480,9 +486,8 @@ class SearchHighlighter { if ( $colon === false ) { return $matches[2]; // replace with caption } - global $wgContLang; $ns = substr( $matches[1], 0, $colon ); - $index = $wgContLang->getNsIndex( $ns ); + $index = MediaWikiServices::getInstance()->getContentLanguage()->getNsIndex( $ns ); if ( $index !== false && ( $index == NS_FILE || $index == NS_CATEGORY ) ) { return $matches[0]; // return the whole thing } else { @@ -503,8 +508,6 @@ class SearchHighlighter { * @return string */ public function highlightSimple( $text, $terms, $contextlines, $contextchars ) { - global $wgContLang; - $lines = explode( "\n", $text ); $terms = implode( '|', $terms ); @@ -514,6 +517,7 @@ class SearchHighlighter { $lineno = 0; $extract = ""; + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); foreach ( $lines as $line ) { if ( 0 == $contextlines ) { break; @@ -525,12 +529,12 @@ class SearchHighlighter { } --$contextlines; // truncate function changes ... to relevant i18n message. - $pre = $wgContLang->truncateForVisual( $m[1], - $contextchars, '...', false ); + $pre = $contLang->truncateForVisual( $m[1], - $contextchars, '...', false ); if ( count( $m ) < 3 ) { $post = ''; } else { - $post = $wgContLang->truncateForVisual( $m[3], $contextchars, '...', false ); + $post = $contLang->truncateForVisual( $m[3], $contextchars, '...', false ); } $found = $m[2]; diff --git a/includes/search/SearchMssql.php b/includes/search/SearchMssql.php index 289f925f83..0e85f9df2f 100644 --- a/includes/search/SearchMssql.php +++ b/includes/search/SearchMssql.php @@ -21,6 +21,7 @@ * @ingroup Search */ +use MediaWiki\MediaWikiServices; use Wikimedia\Rdbms\IResultWrapper; /** @@ -133,7 +134,6 @@ class SearchMssql extends SearchDatabase { * @return string */ private function parseQuery( $filteredText, $fulltext ) { - global $wgContLang; $lc = $this->legalSearchChars( self::CHARS_NO_SYNTAX ); $this->searchTerms = []; @@ -144,7 +144,8 @@ class SearchMssql extends SearchDatabase { if ( preg_match_all( '/([-+<>~]?)(([' . $lc . ']+)(\*?)|"[^"]*")/', $filteredText, $m, PREG_SET_ORDER ) ) { foreach ( $m as $terms ) { - $q[] = $terms[1] . $wgContLang->normalizeForSearch( $terms[2] ); + $q[] = $terms[1] . MediaWikiServices::getInstance()->getContentLanguage()-> + normalizeForSearch( $terms[2] ); if ( !empty( $terms[3] ) ) { $regexp = preg_quote( $terms[3], '/' ); diff --git a/includes/search/SearchMySQL.php b/includes/search/SearchMySQL.php index 6253b5588e..806db7deb9 100644 --- a/includes/search/SearchMySQL.php +++ b/includes/search/SearchMySQL.php @@ -24,6 +24,8 @@ * @ingroup Search */ +use MediaWiki\MediaWikiServices; + /** * Search engine hook for MySQL 4+ * @ingroup Search @@ -43,8 +45,6 @@ class SearchMySQL extends SearchDatabase { * @return array */ private function parseQuery( $filteredText, $fulltext ) { - global $wgContLang; - $lc = $this->legalSearchChars( self::CHARS_NO_SYNTAX ); // Minus syntax chars (" and *) $searchon = ''; $this->searchTerms = []; @@ -76,7 +76,8 @@ class SearchMySQL extends SearchDatabase { // Some languages such as Serbian store the input form in the search index, // so we may need to search for matches in multiple writing system variants. - $convertedVariants = $wgContLang->autoConvertToAllVariants( $term ); + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); + $convertedVariants = $contLang->autoConvertToAllVariants( $term ); if ( is_array( $convertedVariants ) ) { $variants = array_unique( array_values( $convertedVariants ) ); } else { @@ -87,9 +88,7 @@ class SearchMySQL extends SearchDatabase { // around problems with minimum lengths and encoding in MySQL's // fulltext engine. // For Chinese this also inserts spaces between adjacent Han characters. - $strippedVariants = array_map( - [ $wgContLang, 'normalizeForSearch' ], - $variants ); + $strippedVariants = array_map( [ $contLang, 'normalizeForSearch' ], $variants ); // Some languages such as Chinese force all variants to a canonical // form when stripping to the low-level search index, so to be sure @@ -134,10 +133,8 @@ class SearchMySQL extends SearchDatabase { } private function regexTerm( $string, $wildcard ) { - global $wgContLang; - $regex = preg_quote( $string, '/' ); - if ( $wgContLang->hasWordBreaks() ) { + if ( MediaWikiServices::getInstance()->getContentLanguage()->hasWordBreaks() ) { if ( $wildcard ) { // Don't cut off the final bit! $regex = "\b$regex"; @@ -389,8 +386,6 @@ class SearchMySQL extends SearchDatabase { * @return mixed|string */ function normalizeText( $string ) { - global $wgContLang; - $out = parent::normalizeText( $string ); // MySQL fulltext index doesn't grok utf-8, so we @@ -398,7 +393,7 @@ class SearchMySQL extends SearchDatabase { $out = preg_replace_callback( "/([\\xc0-\\xff][\\x80-\\xbf]*)/", [ $this, 'stripForSearchCallback' ], - $wgContLang->lc( $out ) ); + MediaWikiServices::getInstance()->getContentLanguage()->lc( $out ) ); // And to add insult to injury, the default indexing // ignores short words... Pad them so we can pass them diff --git a/includes/search/SearchOracle.php b/includes/search/SearchOracle.php index 6d7e988663..9cd245a860 100644 --- a/includes/search/SearchOracle.php +++ b/includes/search/SearchOracle.php @@ -24,6 +24,8 @@ * @ingroup Search */ +use MediaWiki\MediaWikiServices; + /** * Search engine hook base class for Oracle (ConText). * @ingroup Search @@ -173,7 +175,6 @@ class SearchOracle extends SearchDatabase { * @return string */ private function parseQuery( $filteredText, $fulltext ) { - global $wgContLang; $lc = $this->legalSearchChars( self::CHARS_NO_SYNTAX ); $this->searchTerms = []; @@ -185,7 +186,8 @@ class SearchOracle extends SearchDatabase { foreach ( $m as $terms ) { // Search terms in all variant forms, only // apply on wiki with LanguageConverter - $temp_terms = $wgContLang->autoConvertToAllVariants( $terms[2] ); + $temp_terms = MediaWikiServices::getInstance()->getContentLanguage()-> + autoConvertToAllVariants( $terms[2] ); if ( is_array( $temp_terms ) ) { $temp_terms = array_unique( array_values( $temp_terms ) ); foreach ( $temp_terms as $t ) { @@ -212,8 +214,7 @@ class SearchOracle extends SearchDatabase { } private function escapeTerm( $t ) { - global $wgContLang; - $t = $wgContLang->normalizeForSearch( $t ); + $t = MediaWikiServices::getInstance()->getContentLanguage()->normalizeForSearch( $t ); $t = isset( $this->reservedWords[strtoupper( $t )] ) ? '{' . $t . '}' : $t; $t = preg_replace( '/^"(.*)"$/', '($1)', $t ); $t = preg_replace( '/([-&|])/', '\\\\$1', $t ); diff --git a/includes/search/SearchSqlite.php b/includes/search/SearchSqlite.php index 0ed477ab2f..0bc2d379a6 100644 --- a/includes/search/SearchSqlite.php +++ b/includes/search/SearchSqlite.php @@ -21,6 +21,8 @@ * @ingroup Search */ +use MediaWiki\MediaWikiServices; + /** * Search engine hook for SQLite * @ingroup Search @@ -43,7 +45,6 @@ class SearchSqlite extends SearchDatabase { * @return string */ private function parseQuery( $filteredText, $fulltext ) { - global $wgContLang; $lc = $this->legalSearchChars( self::CHARS_NO_SYNTAX ); // Minus syntax chars (" and *) $searchon = ''; $this->searchTerms = []; @@ -70,7 +71,8 @@ class SearchSqlite extends SearchDatabase { // Some languages such as Serbian store the input form in the search index, // so we may need to search for matches in multiple writing system variants. - $convertedVariants = $wgContLang->autoConvertToAllVariants( $term ); + $convertedVariants = MediaWikiServices::getInstance()->getContentLanguage()-> + autoConvertToAllVariants( $term ); if ( is_array( $convertedVariants ) ) { $variants = array_unique( array_values( $convertedVariants ) ); } else { @@ -82,7 +84,8 @@ class SearchSqlite extends SearchDatabase { // fulltext engine. // For Chinese this also inserts spaces between adjacent Han characters. $strippedVariants = array_map( - [ $wgContLang, 'normalizeForSearch' ], + [ MediaWikiServices::getInstance()->getContentLanguage(), + 'normalizeForSearch' ], $variants ); // Some languages such as Chinese force all variants to a canonical @@ -123,10 +126,8 @@ class SearchSqlite extends SearchDatabase { } private function regexTerm( $string, $wildcard ) { - global $wgContLang; - $regex = preg_quote( $string, '/' ); - if ( $wgContLang->hasWordBreaks() ) { + if ( MediaWikiServices::getInstance()->getContentLanguage()->hasWordBreaks() ) { if ( $wildcard ) { // Don't cut off the final bit! $regex = "\b$regex"; @@ -171,13 +172,12 @@ class SearchSqlite extends SearchDatabase { } protected function searchInternal( $term, $fulltext ) { - global $wgContLang; - if ( !$this->fulltextSearchSupported() ) { return null; } - $filteredTerm = $this->filter( $wgContLang->lc( $term ) ); + $filteredTerm = + $this->filter( MediaWikiServices::getInstance()->getContentLanguage()->lc( $term ) ); $resultSet = $this->db->query( $this->getQuery( $filteredTerm, $fulltext ) ); $total = null; diff --git a/includes/skins/Skin.php b/includes/skins/Skin.php index 72663ca3ad..83d02a0fdd 100644 --- a/includes/skins/Skin.php +++ b/includes/skins/Skin.php @@ -1526,7 +1526,7 @@ abstract class Skin extends ContextSource { * should fall back to the next notice in its sequence */ private function getCachedNotice( $name ) { - global $wgRenderHashAppend, $wgContLang; + global $wgRenderHashAppend; $needParse = false; @@ -1559,12 +1559,13 @@ abstract class Skin extends ContextSource { } ); + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); return Html::rawElement( 'div', [ 'id' => 'localNotice', - 'lang' => $wgContLang->getHtmlCode(), - 'dir' => $wgContLang->getDir() + 'lang' => $contLang->getHtmlCode(), + 'dir' => $contLang->getDir() ], $parsed ); diff --git a/includes/skins/SkinTemplate.php b/includes/skins/SkinTemplate.php index 7b2d79ebad..ceebf12c36 100644 --- a/includes/skins/SkinTemplate.php +++ b/includes/skins/SkinTemplate.php @@ -268,7 +268,7 @@ class SkinTemplate extends Skin { * @return QuickTemplate The template to be executed by outputPage */ protected function prepareQuickTemplate() { - global $wgContLang, $wgScript, $wgStylePath, $wgMimeType, $wgJsMimeType, + global $wgScript, $wgStylePath, $wgMimeType, $wgJsMimeType, $wgSitename, $wgLogo, $wgMaxCredits, $wgShowCreditsIfMax, $wgArticlePath, $wgScriptPath, $wgServer; @@ -363,7 +363,11 @@ class SkinTemplate extends Skin { // heading for the page title. Defaults to empty string. $tpl->set( 'prebodyhtml', '' ); - if ( $userLangCode !== $wgContLang->getHtmlCode() || $userLangDir !== $wgContLang->getDir() ) { + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); + if ( + $userLangCode !== $contLang->getHtmlCode() || + $userLangDir !== $contLang->getDir() + ) { $escUserlang = htmlspecialchars( $userLangCode ); $escUserdir = htmlspecialchars( $userLangDir ); // Attributes must be in double quotes because htmlspecialchars() doesn't @@ -783,9 +787,8 @@ class SkinTemplate extends Skin { if ( $msg->exists() ) { $text = $msg->text(); } else { - global $wgContLang; - $text = $wgContLang->getConverter()->convertNamespace( - MWNamespace::getSubject( $title->getNamespace() ) ); + $text = MediaWikiServices::getInstance()->getContentLanguage()->getConverter()-> + convertNamespace( MWNamespace::getSubject( $title->getNamespace() ) ); } // Avoid PHP 7.1 warning of passing $this by reference diff --git a/includes/specialpage/PageQueryPage.php b/includes/specialpage/PageQueryPage.php index 7d6db0544d..ad66e319df 100644 --- a/includes/specialpage/PageQueryPage.php +++ b/includes/specialpage/PageQueryPage.php @@ -21,6 +21,7 @@ * @ingroup SpecialPage */ +use MediaWiki\MediaWikiServices; use Wikimedia\Rdbms\IResultWrapper; use Wikimedia\Rdbms\IDatabase; @@ -50,12 +51,11 @@ abstract class PageQueryPage extends QueryPage { * @return string */ public function formatResult( $skin, $row ) { - global $wgContLang; - $title = Title::makeTitleSafe( $row->namespace, $row->title ); if ( $title instanceof Title ) { - $text = $wgContLang->convert( $title->getPrefixedText() ); + $text = MediaWikiServices::getInstance()->getContentLanguage()-> + convert( $title->getPrefixedText() ); return $this->getLinkRenderer()->makeLink( $title, $text ); } else { return Html::element( 'span', [ 'class' => 'mw-invalidtitle' ], diff --git a/includes/specialpage/QueryPage.php b/includes/specialpage/QueryPage.php index 96f50bf62c..16a6d303d8 100644 --- a/includes/specialpage/QueryPage.php +++ b/includes/specialpage/QueryPage.php @@ -21,6 +21,7 @@ * @ingroup SpecialPage */ +use MediaWiki\MediaWikiServices; use Wikimedia\Rdbms\IResultWrapper; use Wikimedia\Rdbms\IDatabase; use Wikimedia\Rdbms\DBError; @@ -690,8 +691,6 @@ abstract class QueryPage extends SpecialPage { * @param int $offset Paging offset */ protected function outputResults( $out, $skin, $dbr, $res, $num, $offset ) { - global $wgContLang; - if ( $num > 0 ) { $html = []; if ( !$this->listoutput ) { @@ -726,7 +725,7 @@ abstract class QueryPage extends SpecialPage { } $html = $this->listoutput - ? $wgContLang->listToText( $html ) + ? MediaWikiServices::getInstance()->getContentLanguage()->listToText( $html ) : implode( '', $html ); $out->addHTML( $html ); diff --git a/includes/specialpage/SpecialPage.php b/includes/specialpage/SpecialPage.php index 7a39b3c6fe..13287bde6d 100644 --- a/includes/specialpage/SpecialPage.php +++ b/includes/specialpage/SpecialPage.php @@ -628,10 +628,9 @@ class SpecialPage implements MessageLocalizer { * @param string $summaryMessageKey Message key of the summary */ function outputHeader( $summaryMessageKey = '' ) { - global $wgContLang; - if ( $summaryMessageKey == '' ) { - $msg = $wgContLang->lc( $this->getName() ) . '-summary'; + $msg = MediaWikiServices::getInstance()->getContentLanguage()->lc( $this->getName() ) . + '-summary'; } else { $msg = $summaryMessageKey; } @@ -832,8 +831,9 @@ class SpecialPage implements MessageLocalizer { return; } - global $wgContLang; - $msg = $this->msg( $wgContLang->lc( $this->getName() ) . '-helppage' ); + $msg = $this->msg( + MediaWikiServices::getInstance()->getContentLanguage()->lc( $this->getName() ) . + '-helppage' ); if ( !$msg->isDisabled() ) { $helpUrl = Skin::makeUrl( $msg->plain() ); diff --git a/includes/specialpage/SpecialPageFactory.php b/includes/specialpage/SpecialPageFactory.php index b3b63b008e..964581143d 100644 --- a/includes/specialpage/SpecialPageFactory.php +++ b/includes/specialpage/SpecialPageFactory.php @@ -22,6 +22,7 @@ * @defgroup SpecialPage SpecialPage */ use MediaWiki\Linker\LinkRenderer; +use MediaWiki\MediaWikiServices; use Wikimedia\ObjectFactory; /** @@ -270,9 +271,9 @@ class SpecialPageFactory { * @return array */ private static function getAliasList() { + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); if ( is_null( self::$aliases ) ) { - global $wgContLang; - $aliases = $wgContLang->getSpecialPageAliases(); + $aliases = $contLang->getSpecialPageAliases(); $pageList = self::getPageList(); self::$aliases = []; @@ -280,7 +281,7 @@ class SpecialPageFactory { // Force every canonical name to be an alias for itself. foreach ( $pageList as $name => $stuff ) { - $caseFoldedAlias = $wgContLang->caseFold( $name ); + $caseFoldedAlias = $contLang->caseFold( $name ); self::$aliases[$caseFoldedAlias] = $name; $keepAlias[$caseFoldedAlias] = 'canonical'; } @@ -290,7 +291,7 @@ class SpecialPageFactory { foreach ( $aliases as $realName => $aliasList ) { $aliasList = array_values( $aliasList ); foreach ( $aliasList as $i => $alias ) { - $caseFoldedAlias = $wgContLang->caseFold( $alias ); + $caseFoldedAlias = $contLang->caseFold( $alias ); if ( isset( self::$aliases[$caseFoldedAlias] ) && $realName === self::$aliases[$caseFoldedAlias] @@ -327,10 +328,10 @@ class SpecialPageFactory { * @return array Array( String, String|null ), or array( null, null ) if the page is invalid */ public static function resolveAlias( $alias ) { - global $wgContLang; $bits = explode( '/', $alias, 2 ); - $caseFoldedAlias = $wgContLang->caseFold( $bits[0] ); + $caseFoldedAlias = MediaWikiServices::getInstance()->getContentLanguage()-> + caseFold( $bits[0] ); $caseFoldedAlias = str_replace( ' ', '_', $caseFoldedAlias ); $aliases = self::getAliasList(); if ( isset( $aliases[$caseFoldedAlias] ) ) { @@ -646,15 +647,15 @@ class SpecialPageFactory { * @return string */ public static function getLocalNameFor( $name, $subpage = false ) { - global $wgContLang; - $aliases = $wgContLang->getSpecialPageAliases(); + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); + $aliases = $contLang->getSpecialPageAliases(); $aliasList = self::getAliasList(); // Find the first alias that maps back to $name if ( isset( $aliases[$name] ) ) { $found = false; foreach ( $aliases[$name] as $alias ) { - $caseFoldedAlias = $wgContLang->caseFold( $alias ); + $caseFoldedAlias = $contLang->caseFold( $alias ); $caseFoldedAlias = str_replace( ' ', '_', $caseFoldedAlias ); if ( isset( $aliasList[$caseFoldedAlias] ) && $aliasList[$caseFoldedAlias] === $name @@ -690,7 +691,7 @@ class SpecialPageFactory { $name = "$name/$subpage"; } - return $wgContLang->ucfirst( $name ); + return $contLang->ucfirst( $name ); } /** diff --git a/includes/specials/SpecialAncientpages.php b/includes/specials/SpecialAncientpages.php index ecc030e638..ff44bda1e9 100644 --- a/includes/specials/SpecialAncientpages.php +++ b/includes/specials/SpecialAncientpages.php @@ -21,6 +21,8 @@ * @ingroup SpecialPage */ +use MediaWiki\MediaWikiServices; + /** * Implements Special:Ancientpages * @@ -74,14 +76,13 @@ class AncientPagesPage extends QueryPage { * @return string */ function formatResult( $skin, $result ) { - global $wgContLang; - $d = $this->getLanguage()->userTimeAndDate( $result->value, $this->getUser() ); $title = Title::makeTitle( $result->namespace, $result->title ); $linkRenderer = $this->getLinkRenderer(); $link = $linkRenderer->makeKnownLink( $title, - $wgContLang->convert( $title->getPrefixedText() ) + MediaWikiServices::getInstance()->getContentLanguage()-> + convert( $title->getPrefixedText() ) ); return $this->getLanguage()->specialList( $link, htmlspecialchars( $d ) ); diff --git a/includes/specials/SpecialBooksources.php b/includes/specials/SpecialBooksources.php index 72e0b888fe..c187156bee 100644 --- a/includes/specials/SpecialBooksources.php +++ b/includes/specials/SpecialBooksources.php @@ -21,6 +21,8 @@ * @ingroup SpecialPage */ +use MediaWiki\MediaWikiServices; + /** * Special page outputs information on sourcing a book with a particular ISBN * The parser creates links to this page when dealing with ISBNs in wikitext @@ -154,8 +156,6 @@ class SpecialBookSources extends SpecialPage { private function showList( $isbn ) { $out = $this->getOutput(); - global $wgContLang; - $isbn = self::cleanIsbn( $isbn ); # Hook to allow extensions to insert additional HTML, # e.g. for API-interacting plugins and so on @@ -183,7 +183,7 @@ class SpecialBookSources extends SpecialPage { # Fall back to the defaults given in the language file $out->addWikiMsg( 'booksources-text' ); $out->addHTML( '
    ' ); - $items = $wgContLang->getBookstoreList(); + $items = MediaWikiServices::getInstance()->getContentLanguage()->getBookstoreList(); foreach ( $items as $label => $url ) { $out->addHTML( $this->makeListItem( $isbn, $label, $url ) ); } diff --git a/includes/specials/SpecialEditWatchlist.php b/includes/specials/SpecialEditWatchlist.php index 7491f862c2..7013e40eef 100644 --- a/includes/specials/SpecialEditWatchlist.php +++ b/includes/specials/SpecialEditWatchlist.php @@ -535,8 +535,6 @@ class SpecialEditWatchlist extends UnlistedSpecialPage { * @return HTMLForm */ protected function getNormalForm() { - global $wgContLang; - $fields = []; $count = 0; @@ -582,7 +580,8 @@ class SpecialEditWatchlist extends UnlistedSpecialPage { $nsText = ( $ns == NS_MAIN ) ? $this->msg( 'blanknamespace' )->escaped() - : htmlspecialchars( $wgContLang->getFormattedNsText( $ns ) ); + : htmlspecialchars( MediaWikiServices::getInstance()->getContentLanguage()-> + getFormattedNsText( $ns ) ); $this->toc .= Linker::tocLine( "editwatchlist-{$data['section']}", $nsText, $this->getLanguage()->formatNum( ++$tocLength ), 1 ) . Linker::tocLineEnd(); } diff --git a/includes/specials/SpecialExport.php b/includes/specials/SpecialExport.php index 5a98bb90be..4407259f88 100644 --- a/includes/specials/SpecialExport.php +++ b/includes/specials/SpecialExport.php @@ -421,8 +421,6 @@ class SpecialExport extends SpecialPage { * @return array */ private function getPagesFromCategory( $title ) { - global $wgContLang; - $maxPages = $this->getConfig()->get( 'ExportPagelistLimit' ); $name = $title->getDBkey(); @@ -441,7 +439,8 @@ class SpecialExport extends SpecialPage { foreach ( $res as $row ) { $n = $row->page_title; if ( $row->page_namespace ) { - $ns = $wgContLang->getNsText( $row->page_namespace ); + $ns = MediaWikiServices::getInstance()->getContentLanguage()->getNsText( + $row->page_namespace ); $n = $ns . ':' . $n; } @@ -456,8 +455,6 @@ class SpecialExport extends SpecialPage { * @return array */ private function getPagesFromNamespace( $nsindex ) { - global $wgContLang; - $maxPages = $this->getConfig()->get( 'ExportPagelistLimit' ); $dbr = wfGetDB( DB_REPLICA ); @@ -475,7 +472,8 @@ class SpecialExport extends SpecialPage { $n = $row->page_title; if ( $row->page_namespace ) { - $ns = $wgContLang->getNsText( $row->page_namespace ); + $ns = MediaWikiServices::getInstance()->getContentLanguage()->getNsText( + $row->page_namespace ); $n = $ns . ':' . $n; } diff --git a/includes/specials/SpecialFewestrevisions.php b/includes/specials/SpecialFewestrevisions.php index f20829fd64..4a57c95eb3 100644 --- a/includes/specials/SpecialFewestrevisions.php +++ b/includes/specials/SpecialFewestrevisions.php @@ -21,6 +21,8 @@ * @ingroup SpecialPage */ +use MediaWiki\MediaWikiServices; + /** * Special page for listing the articles with the fewest revisions. * @@ -68,8 +70,6 @@ class FewestrevisionsPage extends QueryPage { * @return string */ function formatResult( $skin, $result ) { - global $wgContLang; - $nt = Title::makeTitleSafe( $result->namespace, $result->title ); if ( !$nt ) { return Html::element( @@ -83,7 +83,8 @@ class FewestrevisionsPage extends QueryPage { ); } $linkRenderer = $this->getLinkRenderer(); - $text = $wgContLang->convert( $nt->getPrefixedText() ); + $text = MediaWikiServices::getInstance()->getContentLanguage()-> + convert( $nt->getPrefixedText() ); $plink = $linkRenderer->makeLink( $nt, $text ); $nl = $this->msg( 'nrevisions' )->numParams( $result->value )->text(); diff --git a/includes/specials/SpecialFileDuplicateSearch.php b/includes/specials/SpecialFileDuplicateSearch.php index 83e18c2d95..3115adcfa6 100644 --- a/includes/specials/SpecialFileDuplicateSearch.php +++ b/includes/specials/SpecialFileDuplicateSearch.php @@ -207,11 +207,9 @@ class FileDuplicateSearchPage extends QueryPage { * @return string HTML */ function formatResult( $skin, $result ) { - global $wgContLang; - $linkRenderer = $this->getLinkRenderer(); $nt = $result->getTitle(); - $text = $wgContLang->convert( $nt->getText() ); + $text = MediaWikiServices::getInstance()->getContentLanguage()->convert( $nt->getText() ); $plink = $linkRenderer->makeLink( $nt, $text diff --git a/includes/specials/SpecialListgrouprights.php b/includes/specials/SpecialListgrouprights.php index 6091a641d0..8802a386c1 100644 --- a/includes/specials/SpecialListgrouprights.php +++ b/includes/specials/SpecialListgrouprights.php @@ -21,6 +21,8 @@ * @ingroup SpecialPage */ +use MediaWiki\MediaWikiServices; + /** * This special page lists all defined user groups and the associated rights. * See also @ref $wgGroupPermissions. @@ -133,7 +135,6 @@ class SpecialListGroupRights extends SpecialPage { } private function outputNamespaceProtectionInfo() { - global $wgContLang; $out = $this->getOutput(); $namespaceProtection = $this->getConfig()->get( 'NamespaceProtection' ); @@ -169,7 +170,8 @@ class SpecialListGroupRights extends SpecialPage { if ( $namespace == NS_MAIN ) { $namespaceText = $this->msg( 'blanknamespace' )->text(); } else { - $namespaceText = $wgContLang->convertNamespace( $namespace ); + $namespaceText = MediaWikiServices::getInstance()->getContentLanguage()-> + convertNamespace( $namespace ); } $out->addHTML( diff --git a/includes/specials/SpecialLockdb.php b/includes/specials/SpecialLockdb.php index fb04b90bae..a2c25305ca 100644 --- a/includes/specials/SpecialLockdb.php +++ b/includes/specials/SpecialLockdb.php @@ -21,6 +21,8 @@ * @ingroup SpecialPage */ +use MediaWiki\MediaWikiServices; + /** * A form to make the database readonly (eg for maintenance purposes). * @@ -74,8 +76,6 @@ class SpecialLockdb extends FormSpecialPage { } public function onSubmit( array $data ) { - global $wgContLang; - if ( !$data['Confirm'] ) { return Status::newFatal( 'locknoconfirm' ); } @@ -92,10 +92,11 @@ class SpecialLockdb extends FormSpecialPage { } fwrite( $fp, $data['Reason'] ); $timestamp = wfTimestampNow(); + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); fwrite( $fp, "\n

    " . $this->msg( 'lockedbyandtime', $this->getUser()->getName(), - $wgContLang->date( $timestamp, false, false ), - $wgContLang->time( $timestamp, false, false ) + $contLang->date( $timestamp, false, false ), + $contLang->time( $timestamp, false, false ) )->inContentLanguage()->text() . "

    \n" ); fclose( $fp ); diff --git a/includes/specials/SpecialMIMEsearch.php b/includes/specials/SpecialMIMEsearch.php index f43ed9bd6a..18c163e138 100644 --- a/includes/specials/SpecialMIMEsearch.php +++ b/includes/specials/SpecialMIMEsearch.php @@ -22,6 +22,8 @@ * @author Ævar Arnfjörð Bjarmason */ +use MediaWiki\MediaWikiServices; + /** * Searches the database for files of the requested MIME type, comparing this with the * 'img_major_mime' and 'img_minor_mime' fields in the image table. @@ -182,11 +184,9 @@ class MIMEsearchPage extends QueryPage { * @return string */ function formatResult( $skin, $result ) { - global $wgContLang; - $linkRenderer = $this->getLinkRenderer(); $nt = Title::makeTitle( $result->namespace, $result->title ); - $text = $wgContLang->convert( $nt->getText() ); + $text = MediaWikiServices::getInstance()->getContentLanguage()->convert( $nt->getText() ); $plink = $linkRenderer->makeLink( Title::newFromText( $nt->getPrefixedText() ), $text diff --git a/includes/specials/SpecialMostlinkedcategories.php b/includes/specials/SpecialMostlinkedcategories.php index f238f6c086..b80e518d82 100644 --- a/includes/specials/SpecialMostlinkedcategories.php +++ b/includes/specials/SpecialMostlinkedcategories.php @@ -24,6 +24,7 @@ * @author Ævar Arnfjörð Bjarmason */ +use MediaWiki\MediaWikiServices; use Wikimedia\Rdbms\IResultWrapper; use Wikimedia\Rdbms\IDatabase; @@ -71,8 +72,6 @@ class MostlinkedCategoriesPage extends QueryPage { * @return string */ function formatResult( $skin, $result ) { - global $wgContLang; - $nt = Title::makeTitleSafe( NS_CATEGORY, $result->title ); if ( !$nt ) { return Html::element( @@ -85,7 +84,7 @@ class MostlinkedCategoriesPage extends QueryPage { ); } - $text = $wgContLang->convert( $nt->getText() ); + $text = MediaWikiServices::getInstance()->getContentLanguage()->convert( $nt->getText() ); $plink = $this->getLinkRenderer()->makeLink( $nt, $text ); $nlinks = $this->msg( 'nmembers' )->numParams( $result->value )->escaped(); diff --git a/includes/specials/SpecialNewimages.php b/includes/specials/SpecialNewimages.php index 693b8aa90e..7526c3e756 100644 --- a/includes/specials/SpecialNewimages.php +++ b/includes/specials/SpecialNewimages.php @@ -21,6 +21,8 @@ * @ingroup SpecialPage */ +use MediaWiki\MediaWikiServices; + class SpecialNewFiles extends IncludableSpecialPage { /** @var FormOptions */ protected $opts; @@ -213,13 +215,15 @@ class SpecialNewFiles extends IncludableSpecialPage { * Send the text to be displayed above the options */ function setTopText() { - global $wgContLang; - $message = $this->msg( 'newimagestext' )->inContentLanguage(); if ( !$message->isDisabled() ) { + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); $this->getOutput()->addWikiText( Html::rawElement( 'p', - [ 'lang' => $wgContLang->getHtmlCode(), 'dir' => $wgContLang->getDir() ], + [ + 'lang' => $contLang->getHtmlCode(), + 'dir' => $contLang->getDir() + ], "\n" . $message->plain() . "\n" ), /* $lineStart */ false, diff --git a/includes/specials/SpecialPrefixindex.php b/includes/specials/SpecialPrefixindex.php index 2a8a09d266..f7906dbb29 100644 --- a/includes/specials/SpecialPrefixindex.php +++ b/includes/specials/SpecialPrefixindex.php @@ -48,8 +48,6 @@ class SpecialPrefixindex extends SpecialAllPages { * @param string $par Becomes "FOO" when called like Special:Prefixindex/FOO (default null) */ function execute( $par ) { - global $wgContLang; - $this->setHeaders(); $this->outputHeader(); @@ -65,7 +63,7 @@ class SpecialPrefixindex extends SpecialAllPages { $this->hideRedirects = $request->getBool( 'hideredirects', $this->hideRedirects ); $this->stripPrefix = $request->getBool( 'stripprefix', $this->stripPrefix ); - $namespaces = $wgContLang->getNamespaces(); + $namespaces = MediaWikiServices::getInstance()->getContentLanguage()->getNamespaces(); $out->setPageTitle( ( $namespace > 0 && array_key_exists( $namespace, $namespaces ) ) ? $this->msg( 'prefixindex-namespace', str_replace( '_', ' ', $namespaces[$namespace] ) ) @@ -143,15 +141,13 @@ class SpecialPrefixindex extends SpecialAllPages { * @param string|null $from List all pages from this name (default false) */ protected function showPrefixChunk( $namespace, $prefix, $from = null ) { - global $wgContLang; - if ( $from === null ) { $from = $prefix; } $fromList = $this->getNamespaceKeyAndText( $namespace, $from ); $prefixList = $this->getNamespaceKeyAndText( $namespace, $prefix ); - $namespaces = $wgContLang->getNamespaces(); + $namespaces = MediaWikiServices::getInstance()->getContentLanguage()->getNamespaces(); $res = null; $n = 0; $nextRow = null; diff --git a/includes/specials/SpecialRandompage.php b/includes/specials/SpecialRandompage.php index e3b567d7fe..7e5a73fb08 100644 --- a/includes/specials/SpecialRandompage.php +++ b/includes/specials/SpecialRandompage.php @@ -22,6 +22,8 @@ * @author Rob Church , Ilmari Karonen */ +use MediaWiki\MediaWikiServices; + /** * Special page to direct the user to a random page * @@ -54,12 +56,11 @@ class RandomPage extends SpecialPage { } public function execute( $par ) { - global $wgContLang; - if ( is_string( $par ) ) { // Testing for stringiness since we want to catch // the empty string to mean main namespace only. - $this->setNamespace( $wgContLang->getNsIndex( $par ) ); + $this->setNamespace( + MediaWikiServices::getInstance()->getContentLanguage()->getNsIndex( $par ) ); } $title = $this->getRandomTitle(); @@ -85,17 +86,17 @@ class RandomPage extends SpecialPage { * @return string */ private function getNsList() { - global $wgContLang; + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); $nsNames = []; foreach ( $this->namespaces as $n ) { if ( $n === NS_MAIN ) { $nsNames[] = $this->msg( 'blanknamespace' )->plain(); } else { - $nsNames[] = $wgContLang->getNsText( $n ); + $nsNames[] = $contLang->getNsText( $n ); } } - return $wgContLang->commaList( $nsNames ); + return $contLang->commaList( $nsNames ); } /** diff --git a/includes/specials/SpecialRecentchanges.php b/includes/specials/SpecialRecentchanges.php index 2496192b2f..983f74cd82 100644 --- a/includes/specials/SpecialRecentchanges.php +++ b/includes/specials/SpecialRecentchanges.php @@ -578,10 +578,9 @@ class SpecialRecentChanges extends ChangesListSpecialPage { * @param FormOptions $opts Unused */ function setTopText( FormOptions $opts ) { - global $wgContLang; - $message = $this->msg( 'recentchangestext' )->inContentLanguage(); if ( !$message->isDisabled() ) { + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); // Parse the message in this weird ugly way to preserve the ability to include interlanguage // links in it (T172461). In the future when T66969 is resolved, perhaps we can just use // $message->parse() instead. This code is copied from Message::parseText(). @@ -592,7 +591,7 @@ class SpecialRecentChanges extends ChangesListSpecialPage { // Message class sets the interface flag to false when parsing in a language different than // user language, and this is wiki content language /*interface*/false, - $wgContLang + $contLang ); $content = $parserOutput->getText( [ 'enableSectionEditLinks' => false, @@ -601,8 +600,8 @@ class SpecialRecentChanges extends ChangesListSpecialPage { $this->getOutput()->addParserOutputMetadata( $parserOutput ); $langAttributes = [ - 'lang' => $wgContLang->getHtmlCode(), - 'dir' => $wgContLang->getDir(), + 'lang' => $contLang->getHtmlCode(), + 'dir' => $contLang->getDir(), ]; $topLinksAttributes = [ 'class' => 'mw-recentchanges-toplinks' ]; diff --git a/includes/specials/SpecialSearch.php b/includes/specials/SpecialSearch.php index 2cff90e396..78a54f5cd6 100644 --- a/includes/specials/SpecialSearch.php +++ b/includes/specials/SpecialSearch.php @@ -269,8 +269,6 @@ class SpecialSearch extends SpecialPage { * @param string $term */ public function showResults( $term ) { - global $wgContLang; - if ( $this->searchEngineType !== null ) { $this->setExtraParam( 'srbackend', $this->searchEngineType ); } @@ -281,7 +279,8 @@ class SpecialSearch extends SpecialPage { $this->searchConfig, $this->getSearchProfiles() ); - $filePrefix = $wgContLang->getFormattedNsText( NS_FILE ) . ':'; + $filePrefix = MediaWikiServices::getInstance()->getContentLanguage()-> + getFormattedNsText( NS_FILE ) . ':'; if ( trim( $term ) === '' || $filePrefix === trim( $term ) ) { // Empty query -- straight view of search form if ( !Hooks::run( 'SpecialSearchResultsPrepend', [ $this, $out, $term ] ) ) { diff --git a/includes/specials/SpecialUnwatchedpages.php b/includes/specials/SpecialUnwatchedpages.php index 0ea7dfae14..a3a9bc6f91 100644 --- a/includes/specials/SpecialUnwatchedpages.php +++ b/includes/specials/SpecialUnwatchedpages.php @@ -24,6 +24,7 @@ * @author Ævar Arnfjörð Bjarmason */ +use MediaWiki\MediaWikiServices; use Wikimedia\Rdbms\IResultWrapper; use Wikimedia\Rdbms\IDatabase; @@ -109,15 +110,14 @@ class UnwatchedpagesPage extends QueryPage { * @return string */ function formatResult( $skin, $result ) { - global $wgContLang; - $nt = Title::makeTitleSafe( $result->namespace, $result->title ); if ( !$nt ) { return Html::element( 'span', [ 'class' => 'mw-invalidtitle' ], Linker::getInvalidTitleDescription( $this->getContext(), $result->namespace, $result->title ) ); } - $text = $wgContLang->convert( $nt->getPrefixedText() ); + $text = MediaWikiServices::getInstance()->getContentLanguage()-> + convert( $nt->getPrefixedText() ); $linkRenderer = $this->getLinkRenderer(); diff --git a/includes/specials/SpecialWantedcategories.php b/includes/specials/SpecialWantedcategories.php index d323c9e2b9..2accef6f74 100644 --- a/includes/specials/SpecialWantedcategories.php +++ b/includes/specials/SpecialWantedcategories.php @@ -23,6 +23,8 @@ * @ingroup SpecialPage */ +use MediaWiki\MediaWikiServices; + /** * A querypage to list the most wanted categories - implements Special:Wantedcategories * @@ -88,10 +90,8 @@ class WantedCategoriesPage extends WantedQueryPage { * @return string */ function formatResult( $skin, $result ) { - global $wgContLang; - $nt = Title::makeTitle( $result->namespace, $result->title ); - $text = $wgContLang->convert( $nt->getText() ); + $text = MediaWikiServices::getInstance()->getContentLanguage()->convert( $nt->getText() ); if ( !$this->isCached() ) { // We can assume the freshest data diff --git a/includes/specials/formfields/Licenses.php b/includes/specials/formfields/Licenses.php index 0b6c1659fb..51e63d9dd0 100644 --- a/includes/specials/formfields/Licenses.php +++ b/includes/specials/formfields/Licenses.php @@ -23,6 +23,8 @@ * @copyright Copyright © 2005, Ævar Arnfjörð Bjarmason */ +use MediaWiki\MediaWikiServices; + /** * A License class for use on Special:Upload */ @@ -57,8 +59,6 @@ class Licenses extends HTMLFormField { * @return string */ protected static function getMessageFromParams( $params ) { - global $wgContLang; - if ( !empty( $params['licenses'] ) ) { return $params['licenses']; } @@ -72,7 +72,8 @@ class Licenses extends HTMLFormField { // Also see https://phabricator.wikimedia.org/T3495 $defaultMsg = wfMessage( 'licenses' )->inContentLanguage(); if ( !$defaultMsg->exists() || $defaultMsg->plain() === '-' ) { - $defaultMsg = wfMessage( 'licenses' )->inLanguage( $wgContLang ); + $defaultMsg = wfMessage( 'licenses' )->inLanguage( + MediaWikiServices::getInstance()->getContentLanguage() ); } return $defaultMsg->plain(); diff --git a/includes/specials/forms/UploadForm.php b/includes/specials/forms/UploadForm.php index e37200f60f..da4398ad9f 100644 --- a/includes/specials/forms/UploadForm.php +++ b/includes/specials/forms/UploadForm.php @@ -260,12 +260,11 @@ class UploadForm extends HTMLForm { $file = null; } if ( $file ) { - global $wgContLang; - $mto = $file->transform( [ 'width' => 120 ] ); if ( $mto ) { $this->addHeaderText( - '
    ' . + '
    ' . Html::element( 'img', [ 'src' => $mto->getUrl(), 'class' => 'thumbimage', diff --git a/includes/specials/pagers/AllMessagesTablePager.php b/includes/specials/pagers/AllMessagesTablePager.php index 5addd9c269..2e451ecd0f 100644 --- a/includes/specials/pagers/AllMessagesTablePager.php +++ b/includes/specials/pagers/AllMessagesTablePager.php @@ -19,6 +19,7 @@ * @ingroup Pager */ +use MediaWiki\MediaWikiServices; use Wikimedia\Rdbms\FakeResultWrapper; /** @@ -27,8 +28,6 @@ use Wikimedia\Rdbms\FakeResultWrapper; * * @ingroup Pager */ -use MediaWiki\MediaWikiServices; - class AllMessagesTablePager extends TablePager { protected $filter, $prefix, $langcode, $displayPrefix; @@ -54,13 +53,12 @@ class AllMessagesTablePager extends TablePager { $this->mDefaultDirection = IndexPager::DIR_DESCENDING; $this->mLimitsShown = [ 20, 50, 100, 250, 500, 5000 ]; - global $wgContLang; - $this->talk = $this->msg( 'talkpagelinktext' )->escaped(); - $this->lang = $langObj ?: $wgContLang; + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); + $this->lang = $langObj ?: $contLang; $this->langcode = $this->lang->getCode(); - $this->foreign = !$this->lang->equals( $wgContLang ); + $this->foreign = !$this->lang->equals( $contLang ); $request = $this->getRequest(); diff --git a/includes/title/NaiveForeignTitleFactory.php b/includes/title/NaiveForeignTitleFactory.php index 44cf90d8da..307050b7ee 100644 --- a/includes/title/NaiveForeignTitleFactory.php +++ b/includes/title/NaiveForeignTitleFactory.php @@ -18,6 +18,8 @@ * @file */ +use MediaWiki\MediaWikiServices; + /** * A parser that translates page titles on a foreign wiki into ForeignTitle * objects, with no knowledge of the namespace setup on the foreign site. @@ -42,8 +44,6 @@ class NaiveForeignTitleFactory implements ForeignTitleFactory { public function createForeignTitle( $title, $ns = null ) { $pieces = explode( ':', $title, 2 ); - global $wgContLang; - /** * Can we assume that the part of the page title before the colon is a * namespace name? @@ -56,9 +56,10 @@ class NaiveForeignTitleFactory implements ForeignTitleFactory { * ID, we fall back to using the local wiki's namespace names to resolve * this -- better than nothing, and mimics the old crappy behavior */ - $isNamespacePartValid = is_null( $ns ) ? - ( $wgContLang->getNsIndex( $pieces[0] ) !== false ) : - $ns != 0; + $isNamespacePartValid = is_null( $ns ) + ? MediaWikiServices::getInstance()->getContentLanguage()->getNsIndex( $pieces[0] ) !== + false + : $ns != 0; if ( count( $pieces ) === 2 && $isNamespacePartValid ) { list( $namespaceName, $pageName ) = $pieces; diff --git a/includes/title/NaiveImportTitleFactory.php b/includes/title/NaiveImportTitleFactory.php index 5cb6112014..4da939511c 100644 --- a/includes/title/NaiveImportTitleFactory.php +++ b/includes/title/NaiveImportTitleFactory.php @@ -18,6 +18,8 @@ * @file */ +use MediaWiki\MediaWikiServices; + /** * A class to convert page titles on a foreign wiki (ForeignTitle objects) into * page titles on the local wiki (Title objects), using a default namespace @@ -39,8 +41,6 @@ class NaiveImportTitleFactory implements ImportTitleFactory { * @return Title|null */ public function createTitleFromForeignTitle( ForeignTitle $foreignTitle ) { - global $wgContLang; - if ( $foreignTitle->isNamespaceIdKnown() ) { $foreignNs = $foreignTitle->getNamespaceId(); @@ -53,7 +53,8 @@ class NaiveImportTitleFactory implements ImportTitleFactory { // Do we have a local namespace by the same name as the foreign // namespace? - $targetNs = $wgContLang->getNsIndex( $foreignTitle->getNamespaceName() ); + $targetNs = MediaWikiServices::getInstance()->getContentLanguage()->getNsIndex( + $foreignTitle->getNamespaceName() ); if ( $targetNs !== false ) { return Title::makeTitleSafe( $targetNs, $foreignTitle->getText() ); } diff --git a/includes/user/User.php b/includes/user/User.php index 5e57a18891..7bebe80715 100644 --- a/includes/user/User.php +++ b/includes/user/User.php @@ -986,13 +986,13 @@ class User implements IDBAccessObject, UserIdentity { * @return bool */ public static function isValidUserName( $name ) { - global $wgContLang, $wgMaxNameChars; + global $wgMaxNameChars; if ( $name == '' || self::isIP( $name ) || strpos( $name, '/' ) !== false || strlen( $name ) > $wgMaxNameChars - || $name != $wgContLang->ucfirst( $name ) + || $name != MediaWikiServices::getInstance()->getContentLanguage()->ucfirst( $name ) ) { return false; } @@ -1228,8 +1228,7 @@ class User implements IDBAccessObject, UserIdentity { */ public static function getCanonicalName( $name, $validate = 'valid' ) { // Force usernames to capital - global $wgContLang; - $name = $wgContLang->ucfirst( $name ); + $name = MediaWikiServices::getInstance()->getContentLanguage()->ucfirst( $name ); # Reject names containing '#'; these will be cleaned up # with title normalisation, but then it's too late to @@ -1761,24 +1760,29 @@ class User implements IDBAccessObject, UserIdentity { * @return array Array of String options */ public static function getDefaultOptions() { - global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin; + global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgDefaultSkin; static $defOpt = null; static $defOptLang = null; - if ( $defOpt !== null && $defOptLang === $wgContLang->getCode() ) { - // $wgContLang does not change (and should not change) mid-request, - // but the unit tests change it anyway, and expect this method to - // return values relevant to the current $wgContLang. + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); + if ( $defOpt !== null && $defOptLang === $contLang->getCode() ) { + // The content language does not change (and should not change) mid-request, but the + // unit tests change it anyway, and expect this method to return values relevant to the + // current content language. return $defOpt; } $defOpt = $wgDefaultUserOptions; // Default language setting - $defOptLang = $wgContLang->getCode(); + $defOptLang = $contLang->getCode(); $defOpt['language'] = $defOptLang; foreach ( LanguageConverter::$languagesWithVariants as $langCode ) { - $defOpt[$langCode == $wgContLang->getCode() ? 'variant' : "variant-$langCode"] = $langCode; + if ( $langCode === $contLang->getCode() ) { + $defOpt['variant'] = $langCode; + } else { + $defOpt["variant-$langCode"] = $langCode; + } } // NOTE: don't use SearchEngineConfig::getSearchableNamespaces here, @@ -5453,8 +5457,6 @@ class User implements IDBAccessObject, UserIdentity { * @param array|null $data Rows for the current user out of the user_properties table */ protected function loadOptions( $data = null ) { - global $wgContLang; - $this->load(); if ( $this->mOptionsLoaded ) { @@ -5468,7 +5470,7 @@ class User implements IDBAccessObject, UserIdentity { // There's no need to do it for logged-in users: they can set preferences, // and handling of page content is done by $pageLang->getPreferredVariant() and such, // so don't override user's choice (especially when the user chooses site default). - $variant = $wgContLang->getDefaultVariant(); + $variant = MediaWikiServices::getInstance()->getContentLanguage()->getDefaultVariant(); $this->mOptions['variant'] = $variant; $this->mOptions['language'] = $variant; $this->mOptionsLoaded = true; diff --git a/includes/widget/search/BasicSearchResultSetWidget.php b/includes/widget/search/BasicSearchResultSetWidget.php index 8521e68f00..1a885b0136 100644 --- a/includes/widget/search/BasicSearchResultSetWidget.php +++ b/includes/widget/search/BasicSearchResultSetWidget.php @@ -2,6 +2,7 @@ namespace MediaWiki\Widget\Search; +use MediaWiki\MediaWikiServices; use Message; use SearchResultSet; use SpecialSearch; @@ -42,8 +43,6 @@ class BasicSearchResultSetWidget { SearchResultSet $titleResultSet = null, SearchResultSet $textResultSet = null ) { - global $wgContLang; - $hasTitle = $titleResultSet ? $titleResultSet->numRows() > 0 : false; $hasText = $textResultSet ? $textResultSet->numRows() > 0 : false; $hasSecondary = $textResultSet @@ -95,7 +94,7 @@ class BasicSearchResultSetWidget { // Convert the whole thing to desired language variant // TODO: Move this up to Special:Search? - return $wgContLang->convert( $out ); + return MediaWikiServices::getInstance()->getContentLanguage()->convert( $out ); } /** @@ -118,9 +117,8 @@ class BasicSearchResultSetWidget { * @return string HTML */ protected function renderResultSet( SearchResultSet $resultSet, $offset ) { - global $wgContLang; - - $terms = $wgContLang->convertForSearchResult( $resultSet->termMatches() ); + $terms = MediaWikiServices::getInstance()->getContentLanguage()-> + convertForSearchResult( $resultSet->termMatches() ); $hits = []; foreach ( $resultSet as $result ) { diff --git a/includes/widget/search/SearchFormWidget.php b/includes/widget/search/SearchFormWidget.php index 95875cd82f..735806b0df 100644 --- a/includes/widget/search/SearchFormWidget.php +++ b/includes/widget/search/SearchFormWidget.php @@ -4,6 +4,7 @@ namespace MediaWiki\Widget\Search; use Hooks; use Html; +use MediaWiki\MediaWikiServices; use MediaWiki\Widget\SearchInputWidget; use MWNamespace; use SearchEngineConfig; @@ -171,11 +172,10 @@ class SearchFormWidget { * @return bool */ protected function startsWithImage( $term ) { - global $wgContLang; - $parts = explode( ':', $term ); return count( $parts ) > 1 - ? $wgContLang->getNsIndex( $parts[0] ) === NS_FILE + ? MediaWikiServices::getInstance()->getContentLanguage()->getNsIndex( $parts[0] ) === + NS_FILE : false; } @@ -236,8 +236,6 @@ class SearchFormWidget { * @return string HTML */ protected function powerSearchBox( $term, array $opts ) { - global $wgContLang; - $rows = []; $activeNamespaces = $this->specialSearch->getNamespaces(); foreach ( $this->searchConfig->searchableNamespaces() as $namespace => $name ) { @@ -246,7 +244,8 @@ class SearchFormWidget { $rows[$subject] = ""; } - $name = $wgContLang->getConverter()->convertNamespace( $namespace ); + $name = MediaWikiServices::getInstance()->getContentLanguage()->getConverter()-> + convertNamespace( $namespace ); if ( $name === '' ) { $name = $this->specialSearch->msg( 'blanknamespace' )->text(); } diff --git a/languages/Language.php b/languages/Language.php index 453a610d42..dfbacfc0a7 100644 --- a/languages/Language.php +++ b/languages/Language.php @@ -550,7 +550,7 @@ class Language { * Get a namespace value by key * * - * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI ); + * $mw_ns = $lang->getNsText( NS_MEDIAWIKI ); * echo $mw_ns; // prints 'MediaWiki' * * @@ -568,7 +568,7 @@ class Language { * producing output. * * - * $mw_ns = $wgContLang->getFormattedNsText( NS_MEDIAWIKI_TALK ); + * $mw_ns = $lang->getFormattedNsText( NS_MEDIAWIKI_TALK ); * echo $mw_ns; // prints 'MediaWiki talk' * * diff --git a/languages/LanguageConverter.php b/languages/LanguageConverter.php index dcc2cf335f..6ab6e8f852 100644 --- a/languages/LanguageConverter.php +++ b/languages/LanguageConverter.php @@ -250,7 +250,7 @@ class LanguageConverter { * @return mixed Variant if one found, null otherwise */ protected function getUserVariant() { - global $wgUser, $wgContLang; + global $wgUser; // memoizing this function wreaks havoc on parserTest.php /* @@ -266,7 +266,10 @@ class LanguageConverter { return false; } if ( $wgUser->isLoggedIn() ) { - if ( $this->mMainLanguageCode == $wgContLang->getCode() ) { + if ( + $this->mMainLanguageCode == + MediaWikiServices::getInstance()->getContentLanguage()->getCode() + ) { $ret = $wgUser->getOption( 'variant' ); } else { $ret = $wgUser->getOption( 'variant-' . $this->mMainLanguageCode ); diff --git a/maintenance/benchmarks/benchmarkTidy.php b/maintenance/benchmarks/benchmarkTidy.php index f2939b33df..5a432fb94e 100644 --- a/maintenance/benchmarks/benchmarkTidy.php +++ b/maintenance/benchmarks/benchmarkTidy.php @@ -1,5 +1,7 @@ getContentLanguage(); $times = []; $innerCount = 10; $outerCount = 10; @@ -44,7 +45,7 @@ class BenchmarkTidy extends Maintenance { $t = microtime( true ); for ( $i = 0; $i < $innerCount; $i++ ) { $driver->tidy( $html ); - print $wgContLang->formatSize( memory_get_usage( true ) ) . "\n"; + print $contLang->formatSize( memory_get_usage( true ) ) . "\n"; } $t = ( ( microtime( true ) - $t ) / $innerCount ) * 1000; $times[] = $t; @@ -67,10 +68,9 @@ class BenchmarkTidy extends Maintenance { print "Median: $median ms\n"; print "Mean: $mean ms\n"; print "Maximum: $max ms\n"; - print "Memory usage: " . - $wgContLang->formatSize( memory_get_usage( true ) ) . "\n"; + print "Memory usage: " . $contLang->formatSize( memory_get_usage( true ) ) . "\n"; print "Peak memory usage: " . - $wgContLang->formatSize( memory_get_peak_usage( true ) ) . "\n"; + $contLang->formatSize( memory_get_peak_usage( true ) ) . "\n"; } } diff --git a/maintenance/cleanupCaps.php b/maintenance/cleanupCaps.php index 2b47056f7e..1b49f0e221 100644 --- a/maintenance/cleanupCaps.php +++ b/maintenance/cleanupCaps.php @@ -29,6 +29,8 @@ * @ingroup Maintenance */ +use MediaWiki\MediaWikiServices; + require_once __DIR__ . '/cleanupTable.inc'; /** @@ -71,12 +73,10 @@ class CleanupCaps extends TableCleanup { } protected function processRowToUppercase( $row ) { - global $wgContLang; - $current = Title::makeTitle( $row->page_namespace, $row->page_title ); $display = $current->getPrefixedText(); $lower = $row->page_title; - $upper = $wgContLang->ucfirst( $row->page_title ); + $upper = MediaWikiServices::getInstance()->getContentLanguage()->ucfirst( $row->page_title ); if ( $upper == $lower ) { $this->output( "\"$display\" already uppercase.\n" ); @@ -109,12 +109,10 @@ class CleanupCaps extends TableCleanup { } protected function processRowToLowercase( $row ) { - global $wgContLang; - $current = Title::makeTitle( $row->page_namespace, $row->page_title ); $display = $current->getPrefixedText(); $upper = $row->page_title; - $lower = $wgContLang->lcfirst( $row->page_title ); + $lower = MediaWikiServices::getInstance()->getContentLanguage()->lcfirst( $row->page_title ); if ( $upper == $lower ) { $this->output( "\"$display\" already lowercase.\n" ); diff --git a/maintenance/cleanupImages.php b/maintenance/cleanupImages.php index 90364e26e2..305a41dddc 100644 --- a/maintenance/cleanupImages.php +++ b/maintenance/cleanupImages.php @@ -25,6 +25,8 @@ * @ingroup Maintenance */ +use MediaWiki\MediaWikiServices; + require_once __DIR__ . '/cleanupTable.inc'; /** @@ -46,8 +48,6 @@ class CleanupImages extends TableCleanup { } protected function processRow( $row ) { - global $wgContLang; - $source = $row->img_name; if ( $source == '' ) { // Ye olde empty rows. Just kill them. @@ -64,11 +64,13 @@ class CleanupImages extends TableCleanup { // We also have some HTML entities there $cleaned = Sanitizer::decodeCharReferences( $cleaned ); + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); + // Some are old latin-1 - $cleaned = $wgContLang->checkTitleEncoding( $cleaned ); + $cleaned = $contLang->checkTitleEncoding( $cleaned ); // Many of remainder look like non-normalized unicode - $cleaned = $wgContLang->normalize( $cleaned ); + $cleaned = $contLang->normalize( $cleaned ); $title = Title::makeTitleSafe( NS_FILE, $cleaned ); diff --git a/maintenance/cleanupTitles.php b/maintenance/cleanupTitles.php index 234e1b1f2a..7f0e340a4a 100644 --- a/maintenance/cleanupTitles.php +++ b/maintenance/cleanupTitles.php @@ -45,9 +45,8 @@ class TitleCleanup extends TableCleanup { * @param object $row */ protected function processRow( $row ) { - global $wgContLang; $display = Title::makeName( $row->page_namespace, $row->page_title ); - $verified = $wgContLang->normalize( $display ); + $verified = MediaWikiServices::getInstance()->getContentLanguage()->normalize( $display ); $title = Title::newFromText( $verified ); if ( !is_null( $title ) diff --git a/maintenance/cleanupWatchlist.php b/maintenance/cleanupWatchlist.php index 5e3aee7402..8e4a353df8 100644 --- a/maintenance/cleanupWatchlist.php +++ b/maintenance/cleanupWatchlist.php @@ -29,6 +29,8 @@ * @ingroup Maintenance */ +use MediaWiki\MediaWikiServices; + require_once __DIR__ . '/cleanupTable.inc'; /** @@ -58,10 +60,9 @@ class CleanupWatchlist extends TableCleanup { } protected function processRow( $row ) { - global $wgContLang; $current = Title::makeTitle( $row->wl_namespace, $row->wl_title ); $display = $current->getPrefixedText(); - $verified = $wgContLang->normalize( $display ); + $verified = MediaWikiServices::getInstance()->getContentLanguage()->normalize( $display ); $title = Title::newFromText( $verified ); if ( $row->wl_user == 0 || is_null( $title ) || !$title->equals( $current ) ) { diff --git a/maintenance/convertLinks.php b/maintenance/convertLinks.php index 8cd029762f..af60eaa2ba 100644 --- a/maintenance/convertLinks.php +++ b/maintenance/convertLinks.php @@ -21,6 +21,8 @@ * @ingroup Maintenance */ +use MediaWiki\MediaWikiServices; + require_once __DIR__ . '/Maintenance.php'; /** @@ -75,8 +77,6 @@ class ConvertLinks extends Maintenance { return; } - global $wgContLang; - # counters etc $numBadLinks = $curRowsRead = 0; @@ -153,7 +153,8 @@ class ConvertLinks extends Maintenance { foreach ( $res as $row ) { $title = $row->cur_title; if ( $row->cur_namespace ) { - $title = $wgContLang->getNsText( $row->cur_namespace ) . ":$title"; + $title = MediaWikiServices::getInstance()->getContentLanguage()-> + getNsText( $row->cur_namespace ) . ":$title"; } $ids[$title] = $row->cur_id; $curRowsRead++; diff --git a/maintenance/deleteEqualMessages.php b/maintenance/deleteEqualMessages.php index cd9ef11160..89885d29d7 100644 --- a/maintenance/deleteEqualMessages.php +++ b/maintenance/deleteEqualMessages.php @@ -19,6 +19,8 @@ * @ingroup Maintenance */ +use MediaWiki\MediaWikiServices; + require_once __DIR__ . '/Maintenance.php'; /** @@ -44,15 +46,14 @@ class DeleteEqualMessages extends Maintenance { * @param array &$messageInfo */ protected function fetchMessageInfo( $langCode, array &$messageInfo ) { - global $wgContLang; - + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); if ( $langCode ) { $this->output( "\n... fetching message info for language: $langCode" ); - $nonContLang = true; + $nonContentLanguage = true; } else { $this->output( "\n... fetching message info for content language" ); - $langCode = $wgContLang->getCode(); - $nonContLang = false; + $langCode = $contLang->getCode(); + $nonContentLanguage = false; } /* Based on SpecialAllmessages::reallyDoQuery #filter=modified */ @@ -60,12 +61,12 @@ class DeleteEqualMessages extends Maintenance { $l10nCache = Language::getLocalisationCache(); $messageNames = $l10nCache->getSubitemList( 'en', 'messages' ); // Normalise message names for NS_MEDIAWIKI page_title - $messageNames = array_map( [ $wgContLang, 'ucfirst' ], $messageNames ); + $messageNames = array_map( [ $contLang, 'ucfirst' ], $messageNames ); $statuses = AllMessagesTablePager::getCustomisedStatuses( - $messageNames, $langCode, $nonContLang ); + $messageNames, $langCode, $nonContentLanguage ); // getCustomisedStatuses is stripping the sub page from the page titles, add it back - $titleSuffix = $nonContLang ? "/$langCode" : ''; + $titleSuffix = $nonContentLanguage ? "/$langCode" : ''; foreach ( $messageNames as $key ) { $customised = isset( $statuses['pages'][$key] ); diff --git a/maintenance/dumpTextPass.php b/maintenance/dumpTextPass.php index 95dd4dab39..e1df1f1a16 100644 --- a/maintenance/dumpTextPass.php +++ b/maintenance/dumpTextPass.php @@ -705,7 +705,6 @@ TEXT * @throws MWException */ private function getTextDb( $id ) { - global $wgContLang; if ( !isset( $this->db ) ) { throw new MWException( __METHOD__ . "No database available" ); } @@ -718,7 +717,8 @@ TEXT return false; } $stripped = str_replace( "\r", "", $text ); - $normalized = $wgContLang->normalize( $stripped ); + $normalized = MediaWikiServices::getInstance()->getContentLanguage()-> + normalize( $stripped ); return $normalized; } @@ -797,8 +797,6 @@ TEXT } private function getTextSpawnedOnce( $id ) { - global $wgContLang; - $ok = fwrite( $this->spawnWrite, "$id\n" ); // $this->progress( ">> $id" ); if ( !$ok ) { @@ -853,7 +851,8 @@ TEXT // Do normalization in the dump thread... $stripped = str_replace( "\r", "", $text ); - $normalized = $wgContLang->normalize( $stripped ); + $normalized = MediaWikiServices::getInstance()->getContentLanguage()-> + normalize( $stripped ); return $normalized; } diff --git a/maintenance/generateSitemap.php b/maintenance/generateSitemap.php index ff3e2fce1a..70fdebf403 100644 --- a/maintenance/generateSitemap.php +++ b/maintenance/generateSitemap.php @@ -26,6 +26,8 @@ * @see http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd */ +use MediaWiki\MediaWikiServices; + require_once __DIR__ . '/Maintenance.php'; /** @@ -316,7 +318,7 @@ class GenerateSitemap extends Maintenance { * Main loop */ public function main() { - global $wgContLang; + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); fwrite( $this->findex, $this->openIndex() ); @@ -327,7 +329,7 @@ class GenerateSitemap extends Maintenance { $length = $this->limit[0]; $i = $smcount = 0; - $fns = $wgContLang->getFormattedNsText( $namespace ); + $fns = $contLang->getFormattedNsText( $namespace ); $this->output( "$namespace ($fns)\n" ); $skippedRedirects = 0; // Number of redirects skipped for that namespace foreach ( $res as $row ) { @@ -358,10 +360,10 @@ class GenerateSitemap extends Maintenance { $length += strlen( $entry ); $this->write( $this->file, $entry ); // generate pages for language variants - if ( $wgContLang->hasVariants() ) { - $variants = $wgContLang->getVariants(); + if ( $contLang->hasVariants() ) { + $variants = $contLang->getVariants(); foreach ( $variants as $vCode ) { - if ( $vCode == $wgContLang->getCode() ) { + if ( $vCode == $contLang->getCode() ) { continue; // we don't want default variant } $entry = $this->fileEntry( diff --git a/maintenance/importDump.php b/maintenance/importDump.php index 965906f229..98344734d1 100644 --- a/maintenance/importDump.php +++ b/maintenance/importDump.php @@ -24,6 +24,8 @@ * @ingroup Maintenance */ +use MediaWiki\MediaWikiServices; + require_once __DIR__ . '/Maintenance.php'; /** @@ -131,13 +133,13 @@ TEXT } private function getNsIndex( $namespace ) { - global $wgContLang; - $result = $wgContLang->getNsIndex( $namespace ); + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); + $result = $contLang->getNsIndex( $namespace ); if ( $result !== false ) { return $result; } $ns = intval( $namespace ); - if ( strval( $ns ) === $namespace && $wgContLang->getNsText( $ns ) !== false ) { + if ( strval( $ns ) === $namespace && $contLang->getNsText( $ns ) !== false ) { return $ns; } $this->fatalError( "Unknown namespace text / index specified: $namespace" ); diff --git a/maintenance/language/dumpMessages.php b/maintenance/language/dumpMessages.php index 543ee06356..949ce48ca9 100644 --- a/maintenance/language/dumpMessages.php +++ b/maintenance/language/dumpMessages.php @@ -20,7 +20,7 @@ * * @file * @ingroup MaintenanceLanguage - * @todo Make this more useful, right now just dumps $wgContLang + * @todo Make this more useful, right now just dumps content language */ require_once __DIR__ . '/../Maintenance.php'; diff --git a/maintenance/namespaceDupes.php b/maintenance/namespaceDupes.php index 71241e7033..075d6f27d6 100644 --- a/maintenance/namespaceDupes.php +++ b/maintenance/namespaceDupes.php @@ -104,14 +104,15 @@ class NamespaceDupes extends Maintenance { * @return bool */ private function checkAll( $options ) { - global $wgContLang, $wgNamespaceAliases, $wgCapitalLinks; + global $wgNamespaceAliases, $wgCapitalLinks; + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); $spaces = []; // List interwikis first, so they'll be overridden // by any conflicting local namespaces. foreach ( $this->getInterwikiList() as $prefix ) { - $name = $wgContLang->ucfirst( $prefix ); + $name = $contLang->ucfirst( $prefix ); $spaces[$name] = 0; } @@ -122,7 +123,7 @@ class NamespaceDupes extends Maintenance { $spaces[$name] = $ns; } } - foreach ( $wgContLang->getNamespaces() as $ns => $name ) { + foreach ( $contLang->getNamespaces() as $ns => $name ) { if ( $name !== '' ) { $spaces[$name] = $ns; } @@ -130,7 +131,7 @@ class NamespaceDupes extends Maintenance { foreach ( $wgNamespaceAliases as $name => $ns ) { $spaces[$name] = $ns; } - foreach ( $wgContLang->getNamespaceAliases() as $name => $ns ) { + foreach ( $contLang->getNamespaceAliases() as $name => $ns ) { $spaces[$name] = $ns; } @@ -138,17 +139,17 @@ class NamespaceDupes extends Maintenance { // since we're doing case-sensitive searches in the db. foreach ( $spaces as $name => $ns ) { $moreNames = []; - $moreNames[] = $wgContLang->uc( $name ); - $moreNames[] = $wgContLang->ucfirst( $wgContLang->lc( $name ) ); - $moreNames[] = $wgContLang->ucwords( $name ); - $moreNames[] = $wgContLang->ucwords( $wgContLang->lc( $name ) ); - $moreNames[] = $wgContLang->ucwordbreaks( $name ); - $moreNames[] = $wgContLang->ucwordbreaks( $wgContLang->lc( $name ) ); + $moreNames[] = $contLang->uc( $name ); + $moreNames[] = $contLang->ucfirst( $contLang->lc( $name ) ); + $moreNames[] = $contLang->ucwords( $name ); + $moreNames[] = $contLang->ucwords( $contLang->lc( $name ) ); + $moreNames[] = $contLang->ucwordbreaks( $name ); + $moreNames[] = $contLang->ucwordbreaks( $contLang->lc( $name ) ); if ( !$wgCapitalLinks ) { foreach ( $moreNames as $altName ) { - $moreNames[] = $wgContLang->lcfirst( $altName ); + $moreNames[] = $contLang->lcfirst( $altName ); } - $moreNames[] = $wgContLang->lcfirst( $name ); + $moreNames[] = $contLang->lcfirst( $name ); } foreach ( array_unique( $moreNames ) as $altName ) { if ( $altName !== $name ) { diff --git a/maintenance/orphans.php b/maintenance/orphans.php index d7decc1b45..fad4e7d8e6 100644 --- a/maintenance/orphans.php +++ b/maintenance/orphans.php @@ -30,6 +30,7 @@ require_once __DIR__ . '/Maintenance.php'; +use MediaWiki\MediaWikiServices; use Wikimedia\Rdbms\IMaintainableDatabase; /** @@ -97,8 +98,6 @@ class Orphans extends Maintenance { ); $orphans = $result->numRows(); if ( $orphans > 0 ) { - global $wgContLang; - $this->output( "$orphans orphan revisions...\n" ); $this->output( sprintf( "%10s %10s %14s %20s %s\n", @@ -107,10 +106,11 @@ class Orphans extends Maintenance { foreach ( $result as $row ) { $comment = $commentStore->getComment( 'rev_comment', $row )->text; + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); if ( $comment !== '' ) { - $comment = '(' . $wgContLang->truncateForVisual( $comment, 40 ) . ')'; + $comment = '(' . $contLang->truncateForVisual( $comment, 40 ) . ')'; } - $rev_user_text = $wgContLang->truncateForVisual( $row->rev_user_text, 20 ); + $rev_user_text = $contLang->truncateForVisual( $row->rev_user_text, 20 ); # pad $rev_user_text to 20 characters. Note that this may # yield poor results if $rev_user_text contains combining # or half-width characters. Alas. diff --git a/maintenance/preprocessorFuzzTest.php b/maintenance/preprocessorFuzzTest.php index 2503ed25e2..d5d27ad8ce 100644 --- a/maintenance/preprocessorFuzzTest.php +++ b/maintenance/preprocessorFuzzTest.php @@ -21,6 +21,8 @@ * @ingroup Maintenance */ +use MediaWiki\MediaWikiServices; + $optionsWithoutArgs = [ 'verbose' ]; require_once __DIR__ . '/commandLine.inc'; @@ -123,8 +125,7 @@ class PPFuzzTester { // This resolves a few differences between the old preprocessor and the // XML-based one, which doesn't like illegals and converts line endings. // It's done by the MW UI, so it's a reasonably legitimate thing to do. - global $wgContLang; - $s = $wgContLang->normalize( $s ); + $s = MediaWikiServices::getInstance()->getContentLanguage()->normalize( $s ); return $s; } diff --git a/maintenance/rebuildImages.php b/maintenance/rebuildImages.php index 713492a285..c0de33412e 100644 --- a/maintenance/rebuildImages.php +++ b/maintenance/rebuildImages.php @@ -32,6 +32,7 @@ require_once __DIR__ . '/Maintenance.php'; +use MediaWiki\MediaWikiServices; use Wikimedia\Rdbms\IMaintainableDatabase; /** @@ -193,11 +194,10 @@ class ImageBuilder extends Maintenance { } function addMissingImage( $filename, $fullpath ) { - global $wgContLang; - $timestamp = $this->dbw->timestamp( $this->getRepo()->getFileTimestamp( $fullpath ) ); - $altname = $wgContLang->checkTitleEncoding( $filename ); + $altname = MediaWikiServices::getInstance()->getContentLanguage()-> + checkTitleEncoding( $filename ); if ( $altname != $filename ) { if ( $this->dryrun ) { $filename = $altname; diff --git a/tests/phpunit/MediaWikiLangTestCase.php b/tests/phpunit/MediaWikiLangTestCase.php index fd308b2d95..4b0edb13f1 100644 --- a/tests/phpunit/MediaWikiLangTestCase.php +++ b/tests/phpunit/MediaWikiLangTestCase.php @@ -1,16 +1,19 @@ getCode() ) { + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); + if ( $wgLanguageCode != $contLang->getCode() ) { throw new MWException( "Error in MediaWikiLangTestCase::setUp(): " . - "\$wgLanguageCode ('$wgLanguageCode') is different from " . - "\$wgContLang->getCode() (" . $wgContLang->getCode() . ")" ); + "\$wgLanguageCode ('$wgLanguageCode') is different from content language code (" . + $contLang->getCode() . ")" ); } parent::setUp(); diff --git a/tests/phpunit/includes/CommentStoreTest.php b/tests/phpunit/includes/CommentStoreTest.php index c41361cd82..f9b592ec01 100644 --- a/tests/phpunit/includes/CommentStoreTest.php +++ b/tests/phpunit/includes/CommentStoreTest.php @@ -1,5 +1,6 @@ getContentLanguage(), $stage ); return $store; } diff --git a/tests/phpunit/includes/EditPageTest.php b/tests/phpunit/includes/EditPageTest.php index 216d92c01e..587f2c4b84 100644 --- a/tests/phpunit/includes/EditPageTest.php +++ b/tests/phpunit/includes/EditPageTest.php @@ -1,5 +1,7 @@ getContentLanguage(); + $this->setContentLang( $contLang ); + $this->setMwGlobals( [ 'wgExtraNamespaces' => [ 12312 => 'Dummy', diff --git a/tests/phpunit/includes/ExportTest.php b/tests/phpunit/includes/ExportTest.php index a5d357066b..af10b9c4a6 100644 --- a/tests/phpunit/includes/ExportTest.php +++ b/tests/phpunit/includes/ExportTest.php @@ -1,5 +1,7 @@ getNamespaces(); + $actualNamespaces = (array)MediaWikiServices::getInstance()->getContentLanguage()-> + getNamespaces(); $actualNamespaces = array_values( $actualNamespaces ); $this->assertEquals( $actualNamespaces, $xmlNamespaces ); diff --git a/tests/phpunit/includes/Storage/DerivedPageDataUpdaterTest.php b/tests/phpunit/includes/Storage/DerivedPageDataUpdaterTest.php index 3a1f078c31..c7f83dedbf 100644 --- a/tests/phpunit/includes/Storage/DerivedPageDataUpdaterTest.php +++ b/tests/phpunit/includes/Storage/DerivedPageDataUpdaterTest.php @@ -94,8 +94,6 @@ class DerivedPageDataUpdaterTest extends MediaWikiTestCase { * @covers \MediaWiki\Storage\DerivedPageDataUpdater::getCanonicalParserOptions() */ public function testGetCanonicalParserOptions() { - global $wgContLang; - $user = $this->getTestUser()->getUser(); $page = $this->getPage( __METHOD__ ); @@ -109,7 +107,8 @@ class DerivedPageDataUpdaterTest extends MediaWikiTestCase { $updater->prepareContent( $user, $update, false ); $options1 = $updater->getCanonicalParserOptions(); - $this->assertSame( $wgContLang, $options1->getUserLangObj() ); + $this->assertSame( MediaWikiServices::getInstance()->getContentLanguage(), + $options1->getUserLangObj() ); $speculativeId = call_user_func( $options1->getSpeculativeRevIdCallback(), $page->getTitle() ); $this->assertSame( $parentRev->getId() + 1, $speculativeId ); diff --git a/tests/phpunit/includes/TimeAdjustTest.php b/tests/phpunit/includes/TimeAdjustTest.php index 93aef34b13..b59282dd79 100644 --- a/tests/phpunit/includes/TimeAdjustTest.php +++ b/tests/phpunit/includes/TimeAdjustTest.php @@ -1,5 +1,7 @@ setMwGlobals( 'wgLocalTZoffset', $localTZoffset ); $this->assertEquals( $expected, - strval( $wgContLang->userAdjust( $date, '' ) ), + strval( MediaWikiServices::getInstance()->getContentLanguage()-> + userAdjust( $date, '' ) ), "User adjust {$date} by {$localTZoffset} minutes should give {$expected}" ); } diff --git a/tests/phpunit/includes/TitlePermissionTest.php b/tests/phpunit/includes/TitlePermissionTest.php index 6600aa23c7..f1f6f5f502 100644 --- a/tests/phpunit/includes/TitlePermissionTest.php +++ b/tests/phpunit/includes/TitlePermissionTest.php @@ -1,5 +1,7 @@ getFormattedNsText( NS_PROJECT ); + $prefix = MediaWikiServices::getInstance()->getContentLanguage()-> + getFormattedNsText( NS_PROJECT ); $this->setUser( 'anon' ); $this->setTitle( NS_TALK ); @@ -643,9 +645,8 @@ class TitlePermissionTest extends MediaWikiLangTestCase { * @covers Title::checkPageRestrictions */ public function testPageRestrictions() { - global $wgContLang; - - $prefix = $wgContLang->getFormattedNsText( NS_PROJECT ); + $prefix = MediaWikiServices::getInstance()->getContentLanguage()-> + getFormattedNsText( NS_PROJECT ); $this->setTitle( NS_MAIN ); $this->title->mRestrictionsLoaded = true; diff --git a/tests/phpunit/includes/TitleTest.php b/tests/phpunit/includes/TitleTest.php index f9ffeae924..d585240d52 100644 --- a/tests/phpunit/includes/TitleTest.php +++ b/tests/phpunit/includes/TitleTest.php @@ -449,7 +449,7 @@ class TitleTest extends MediaWikiTestCase { # Format: # - expected # - Title name - # - wgContLang (expected in most case) + # - content language (expected in most cases) # - wgLang (on some specific pages) # - wgDefaultLanguageVariant # - Optional message diff --git a/tests/phpunit/includes/cache/MessageCacheTest.php b/tests/phpunit/includes/cache/MessageCacheTest.php index b03eeba295..1edb9354ff 100644 --- a/tests/phpunit/includes/cache/MessageCacheTest.php +++ b/tests/phpunit/includes/cache/MessageCacheTest.php @@ -1,5 +1,7 @@ configureLanguages(); + MessageCache::destroyInstance(); MessageCache::singleton()->enable(); } @@ -57,12 +60,10 @@ class MessageCacheTest extends MediaWikiLangTestCase { * @param string|null $content Content of the created page, or null for a generic string */ protected function makePage( $title, $lang, $content = null ) { - global $wgContLang; - if ( $content === null ) { $content = $lang; } - if ( $lang !== $wgContLang->getCode() ) { + if ( $lang !== MediaWikiServices::getInstance()->getContentLanguage()->getCode() ) { $title = "$title/$lang"; } @@ -100,11 +101,9 @@ class MessageCacheTest extends MediaWikiLangTestCase { } public function testReplaceMsg() { - global $wgContLang; - $messageCache = MessageCache::singleton(); $message = 'go'; - $uckey = $wgContLang->ucfirst( $message ); + $uckey = MediaWikiServices::getInstance()->getContentLanguage()->ucfirst( $message ); $oldText = $messageCache->get( $message ); // "Ausführen" $dbw = wfGetDB( DB_MASTER ); diff --git a/tests/phpunit/includes/content/TextContentTest.php b/tests/phpunit/includes/content/TextContentTest.php index 406bc96b95..b01a7db04a 100644 --- a/tests/phpunit/includes/content/TextContentTest.php +++ b/tests/phpunit/includes/content/TextContentTest.php @@ -1,5 +1,7 @@ context->getUser(), $wgContLang ); + $options = ParserOptions::newFromUserAndLang( $this->context->getUser(), + MediaWikiServices::getInstance()->getContentLanguage() ); $content = $this->newContent( $text ); $content = $content->preSaveTransform( @@ -143,8 +144,8 @@ class TextContentTest extends MediaWikiLangTestCase { * @covers TextContent::preloadTransform */ public function testPreloadTransform( $text, $expected ) { - global $wgContLang; - $options = ParserOptions::newFromUserAndLang( $this->context->getUser(), $wgContLang ); + $options = ParserOptions::newFromUserAndLang( $this->context->getUser(), + MediaWikiServices::getInstance()->getContentLanguage() ); $content = $this->newContent( $text ); $content = $content->preloadTransform( $this->context->getTitle(), $options ); diff --git a/tests/phpunit/includes/content/WikitextContentHandlerTest.php b/tests/phpunit/includes/content/WikitextContentHandlerTest.php index 4bb1ed2501..b4b2948ba8 100644 --- a/tests/phpunit/includes/content/WikitextContentHandlerTest.php +++ b/tests/phpunit/includes/content/WikitextContentHandlerTest.php @@ -80,8 +80,7 @@ class WikitextContentHandlerTest extends MediaWikiLangTestCase { * @covers WikitextContentHandler::makeRedirectContent */ public function testMakeRedirectContent( $title, $expected ) { - global $wgContLang; - $wgContLang->resetNamespaces(); + MediaWikiServices::getInstance()->getContentLanguage()->resetNamespaces(); MediaWikiServices::getInstance()->resetServiceForTesting( 'MagicWordFactory' ); diff --git a/tests/phpunit/includes/parser/ParserOptionsTest.php b/tests/phpunit/includes/parser/ParserOptionsTest.php index 29f1c8c598..8c17780fe5 100644 --- a/tests/phpunit/includes/parser/ParserOptionsTest.php +++ b/tests/phpunit/includes/parser/ParserOptionsTest.php @@ -45,9 +45,9 @@ class ParserOptionsTest extends MediaWikiTestCase { public function testNewCanonical() { $wgUser = $this->getMutableTestUser()->getUser(); $wgLang = Language::factory( 'fr' ); - $wgContLang = Language::factory( 'qqx' ); + $contLang = Language::factory( 'qqx' ); - $this->setContentLang( $wgContLang ); + $this->setContentLang( $contLang ); $this->setMwGlobals( [ 'wgUser' => $wgUser, 'wgLang' => $wgLang, @@ -80,13 +80,12 @@ class ParserOptionsTest extends MediaWikiTestCase { $this->assertSame( $user, $popt->getUser() ); $this->assertSame( $lang, $popt->getUserLangObj() ); - // Passing 'canonical' uses an anon and $wgContLang, and ignores - // any passed $userLang + // Passing 'canonical' uses an anon and $contLang, and ignores any passed $userLang $popt = ParserOptions::newCanonical( 'canonical' ); $this->assertTrue( $popt->getUser()->isAnon() ); - $this->assertSame( $wgContLang, $popt->getUserLangObj() ); + $this->assertSame( $contLang, $popt->getUserLangObj() ); $popt = ParserOptions::newCanonical( 'canonical', $lang2 ); - $this->assertSame( $wgContLang, $popt->getUserLangObj() ); + $this->assertSame( $contLang, $popt->getUserLangObj() ); // Passing an IContextSource uses the user and lang from it, and ignores // any passed $userLang diff --git a/tests/phpunit/includes/parser/ParserPreloadTest.php b/tests/phpunit/includes/parser/ParserPreloadTest.php index 77073955bd..560b921a8d 100644 --- a/tests/phpunit/includes/parser/ParserPreloadTest.php +++ b/tests/phpunit/includes/parser/ParserPreloadTest.php @@ -1,4 +1,7 @@ testParserOptions = ParserOptions::newFromUserAndLang( new User, $wgContLang ); + $this->testParserOptions = ParserOptions::newFromUserAndLang( new User, + MediaWikiServices::getInstance()->getContentLanguage() ); $this->testParser = new Parser(); $this->testParser->Options( $this->testParserOptions ); diff --git a/tests/phpunit/includes/parser/PreprocessorTest.php b/tests/phpunit/includes/parser/PreprocessorTest.php index c415b58642..6b3e05da51 100644 --- a/tests/phpunit/includes/parser/PreprocessorTest.php +++ b/tests/phpunit/includes/parser/PreprocessorTest.php @@ -1,5 +1,7 @@ mOptions = ParserOptions::newFromUserAndLang( new User, $wgContLang ); + $this->mOptions = ParserOptions::newFromUserAndLang( new User, + MediaWikiServices::getInstance()->getContentLanguage() ); $this->mPreprocessors = []; foreach ( self::$classNames as $className ) { diff --git a/tests/phpunit/includes/parser/TagHooksTest.php b/tests/phpunit/includes/parser/TagHooksTest.php index 48312d98f9..06da7a53f7 100644 --- a/tests/phpunit/includes/parser/TagHooksTest.php +++ b/tests/phpunit/includes/parser/TagHooksTest.php @@ -47,8 +47,8 @@ class TagHooksTest extends MediaWikiTestCase { } private function getParserOptions() { - global $wgContLang; - $popt = ParserOptions::newFromUserAndLang( new User, $wgContLang ); + $popt = ParserOptions::newFromUserAndLang( new User, + MediaWikiServices::getInstance()->getContentLanguage() ); return $popt; } diff --git a/tests/phpunit/includes/specialpage/SpecialPageFactoryTest.php b/tests/phpunit/includes/specialpage/SpecialPageFactoryTest.php index 784fed0c5e..1da6fb36a7 100644 --- a/tests/phpunit/includes/specialpage/SpecialPageFactoryTest.php +++ b/tests/phpunit/includes/specialpage/SpecialPageFactoryTest.php @@ -1,4 +1,6 @@ getContentLanguage(); $lang->mExtendedSpecialPageAliases = $aliasesList; $this->setContentLang( $lang ); $this->setMwGlobals( 'wgSpecialPages', diff --git a/tests/phpunit/languages/LanguageConverterTest.php b/tests/phpunit/languages/LanguageConverterTest.php index c97bdaf278..8ccacfc23a 100644 --- a/tests/phpunit/languages/LanguageConverterTest.php +++ b/tests/phpunit/languages/LanguageConverterTest.php @@ -103,9 +103,9 @@ class LanguageConverterTest extends MediaWikiLangTestCase { * @covers LanguageConverter::getUserVariant */ public function testGetPreferredVariantUserOptionForForeignLanguage() { - global $wgContLang, $wgUser; + global $wgUser; - $wgContLang = Language::factory( 'en' ); + $this->setContentLang( 'en' ); $wgUser = new User; $wgUser->load(); // from 'defaults' $wgUser->mId = 1; @@ -122,9 +122,9 @@ class LanguageConverterTest extends MediaWikiLangTestCase { * @covers LanguageConverter::getURLVariant */ public function testGetPreferredVariantHeaderUserVsUrl() { - global $wgContLang, $wgRequest, $wgUser; + global $wgRequest, $wgUser; - $wgContLang = Language::factory( 'tg-latn' ); + $this->setContentLang( 'tg-latn' ); $wgRequest->setVal( 'variant', 'tg' ); $wgUser = User::newFromId( "admin" ); $wgUser->setId( 1 ); @@ -150,9 +150,9 @@ class LanguageConverterTest extends MediaWikiLangTestCase { * @covers LanguageConverter::getURLVariant */ public function testGetPreferredVariantDefaultLanguageVsUrlVariant() { - global $wgDefaultLanguageVariant, $wgRequest, $wgContLang; + global $wgDefaultLanguageVariant, $wgRequest; - $wgContLang = Language::factory( 'tg-latn' ); + $this->setContentLang( 'tg-latn' ); $wgDefaultLanguageVariant = 'tg'; $wgRequest->setVal( 'variant', null ); $this->assertEquals( 'tg', $this->lc->getPreferredVariant() ); diff --git a/tests/phpunit/maintenance/backup_LogTest.php b/tests/phpunit/maintenance/backup_LogTest.php index c215b9973d..9357451481 100644 --- a/tests/phpunit/maintenance/backup_LogTest.php +++ b/tests/phpunit/maintenance/backup_LogTest.php @@ -2,6 +2,7 @@ namespace MediaWiki\Tests\Maintenance; +use MediaWiki\MediaWikiServices; use DumpBackup; use ManualLogEntry; use Title; @@ -145,8 +146,6 @@ class BackupDumperLoggerTest extends DumpTestCase { } function testPlain() { - global $wgContLang; - // Preparing the dump $fname = $this->getNewTempFile(); @@ -165,8 +164,9 @@ class BackupDumperLoggerTest extends DumpTestCase { $this->assertLogItem( $this->logId1, "BackupDumperLogUserA", $this->userId1, null, "type", "subtype", "PageA" ); - $this->assertNotNull( $wgContLang, "Content language object validation" ); - $namespace = $wgContLang->getNsText( NS_TALK ); + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); + $this->assertNotNull( $contLang, "Content language object validation" ); + $namespace = $contLang->getNsText( NS_TALK ); $this->assertInternalType( 'string', $namespace ); $this->assertGreaterThan( 0, strlen( $namespace ) ); $this->assertLogItem( $this->logId2, "BackupDumperLogUserB", @@ -181,8 +181,6 @@ class BackupDumperLoggerTest extends DumpTestCase { } function testXmlDumpsBackupUseCaseLogging() { - global $wgContLang; - $this->checkHasGzip(); // Preparing the dump @@ -218,8 +216,9 @@ class BackupDumperLoggerTest extends DumpTestCase { $this->assertLogItem( $this->logId1, "BackupDumperLogUserA", $this->userId1, null, "type", "subtype", "PageA" ); - $this->assertNotNull( $wgContLang, "Content language object validation" ); - $namespace = $wgContLang->getNsText( NS_TALK ); + $contLang = MediaWikiServices::getInstance()->getContentLanguage(); + $this->assertNotNull( $contLang, "Content language object validation" ); + $namespace = $contLang->getNsText( NS_TALK ); $this->assertInternalType( 'string', $namespace ); $this->assertGreaterThan( 0, strlen( $namespace ) ); $this->assertLogItem( $this->logId2, "BackupDumperLogUserB", -- 2.20.1