Merge "Rename Special:ListGroupRights in Czech"
[lhc/web/wiklou.git] / resources / src / mediawiki / api.js
1 ( function ( mw, $ ) {
2
3 /**
4 * @class mw.Api
5 */
6
7 /**
8 * @property {Object} defaultOptions Default options for #ajax calls. Can be overridden by passing
9 * `options` to mw.Api constructor.
10 * @property {Object} defaultOptions.parameters Default query parameters for API requests.
11 * @property {Object} defaultOptions.ajax Default options for jQuery#ajax.
12 * @private
13 */
14 var defaultOptions = {
15 parameters: {
16 action: 'query',
17 format: 'json'
18 },
19 ajax: {
20 url: mw.util.wikiScript( 'api' ),
21 timeout: 30 * 1000, // 30 seconds
22 dataType: 'json'
23 }
24 },
25
26 // Keyed by ajax url and symbolic name for the individual request
27 promises = {};
28
29 function mapLegacyToken( action ) {
30 // Legacy types for backward-compatibility with API action=tokens.
31 var csrfActions = [
32 'edit',
33 'delete',
34 'protect',
35 'move',
36 'block',
37 'unblock',
38 'email',
39 'import',
40 'options'
41 ];
42 return $.inArray( action, csrfActions ) !== -1 ? 'csrf' : action;
43 }
44
45 // Pre-populate with fake ajax promises to save http requests for tokens
46 // we already have on the page via the user.tokens module (bug 34733).
47 promises[ defaultOptions.ajax.url ] = {};
48 $.each( mw.user.tokens.get(), function ( key, value ) {
49 // This requires #getToken to use the same key as user.tokens.
50 // Format: token-type + "Token" (eg. editToken, patrolToken, watchToken).
51 promises[ defaultOptions.ajax.url ][ key ] = $.Deferred()
52 .resolve( value )
53 .promise( { abort: function () {} } );
54 } );
55
56 /**
57 * Constructor to create an object to interact with the API of a particular MediaWiki server.
58 * mw.Api objects represent the API of a particular MediaWiki server.
59 *
60 * var api = new mw.Api();
61 * api.get( {
62 * action: 'query',
63 * meta: 'userinfo'
64 * } ).done( function ( data ) {
65 * console.log( data );
66 * } );
67 *
68 * Since MW 1.25, multiple values for a parameter can be specified using an array:
69 *
70 * var api = new mw.Api();
71 * api.get( {
72 * action: 'query',
73 * meta: [ 'userinfo', 'siteinfo' ] // same effect as 'userinfo|siteinfo'
74 * } ).done( function ( data ) {
75 * console.log( data );
76 * } );
77 *
78 * Since MW 1.26, boolean values for a parameter can be specified directly. If the value is
79 * `false` or `undefined`, the parameter will be omitted from the request, as required by the API.
80 *
81 * @constructor
82 * @param {Object} [options] See #defaultOptions documentation above. Can also be overridden for
83 * each individual request by passing them to #get or #post (or directly #ajax) later on.
84 */
85 mw.Api = function ( options ) {
86 options = options || {};
87
88 // Force a string if we got a mw.Uri object
89 if ( options.ajax && options.ajax.url !== undefined ) {
90 options.ajax.url = String( options.ajax.url );
91 }
92
93 options.parameters = $.extend( {}, defaultOptions.parameters, options.parameters );
94 options.ajax = $.extend( {}, defaultOptions.ajax, options.ajax );
95
96 this.defaults = options;
97 this.requests = [];
98 };
99
100 mw.Api.prototype = {
101 /**
102 * Abort all unfinished requests issued by this Api object.
103 *
104 * @method
105 */
106 abort: function () {
107 $.each( this.requests, function ( index, request ) {
108 if ( request ) {
109 request.abort();
110 }
111 } );
112 },
113
114 /**
115 * Perform API get request
116 *
117 * @param {Object} parameters
118 * @param {Object} [ajaxOptions]
119 * @return {jQuery.Promise}
120 */
121 get: function ( parameters, ajaxOptions ) {
122 ajaxOptions = ajaxOptions || {};
123 ajaxOptions.type = 'GET';
124 return this.ajax( parameters, ajaxOptions );
125 },
126
127 /**
128 * Perform API post request
129 *
130 * @param {Object} parameters
131 * @param {Object} [ajaxOptions]
132 * @return {jQuery.Promise}
133 */
134 post: function ( parameters, ajaxOptions ) {
135 ajaxOptions = ajaxOptions || {};
136 ajaxOptions.type = 'POST';
137 return this.ajax( parameters, ajaxOptions );
138 },
139
140 /**
141 * Massage parameters from the nice format we accept into a format suitable for the API.
142 *
143 * @private
144 * @param {Object} parameters (modified in-place)
145 */
146 preprocessParameters: function ( parameters ) {
147 var key;
148 // Handle common MediaWiki API idioms for passing parameters
149 for ( key in parameters ) {
150 // Multiple values are pipe-separated
151 if ( $.isArray( parameters[ key ] ) ) {
152 parameters[ key ] = parameters[ key ].join( '|' );
153 }
154 // Boolean values are only false when not given at all
155 if ( parameters[ key ] === false || parameters[ key ] === undefined ) {
156 delete parameters[ key ];
157 }
158 }
159 },
160
161 /**
162 * Perform the API call.
163 *
164 * @param {Object} parameters
165 * @param {Object} [ajaxOptions]
166 * @return {jQuery.Promise} Done: API response data and the jqXHR object.
167 * Fail: Error code
168 */
169 ajax: function ( parameters, ajaxOptions ) {
170 var token, requestIndex,
171 api = this,
172 apiDeferred = $.Deferred(),
173 xhr, key, formData;
174
175 parameters = $.extend( {}, this.defaults.parameters, parameters );
176 ajaxOptions = $.extend( {}, this.defaults.ajax, ajaxOptions );
177
178 // Ensure that token parameter is last (per [[mw:API:Edit#Token]]).
179 if ( parameters.token ) {
180 token = parameters.token;
181 delete parameters.token;
182 }
183
184 this.preprocessParameters( parameters );
185
186 // If multipart/form-data has been requested and emulation is possible, emulate it
187 if (
188 ajaxOptions.type === 'POST' &&
189 window.FormData &&
190 ajaxOptions.contentType === 'multipart/form-data'
191 ) {
192
193 formData = new FormData();
194
195 for ( key in parameters ) {
196 formData.append( key, parameters[ key ] );
197 }
198 // If we extracted a token parameter, add it back in.
199 if ( token ) {
200 formData.append( 'token', token );
201 }
202
203 ajaxOptions.data = formData;
204
205 // Prevent jQuery from mangling our FormData object
206 ajaxOptions.processData = false;
207 // Prevent jQuery from overriding the Content-Type header
208 ajaxOptions.contentType = false;
209 } else {
210 // Some deployed MediaWiki >= 1.17 forbid periods in URLs, due to an IE XSS bug
211 // So let's escape them here. See bug #28235
212 // This works because jQuery accepts data as a query string or as an Object
213 ajaxOptions.data = $.param( parameters ).replace( /\./g, '%2E' );
214
215 // If we extracted a token parameter, add it back in.
216 if ( token ) {
217 ajaxOptions.data += '&token=' + encodeURIComponent( token );
218 }
219
220 if ( ajaxOptions.contentType === 'multipart/form-data' ) {
221 // We were asked to emulate but can't, so drop the Content-Type header, otherwise
222 // it'll be wrong and the server will fail to decode the POST body
223 delete ajaxOptions.contentType;
224 }
225 }
226
227 // Make the AJAX request
228 xhr = $.ajax( ajaxOptions )
229 // If AJAX fails, reject API call with error code 'http'
230 // and details in second argument.
231 .fail( function ( xhr, textStatus, exception ) {
232 apiDeferred.reject( 'http', {
233 xhr: xhr,
234 textStatus: textStatus,
235 exception: exception
236 } );
237 } )
238 // AJAX success just means "200 OK" response, also check API error codes
239 .done( function ( result, textStatus, jqXHR ) {
240 if ( result === undefined || result === null || result === '' ) {
241 apiDeferred.reject( 'ok-but-empty',
242 'OK response but empty result (check HTTP headers?)',
243 result,
244 jqXHR
245 );
246 } else if ( result.error ) {
247 var code = result.error.code === undefined ? 'unknown' : result.error.code;
248 apiDeferred.reject( code, result, result, jqXHR );
249 } else {
250 apiDeferred.resolve( result, jqXHR );
251 }
252 } );
253
254 requestIndex = this.requests.length;
255 this.requests.push( xhr );
256 xhr.always( function () {
257 api.requests[ requestIndex ] = null;
258 } );
259 // Return the Promise
260 return apiDeferred.promise( { abort: xhr.abort } ).fail( function ( code, details ) {
261 if ( !( code === 'http' && details && details.textStatus === 'abort' ) ) {
262 mw.log( 'mw.Api error: ', code, details );
263 }
264 } );
265 },
266
267 /**
268 * Post to API with specified type of token. If we have no token, get one and try to post.
269 * If we have a cached token try using that, and if it fails, blank out the
270 * cached token and start over. For example to change an user option you could do:
271 *
272 * new mw.Api().postWithToken( 'options', {
273 * action: 'options',
274 * optionname: 'gender',
275 * optionvalue: 'female'
276 * } );
277 *
278 * @param {string} tokenType The name of the token, like options or edit.
279 * @param {Object} params API parameters
280 * @param {Object} [ajaxOptions]
281 * @return {jQuery.Promise} See #post
282 * @since 1.22
283 */
284 postWithToken: function ( tokenType, params, ajaxOptions ) {
285 var api = this;
286
287 return api.getToken( tokenType, params.assert ).then( function ( token ) {
288 params.token = token;
289 return api.post( params, ajaxOptions ).then(
290 // If no error, return to caller as-is
291 null,
292 // Error handler
293 function ( code ) {
294 if ( code === 'badtoken' ) {
295 api.badToken( tokenType );
296 // Try again, once
297 params.token = undefined;
298 return api.getToken( tokenType, params.assert ).then( function ( token ) {
299 params.token = token;
300 return api.post( params, ajaxOptions );
301 } );
302 }
303
304 // Different error, pass on to let caller handle the error code
305 return this;
306 }
307 );
308 } );
309 },
310
311 /**
312 * Get a token for a certain action from the API.
313 *
314 * The assert parameter is only for internal use by #postWithToken.
315 *
316 * @since 1.22
317 * @param {string} type Token type
318 * @return {jQuery.Promise} Received token.
319 */
320 getToken: function ( type, assert ) {
321 var apiPromise, promiseGroup, d;
322 type = mapLegacyToken( type );
323 promiseGroup = promises[ this.defaults.ajax.url ];
324 d = promiseGroup && promiseGroup[ type + 'Token' ];
325
326 if ( !d ) {
327 apiPromise = this.get( {
328 action: 'query',
329 meta: 'tokens',
330 type: type,
331 assert: assert
332 } );
333 d = apiPromise
334 .then( function ( res ) {
335 // If token type is unknown, it is omitted from the response
336 if ( !res.query.tokens[ type + 'token' ] ) {
337 return $.Deferred().reject( 'token-missing', res );
338 }
339
340 return res.query.tokens[ type + 'token' ];
341 }, function () {
342 // Clear promise. Do not cache errors.
343 delete promiseGroup[ type + 'Token' ];
344
345 // Pass on to allow the caller to handle the error
346 return this;
347 } )
348 // Attach abort handler
349 .promise( { abort: apiPromise.abort } );
350
351 // Store deferred now so that we can use it again even if it isn't ready yet
352 if ( !promiseGroup ) {
353 promiseGroup = promises[ this.defaults.ajax.url ] = {};
354 }
355 promiseGroup[ type + 'Token' ] = d;
356 }
357
358 return d;
359 },
360
361 /**
362 * Indicate that the cached token for a certain action of the API is bad.
363 *
364 * Call this if you get a 'badtoken' error when using the token returned by #getToken.
365 * You may also want to use #postWithToken instead, which invalidates bad cached tokens
366 * automatically.
367 *
368 * @param {string} type Token type
369 * @since 1.26
370 */
371 badToken: function ( type ) {
372 var promiseGroup = promises[ this.defaults.ajax.url ];
373
374 type = mapLegacyToken( type );
375 if ( promiseGroup ) {
376 delete promiseGroup[ type + 'Token' ];
377 }
378 }
379 };
380
381 /**
382 * @static
383 * @property {Array}
384 * List of errors we might receive from the API.
385 * For now, this just documents our expectation that there should be similar messages
386 * available.
387 */
388 mw.Api.errors = [
389 // occurs when POST aborted
390 // jQuery 1.4 can't distinguish abort or lost connection from 200 OK + empty result
391 'ok-but-empty',
392
393 // timeout
394 'timeout',
395
396 // really a warning, but we treat it like an error
397 'duplicate',
398 'duplicate-archive',
399
400 // upload succeeded, but no image info.
401 // this is probably impossible, but might as well check for it
402 'noimageinfo',
403 // remote errors, defined in API
404 'uploaddisabled',
405 'nomodule',
406 'mustbeposted',
407 'badaccess-groups',
408 'missingresult',
409 'missingparam',
410 'invalid-file-key',
411 'copyuploaddisabled',
412 'mustbeloggedin',
413 'empty-file',
414 'file-too-large',
415 'filetype-missing',
416 'filetype-banned',
417 'filetype-banned-type',
418 'filename-tooshort',
419 'illegal-filename',
420 'verification-error',
421 'hookaborted',
422 'unknown-error',
423 'internal-error',
424 'overwrite',
425 'badtoken',
426 'fetchfileerror',
427 'fileexists-shared-forbidden',
428 'invalidtitle',
429 'notloggedin',
430
431 // Stash-specific errors - expanded
432 'stashfailed',
433 'stasherror',
434 'stashedfilenotfound',
435 'stashpathinvalid',
436 'stashfilestorage',
437 'stashzerolength',
438 'stashnotloggedin',
439 'stashwrongowner',
440 'stashnosuchfilekey'
441 ];
442
443 /**
444 * @static
445 * @property {Array}
446 * List of warnings we might receive from the API.
447 * For now, this just documents our expectation that there should be similar messages
448 * available.
449 */
450 mw.Api.warnings = [
451 'duplicate',
452 'exists'
453 ];
454
455 }( mediaWiki, jQuery ) );