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 ( $.inArray( action
, csrfActions
) !== -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 $.each( mw
.user
.tokens
.get(), function ( key
, value
) {
57 // This requires #getToken to use the same key as user.tokens.
58 // Format: token-type + "Token" (eg. csrfToken, patrolToken, watchToken).
59 promises
[ defaultOptions
.ajax
.url
][ key
] = $.Deferred()
61 .promise( { abort: function () {} } );
65 * Constructor to create an object to interact with the API of a particular MediaWiki server.
66 * mw.Api objects represent the API of a particular MediaWiki server.
68 * var api = new mw.Api();
72 * } ).done( function ( data ) {
73 * console.log( data );
76 * Since MW 1.25, multiple values for a parameter can be specified using an array:
78 * var api = new mw.Api();
81 * meta: [ 'userinfo', 'siteinfo' ] // same effect as 'userinfo|siteinfo'
82 * } ).done( function ( data ) {
83 * console.log( data );
86 * Since MW 1.26, boolean values for a parameter can be specified directly. If the value is
87 * `false` or `undefined`, the parameter will be omitted from the request, as required by the API.
90 * @param {Object} [options] See #defaultOptions documentation above. Can also be overridden for
91 * each individual request by passing them to #get or #post (or directly #ajax) later on.
93 mw
.Api = function ( options
) {
94 options
= options
|| {};
96 // Force a string if we got a mw.Uri object
97 if ( options
.ajax
&& options
.ajax
.url
!== undefined ) {
98 options
.ajax
.url
= String( options
.ajax
.url
);
101 options
= $.extend( { useUS
: !options
.ajax
|| !options
.ajax
.url
}, options
);
103 options
.parameters
= $.extend( {}, defaultOptions
.parameters
, options
.parameters
);
104 options
.ajax
= $.extend( {}, defaultOptions
.ajax
, options
.ajax
);
106 this.defaults
= options
;
112 * Abort all unfinished requests issued by this Api object.
117 this.requests
.forEach( function ( request
) {
125 * Perform API get request
127 * @param {Object} parameters
128 * @param {Object} [ajaxOptions]
129 * @return {jQuery.Promise}
131 get: function ( parameters
, ajaxOptions
) {
132 ajaxOptions
= ajaxOptions
|| {};
133 ajaxOptions
.type
= 'GET';
134 return this.ajax( parameters
, ajaxOptions
);
138 * Perform API post request
140 * @param {Object} parameters
141 * @param {Object} [ajaxOptions]
142 * @return {jQuery.Promise}
144 post: function ( parameters
, ajaxOptions
) {
145 ajaxOptions
= ajaxOptions
|| {};
146 ajaxOptions
.type
= 'POST';
147 return this.ajax( parameters
, ajaxOptions
);
151 * Massage parameters from the nice format we accept into a format suitable for the API.
153 * NOTE: A value of undefined/null in an array will be represented by Array#join()
154 * as the empty string. Should we filter silently? Warn? Leave as-is?
157 * @param {Object} parameters (modified in-place)
158 * @param {boolean} useUS Whether to use U+001F when joining multi-valued parameters.
160 preprocessParameters: function ( parameters
, useUS
) {
162 // Handle common MediaWiki API idioms for passing parameters
163 for ( key
in parameters
) {
164 // Multiple values are pipe-separated
165 if ( Array
.isArray( parameters
[ key
] ) ) {
166 if ( !useUS
|| parameters
[ key
].join( '' ).indexOf( '|' ) === -1 ) {
167 parameters
[ key
] = parameters
[ key
].join( '|' );
169 parameters
[ key
] = '\x1f' + parameters
[ key
].join( '\x1f' );
171 } else if ( parameters
[ key
] === false || parameters
[ key
] === undefined ) {
172 // Boolean values are only false when not given at all
173 delete parameters
[ key
];
179 * Perform the API call.
181 * @param {Object} parameters
182 * @param {Object} [ajaxOptions]
183 * @return {jQuery.Promise} Done: API response data and the jqXHR object.
186 ajax: function ( parameters
, ajaxOptions
) {
187 var token
, requestIndex
,
189 apiDeferred
= $.Deferred(),
192 parameters
= $.extend( {}, this.defaults
.parameters
, parameters
);
193 ajaxOptions
= $.extend( {}, this.defaults
.ajax
, ajaxOptions
);
195 // Ensure that token parameter is last (per [[mw:API:Edit#Token]]).
196 if ( parameters
.token
) {
197 token
= parameters
.token
;
198 delete parameters
.token
;
201 this.preprocessParameters( parameters
, this.defaults
.useUS
);
203 // If multipart/form-data has been requested and emulation is possible, emulate it
205 ajaxOptions
.type
=== 'POST' &&
207 ajaxOptions
.contentType
=== 'multipart/form-data'
210 formData
= new FormData();
212 for ( key
in parameters
) {
213 formData
.append( key
, parameters
[ key
] );
215 // If we extracted a token parameter, add it back in.
217 formData
.append( 'token', token
);
220 ajaxOptions
.data
= formData
;
222 // Prevent jQuery from mangling our FormData object
223 ajaxOptions
.processData
= false;
224 // Prevent jQuery from overriding the Content-Type header
225 ajaxOptions
.contentType
= false;
227 // This works because jQuery accepts data as a query string or as an Object
228 ajaxOptions
.data
= $.param( parameters
);
229 // If we extracted a token parameter, add it back in.
231 ajaxOptions
.data
+= '&token=' + encodeURIComponent( token
);
234 // Depending on server configuration, MediaWiki may forbid periods in URLs, due to an IE 6
235 // XSS bug. So let's escape them here. See WebRequest::checkUrlExtension() and T30235.
236 ajaxOptions
.data
= ajaxOptions
.data
.replace( /\./g, '%2E' );
238 if ( ajaxOptions
.contentType
=== 'multipart/form-data' ) {
239 // We were asked to emulate but can't, so drop the Content-Type header, otherwise
240 // it'll be wrong and the server will fail to decode the POST body
241 delete ajaxOptions
.contentType
;
245 // Make the AJAX request
246 xhr
= $.ajax( ajaxOptions
)
247 // If AJAX fails, reject API call with error code 'http'
248 // and details in second argument.
249 .fail( function ( xhr
, textStatus
, exception
) {
250 apiDeferred
.reject( 'http', {
252 textStatus
: textStatus
,
256 // AJAX success just means "200 OK" response, also check API error codes
257 .done( function ( result
, textStatus
, jqXHR
) {
259 if ( result
=== undefined || result
=== null || result
=== '' ) {
260 apiDeferred
.reject( 'ok-but-empty',
261 'OK response but empty result (check HTTP headers?)',
265 } else if ( result
.error
) {
267 code
= result
.error
.code
=== undefined ? 'unknown' : result
.error
.code
;
268 apiDeferred
.reject( code
, result
, result
, jqXHR
);
269 } else if ( result
.errors
) {
271 code
= result
.errors
[ 0 ].code
=== undefined ? 'unknown' : result
.errors
[ 0 ].code
;
272 apiDeferred
.reject( code
, result
, result
, jqXHR
);
274 apiDeferred
.resolve( result
, jqXHR
);
278 requestIndex
= this.requests
.length
;
279 this.requests
.push( xhr
);
280 xhr
.always( function () {
281 api
.requests
[ requestIndex
] = null;
283 // Return the Promise
284 return apiDeferred
.promise( { abort
: xhr
.abort
} ).fail( function ( code
, details
) {
285 if ( !( code
=== 'http' && details
&& details
.textStatus
=== 'abort' ) ) {
286 mw
.log( 'mw.Api error: ', code
, details
);
292 * Post to API with specified type of token. If we have no token, get one and try to post.
293 * If we have a cached token try using that, and if it fails, blank out the
294 * cached token and start over. For example to change an user option you could do:
296 * new mw.Api().postWithToken( 'csrf', {
298 * optionname: 'gender',
299 * optionvalue: 'female'
302 * @param {string} tokenType The name of the token, like options or edit.
303 * @param {Object} params API parameters
304 * @param {Object} [ajaxOptions]
305 * @return {jQuery.Promise} See #post
308 postWithToken: function ( tokenType
, params
, ajaxOptions
) {
310 abortedPromise
= $.Deferred().reject( 'http',
311 { textStatus
: 'abort', exception
: 'abort' } ).promise(),
315 return api
.getToken( tokenType
, params
.assert
).then( function ( token
) {
316 params
.token
= token
;
317 // Request was aborted while token request was running, but we
318 // don't want to unnecessarily abort token requests, so abort
319 // a fake request instead
321 return abortedPromise
;
324 return ( abortable
= api
.post( params
, ajaxOptions
) ).then(
325 // If no error, return to caller as-is
329 if ( code
=== 'badtoken' ) {
330 api
.badToken( tokenType
);
332 params
.token
= undefined;
334 return api
.getToken( tokenType
, params
.assert
).then( function ( token
) {
335 params
.token
= token
;
337 return abortedPromise
;
340 return ( abortable
= api
.post( params
, ajaxOptions
) );
344 // Let caller handle the error code
345 return $.Deferred().rejectWith( this, arguments
);
348 } ).promise( { abort: function () {
358 * Get a token for a certain action from the API.
360 * The assert parameter is only for internal use by #postWithToken.
363 * @param {string} type Token type
364 * @param {string} [assert]
365 * @return {jQuery.Promise} Received token.
367 getToken: function ( type
, assert
) {
368 var apiPromise
, promiseGroup
, d
;
369 type
= mapLegacyToken( type
);
370 promiseGroup
= promises
[ this.defaults
.ajax
.url
];
371 d
= promiseGroup
&& promiseGroup
[ type
+ 'Token' ];
373 if ( !promiseGroup
) {
374 promiseGroup
= promises
[ this.defaults
.ajax
.url
] = {};
378 apiPromise
= this.get( {
385 .then( function ( res
) {
386 // If token type is unknown, it is omitted from the response
387 if ( !res
.query
.tokens
[ type
+ 'token' ] ) {
388 return $.Deferred().reject( 'token-missing', res
);
391 return res
.query
.tokens
[ type
+ 'token' ];
393 // Clear promise. Do not cache errors.
394 delete promiseGroup
[ type
+ 'Token' ];
396 // Let caller handle the error code
397 return $.Deferred().rejectWith( this, arguments
);
399 // Attach abort handler
400 .promise( { abort
: apiPromise
.abort
} );
402 // Store deferred now so that we can use it again even if it isn't ready yet
403 promiseGroup
[ type
+ 'Token' ] = d
;
410 * Indicate that the cached token for a certain action of the API is bad.
412 * Call this if you get a 'badtoken' error when using the token returned by #getToken.
413 * You may also want to use #postWithToken instead, which invalidates bad cached tokens
416 * @param {string} type Token type
419 badToken: function ( type
) {
420 var promiseGroup
= promises
[ this.defaults
.ajax
.url
];
422 type
= mapLegacyToken( type
);
423 if ( promiseGroup
) {
424 delete promiseGroup
[ type
+ 'Token' ];
432 * Very incomplete and outdated list of errors we might receive from the API. Do not use.
433 * @deprecated since 1.29
436 // occurs when POST aborted
437 // jQuery 1.4 can't distinguish abort or lost connection from 200 OK + empty result
443 // really a warning, but we treat it like an error
447 // upload succeeded, but no image info.
448 // this is probably impossible, but might as well check for it
450 // remote errors, defined in API
458 'copyuploaddisabled',
464 'filetype-banned-type',
467 'verification-error',
474 'fileexists-shared-forbidden',
480 // Stash-specific errors - expanded
483 'stashedfilenotfound',
491 mw
.log
.deprecate( mw
.Api
, 'errors', mw
.Api
.errors
, null, 'mw.Api.errors' );
496 * Very incomplete and outdated list of warnings we might receive from the API. Do not use.
497 * @deprecated since 1.29
503 mw
.log
.deprecate( mw
.Api
, 'warnings', mw
.Api
.warnings
, null, 'mw.Api.warnings' );
505 }( mediaWiki
, jQuery
) );