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 // This works because jQuery accepts data as a query string or as an Object
216 ajaxOptions
.data
= $.param( parameters
);
217 // If we extracted a token parameter, add it back in.
219 ajaxOptions
.data
+= '&token=' + encodeURIComponent( token
);
222 // Depending on server configuration, MediaWiki may forbid periods in URLs, due to an IE 6
223 // XSS bug. So let's escape them here. See WebRequest::checkUrlExtension() and T30235.
224 ajaxOptions
.data
= ajaxOptions
.data
.replace( /\./g, '%2E' );
226 if ( ajaxOptions
.contentType
=== 'multipart/form-data' ) {
227 // We were asked to emulate but can't, so drop the Content-Type header, otherwise
228 // it'll be wrong and the server will fail to decode the POST body
229 delete ajaxOptions
.contentType
;
233 // Make the AJAX request
234 xhr
= $.ajax( ajaxOptions
)
235 // If AJAX fails, reject API call with error code 'http'
236 // and details in second argument.
237 .fail( function ( xhr
, textStatus
, exception
) {
238 apiDeferred
.reject( 'http', {
240 textStatus
: textStatus
,
244 // AJAX success just means "200 OK" response, also check API error codes
245 .done( function ( result
, textStatus
, jqXHR
) {
246 if ( result
=== undefined || result
=== null || result
=== '' ) {
247 apiDeferred
.reject( 'ok-but-empty',
248 'OK response but empty result (check HTTP headers?)',
252 } else if ( result
.error
) {
253 var code
= result
.error
.code
=== undefined ? 'unknown' : result
.error
.code
;
254 apiDeferred
.reject( code
, result
, result
, jqXHR
);
256 apiDeferred
.resolve( result
, jqXHR
);
260 requestIndex
= this.requests
.length
;
261 this.requests
.push( xhr
);
262 xhr
.always( function () {
263 api
.requests
[ requestIndex
] = null;
265 // Return the Promise
266 return apiDeferred
.promise( { abort
: xhr
.abort
} ).fail( function ( code
, details
) {
267 if ( !( code
=== 'http' && details
&& details
.textStatus
=== 'abort' ) ) {
268 mw
.log( 'mw.Api error: ', code
, details
);
274 * Post to API with specified type of token. If we have no token, get one and try to post.
275 * If we have a cached token try using that, and if it fails, blank out the
276 * cached token and start over. For example to change an user option you could do:
278 * new mw.Api().postWithToken( 'csrf', {
280 * optionname: 'gender',
281 * optionvalue: 'female'
284 * @param {string} tokenType The name of the token, like options or edit.
285 * @param {Object} params API parameters
286 * @param {Object} [ajaxOptions]
287 * @return {jQuery.Promise} See #post
290 postWithToken: function ( tokenType
, params
, ajaxOptions
) {
293 return api
.getToken( tokenType
, params
.assert
).then( function ( token
) {
294 params
.token
= token
;
295 return api
.post( params
, ajaxOptions
).then(
296 // If no error, return to caller as-is
300 if ( code
=== 'badtoken' ) {
301 api
.badToken( tokenType
);
303 params
.token
= undefined;
304 return api
.getToken( tokenType
, params
.assert
).then( function ( token
) {
305 params
.token
= token
;
306 return api
.post( params
, ajaxOptions
);
310 // Different error, pass on to let caller handle the error code
318 * Get a token for a certain action from the API.
320 * The assert parameter is only for internal use by #postWithToken.
323 * @param {string} type Token type
324 * @return {jQuery.Promise} Received token.
326 getToken: function ( type
, assert
) {
327 var apiPromise
, promiseGroup
, d
;
328 type
= mapLegacyToken( type
);
329 promiseGroup
= promises
[ this.defaults
.ajax
.url
];
330 d
= promiseGroup
&& promiseGroup
[ type
+ 'Token' ];
333 apiPromise
= this.get( {
340 .then( function ( res
) {
341 // If token type is unknown, it is omitted from the response
342 if ( !res
.query
.tokens
[ type
+ 'token' ] ) {
343 return $.Deferred().reject( 'token-missing', res
);
346 return res
.query
.tokens
[ type
+ 'token' ];
348 // Clear promise. Do not cache errors.
349 delete promiseGroup
[ type
+ 'Token' ];
351 // Pass on to allow the caller to handle the error
354 // Attach abort handler
355 .promise( { abort
: apiPromise
.abort
} );
357 // Store deferred now so that we can use it again even if it isn't ready yet
358 if ( !promiseGroup
) {
359 promiseGroup
= promises
[ this.defaults
.ajax
.url
] = {};
361 promiseGroup
[ type
+ 'Token' ] = d
;
368 * Indicate that the cached token for a certain action of the API is bad.
370 * Call this if you get a 'badtoken' error when using the token returned by #getToken.
371 * You may also want to use #postWithToken instead, which invalidates bad cached tokens
374 * @param {string} type Token type
377 badToken: function ( type
) {
378 var promiseGroup
= promises
[ this.defaults
.ajax
.url
];
380 type
= mapLegacyToken( type
);
381 if ( promiseGroup
) {
382 delete promiseGroup
[ type
+ 'Token' ];
390 * List of errors we might receive from the API.
391 * For now, this just documents our expectation that there should be similar messages
395 // occurs when POST aborted
396 // jQuery 1.4 can't distinguish abort or lost connection from 200 OK + empty result
402 // really a warning, but we treat it like an error
406 // upload succeeded, but no image info.
407 // this is probably impossible, but might as well check for it
409 // remote errors, defined in API
417 'copyuploaddisabled',
423 'filetype-banned-type',
426 'verification-error',
433 'fileexists-shared-forbidden',
437 // Stash-specific errors - expanded
440 'stashedfilenotfound',
452 * List of warnings we might receive from the API.
453 * For now, this just documents our expectation that there should be similar messages
461 }( mediaWiki
, jQuery
) );