Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 84
0.00% covered (danger)
0.00%
0 / 8
CRAP
0.00% covered (danger)
0.00%
0 / 1
LanguageBabelBox
0.00% covered (danger)
0.00%
0 / 84
0.00% covered (danger)
0.00%
0 / 8
756
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getConfig
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 render
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
6
 getText
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
6
 addCategories
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
42
 addCategory
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
42
 getCategoryName
0.00% covered (danger)
0.00%
0 / 20
0.00% covered (danger)
0.00%
0 / 1
56
 getCategoryLink
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
1<?php
2/**
3 * Contains code for language boxes.
4 *
5 * @file
6 * @author Robert Leverington
7 * @author Robin Pepermans
8 * @author Niklas Laxström
9 * @author Brian Wolff
10 * @author Purodha Blissenbach
11 * @author Sam Reed
12 * @author Siebrand Mazeland
13 * @license GPL-2.0-or-later
14 */
15
16declare( strict_types = 1 );
17
18namespace MediaWiki\Babel\BabelBox;
19
20use MediaWiki\Babel\BabelAutoCreate;
21use MediaWiki\Babel\BabelLanguageCodes;
22use MediaWiki\Babel\BabelServices;
23use MediaWiki\Config\Config;
24use MediaWiki\Language\Language;
25use MediaWiki\Language\LanguageCode;
26use MediaWiki\MediaWikiServices;
27use MediaWiki\Page\PageReference;
28use MediaWiki\Parser\ParserOutput;
29use MediaWiki\Title\Title;
30
31/**
32 * Class for babel language boxes.
33 */
34class LanguageBabelBox implements BabelBox {
35
36    private readonly string $code;
37
38    /**
39     * Construct a babel box for the given language and level.
40     *
41     * @param Config $config
42     * @param PageReference $page
43     * @param Language $targetLanguage Target language of the parse.
44     * @param string $code Language code to use.
45     *   This is a mediawiki-internal code (not necessarily a valid BCP-47 code)
46     * @param string $level Level of ability to use.
47     */
48    public function __construct(
49        private readonly Config $config,
50        private readonly PageReference $page,
51        private readonly Language $targetLanguage,
52        string $code,
53        private readonly string $level,
54    ) {
55        $this->code = BabelLanguageCodes::getCode( $code ) ?? $code;
56    }
57
58    /**
59     * Get a Config instance to use
60     *
61     * @todo Use proper Dependency Injection.
62     * @return Config
63     */
64    private static function getConfig(): Config {
65        return BabelServices::wrap( MediaWikiServices::getInstance() )->getConfig();
66    }
67
68    /**
69     * Return the babel box code.
70     *
71     * @return string A babel box for the given language and level.
72     */
73    public function render(): string {
74        $code = $this->code;
75        $catCode = BabelLanguageCodes::getCategoryCode( $code );
76        $bcp47 = LanguageCode::bcp47( $code );
77
78        $portal = wfMessage( 'babel-portal', $catCode )->inContentLanguage()->text();
79        if ( $portal !== '' ) {
80            $portal = "[[$portal|$catCode]]";
81        } else {
82            $portal = $catCode;
83        }
84        $header = "$portal<span class=\"mw-babel-box-level-{$this->level}\">-{$this->level}</span>";
85
86        $name = BabelLanguageCodes::getName( $code );
87        $text = self::getText( $this->page, $name, $code, $this->level );
88
89        $dir_current = MediaWikiServices::getInstance()->getLanguageFactory()->getLanguage( $code )->getDir();
90
91        $dir_head = $this->targetLanguage->getDir();
92
93        return <<<EOT
94<div class="mw-babel-box mw-babel-box-{$this->level} mw-babel-box-{$catCode}" dir="$dir_head">
95{|
96! dir="$dir_head" | $header
97| dir="$dir_current" lang="$bcp47" | $text
98|}
99</div>
100EOT;
101    }
102
103    /**
104     * Get the text to display in the language box for specific language and
105     * level. If MediaWiki:Babel-<level>-n (the message that includes the
106     * language autonym) is translated into the given language, use that
107     * otherwise use MediaWiki:Babel-<level> (the message that takes the
108     * language name as a parameter)
109     *
110     * @param PageReference $page
111     * @param string $name
112     * @param string $code Mediawiki-internal language code of language to use.
113     * @param string $level Level to use.
114     * @return string Text for display, in wikitext format.
115     */
116    private static function getText(
117        PageReference $page,
118        string $name,
119        string $code,
120        string $level
121    ): string {
122        $categoryLevel = self::getCategoryLink( $page, $level, $code );
123        $categoryMain = self::getCategoryLink( $page, null, $code );
124
125        // Give grep a chance to find the usages:
126        // babel-0-n, babel-1-n, babel-2-n, babel-3-n, babel-4-n, babel-5-n, babel-N-n
127        $text = wfMessage( "babel-$level-n",
128            $categoryLevel, $categoryMain, '', $page->getDBkey()
129        )->inLanguage( $code )->text();
130
131        $fallbackLanguage = MediaWikiServices::getInstance()->getLanguageFallback()->getFirst( $code );
132        // Because of T75473, the above wfMessage call will ignore any
133        // MediaWiki namespace overrides for fallback languages. Hence, we
134        // must explicitly ignore them here, or else the comparison will fail,
135        // resulting in a message claiming that the user knows the fallback
136        // language (probably English), rather than the language
137        // they actually specified.
138        $fallback = wfMessage( "babel-$level-n",
139            $categoryLevel, $categoryMain, '', $page->getDBkey()
140        )->useDatabase( false )->inLanguage( $fallbackLanguage ?? $code )->text();
141
142        // Give grep a chance to find the usages:
143        // babel-0, babel-1, babel-2, babel-3, babel-4, babel-5, babel-N
144        if ( $text == $fallback ) {
145            $text = wfMessage( "babel-$level",
146                $categoryLevel, $categoryMain, $name, $page->getDBkey()
147            )->inLanguage( $code )->text();
148        }
149
150        return $text;
151    }
152
153    /**
154     * Add appropriate categories for the language box to the given parser output
155     *
156     * @param ParserOutput $parserOutput Output to add categories to
157     */
158    public function addCategories( ParserOutput $parserOutput ): void {
159        $namespaces = $this->config->get( 'BabelCategorizeNamespaces' );
160        if (
161            $namespaces !== null &&
162            !Title::newFromPageReference( $this->page )->inNamespaces( $namespaces )
163        ) {
164            return;
165        }
166
167        $footerPage = Title::newFromText( wfMessage( 'babel-footer-url' )->inContentLanguage()->text() );
168        if ( $footerPage != null && $footerPage->inNamespace( NS_CATEGORY ) ) {
169            $footerCategory = $footerPage->getDBkey();
170        } else {
171            $footerCategory = null;
172        }
173        # Add main category
174        if ( $this->level !== '0' ) {
175            $mainCategory = $this->addCategory( $parserOutput, $this->code, null, $this->level, $footerCategory );
176        } else {
177            $mainCategory = null;
178        }
179
180        # Add level category
181        $this->addCategory( $parserOutput, $this->code, $this->level, false, $mainCategory );
182    }
183
184    /**
185     * Adds one category to the given ParserOutput, and arranges for its creation if it doesn't exist.
186     *
187     * @param ParserOutput $parserOutput Parser output to use
188     * @param string $code Code of language that the category is for.
189     * @param string|null $level Level that the category is for.
190     * @param string|bool $sortkey The sortkey to use for the category, or false to use the default sort
191     * @param string|null $parent An eventual parent category to add to the newly-created category if one is created.
192     * @return string|null The name of the category that was eventually added
193     */
194    private function addCategory( ParserOutput $parserOutput,
195        string $code, ?string $level, $sortkey, ?string $parent
196    ): ?string {
197        $isOverridden = false;
198        $category = self::getCategoryName( $level, $code, $isOverridden );
199        if ( $category === null ) {
200            return null;
201        }
202        if ( $sortkey === false ) {
203            $sortkey = $parserOutput->getPageProperty( 'defaultsort' );
204        }
205        $parserOutput->addCategory( $category, $sortkey ?? '' );
206
207        if ( $this->config->get( 'BabelAutoCreate' ) ) {
208            // Now arrange for autocreation (in LinksUpdate hook) unless the category was overridden locally
209            // (to reduce the risk if a compromised admin edits MediaWiki:Babel-category-override)
210            $title = Title::makeTitleSafe( NS_CATEGORY, $category );
211            $text = BabelAutoCreate::getCategoryText( $code, $level, $parent );
212            if ( !$isOverridden && !$title->exists() ) {
213                $parserOutput->appendExtensionData( "babel-tocreate", $category );
214                $parserOutput->setExtensionData( "babel-category-text-$category", $text );
215            }
216        }
217        return $category;
218    }
219
220    /**
221     * Replace the placeholder variables from the category names configuration
222     * array with actual values.
223     *
224     * @param ?string $level Level of babel category in question, or null for the main category
225     * @param string $code Mediawiki-internal language code of category.
226     * @param bool &$isOverridden Output parameter. Set to true if the category is overridden on-wiki
227     * so that the caller knows not to create categories.
228     * @return string|null Category name with variables replaced and possibly
229     * overridden by the wiki, or null if no category is desired.
230     */
231    private static function getCategoryName( ?string $level, string $code, bool &$isOverridden ): ?string {
232        global $wgLanguageCode;
233
234        $categoryDef = $level !== null ? self::getConfig()->get( 'BabelCategoryNames' )[$level] :
235            self::getConfig()->get( 'BabelMainCategory' );
236        if ( $categoryDef === false || $categoryDef === '' ) {
237            return null;
238        }
239
240        $category = strtr( $categoryDef, [
241            '%code%' => BabelLanguageCodes::getCategoryCode( $code ),
242            '%wikiname%' => BabelLanguageCodes::getName( $code, $wgLanguageCode ),
243            '%nativename%' => BabelLanguageCodes::getName( $code )
244        ] );
245
246        $oldCategory = $category;
247
248        // Chance to locally override categorization
249        if ( self::getConfig()->get( 'BabelAllowOverride' ) ) {
250            $category = wfMessage( "babel-category-override",
251                $category, $code, $level ?? ''
252            )->inContentLanguage()->text();
253            if ( $category !== $oldCategory ) {
254                $isOverridden = true;
255            }
256        }
257
258        // Normalize using Title
259        $title = Title::makeTitleSafe( NS_CATEGORY, $category );
260        if ( !$title ) {
261            // babel-category-override returned an invalid page name
262            return null;
263        }
264
265        return $title->getDBkey();
266    }
267
268    /**
269     * Returns the right link target for a category (either the category itself or the
270     * title given to get a self-link)
271     * @param PageReference $page The page to point the self-link to
272     * @param ?string $level Level of babel category in question, or null for the main category
273     * @param string $code Mediawiki-internal language code of category.
274     * @return string Link target to use for the given category
275     */
276    private static function getCategoryLink( PageReference $page, ?string $level, string $code ): string {
277        $isOverridden = false;
278        $category = self::getCategoryName( $level, $code, $isOverridden );
279        if ( $category !== null ) {
280            return ":Category:" . $category;
281        }
282        return ":" . MediaWikiServices::getInstance()->getTitleFormatter()->getPrefixedText( $page );
283    }
284}