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 (bug 34733).
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 $.each( this.requests
, function ( index
, 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.
154 * @param {Object} parameters (modified in-place)
155 * @param {boolean} useUS Whether to use U+001F when joining multi-valued parameters.
157 preprocessParameters: function ( parameters
, useUS
) {
159 // Handle common MediaWiki API idioms for passing parameters
160 for ( key
in parameters
) {
161 // Multiple values are pipe-separated
162 if ( $.isArray( parameters
[ key
] ) ) {
163 if ( !useUS
|| parameters
[ key
].join( '' ).indexOf( '|' ) === -1 ) {
164 parameters
[ key
] = parameters
[ key
].join( '|' );
166 parameters
[ key
] = '\x1f' + parameters
[ key
].join( '\x1f' );
169 // Boolean values are only false when not given at all
170 if ( parameters
[ key
] === false || parameters
[ key
] === undefined ) {
171 delete parameters
[ key
];
177 * Perform the API call.
179 * @param {Object} parameters
180 * @param {Object} [ajaxOptions]
181 * @return {jQuery.Promise} Done: API response data and the jqXHR object.
184 ajax: function ( parameters
, ajaxOptions
) {
185 var token
, requestIndex
,
187 apiDeferred
= $.Deferred(),
190 parameters
= $.extend( {}, this.defaults
.parameters
, parameters
);
191 ajaxOptions
= $.extend( {}, this.defaults
.ajax
, ajaxOptions
);
193 // Ensure that token parameter is last (per [[mw:API:Edit#Token]]).
194 if ( parameters
.token
) {
195 token
= parameters
.token
;
196 delete parameters
.token
;
199 this.preprocessParameters( parameters
, this.defaults
.useUS
);
201 // If multipart/form-data has been requested and emulation is possible, emulate it
203 ajaxOptions
.type
=== 'POST' &&
205 ajaxOptions
.contentType
=== 'multipart/form-data'
208 formData
= new FormData();
210 for ( key
in parameters
) {
211 formData
.append( key
, parameters
[ key
] );
213 // If we extracted a token parameter, add it back in.
215 formData
.append( 'token', token
);
218 ajaxOptions
.data
= formData
;
220 // Prevent jQuery from mangling our FormData object
221 ajaxOptions
.processData
= false;
222 // Prevent jQuery from overriding the Content-Type header
223 ajaxOptions
.contentType
= false;
225 // This works because jQuery accepts data as a query string or as an Object
226 ajaxOptions
.data
= $.param( parameters
);
227 // If we extracted a token parameter, add it back in.
229 ajaxOptions
.data
+= '&token=' + encodeURIComponent( token
);
232 // Depending on server configuration, MediaWiki may forbid periods in URLs, due to an IE 6
233 // XSS bug. So let's escape them here. See WebRequest::checkUrlExtension() and T30235.
234 ajaxOptions
.data
= ajaxOptions
.data
.replace( /\./g, '%2E' );
236 if ( ajaxOptions
.contentType
=== 'multipart/form-data' ) {
237 // We were asked to emulate but can't, so drop the Content-Type header, otherwise
238 // it'll be wrong and the server will fail to decode the POST body
239 delete ajaxOptions
.contentType
;
243 // Make the AJAX request
244 xhr
= $.ajax( ajaxOptions
)
245 // If AJAX fails, reject API call with error code 'http'
246 // and details in second argument.
247 .fail( function ( xhr
, textStatus
, exception
) {
248 apiDeferred
.reject( 'http', {
250 textStatus
: textStatus
,
254 // AJAX success just means "200 OK" response, also check API error codes
255 .done( function ( result
, textStatus
, jqXHR
) {
257 if ( result
=== undefined || result
=== null || result
=== '' ) {
258 apiDeferred
.reject( 'ok-but-empty',
259 'OK response but empty result (check HTTP headers?)',
263 } else if ( result
.error
) {
265 code
= result
.error
.code
=== undefined ? 'unknown' : result
.error
.code
;
266 apiDeferred
.reject( code
, result
, result
, jqXHR
);
267 } else if ( result
.errors
) {
269 code
= result
.errors
[ 0 ].code
=== undefined ? 'unknown' : result
.errors
[ 0 ].code
;
270 apiDeferred
.reject( code
, result
, result
, jqXHR
);
272 apiDeferred
.resolve( result
, jqXHR
);
276 requestIndex
= this.requests
.length
;
277 this.requests
.push( xhr
);
278 xhr
.always( function () {
279 api
.requests
[ requestIndex
] = null;
281 // Return the Promise
282 return apiDeferred
.promise( { abort
: xhr
.abort
} ).fail( function ( code
, details
) {
283 if ( !( code
=== 'http' && details
&& details
.textStatus
=== 'abort' ) ) {
284 mw
.log( 'mw.Api error: ', code
, details
);
290 * Post to API with specified type of token. If we have no token, get one and try to post.
291 * If we have a cached token try using that, and if it fails, blank out the
292 * cached token and start over. For example to change an user option you could do:
294 * new mw.Api().postWithToken( 'csrf', {
296 * optionname: 'gender',
297 * optionvalue: 'female'
300 * @param {string} tokenType The name of the token, like options or edit.
301 * @param {Object} params API parameters
302 * @param {Object} [ajaxOptions]
303 * @return {jQuery.Promise} See #post
306 postWithToken: function ( tokenType
, params
, ajaxOptions
) {
308 abortedPromise
= $.Deferred().reject( 'http',
309 { textStatus
: 'abort', exception
: 'abort' } ).promise(),
313 return api
.getToken( tokenType
, params
.assert
).then( function ( token
) {
314 params
.token
= token
;
315 // Request was aborted while token request was running, but we
316 // don't want to unnecessarily abort token requests, so abort
317 // a fake request instead
319 return abortedPromise
;
322 return ( abortable
= api
.post( params
, ajaxOptions
) ).then(
323 // If no error, return to caller as-is
327 if ( code
=== 'badtoken' ) {
328 api
.badToken( tokenType
);
330 params
.token
= undefined;
332 return api
.getToken( tokenType
, params
.assert
).then( function ( token
) {
333 params
.token
= token
;
335 return abortedPromise
;
338 return ( abortable
= api
.post( params
, ajaxOptions
) );
342 // Let caller handle the error code
343 return $.Deferred().rejectWith( this, arguments
);
346 } ).promise( { abort: function () {
356 * Get a token for a certain action from the API.
358 * The assert parameter is only for internal use by #postWithToken.
361 * @param {string} type Token type
362 * @param {string} [assert]
363 * @return {jQuery.Promise} Received token.
365 getToken: function ( type
, assert
) {
366 var apiPromise
, promiseGroup
, d
;
367 type
= mapLegacyToken( type
);
368 promiseGroup
= promises
[ this.defaults
.ajax
.url
];
369 d
= promiseGroup
&& promiseGroup
[ type
+ 'Token' ];
371 if ( !promiseGroup
) {
372 promiseGroup
= promises
[ this.defaults
.ajax
.url
] = {};
376 apiPromise
= this.get( {
383 .then( function ( res
) {
384 // If token type is unknown, it is omitted from the response
385 if ( !res
.query
.tokens
[ type
+ 'token' ] ) {
386 return $.Deferred().reject( 'token-missing', res
);
389 return res
.query
.tokens
[ type
+ 'token' ];
391 // Clear promise. Do not cache errors.
392 delete promiseGroup
[ type
+ 'Token' ];
394 // Let caller handle the error code
395 return $.Deferred().rejectWith( this, arguments
);
397 // Attach abort handler
398 .promise( { abort
: apiPromise
.abort
} );
400 // Store deferred now so that we can use it again even if it isn't ready yet
401 promiseGroup
[ type
+ 'Token' ] = d
;
408 * Indicate that the cached token for a certain action of the API is bad.
410 * Call this if you get a 'badtoken' error when using the token returned by #getToken.
411 * You may also want to use #postWithToken instead, which invalidates bad cached tokens
414 * @param {string} type Token type
417 badToken: function ( type
) {
418 var promiseGroup
= promises
[ this.defaults
.ajax
.url
];
420 type
= mapLegacyToken( type
);
421 if ( promiseGroup
) {
422 delete promiseGroup
[ type
+ 'Token' ];
430 * Very incomplete and outdated list of errors we might receive from the API. Do not use.
431 * @deprecated since 1.29
434 // occurs when POST aborted
435 // jQuery 1.4 can't distinguish abort or lost connection from 200 OK + empty result
441 // really a warning, but we treat it like an error
445 // upload succeeded, but no image info.
446 // this is probably impossible, but might as well check for it
448 // remote errors, defined in API
456 'copyuploaddisabled',
462 'filetype-banned-type',
465 'verification-error',
472 'fileexists-shared-forbidden',
478 // Stash-specific errors - expanded
481 'stashedfilenotfound',
489 mw
.log
.deprecate( mw
.Api
, 'errors', mw
.Api
.errors
);
494 * Very incomplete and outdated list of warnings we might receive from the API. Do not use.
495 * @deprecated since 1.29
501 mw
.log
.deprecate( mw
.Api
, 'warnings', mw
.Api
.warnings
);
503 }( mediaWiki
, jQuery
) );