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 if ( $.inArray( action
, csrfActions
) !== -1 ) {
43 mw
.track( 'mw.deprecate', 'apitoken_' + action
);
44 mw
.log
.warn( 'Use of the "' + action
+ '" token is deprecated. Use "csrf" instead.' );
50 // Pre-populate with fake ajax promises to save http requests for tokens
51 // we already have on the page via the user.tokens module (bug 34733).
52 promises
[ defaultOptions
.ajax
.url
] = {};
53 $.each( mw
.user
.tokens
.get(), function ( key
, value
) {
54 // This requires #getToken to use the same key as user.tokens.
55 // Format: token-type + "Token" (eg. csrfToken, patrolToken, watchToken).
56 promises
[ defaultOptions
.ajax
.url
][ key
] = $.Deferred()
58 .promise( { abort: function () {} } );
62 * Constructor to create an object to interact with the API of a particular MediaWiki server.
63 * mw.Api objects represent the API of a particular MediaWiki server.
65 * var api = new mw.Api();
69 * } ).done( function ( data ) {
70 * console.log( data );
73 * Since MW 1.25, multiple values for a parameter can be specified using an array:
75 * var api = new mw.Api();
78 * meta: [ 'userinfo', 'siteinfo' ] // same effect as 'userinfo|siteinfo'
79 * } ).done( function ( data ) {
80 * console.log( data );
83 * Since MW 1.26, boolean values for a parameter can be specified directly. If the value is
84 * `false` or `undefined`, the parameter will be omitted from the request, as required by the API.
87 * @param {Object} [options] See #defaultOptions documentation above. Can also be overridden for
88 * each individual request by passing them to #get or #post (or directly #ajax) later on.
90 mw
.Api = function ( options
) {
91 options
= options
|| {};
93 // Force a string if we got a mw.Uri object
94 if ( options
.ajax
&& options
.ajax
.url
!== undefined ) {
95 options
.ajax
.url
= String( options
.ajax
.url
);
98 options
.parameters
= $.extend( {}, defaultOptions
.parameters
, options
.parameters
);
99 options
.ajax
= $.extend( {}, defaultOptions
.ajax
, options
.ajax
);
101 this.defaults
= options
;
107 * Abort all unfinished requests issued by this Api object.
112 $.each( this.requests
, function ( index
, request
) {
120 * Perform API get request
122 * @param {Object} parameters
123 * @param {Object} [ajaxOptions]
124 * @return {jQuery.Promise}
126 get: function ( parameters
, ajaxOptions
) {
127 ajaxOptions
= ajaxOptions
|| {};
128 ajaxOptions
.type
= 'GET';
129 return this.ajax( parameters
, ajaxOptions
);
133 * Perform API post request
135 * @param {Object} parameters
136 * @param {Object} [ajaxOptions]
137 * @return {jQuery.Promise}
139 post: function ( parameters
, ajaxOptions
) {
140 ajaxOptions
= ajaxOptions
|| {};
141 ajaxOptions
.type
= 'POST';
142 return this.ajax( parameters
, ajaxOptions
);
146 * Massage parameters from the nice format we accept into a format suitable for the API.
149 * @param {Object} parameters (modified in-place)
151 preprocessParameters: function ( parameters
) {
153 // Handle common MediaWiki API idioms for passing parameters
154 for ( key
in parameters
) {
155 // Multiple values are pipe-separated
156 if ( $.isArray( parameters
[ key
] ) ) {
157 parameters
[ key
] = parameters
[ key
].join( '|' );
159 // Boolean values are only false when not given at all
160 if ( parameters
[ key
] === false || parameters
[ key
] === undefined ) {
161 delete parameters
[ key
];
167 * Perform the API call.
169 * @param {Object} parameters
170 * @param {Object} [ajaxOptions]
171 * @return {jQuery.Promise} Done: API response data and the jqXHR object.
174 ajax: function ( parameters
, ajaxOptions
) {
175 var token
, requestIndex
,
177 apiDeferred
= $.Deferred(),
180 parameters
= $.extend( {}, this.defaults
.parameters
, parameters
);
181 ajaxOptions
= $.extend( {}, this.defaults
.ajax
, ajaxOptions
);
183 // Ensure that token parameter is last (per [[mw:API:Edit#Token]]).
184 if ( parameters
.token
) {
185 token
= parameters
.token
;
186 delete parameters
.token
;
189 this.preprocessParameters( parameters
);
191 // If multipart/form-data has been requested and emulation is possible, emulate it
193 ajaxOptions
.type
=== 'POST' &&
195 ajaxOptions
.contentType
=== 'multipart/form-data'
198 formData
= new FormData();
200 for ( key
in parameters
) {
201 formData
.append( key
, parameters
[ key
] );
203 // If we extracted a token parameter, add it back in.
205 formData
.append( 'token', token
);
208 ajaxOptions
.data
= formData
;
210 // Prevent jQuery from mangling our FormData object
211 ajaxOptions
.processData
= false;
212 // Prevent jQuery from overriding the Content-Type header
213 ajaxOptions
.contentType
= false;
215 // Some deployed MediaWiki >= 1.17 forbid periods in URLs, due to an IE XSS bug
216 // So let's escape them here. See bug #28235
217 // This works because jQuery accepts data as a query string or as an Object
218 ajaxOptions
.data
= $.param( parameters
).replace( /\./g, '%2E' );
220 // If we extracted a token parameter, add it back in.
222 ajaxOptions
.data
+= '&token=' + encodeURIComponent( token
);
225 if ( ajaxOptions
.contentType
=== 'multipart/form-data' ) {
226 // We were asked to emulate but can't, so drop the Content-Type header, otherwise
227 // it'll be wrong and the server will fail to decode the POST body
228 delete ajaxOptions
.contentType
;
232 // Make the AJAX request
233 xhr
= $.ajax( ajaxOptions
)
234 // If AJAX fails, reject API call with error code 'http'
235 // and details in second argument.
236 .fail( function ( xhr
, textStatus
, exception
) {
237 apiDeferred
.reject( 'http', {
239 textStatus
: textStatus
,
243 // AJAX success just means "200 OK" response, also check API error codes
244 .done( function ( result
, textStatus
, jqXHR
) {
245 if ( result
=== undefined || result
=== null || result
=== '' ) {
246 apiDeferred
.reject( 'ok-but-empty',
247 'OK response but empty result (check HTTP headers?)',
251 } else if ( result
.error
) {
252 var code
= result
.error
.code
=== undefined ? 'unknown' : result
.error
.code
;
253 apiDeferred
.reject( code
, result
, result
, jqXHR
);
255 apiDeferred
.resolve( result
, jqXHR
);
259 requestIndex
= this.requests
.length
;
260 this.requests
.push( xhr
);
261 xhr
.always( function () {
262 api
.requests
[ requestIndex
] = null;
264 // Return the Promise
265 return apiDeferred
.promise( { abort
: xhr
.abort
} ).fail( function ( code
, details
) {
266 if ( !( code
=== 'http' && details
&& details
.textStatus
=== 'abort' ) ) {
267 mw
.log( 'mw.Api error: ', code
, details
);
273 * Post to API with specified type of token. If we have no token, get one and try to post.
274 * If we have a cached token try using that, and if it fails, blank out the
275 * cached token and start over. For example to change an user option you could do:
277 * new mw.Api().postWithToken( 'csrf', {
279 * optionname: 'gender',
280 * optionvalue: 'female'
283 * @param {string} tokenType The name of the token, like options or edit.
284 * @param {Object} params API parameters
285 * @param {Object} [ajaxOptions]
286 * @return {jQuery.Promise} See #post
289 postWithToken: function ( tokenType
, params
, ajaxOptions
) {
292 return api
.getToken( tokenType
, params
.assert
).then( function ( token
) {
293 params
.token
= token
;
294 return api
.post( params
, ajaxOptions
).then(
295 // If no error, return to caller as-is
299 if ( code
=== 'badtoken' ) {
300 api
.badToken( tokenType
);
302 params
.token
= undefined;
303 return api
.getToken( tokenType
, params
.assert
).then( function ( token
) {
304 params
.token
= token
;
305 return api
.post( params
, ajaxOptions
);
309 // Different error, pass on to let caller handle the error code
317 * Get a token for a certain action from the API.
319 * The assert parameter is only for internal use by #postWithToken.
322 * @param {string} type Token type
323 * @return {jQuery.Promise} Received token.
325 getToken: function ( type
, assert
) {
326 var apiPromise
, promiseGroup
, d
;
327 type
= mapLegacyToken( type
);
328 promiseGroup
= promises
[ this.defaults
.ajax
.url
];
329 d
= promiseGroup
&& promiseGroup
[ type
+ 'Token' ];
332 apiPromise
= this.get( {
339 .then( function ( res
) {
340 // If token type is unknown, it is omitted from the response
341 if ( !res
.query
.tokens
[ type
+ 'token' ] ) {
342 return $.Deferred().reject( 'token-missing', res
);
345 return res
.query
.tokens
[ type
+ 'token' ];
347 // Clear promise. Do not cache errors.
348 delete promiseGroup
[ type
+ 'Token' ];
350 // Pass on to allow the caller to handle the error
353 // Attach abort handler
354 .promise( { abort
: apiPromise
.abort
} );
356 // Store deferred now so that we can use it again even if it isn't ready yet
357 if ( !promiseGroup
) {
358 promiseGroup
= promises
[ this.defaults
.ajax
.url
] = {};
360 promiseGroup
[ type
+ 'Token' ] = d
;
367 * Indicate that the cached token for a certain action of the API is bad.
369 * Call this if you get a 'badtoken' error when using the token returned by #getToken.
370 * You may also want to use #postWithToken instead, which invalidates bad cached tokens
373 * @param {string} type Token type
376 badToken: function ( type
) {
377 var promiseGroup
= promises
[ this.defaults
.ajax
.url
];
379 type
= mapLegacyToken( type
);
380 if ( promiseGroup
) {
381 delete promiseGroup
[ type
+ 'Token' ];
389 * List of errors we might receive from the API.
390 * For now, this just documents our expectation that there should be similar messages
394 // occurs when POST aborted
395 // jQuery 1.4 can't distinguish abort or lost connection from 200 OK + empty result
401 // really a warning, but we treat it like an error
405 // upload succeeded, but no image info.
406 // this is probably impossible, but might as well check for it
408 // remote errors, defined in API
416 'copyuploaddisabled',
422 'filetype-banned-type',
425 'verification-error',
432 'fileexists-shared-forbidden',
436 // Stash-specific errors - expanded
439 'stashedfilenotfound',
451 * List of warnings we might receive from the API.
452 * For now, this just documents our expectation that there should be similar messages
460 }( mediaWiki
, jQuery
) );