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 * @property {boolean} defaultOptions.useUS Whether to use U+001F when joining multi-valued
13 * parameters (since 1.28). Default is true if ajax.url is not set, false otherwise for
17 var defaultOptions
= {
23 url
: mw
.util
.wikiScript( 'api' ),
24 timeout
: 30 * 1000, // 30 seconds
29 // Keyed by ajax url and symbolic name for the individual request
32 function mapLegacyToken( action
) {
33 // Legacy types for backward-compatibility with API action=tokens.
45 if ( csrfActions
.indexOf( action
) !== -1 ) {
46 mw
.track( 'mw.deprecate', 'apitoken_' + action
);
47 mw
.log
.warn( 'Use of the "' + action
+ '" token is deprecated. Use "csrf" instead.' );
53 // Pre-populate with fake ajax promises to save http requests for tokens
54 // we already have on the page via the user.tokens module (T36733).
55 promises
[ defaultOptions
.ajax
.url
] = {};
56 // eslint-disable-next-line no-restricted-properties
57 $.each( mw
.user
.tokens
.get(), function ( key
, value
) {
58 // This requires #getToken to use the same key as user.tokens.
59 // Format: token-type + "Token" (eg. csrfToken, patrolToken, watchToken).
60 promises
[ defaultOptions
.ajax
.url
][ key
] = $.Deferred()
62 .promise( { abort: function () {} } );
66 * Constructor to create an object to interact with the API of a particular MediaWiki server.
67 * mw.Api objects represent the API of a particular MediaWiki server.
69 * var api = new mw.Api();
73 * } ).done( function ( data ) {
74 * console.log( data );
77 * Since MW 1.25, multiple values for a parameter can be specified using an array:
79 * var api = new mw.Api();
82 * meta: [ 'userinfo', 'siteinfo' ] // same effect as 'userinfo|siteinfo'
83 * } ).done( function ( data ) {
84 * console.log( data );
87 * Since MW 1.26, boolean values for a parameter can be specified directly. If the value is
88 * `false` or `undefined`, the parameter will be omitted from the request, as required by the API.
91 * @param {Object} [options] See #defaultOptions documentation above. Can also be overridden for
92 * each individual request by passing them to #get or #post (or directly #ajax) later on.
94 mw
.Api = function ( options
) {
95 var defaults
= $.extend( {}, options
),
96 setsUrl
= options
&& options
.ajax
&& options
.ajax
.url
!== undefined;
98 defaults
.parameters
= $.extend( {}, defaultOptions
.parameters
, defaults
.parameters
);
99 defaults
.ajax
= $.extend( {}, defaultOptions
.ajax
, defaults
.ajax
);
101 // Force a string if we got a mw.Uri object
103 defaults
.ajax
.url
= String( defaults
.ajax
.url
);
105 if ( defaults
.useUS
=== undefined ) {
106 defaults
.useUS
= !setsUrl
;
109 this.defaults
= defaults
;
115 * Abort all unfinished requests issued by this Api object.
120 this.requests
.forEach( function ( request
) {
128 * Perform API get request
130 * @param {Object} parameters
131 * @param {Object} [ajaxOptions]
132 * @return {jQuery.Promise}
134 get: function ( parameters
, ajaxOptions
) {
135 ajaxOptions
= ajaxOptions
|| {};
136 ajaxOptions
.type
= 'GET';
137 return this.ajax( parameters
, ajaxOptions
);
141 * Perform API post request
143 * @param {Object} parameters
144 * @param {Object} [ajaxOptions]
145 * @return {jQuery.Promise}
147 post: function ( parameters
, ajaxOptions
) {
148 ajaxOptions
= ajaxOptions
|| {};
149 ajaxOptions
.type
= 'POST';
150 return this.ajax( parameters
, ajaxOptions
);
154 * Massage parameters from the nice format we accept into a format suitable for the API.
156 * NOTE: A value of undefined/null in an array will be represented by Array#join()
157 * as the empty string. Should we filter silently? Warn? Leave as-is?
160 * @param {Object} parameters (modified in-place)
161 * @param {boolean} useUS Whether to use U+001F when joining multi-valued parameters.
163 preprocessParameters: function ( parameters
, useUS
) {
165 // Handle common MediaWiki API idioms for passing parameters
166 for ( key
in parameters
) {
167 // Multiple values are pipe-separated
168 if ( Array
.isArray( parameters
[ key
] ) ) {
169 if ( !useUS
|| parameters
[ key
].join( '' ).indexOf( '|' ) === -1 ) {
170 parameters
[ key
] = parameters
[ key
].join( '|' );
172 parameters
[ key
] = '\x1f' + parameters
[ key
].join( '\x1f' );
174 } else if ( parameters
[ key
] === false || parameters
[ key
] === undefined ) {
175 // Boolean values are only false when not given at all
176 delete parameters
[ key
];
182 * Perform the API call.
184 * @param {Object} parameters
185 * @param {Object} [ajaxOptions]
186 * @return {jQuery.Promise} Done: API response data and the jqXHR object.
189 ajax: function ( parameters
, ajaxOptions
) {
190 var token
, requestIndex
,
192 apiDeferred
= $.Deferred(),
195 parameters
= $.extend( {}, this.defaults
.parameters
, parameters
);
196 ajaxOptions
= $.extend( {}, this.defaults
.ajax
, ajaxOptions
);
198 // Ensure that token parameter is last (per [[mw:API:Edit#Token]]).
199 if ( parameters
.token
) {
200 token
= parameters
.token
;
201 delete parameters
.token
;
204 this.preprocessParameters( parameters
, this.defaults
.useUS
);
206 // If multipart/form-data has been requested and emulation is possible, emulate it
208 ajaxOptions
.type
=== 'POST' &&
210 ajaxOptions
.contentType
=== 'multipart/form-data'
213 formData
= new FormData();
215 for ( key
in parameters
) {
216 formData
.append( key
, parameters
[ key
] );
218 // If we extracted a token parameter, add it back in.
220 formData
.append( 'token', token
);
223 ajaxOptions
.data
= formData
;
225 // Prevent jQuery from mangling our FormData object
226 ajaxOptions
.processData
= false;
227 // Prevent jQuery from overriding the Content-Type header
228 ajaxOptions
.contentType
= false;
230 // This works because jQuery accepts data as a query string or as an Object
231 ajaxOptions
.data
= $.param( parameters
);
232 // If we extracted a token parameter, add it back in.
234 ajaxOptions
.data
+= '&token=' + encodeURIComponent( token
);
237 // Depending on server configuration, MediaWiki may forbid periods in URLs, due to an IE 6
238 // XSS bug. So let's escape them here. See WebRequest::checkUrlExtension() and T30235.
239 ajaxOptions
.data
= ajaxOptions
.data
.replace( /\./g, '%2E' );
241 if ( ajaxOptions
.contentType
=== 'multipart/form-data' ) {
242 // We were asked to emulate but can't, so drop the Content-Type header, otherwise
243 // it'll be wrong and the server will fail to decode the POST body
244 delete ajaxOptions
.contentType
;
248 // Make the AJAX request
249 xhr
= $.ajax( ajaxOptions
)
250 // If AJAX fails, reject API call with error code 'http'
251 // and details in second argument.
252 .fail( function ( xhr
, textStatus
, exception
) {
253 apiDeferred
.reject( 'http', {
255 textStatus
: textStatus
,
259 // AJAX success just means "200 OK" response, also check API error codes
260 .done( function ( result
, textStatus
, jqXHR
) {
262 if ( result
=== undefined || result
=== null || result
=== '' ) {
263 apiDeferred
.reject( 'ok-but-empty',
264 'OK response but empty result (check HTTP headers?)',
268 } else if ( result
.error
) {
270 code
= result
.error
.code
=== undefined ? 'unknown' : result
.error
.code
;
271 apiDeferred
.reject( code
, result
, result
, jqXHR
);
272 } else if ( result
.errors
) {
274 code
= result
.errors
[ 0 ].code
=== undefined ? 'unknown' : result
.errors
[ 0 ].code
;
275 apiDeferred
.reject( code
, result
, result
, jqXHR
);
277 apiDeferred
.resolve( result
, jqXHR
);
281 requestIndex
= this.requests
.length
;
282 this.requests
.push( xhr
);
283 xhr
.always( function () {
284 api
.requests
[ requestIndex
] = null;
286 // Return the Promise
287 return apiDeferred
.promise( { abort
: xhr
.abort
} ).fail( function ( code
, details
) {
288 if ( !( code
=== 'http' && details
&& details
.textStatus
=== 'abort' ) ) {
289 mw
.log( 'mw.Api error: ', code
, details
);
295 * Post to API with specified type of token. If we have no token, get one and try to post.
296 * If we have a cached token try using that, and if it fails, blank out the
297 * cached token and start over. For example to change an user option you could do:
299 * new mw.Api().postWithToken( 'csrf', {
301 * optionname: 'gender',
302 * optionvalue: 'female'
305 * @param {string} tokenType The name of the token, like options or edit.
306 * @param {Object} params API parameters
307 * @param {Object} [ajaxOptions]
308 * @return {jQuery.Promise} See #post
311 postWithToken: function ( tokenType
, params
, ajaxOptions
) {
313 abortedPromise
= $.Deferred().reject( 'http',
314 { textStatus
: 'abort', exception
: 'abort' } ).promise(),
318 return api
.getToken( tokenType
, params
.assert
).then( function ( token
) {
319 params
.token
= token
;
320 // Request was aborted while token request was running, but we
321 // don't want to unnecessarily abort token requests, so abort
322 // a fake request instead
324 return abortedPromise
;
327 return ( abortable
= api
.post( params
, ajaxOptions
) ).catch(
330 if ( code
=== 'badtoken' ) {
331 api
.badToken( tokenType
);
333 params
.token
= undefined;
335 return api
.getToken( tokenType
, params
.assert
).then( function ( token
) {
336 params
.token
= token
;
338 return abortedPromise
;
341 return ( abortable
= api
.post( params
, ajaxOptions
) );
345 // Let caller handle the error code
346 return $.Deferred().rejectWith( this, arguments
);
349 } ).promise( { abort: function () {
359 * Get a token for a certain action from the API.
361 * The assert parameter is only for internal use by #postWithToken.
364 * @param {string} type Token type
365 * @param {string} [assert]
366 * @return {jQuery.Promise} Received token.
368 getToken: function ( type
, assert
) {
369 var apiPromise
, promiseGroup
, d
, reject
;
370 type
= mapLegacyToken( type
);
371 promiseGroup
= promises
[ this.defaults
.ajax
.url
];
372 d
= promiseGroup
&& promiseGroup
[ type
+ 'Token' ];
374 if ( !promiseGroup
) {
375 promiseGroup
= promises
[ this.defaults
.ajax
.url
] = {};
379 apiPromise
= this.get( {
385 reject = function () {
386 // Clear promise. Do not cache errors.
387 delete promiseGroup
[ type
+ 'Token' ];
389 // Let caller handle the error code
390 return $.Deferred().rejectWith( this, arguments
);
393 .then( function ( res
) {
395 return reject( 'query-missing', res
);
397 // If token type is unknown, it is omitted from the response
398 if ( !res
.query
.tokens
[ type
+ 'token' ] ) {
399 return $.Deferred().reject( 'token-missing', res
);
401 return res
.query
.tokens
[ type
+ 'token' ];
403 // Attach abort handler
404 .promise( { abort
: apiPromise
.abort
} );
406 // Store deferred now so that we can use it again even if it isn't ready yet
407 promiseGroup
[ type
+ 'Token' ] = d
;
414 * Indicate that the cached token for a certain action of the API is bad.
416 * Call this if you get a 'badtoken' error when using the token returned by #getToken.
417 * You may also want to use #postWithToken instead, which invalidates bad cached tokens
420 * @param {string} type Token type
423 badToken: function ( type
) {
424 var promiseGroup
= promises
[ this.defaults
.ajax
.url
];
426 type
= mapLegacyToken( type
);
427 if ( promiseGroup
) {
428 delete promiseGroup
[ type
+ 'Token' ];
436 * Very incomplete and outdated list of errors we might receive from the API. Do not use.
437 * @deprecated since 1.29
440 // occurs when POST aborted
441 // jQuery 1.4 can't distinguish abort or lost connection from 200 OK + empty result
447 // really a warning, but we treat it like an error
451 // upload succeeded, but no image info.
452 // this is probably impossible, but might as well check for it
454 // remote errors, defined in API
462 'copyuploaddisabled',
468 'filetype-banned-type',
471 'verification-error',
478 'fileexists-shared-forbidden',
484 // Stash-specific errors - expanded
487 'stashedfilenotfound',
495 mw
.log
.deprecate( mw
.Api
, 'errors', mw
.Api
.errors
, null, 'mw.Api.errors' );
500 * Very incomplete and outdated list of warnings we might receive from the API. Do not use.
501 * @deprecated since 1.29
507 mw
.log
.deprecate( mw
.Api
, 'warnings', mw
.Api
.warnings
, null, 'mw.Api.warnings' );
509 }( mediaWiki
, jQuery
) );