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.
14 var defaultOptions = {
20 url: mw.util.wikiScript( 'api' ),
21 timeout: 30 * 1000, // 30 seconds
26 // Keyed by ajax url and symbolic name for the individual request
29 function mapLegacyToken( action ) {
30 // Legacy types for backward-compatibility with API action=tokens.
42 return $.inArray( action, csrfActions ) !== -1 ? 'csrf' : action;
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()
53 .promise( { abort: function () {} } );
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.
60 * var api = new mw.Api();
64 * } ).done( function ( data ) {
65 * console.log( data );
68 * Since MW 1.25, multiple values for a parameter can be specified using an array:
70 * var api = new mw.Api();
73 * meta: [ 'userinfo', 'siteinfo' ] // same effect as 'userinfo|siteinfo'
74 * } ).done( function ( data ) {
75 * console.log( data );
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.
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.
85 mw.Api = function ( options ) {
86 options = options || {};
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 );
93 options.parameters = $.extend( {}, defaultOptions.parameters, options.parameters );
94 options.ajax = $.extend( {}, defaultOptions.ajax, options.ajax );
96 this.defaults = options;
102 * Abort all unfinished requests issued by this Api object.
107 $.each( this.requests, function ( index, request ) {
115 * Perform API get request
117 * @param {Object} parameters
118 * @param {Object} [ajaxOptions]
119 * @return {jQuery.Promise}
121 get: function ( parameters, ajaxOptions ) {
122 ajaxOptions = ajaxOptions || {};
123 ajaxOptions.type = 'GET';
124 return this.ajax( parameters, ajaxOptions );
128 * Perform API post request
130 * @param {Object} parameters
131 * @param {Object} [ajaxOptions]
132 * @return {jQuery.Promise}
134 post: function ( parameters, ajaxOptions ) {
135 ajaxOptions = ajaxOptions || {};
136 ajaxOptions.type = 'POST';
137 return this.ajax( parameters, ajaxOptions );
141 * Massage parameters from the nice format we accept into a format suitable for the API.
144 * @param {Object} parameters (modified in-place)
146 preprocessParameters: function ( parameters ) {
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( '|' );
154 // Boolean values are only false when not given at all
155 if ( parameters[ key ] === false || parameters[ key ] === undefined ) {
156 delete parameters[ key ];
162 * Perform the API call.
164 * @param {Object} parameters
165 * @param {Object} [ajaxOptions]
166 * @return {jQuery.Promise} Done: API response data and the jqXHR object.
169 ajax: function ( parameters, ajaxOptions ) {
170 var token, requestIndex,
172 apiDeferred = $.Deferred(),
175 parameters = $.extend( {}, this.defaults.parameters, parameters );
176 ajaxOptions = $.extend( {}, this.defaults.ajax, ajaxOptions );
178 // Ensure that token parameter is last (per [[mw:API:Edit#Token]]).
179 if ( parameters.token ) {
180 token = parameters.token;
181 delete parameters.token;
184 this.preprocessParameters( parameters );
186 // If multipart/form-data has been requested and emulation is possible, emulate it
188 ajaxOptions.type === 'POST' &&
190 ajaxOptions.contentType === 'multipart/form-data'
193 formData = new FormData();
195 for ( key in parameters ) {
196 formData.append( key, parameters[ key ] );
198 // If we extracted a token parameter, add it back in.
200 formData.append( 'token', token );
203 ajaxOptions.data = formData;
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;
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' );
215 // If we extracted a token parameter, add it back in.
217 ajaxOptions.data += '&token=' + encodeURIComponent( token );
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;
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', {
234 textStatus: textStatus,
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?)'
244 } else if ( result.error ) {
245 var code = result.error.code === undefined ? 'unknown' : result.error.code;
246 apiDeferred.reject( code, result );
248 apiDeferred.resolve( result, jqXHR );
252 requestIndex = this.requests.length;
253 this.requests.push( xhr );
254 xhr.always( function () {
255 api.requests[ requestIndex ] = null;
257 // Return the Promise
258 return apiDeferred.promise( { abort: xhr.abort } ).fail( function ( code, details ) {
259 if ( !( code === 'http' && details && details.textStatus === 'abort' ) ) {
260 mw.log( 'mw.Api error: ', code, details );
266 * Post to API with specified type of token. If we have no token, get one and try to post.
267 * If we have a cached token try using that, and if it fails, blank out the
268 * cached token and start over. For example to change an user option you could do:
270 * new mw.Api().postWithToken( 'options', {
272 * optionname: 'gender',
273 * optionvalue: 'female'
276 * @param {string} tokenType The name of the token, like options or edit.
277 * @param {Object} params API parameters
278 * @param {Object} [ajaxOptions]
279 * @return {jQuery.Promise} See #post
282 postWithToken: function ( tokenType, params, ajaxOptions ) {
285 return api.getToken( tokenType, params.assert ).then( function ( token ) {
286 params.token = token;
287 return api.post( params, ajaxOptions ).then(
288 // If no error, return to caller as-is
292 if ( code === 'badtoken' ) {
293 api.badToken( tokenType );
295 params.token = undefined;
296 return api.getToken( tokenType, params.assert ).then( function ( token ) {
297 params.token = token;
298 return api.post( params, ajaxOptions );
302 // Different error, pass on to let caller handle the error code
310 * Get a token for a certain action from the API.
312 * The assert parameter is only for internal use by #postWithToken.
315 * @param {string} type Token type
316 * @return {jQuery.Promise} Received token.
318 getToken: function ( type, assert ) {
319 var apiPromise, promiseGroup, d;
320 type = mapLegacyToken( type );
321 promiseGroup = promises[ this.defaults.ajax.url ];
322 d = promiseGroup && promiseGroup[ type + 'Token' ];
325 apiPromise = this.get( {
332 .then( function ( res ) {
333 // If token type is unknown, it is omitted from the response
334 if ( !res.query.tokens[ type + 'token' ] ) {
335 return $.Deferred().reject( 'token-missing', res );
338 return res.query.tokens[ type + 'token' ];
340 // Clear promise. Do not cache errors.
341 delete promiseGroup[ type + 'Token' ];
343 // Pass on to allow the caller to handle the error
346 // Attach abort handler
347 .promise( { abort: apiPromise.abort } );
349 // Store deferred now so that we can use it again even if it isn't ready yet
350 if ( !promiseGroup ) {
351 promiseGroup = promises[ this.defaults.ajax.url ] = {};
353 promiseGroup[ type + 'Token' ] = d;
360 * Indicate that the cached token for a certain action of the API is bad.
362 * Call this if you get a 'badtoken' error when using the token returned by #getToken.
363 * You may also want to use #postWithToken instead, which invalidates bad cached tokens
366 * @param {string} type Token type
369 badToken: function ( type ) {
370 var promiseGroup = promises[ this.defaults.ajax.url ];
372 type = mapLegacyToken( type );
373 if ( promiseGroup ) {
374 delete promiseGroup[ type + 'Token' ];
382 * List of errors we might receive from the API.
383 * For now, this just documents our expectation that there should be similar messages
387 // occurs when POST aborted
388 // jQuery 1.4 can't distinguish abort or lost connection from 200 OK + empty result
394 // really a warning, but we treat it like an error
398 // upload succeeded, but no image info.
399 // this is probably impossible, but might as well check for it
401 // remote errors, defined in API
409 'copyuploaddisabled',
415 'filetype-banned-type',
418 'verification-error',
425 'fileexists-shared-forbidden',
429 // Stash-specific errors - expanded
432 'stashedfilenotfound',
444 * List of warnings we might receive from the API.
445 * For now, this just documents our expectation that there should be similar messages
453 }( mediaWiki, jQuery ) );