Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
85.45% covered (warning)
85.45%
94 / 110
33.33% covered (danger)
33.33%
1 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
LanguageData
85.45% covered (warning)
85.45%
94 / 110
33.33% covered (danger)
33.33%
1 / 3
43.68
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getLocalData
96.83% covered (success)
96.83%
61 / 63
0.00% covered (danger)
0.00%
0 / 1
9
 convertDateFormat
69.57% covered (warning)
69.57%
32 / 46
0.00% covered (danger)
0.00%
0 / 1
52.71
1<?php
2/**
3 * Generates language-specific data used by DiscussionTools.
4 *
5 * @file
6 * @ingroup Extensions
7 * @license MIT
8 */
9
10namespace MediaWiki\Extension\DiscussionTools;
11
12use DateTimeZone;
13use MediaWiki\Config\Config;
14use MediaWiki\Language\ILanguageConverter;
15use MediaWiki\Language\Language;
16use MediaWiki\Language\LanguageConverterFactory;
17use MediaWiki\MainConfigNames;
18use MediaWiki\SpecialPage\SpecialPageFactory;
19
20class LanguageData {
21
22    public function __construct(
23        private readonly Config $config,
24        private readonly Language $language,
25        private readonly LanguageConverterFactory $languageConverterFactory,
26        private readonly SpecialPageFactory $specialPageFactory,
27    ) {
28    }
29
30    /**
31     * Compute data we need to parse discussion threads on pages.
32     */
33    public function getLocalData(): array {
34        $config = $this->config;
35        $lang = $this->language;
36        $langConv = $this->languageConverterFactory->getLanguageConverter( $lang );
37
38        $data = [];
39
40        $data['dateFormat'] = [];
41        $dateFormat = $lang->getDateFormatString( 'both', $lang->dateFormat( false ) );
42        foreach ( $langConv->getVariants() as $variant ) {
43            $convDateFormat = $this->convertDateFormat( $dateFormat, $langConv, $variant );
44            $data['dateFormat'][$variant] = $convDateFormat;
45        }
46
47        $data['digits'] = [];
48        foreach ( $langConv->getVariants() as $variant ) {
49            $data['digits'][$variant] = [];
50            foreach ( str_split( '0123456789' ) as $digit ) {
51                if ( $config->get( MainConfigNames::TranslateNumerals ) ) {
52                    $localDigit = $lang->formatNumNoSeparators( $digit );
53                } else {
54                    $localDigit = $digit;
55                }
56                $convLocalDigit = $langConv->translate( $localDigit, $variant );
57                $data['digits'][$variant][] = $convLocalDigit;
58            }
59        }
60
61        // ApiQuerySiteinfo
62        $data['localTimezone'] = $config->get( MainConfigNames::Localtimezone );
63
64        // special page names compared against Title::getText, which contains space
65        // But aliases are stored with underscores (db key) in the alias files
66        $data['specialContributionsName'] = str_replace( '_', ' ', $this->specialPageFactory
67            ->getLocalNameFor( 'Contributions' ) );
68        $data['specialNewSectionName'] = str_replace( '_', ' ', $this->specialPageFactory
69            ->getLocalNameFor( 'NewSection' ) );
70
71        $localTimezone = $config->get( MainConfigNames::Localtimezone );
72        // Return all timezone abbreviations for the local timezone (there will often be two, for
73        // non-DST and DST timestamps, and sometimes more due to historical data, but that's okay).
74        // Avoid DateTimeZone::listAbbreviations(), it returns some half-baked list that is different
75        // from the timezone data used by everything else in PHP.
76        $timezoneTransitions = ( new DateTimeZone( $localTimezone ) )->getTransitions();
77        if ( !is_array( $timezoneTransitions ) ) {
78            // Handle (arguably invalid) config where $wgLocaltimezone is an abbreviation like "CST"
79            // instead of a real IANA timezone name like "America/Chicago". (T312310)
80            // "DateTimeZone objects wrapping type 1 (UTC offsets) and type 2 (abbreviations) do not
81            // contain any transitions, and calling this method on them will return false."
82            // https://www.php.net/manual/en/datetimezone.gettransitions.php
83            $timezoneAbbrs = [ $localTimezone ];
84        } else {
85            $timezoneAbbrs = array_values( array_unique(
86                array_map( static function ( $transition ) {
87                    return $transition['abbr'];
88                }, $timezoneTransitions )
89            ) );
90        }
91
92        $data['timezones'] = [];
93        foreach ( $langConv->getVariants() as $variant ) {
94            $data['timezones'][$variant] = array_combine(
95                array_map( static function ( string $tzMsg ) use ( $lang, $langConv, $variant ) {
96                    // MWTimestamp::getTimezoneMessage()
97                    // Parser::pstPass2()
98                    // Messages used here: 'timezone-utc' and so on
99                    $key = 'timezone-' . strtolower( trim( $tzMsg ) );
100                    $msg = wfMessage( $key )->inLanguage( $lang );
101                    // TODO: This probably causes a similar issue to https://phabricator.wikimedia.org/T221294,
102                    // but we *must* check the message existence in the database, because the messages are not
103                    // actually defined by MediaWiki core for any timezone other than UTC...
104                    if ( $msg->exists() ) {
105                        $text = $msg->text();
106                    } else {
107                        $text = strtoupper( $tzMsg );
108                    }
109                    $convText = $langConv->translate( $text, $variant );
110                    return $convText;
111                }, $timezoneAbbrs ),
112                array_map( 'strtoupper', $timezoneAbbrs )
113            );
114        }
115
116        // Messages in content language
117        $messagesKeys = array_merge(
118            Language::WEEKDAY_MESSAGES,
119            Language::WEEKDAY_ABBREVIATED_MESSAGES,
120            Language::MONTH_MESSAGES,
121            Language::MONTH_GENITIVE_MESSAGES,
122            Language::MONTH_ABBREVIATED_MESSAGES
123        );
124        $data['contLangMessages'] = [];
125        foreach ( $langConv->getVariants() as $variant ) {
126            $data['contLangMessages'][$variant] = array_combine(
127                $messagesKeys,
128                array_map( static function ( $key ) use ( $lang, $langConv, $variant ) {
129                    $text = wfMessage( $key )->inLanguage( $lang )->text();
130                    return $langConv->translate( $text, $variant );
131                }, $messagesKeys )
132            );
133        }
134
135        return $data;
136    }
137
138    /**
139     * Convert a date format string to a different language variant, leaving all special characters
140     * unchanged and applying language conversion to the plain text fragments.
141     */
142    private function convertDateFormat(
143        string $format,
144        ILanguageConverter $langConv,
145        string $variant
146    ): string {
147        $formatLength = strlen( $format );
148        $s = '';
149        // The supported codes must match CommentParser::getTimestampRegexp()
150        for ( $p = 0; $p < $formatLength; $p++ ) {
151            $num = false;
152            $code = $format[ $p ];
153            if ( $code === 'x' && $p < $formatLength - 1 ) {
154                $code .= $format[++$p];
155            }
156            if ( $code === 'xk' && $p < $formatLength - 1 ) {
157                $code .= $format[++$p];
158            }
159
160            // LAZY SHORTCUTS that might cause bugs:
161            // * We assume that result of $langConv->translate() doesn't produce any special codes/characters
162            // * We assume that calling $langConv->translate() separately for each character is correct
163            switch ( $code ) {
164                case 'xx':
165                case 'xg':
166                case 'xn':
167                case 'd':
168                case 'D':
169                case 'j':
170                case 'l':
171                case 'F':
172                case 'M':
173                case 'm':
174                case 'n':
175                case 'Y':
176                case 'xkY':
177                case 'G':
178                case 'H':
179                case 'i':
180                case 's':
181                    // Special code - pass through unchanged
182                    $s .= $code;
183                    break;
184                case '\\':
185                    // Plain text (backslash escaping) - convert to language variant
186                    if ( $p < $formatLength - 1 ) {
187                        $s .= '\\' . $langConv->translate( $format[++$p], $variant );
188                    } else {
189                        $s .= $code;
190                    }
191                    break;
192                case '"':
193                    // Plain text (quoted literal) - convert to language variant
194                    if ( $p < $formatLength - 1 ) {
195                        $endQuote = strpos( $format, '"', $p + 1 );
196                        if ( $endQuote === false ) {
197                            // No terminating quote, assume literal "
198                            $s .= $code;
199                        } else {
200                            $s .= '"' .
201                                $langConv->translate( substr( $format, $p + 1, $endQuote - $p - 1 ), $variant ) .
202                                '"';
203                            $p = $endQuote;
204                        }
205                    } else {
206                        // Quote at end of string, assume literal "
207                        $s .= $code;
208                    }
209                    break;
210                default:
211                    // Plain text - convert to language variant
212                    $s .= $langConv->translate( $format[$p], $variant );
213            }
214        }
215
216        return $s;
217    }
218}