Translate extension for MediaWiki
 
Loading...
Searching...
No Matches
ActiveLanguagesSpecialPage.php
1<?php
2declare( strict_types = 1 );
3
4namespace MediaWiki\Extension\Translate\Statistics;
5
6use Config;
7use Html;
8use HtmlArmor;
9use InvalidArgumentException;
10use Language;
11use LanguageCode;
12use LinkBatch;
13use MediaWiki\Config\ServiceOptions;
15use MediaWiki\Languages\LanguageNameUtils;
16use MediaWiki\Logger\LoggerFactory;
17use ObjectCache;
18use SpecialPage;
19use Title;
20use Wikimedia\Rdbms\ILoadBalancer;
21
30class ActiveLanguagesSpecialPage extends SpecialPage {
32 private $options;
34 private $translatorActivity;
36 private $langNameUtils;
38 private $loadBalancer;
40 private $configHelper;
42 private $contentLanguage;
44 private $progressStatsTableFactory;
46 private $progressStatsTable;
48 private $period = 180;
49
50 public const CONSTRUCTOR_OPTIONS = [
51 'TranslateMessageNamespaces',
52 ];
53
54 public function __construct(
55 Config $config,
56 TranslatorActivity $translatorActivity,
57 LanguageNameUtils $langNameUtils,
58 ILoadBalancer $loadBalancer,
59 ConfigHelper $configHelper,
60 Language $contentLanguage,
61 ProgressStatsTableFactory $progressStatsTableFactory
62 ) {
63 parent::__construct( 'SupportedLanguages' );
64 $this->options = new ServiceOptions( self::CONSTRUCTOR_OPTIONS, $config );
65 $this->translatorActivity = $translatorActivity;
66 $this->langNameUtils = $langNameUtils;
67 $this->loadBalancer = $loadBalancer;
68 $this->configHelper = $configHelper;
69 $this->contentLanguage = $contentLanguage;
70 $this->progressStatsTableFactory = $progressStatsTableFactory;
71 }
72
73 protected function getGroupName() {
74 return 'translation';
75 }
76
77 public function getDescription() {
78 return $this->msg( 'supportedlanguages' )->text();
79 }
80
81 public function execute( $par ) {
82 $out = $this->getOutput();
83 $lang = $this->getLanguage();
84 $this->progressStatsTable = $this->progressStatsTableFactory->newFromContext( $this->getContext() );
85
86 $this->setHeaders();
87 $out->addModuleStyles( 'ext.translate.specialpages.styles' );
88
89 $out->addHelpLink(
90 'Help:Extension:Translate/Statistics_and_reporting#List_of_languages_and_translators'
91 );
92
93 $this->outputHeader( 'supportedlanguages-summary' );
94 $dbr = $this->loadBalancer->getConnectionRef( DB_REPLICA );
95 $dbType = $dbr->getType();
96 if ( $dbType === 'sqlite' || $dbType === 'postgres' ) {
97 $out->addHTML(
98 Html::errorBox(
99 // Messages used: supportedlanguages-sqlite-error, supportedlanguages-postgres-error
100 $out->msg( 'supportedlanguages-' . $dbType . '-error' )->parse()
101 )
102 );
103 return;
104 }
105
106 $out->addWikiMsg( 'supportedlanguages-localsummary' );
107
108 $names = $this->langNameUtils->getLanguageNames( null, 'all' );
109 $languages = $this->languageCloud();
110 // There might be all sorts of subpages which are not languages
111 $languages = array_intersect_key( $languages, $names );
112
113 $this->outputLanguageCloud( $languages, $names );
114 $out->addWikiMsg( 'supportedlanguages-count', $lang->formatNum( count( $languages ) ) );
115
116 if ( !$par ) {
117 return;
118 }
119
120 // Convert formatted language tag like zh-Hant to internal format like zh-hant
121 $language = strtolower( $par );
122 try {
123 $data = $this->translatorActivity->inLanguage( $language );
124 } catch ( StatisticsUnavailable $e ) {
125 // generic-pool-error is from MW core
126 $out->addHTML( Html::errorBox( $this->msg( 'generic-pool-error' )->parse() ) );
127 return;
128 } catch ( InvalidArgumentException $e ) {
129 $errorMessageHtml = $this->msg( 'translate-activelanguages-invalid-code' )
130 ->params( LanguageCode::bcp47( $language ) )
131 ->parse();
132 $out->addHTML( Html::errorBox( $errorMessageHtml ) );
133 return;
134 }
135
136 $users = $data['users'];
137 $users = $this->filterUsers( $users, $language );
138 $this->preQueryUsers( $users );
139 $this->showLanguage( $language, $users, (int)$data['asOfTime'] );
140 }
141
142 private function showLanguage( string $code, array $users, int $cachedAt ): void {
143 $out = $this->getOutput();
144 $lang = $this->getLanguage();
145 $bcp47Code = LanguageCode::bcp47( $code );
146
147 // Information to be used inside the foreach loop.
148 $linkInfo = [];
149 $linkInfo['rc']['title'] = SpecialPage::getTitleFor( 'Recentchanges' );
150 $linkInfo['rc']['msg'] = $this->msg( 'supportedlanguages-recenttranslations' )->text();
151 $linkInfo['stats']['title'] = SpecialPage::getTitleFor( 'LanguageStats' );
152 $linkInfo['stats']['msg'] = $this->msg( 'languagestats' )->text();
153
154 $local = $this->langNameUtils->getLanguageName( $code, $lang->getCode(), 'all' );
155 $native = $this->langNameUtils->getLanguageName( $code, null, 'all' );
156
157 if ( $local !== $native ) {
158
159 $headerText = $this->msg( 'supportedlanguages-portallink' )
160 ->params( $bcp47Code, $local, $native )->escaped();
161 } else {
162 // No CLDR, so a less localised header and link title.
163 $headerText = $this->msg( 'supportedlanguages-portallink-nocldr' )
164 ->params( $bcp47Code, $native )->escaped();
165 }
166
167 $out->addHTML( Html::rawElement( 'h2', [ 'id' => $code ], $headerText ) );
168
169 // Add useful links for language stats and recent changes for the language.
170 $links = [];
171 $links[] = $this->getLinkRenderer()->makeKnownLink(
172 $linkInfo['stats']['title'],
173 $linkInfo['stats']['msg'],
174 [],
175 [
176 'code' => $code,
177 'suppresscomplete' => '1'
178 ]
179 );
180 $links[] = $this->getLinkRenderer()->makeKnownLink(
181 $linkInfo['rc']['title'],
182 $linkInfo['rc']['msg'],
183 [],
184 [
185 'translations' => 'only',
186 'trailer' => '/' . $code
187 ]
188 );
189 $linkList = $lang->listToText( $links );
190
191 $out->addHTML( '<p>' . $linkList . "</p>\n" );
192 $this->makeUserList( $users );
193
194 $ageString = $this->getLanguage()->formatTimePeriod(
195 time() - $cachedAt,
196 [ 'noabbrevs' => true, 'avoid' => 'avoidseconds' ]
197 );
198 $out->addWikiMsg( 'supportedlanguages-colorlegend', $this->getColorLegend() );
199 $out->addWikiMsg( 'translate-supportedlanguages-cached', $ageString );
200 }
201
202 private function languageCloud(): array {
203 // TODO: Inject a factory when such a thing is available in MediaWiki core
204 $cache = ObjectCache::getInstance( CACHE_ANYTHING );
205 $cachekey = $cache->makeKey( 'translate-supportedlanguages-language-cloud', 'v2' );
206
207 $data = $cache->get( $cachekey );
208 if ( is_array( $data ) ) {
209 return $data;
210 }
211
212 $dbr = $this->loadBalancer->getConnectionRef( DB_REPLICA );
213 $tables = [ 'recentchanges' ];
214 $fields = [ 'substring_index(rc_title, \'/\', -1) as lang', 'count(*) as count' ];
215 $timestamp = $dbr->timestamp( wfTimestamp( TS_UNIX ) - 60 * 60 * 24 * $this->period );
216 $conds = [
217 'rc_timestamp > ' . $dbr->addQuotes( $timestamp ),
218 'rc_namespace' => $this->options->get( 'TranslateMessageNamespaces' ),
219 'rc_title' . $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() ),
220 ];
221 $options = [ 'GROUP BY' => 'lang', 'HAVING' => 'count > 20', 'ORDER BY' => 'NULL' ];
222
223 $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $options );
224
225 $data = [];
226 foreach ( $res as $row ) {
227 $data[$row->lang] = (int)$row->count;
228 }
229
230 $cache->set( $cachekey, $data, 3600 );
231
232 return $data;
233 }
234
235 protected function filterUsers( array $users, string $code ): array {
236 foreach ( $users as $index => $user ) {
237 $username = $user[TranslatorActivityQuery::USER_NAME];
238 // We do not know the group
239 if ( $this->configHelper->isAuthorExcluded( '#', $code, $username ) ) {
240 unset( $users[$index] );
241 }
242 }
243
244 return $users;
245 }
246
247 protected function outputLanguageCloud( array $languages, array $names ) {
248 global $wgTranslateDocumentationLanguageCode;
249
250 $out = $this->getOutput();
251
252 $out->addHTML( '<div class="tagcloud autonym">' );
253
254 foreach ( $languages as $k => $v ) {
255 $name = $names[$k];
256 $langAttribute = $k;
257 $size = round( log( $v ) * 20 ) + 10;
258
259 if ( $langAttribute === $wgTranslateDocumentationLanguageCode ) {
260 $langAttribute = $this->contentLanguage->getHtmlCode();
261 }
262
263 $params = [
264 'href' => $this->getPageTitle( $k )->getLocalURL(),
265 'class' => 'tag',
266 'style' => "font-size:$size%",
267 'lang' => $langAttribute,
268 ];
269
270 $tag = Html::element( 'a', $params, $name );
271 $out->addHTML( $tag . "\n" );
272 }
273 $out->addHTML( '</div>' );
274 }
275
276 private function makeUserList( array $userStats ): void {
277 $day = 60 * 60 * 24;
278
279 // Scale of the activity colors, anything
280 // longer than this is just inactive
281 $period = $this->period;
282
283 $links = [];
284 // List users in descending order by number of translations in this language
285 usort( $userStats, static function ( $a, $b ) {
286 return -(
287 $a[TranslatorActivityQuery::USER_TRANSLATIONS]
288 <=>
289 $b[TranslatorActivityQuery::USER_TRANSLATIONS]
290 );
291 } );
292
293 foreach ( $userStats as $stats ) {
294 $username = $stats[TranslatorActivityQuery::USER_NAME];
295 $title = Title::makeTitleSafe( NS_USER, $username );
296 if ( !$title ) {
297 LoggerFactory::getInstance( 'Translate' )->warning(
298 "T248125: Got Title-invalid username '{username}'",
299 [ 'username' => $username ]
300 );
301 continue;
302 }
303
304 $count = $stats[TranslatorActivityQuery::USER_TRANSLATIONS];
305 $lastTranslationTimestamp = $stats[TranslatorActivityQuery::USER_LAST_ACTIVITY];
306
307 $enc = htmlspecialchars( $username );
308
309 $attribs = [];
310 $styles = [];
311 $styles['font-size'] = round( log( $count, 10 ) * 30 ) + 70 . '%';
312
313 $last = wfTimestamp( TS_UNIX ) - wfTimestamp( TS_UNIX, $lastTranslationTimestamp );
314 $last = round( $last / $day );
315 $attribs['title'] =
316 $this->msg( 'supportedlanguages-activity', $username )
317 ->numParams( $count, $last )
318 ->text();
319 $last = max( 1, min( $period, $last ) );
320 $styles['border-bottom'] =
321 '3px solid #' . $this->progressStatsTable->getBackgroundColor( ( $period - $last ) / $period );
322
323 $stylestr = $this->formatStyle( $styles );
324 if ( $stylestr ) {
325 $attribs['style'] = $stylestr;
326 }
327
328 $links[] =
329 $this->getLinkRenderer()->makeLink( $title, new HtmlArmor( $enc ), $attribs );
330 }
331
332 // for GENDER support
333 $usernameForGender = '';
334 if ( count( $userStats ) === 1 ) {
335 $usernameForGender = $userStats[0][TranslatorActivityQuery::USER_NAME];
336 }
337
338 $linkList = $this->getLanguage()->listToText( $links );
339 $html = "<p class='mw-translate-spsl-translators'>";
340 $html .= $this->msg( 'supportedlanguages-translators' )
341 ->rawParams( $linkList )
342 ->numParams( count( $links ) )
343 ->params( $usernameForGender )
344 ->escaped();
345 $html .= "</p>\n";
346 $this->getOutput()->addHTML( $html );
347 }
348
349 protected function formatStyle( $styles ) {
350 $stylestr = '';
351 foreach ( $styles as $key => $value ) {
352 $stylestr .= "$key:$value;";
353 }
354
355 return $stylestr;
356 }
357
358 protected function preQueryUsers( array $users ): void {
359 $lb = new LinkBatch();
360 foreach ( $users as $data ) {
361 $username = $data[TranslatorActivityQuery::USER_NAME];
362 $user = Title::capitalize( $username, NS_USER );
363 $lb->add( NS_USER, $user );
364 $lb->add( NS_USER_TALK, $user );
365 }
366 $lb->execute();
367 }
368
369 protected function getColorLegend() {
370 $legend = '';
371 $period = $this->period;
372
373 for ( $i = 0; $i <= $period; $i += 30 ) {
374 $iFormatted = htmlspecialchars( $this->getLanguage()->formatNum( $i ) );
375 $legend .= '<span style="background-color:#' .
376 $this->progressStatsTable->getBackgroundColor( ( $period - $i ) / $period ) .
377 "\"> $iFormatted</span>";
378 }
379
380 return $legend;
381 }
382}
This special page shows active languages and active translators per language.
A helper class added to work with configuration values of the Translate Extension.