summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/UniversalLanguageSelector/resources/js/ext.uls.common.js
blob: 3b1a6e37a7a4270e75751cca75f89abb2384386b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
/*!
 * ULS startup script - MediaWiki specific customization for jquery.uls
 *
 * Copyright (C) 2012-2013 Alolita Sharma, Amir Aharoni, Arun Ganesh, Brandon Harris,
 * Niklas Laxström, Pau Giner, Santhosh Thottingal, Siebrand Mazeland and other
 * contributors. See CREDITS for a list.
 *
 * UniversalLanguageSelector is dual licensed GPLv2 or later and MIT. You don't
 * have to do anything special to choose one license or the other and you don't
 * have to notify anyone which license you are using. You are free to use
 * UniversalLanguageSelector in commercial projects as long as the copyright
 * header is left intact. See files GPL-LICENSE and MIT-LICENSE for details.
 *
 * @file
 * @ingroup Extensions
 * @licence GNU General Public Licence 2.0 or later
 * @licence MIT License
 */

( function () {
	'use strict';

	/*
	 * The 'als' is used in a non-standard way in MediaWiki -
	 * it may be used to represent the Allemanic language,
	 * the standard code of which is 'gsw', while 'als'
	 * is ISO 639 3 refers to Tosk Albanian, which is
	 * not currently used in any way in MediaWiki.
	 * This local fix adds a redirect for it.
	 */
	$.uls.data.addLanguage( 'als', { target: 'gsw' } );

	mw.uls = mw.uls || {};
	mw.uls.previousLanguagesStorageKey = 'uls-previous-languages';
	mw.uls.languageSettingsModules = [ 'ext.uls.inputsettings', 'ext.uls.displaysettings' ];

	/**
	 * Change the language of wiki using API or set cookie and reload the page
	 *
	 * @param {string} language Language code.
	 */
	mw.uls.changeLanguage = function ( language ) {
		var deferred = new $.Deferred();

		function changeLanguageAnon() {
			if ( mw.config.get( 'wgULSAnonCanChangeLanguage' ) ) {
				mw.cookie.set( 'language', language );
				location.reload();
			}
		}

		deferred.done( function () {
			var api = new mw.Api();

			if ( mw.user.isAnon() ) {
				changeLanguageAnon();
				return;
			}

			// TODO We can avoid doing this query if we know global preferences are not enabled
			api.get( {
				action: 'query',
				meta: 'globalpreferences',
				gprprop: 'preferences'
			} ).then( function ( res ) {
				// Check whether global preferences are in use. If they are not, `res.query` is
				// an empty object. `res` will also contain warnings about unknown parameters.
				try {
					return !!res.query.globalpreferences.preferences.language;
				} catch ( e ) {
					return false;
				}
			} ).then( function ( hasGlobalPreference ) {
				var apiModule;

				if ( hasGlobalPreference ) {
					apiModule = 'globalpreferenceoverrides';
					mw.storage.set( 'uls-gp', '1' );
				} else {
					apiModule = 'options';
					mw.storage.remove( 'uls-gp' );
				}

				return api.postWithToken( 'csrf', {
					action: apiModule,
					optionname: 'language',
					optionvalue: language
				} );
			} ).done( function () {
				location.reload();
			} ).fail( function () {
				// Setting the option failed. Maybe the user has logged off.
				// Continue like anonymous user and set cookie.
				changeLanguageAnon();
			} );
		} );

		mw.hook( 'mw.uls.interface.language.change' ).fire( language, deferred );

		// Delay is zero if event logging is not enabled
		window.setTimeout( function () {
			deferred.resolve();
		}, mw.config.get( 'wgULSEventLogging' ) * 500 );

	};

	mw.uls.setPreviousLanguages = function ( previousLanguages ) {
		try {
			localStorage.setItem(
				mw.uls.previousLanguagesStorageKey,
				JSON.stringify( previousLanguages.slice( 0, 9 ) )
			);
		} catch ( e ) {}
	};

	mw.uls.getPreviousLanguages = function () {
		var previousLanguages = [];

		try {
			previousLanguages.push.apply(
				previousLanguages,
				JSON.parse( localStorage.getItem( mw.uls.previousLanguagesStorageKey ) )
			);
		} catch ( e ) {}

		return previousLanguages.slice( 0, 9 );
	};

	/**
	 * Add a selected language to the list of previously selected languages.
	 *
	 * @param {string} language Language code.
	 * @since 2016.05
	 */
	mw.uls.addPreviousLanguage = function ( language ) {
		var languages = mw.uls.getPreviousLanguages(),
			index = languages.indexOf( language );

		// Avoid duplicates
		if ( index !== -1 ) {
			languages.splice( index, 1 );
		}
		languages.unshift( language );

		mw.uls.setPreviousLanguages( languages );
	};

	/**
	 * Returns the browser's user interface language or the system language.
	 * The caller should check the validity of the returned language code.
	 *
	 * @return {string} Language code or empty string.
	 */
	mw.uls.getBrowserLanguage = function () {
		// language is the standard property.
		// userLanguage is only for IE and returns system locale.
		// Empty string is a fallback in case both are undefined
		// to avoid runtime error with split().
		return ( window.navigator.language || window.navigator.userLanguage || '' ).split( '-' )[ 0 ];
	};

	mw.uls.getCountryCode = function () {
		return window.Geo && ( window.Geo.country || window.Geo.country_code );
	};

	mw.uls.getAcceptLanguageList = function () {
		return mw.config.get( 'wgULSAcceptLanguageList' ) || window.navigator.languages || [];
	};

	/**
	 * Get a list of codes for languages to show in
	 * the "Common languages" section of the ULS.
	 * The list consists of the user's current selected language,
	 * the wiki's content language, the browser' UI language
	 * and Accept-Language, user's previous selected languages
	 * and finally, the languages of countryCode taken from the CLDR,
	 * taken by default from the user's geolocation.
	 *
	 * @param {string} [countryCode] Uppercase country code.
	 * @return {Array} List of language codes without duplicates.
	 */
	mw.uls.getFrequentLanguageList = function ( countryCode ) {
		var i, j, lang,
			ret = [],
			lists = [
				[
					mw.config.get( 'wgUserLanguage' ),
					mw.config.get( 'wgContentLanguage' ),
					mw.uls.getBrowserLanguage()
				],
				mw.uls.getPreviousLanguages(),
				mw.uls.getAcceptLanguageList()
			];

		countryCode = countryCode || mw.uls.getCountryCode();
		if ( countryCode ) {
			lists.push( $.uls.data.getLanguagesInTerritory( countryCode ) );
		}

		for ( i = 0; i < lists.length; i++ ) {
			for ( j = 0; j < lists[ i ].length; j++ ) {
				lang = lists[ i ][ j ];
				// Make flat, make unique, and ignore unknown/unsupported languages
				if ( ret.indexOf( lang ) === -1 && $.uls.data.getAutonym( lang ) !== lang ) {
					ret.push( lang );
				}
			}
		}

		return ret;
	};

}() );