Merge "Mention translatewiki.net on edits only, when edit a default message"
[lhc/web/wiklou.git] / resources / src / mediawiki.api / mediawiki.api.js
1 ( function ( mw, $ ) {
2
3 // We allow people to omit these default parameters from API requests
4 // there is very customizable error handling here, on a per-call basis
5 // wondering, would it be simpler to make it easy to clone the api object,
6 // change error handling, and use that instead?
7 var defaultOptions = {
8
9 // Query parameters for API requests
10 parameters: {
11 action: 'query',
12 format: 'json'
13 },
14
15 // Ajax options for jQuery.ajax()
16 ajax: {
17 url: mw.util.wikiScript( 'api' ),
18
19 timeout: 30 * 1000, // 30 seconds
20
21 dataType: 'json'
22 }
23 },
24 // Keyed by ajax url and symbolic name for the individual request
25 promises = {};
26
27 // Pre-populate with fake ajax promises to save http requests for tokens
28 // we already have on the page via the user.tokens module (bug 34733).
29 promises[ defaultOptions.ajax.url ] = {};
30 $.each( mw.user.tokens.get(), function ( key, value ) {
31 // This requires #getToken to use the same key as user.tokens.
32 // Format: token-type + "Token" (eg. editToken, patrolToken, watchToken).
33 promises[ defaultOptions.ajax.url ][ key ] = $.Deferred()
34 .resolve( value )
35 .promise( { abort: function () {} } );
36 } );
37
38 /**
39 * Constructor to create an object to interact with the API of a particular MediaWiki server.
40 * mw.Api objects represent the API of a particular MediaWiki server.
41 *
42 * TODO: Share API objects with exact same config.
43 *
44 * var api = new mw.Api();
45 * api.get( {
46 * action: 'query',
47 * meta: 'userinfo'
48 * } ).done ( function ( data ) {
49 * console.log( data );
50 * } );
51 *
52 * @class
53 *
54 * @constructor
55 * @param {Object} options See defaultOptions documentation above. Ajax options can also be
56 * overridden for each individual request to {@link jQuery#ajax} later on.
57 */
58 mw.Api = function ( options ) {
59
60 if ( options === undefined ) {
61 options = {};
62 }
63
64 // Force a string if we got a mw.Uri object
65 if ( options.ajax && options.ajax.url !== undefined ) {
66 options.ajax.url = String( options.ajax.url );
67 }
68
69 options.parameters = $.extend( {}, defaultOptions.parameters, options.parameters );
70 options.ajax = $.extend( {}, defaultOptions.ajax, options.ajax );
71
72 this.defaults = options;
73 };
74
75 mw.Api.prototype = {
76
77 /**
78 * Perform API get request
79 *
80 * @param {Object} parameters
81 * @param {Object} [ajaxOptions]
82 * @return {jQuery.Promise}
83 */
84 get: function ( parameters, ajaxOptions ) {
85 ajaxOptions = ajaxOptions || {};
86 ajaxOptions.type = 'GET';
87 return this.ajax( parameters, ajaxOptions );
88 },
89
90 /**
91 * Perform API post request
92 *
93 * TODO: Post actions for non-local hostnames will need proxy.
94 *
95 * @param {Object} parameters
96 * @param {Object} [ajaxOptions]
97 * @return {jQuery.Promise}
98 */
99 post: function ( parameters, ajaxOptions ) {
100 ajaxOptions = ajaxOptions || {};
101 ajaxOptions.type = 'POST';
102 return this.ajax( parameters, ajaxOptions );
103 },
104
105 /**
106 * Perform the API call.
107 *
108 * @param {Object} parameters
109 * @param {Object} [ajaxOptions]
110 * @return {jQuery.Promise} Done: API response data and the jqXHR object.
111 * Fail: Error code
112 */
113 ajax: function ( parameters, ajaxOptions ) {
114 var token,
115 apiDeferred = $.Deferred(),
116 xhr, key, formData;
117
118 parameters = $.extend( {}, this.defaults.parameters, parameters );
119 ajaxOptions = $.extend( {}, this.defaults.ajax, ajaxOptions );
120
121 // Ensure that token parameter is last (per [[mw:API:Edit#Token]]).
122 if ( parameters.token ) {
123 token = parameters.token;
124 delete parameters.token;
125 }
126
127 // If multipart/form-data has been requested and emulation is possible, emulate it
128 if (
129 ajaxOptions.type === 'POST' &&
130 window.FormData &&
131 ajaxOptions.contentType === 'multipart/form-data'
132 ) {
133
134 formData = new FormData();
135
136 for ( key in parameters ) {
137 formData.append( key, parameters[key] );
138 }
139 // If we extracted a token parameter, add it back in.
140 if ( token ) {
141 formData.append( 'token', token );
142 }
143
144 ajaxOptions.data = formData;
145
146 // Prevent jQuery from mangling our FormData object
147 ajaxOptions.processData = false;
148 // Prevent jQuery from overriding the Content-Type header
149 ajaxOptions.contentType = false;
150 } else {
151 // Some deployed MediaWiki >= 1.17 forbid periods in URLs, due to an IE XSS bug
152 // So let's escape them here. See bug #28235
153 // This works because jQuery accepts data as a query string or as an Object
154 ajaxOptions.data = $.param( parameters ).replace( /\./g, '%2E' );
155
156 // If we extracted a token parameter, add it back in.
157 if ( token ) {
158 ajaxOptions.data += '&token=' + encodeURIComponent( token );
159 }
160
161 if ( ajaxOptions.contentType === 'multipart/form-data' ) {
162 // We were asked to emulate but can't, so drop the Content-Type header, otherwise
163 // it'll be wrong and the server will fail to decode the POST body
164 delete ajaxOptions.contentType;
165 }
166 }
167
168 // Make the AJAX request
169 xhr = $.ajax( ajaxOptions )
170 // If AJAX fails, reject API call with error code 'http'
171 // and details in second argument.
172 .fail( function ( xhr, textStatus, exception ) {
173 apiDeferred.reject( 'http', {
174 xhr: xhr,
175 textStatus: textStatus,
176 exception: exception
177 } );
178 } )
179 // AJAX success just means "200 OK" response, also check API error codes
180 .done( function ( result, textStatus, jqXHR ) {
181 if ( result === undefined || result === null || result === '' ) {
182 apiDeferred.reject( 'ok-but-empty',
183 'OK response but empty result (check HTTP headers?)'
184 );
185 } else if ( result.error ) {
186 var code = result.error.code === undefined ? 'unknown' : result.error.code;
187 apiDeferred.reject( code, result );
188 } else {
189 apiDeferred.resolve( result, jqXHR );
190 }
191 } );
192
193 // Return the Promise
194 return apiDeferred.promise( { abort: xhr.abort } ).fail( function ( code, details ) {
195 if ( !( code === 'http' && details && details.textStatus === 'abort' ) ) {
196 mw.log( 'mw.Api error: ', code, details );
197 }
198 } );
199 },
200
201 /**
202 * Post to API with specified type of token. If we have no token, get one and try to post.
203 * If we have a cached token try using that, and if it fails, blank out the
204 * cached token and start over. For example to change an user option you could do:
205 *
206 * new mw.Api().postWithToken( 'options', {
207 * action: 'options',
208 * optionname: 'gender',
209 * optionvalue: 'female'
210 * } );
211 *
212 * @param {string} tokenType The name of the token, like options or edit.
213 * @param {Object} params API parameters
214 * @param {Object} [ajaxOptions]
215 * @return {jQuery.Promise} See #post
216 * @since 1.22
217 */
218 postWithToken: function ( tokenType, params, ajaxOptions ) {
219 var api = this;
220
221 return api.getToken( tokenType, params.assert ).then( function ( token ) {
222 params.token = token;
223 return api.post( params, ajaxOptions ).then(
224 // If no error, return to caller as-is
225 null,
226 // Error handler
227 function ( code ) {
228 if ( code === 'badtoken' ) {
229 // Clear from cache
230 promises[ api.defaults.ajax.url ][ tokenType + 'Token' ] =
231 params.token = undefined;
232
233 // Try again, once
234 return api.getToken( tokenType, params.assert ).then( function ( token ) {
235 params.token = token;
236 return api.post( params, ajaxOptions );
237 } );
238 }
239
240 // Different error, pass on to let caller handle the error code
241 return this;
242 }
243 );
244 } );
245 },
246
247 /**
248 * Get a token for a certain action from the API.
249 *
250 * The assert parameter is only for internal use by postWithToken.
251 *
252 * @param {string} type Token type
253 * @return {jQuery.Promise}
254 * @return {Function} return.done
255 * @return {string} return.done.token Received token.
256 * @since 1.22
257 */
258 getToken: function ( type, assert ) {
259 var apiPromise,
260 promiseGroup = promises[ this.defaults.ajax.url ],
261 d = promiseGroup && promiseGroup[ type + 'Token' ];
262
263 if ( !d ) {
264 apiPromise = this.get( { action: 'tokens', type: type, assert: assert } );
265
266 d = apiPromise
267 .then( function ( data ) {
268 // If token type is not available for this user,
269 // key '...token' is either missing or set to boolean false
270 if ( data.tokens && data.tokens[type + 'token'] ) {
271 return data.tokens[type + 'token'];
272 }
273
274 return $.Deferred().reject( 'token-missing', data );
275 }, function () {
276 // Clear promise. Do not cache errors.
277 delete promiseGroup[ type + 'Token' ];
278
279 // Pass on to allow the caller to handle the error
280 return this;
281 } )
282 // Attach abort handler
283 .promise( { abort: apiPromise.abort } );
284
285 // Store deferred now so that we can use it again even if it isn't ready yet
286 if ( !promiseGroup ) {
287 promiseGroup = promises[ this.defaults.ajax.url ] = {};
288 }
289 promiseGroup[ type + 'Token' ] = d;
290 }
291
292 return d;
293 }
294 };
295
296 /**
297 * @static
298 * @property {Array}
299 * List of errors we might receive from the API.
300 * For now, this just documents our expectation that there should be similar messages
301 * available.
302 */
303 mw.Api.errors = [
304 // occurs when POST aborted
305 // jQuery 1.4 can't distinguish abort or lost connection from 200 OK + empty result
306 'ok-but-empty',
307
308 // timeout
309 'timeout',
310
311 // really a warning, but we treat it like an error
312 'duplicate',
313 'duplicate-archive',
314
315 // upload succeeded, but no image info.
316 // this is probably impossible, but might as well check for it
317 'noimageinfo',
318 // remote errors, defined in API
319 'uploaddisabled',
320 'nomodule',
321 'mustbeposted',
322 'badaccess-groups',
323 'stashfailed',
324 'missingresult',
325 'missingparam',
326 'invalid-file-key',
327 'copyuploaddisabled',
328 'mustbeloggedin',
329 'empty-file',
330 'file-too-large',
331 'filetype-missing',
332 'filetype-banned',
333 'filetype-banned-type',
334 'filename-tooshort',
335 'illegal-filename',
336 'verification-error',
337 'hookaborted',
338 'unknown-error',
339 'internal-error',
340 'overwrite',
341 'badtoken',
342 'fetchfileerror',
343 'fileexists-shared-forbidden',
344 'invalidtitle',
345 'notloggedin'
346 ];
347
348 /**
349 * @static
350 * @property {Array}
351 * List of warnings we might receive from the API.
352 * For now, this just documents our expectation that there should be similar messages
353 * available.
354 */
355 mw.Api.warnings = [
356 'duplicate',
357 'exists'
358 ];
359
360 }( mediaWiki, jQuery ) );