1a9c1b555a3ec1382cb495a461f5e26f1a5e42ac
3 function getTokenType( action
) {
4 // Token types from `action=tokens` that need to be mapped to the 'csrf' token type for backward-compatibility.
5 var csrfActions
= [ 'block', 'delete', 'edit', 'email', 'import', 'move', 'options', 'protect', 'unblock' ];
6 return $.inArray( action
, csrfActions
) === -1 ? action
: 'csrf';
9 // We allow people to omit these default parameters from API requests
10 // there is very customizable error handling here, on a per-call basis
11 // wondering, would it be simpler to make it easy to clone the api object,
12 // change error handling, and use that instead?
13 var defaultOptions
= {
15 // Query parameters for API requests
21 // Ajax options for jQuery.ajax()
23 url
: mw
.util
.wikiScript( 'api' ),
25 timeout
: 30 * 1000, // 30 seconds
30 // Keyed by ajax url and symbolic name for the individual request
33 // Pre-populate with fake ajax promises to save http requests for tokens
34 // we already have on the page via the user.tokens module (bug 34733).
35 promises
[ defaultOptions
.ajax
.url
] = {};
36 $.each( mw
.user
.tokens
.get(), function ( key
, value
) {
37 // This requires #getToken to use the same key as user.tokens.
38 // Format: token-type + "Token" (eg. editToken, patrolToken, watchToken).
39 promises
[ defaultOptions
.ajax
.url
][ key
] = $.Deferred()
41 .promise( { abort: function () {} } );
45 * Constructor to create an object to interact with the API of a particular MediaWiki server.
46 * mw.Api objects represent the API of a particular MediaWiki server.
48 * TODO: Share API objects with exact same config.
50 * var api = new mw.Api();
54 * } ).done ( function ( data ) {
55 * console.log( data );
58 * Multiple values for a parameter can be specified using an array (since MW 1.25):
60 * var api = new mw.Api();
63 * meta: [ 'userinfo', 'siteinfo' ] // same effect as 'userinfo|siteinfo'
64 * } ).done ( function ( data ) {
65 * console.log( data );
71 * @param {Object} options See defaultOptions documentation above. Ajax options can also be
72 * overridden for each individual request to {@link jQuery#ajax} later on.
74 mw
.Api = function ( options
) {
76 if ( options
=== undefined ) {
80 // Force a string if we got a mw.Uri object
81 if ( options
.ajax
&& options
.ajax
.url
!== undefined ) {
82 options
.ajax
.url
= String( options
.ajax
.url
);
85 options
.parameters
= $.extend( {}, defaultOptions
.parameters
, options
.parameters
);
86 options
.ajax
= $.extend( {}, defaultOptions
.ajax
, options
.ajax
);
88 this.defaults
= options
;
94 * Perform API get request
96 * @param {Object} parameters
97 * @param {Object} [ajaxOptions]
98 * @return {jQuery.Promise}
100 get: function ( parameters
, ajaxOptions
) {
101 ajaxOptions
= ajaxOptions
|| {};
102 ajaxOptions
.type
= 'GET';
103 return this.ajax( parameters
, ajaxOptions
);
107 * Perform API post request
109 * TODO: Post actions for non-local hostnames will need proxy.
111 * @param {Object} parameters
112 * @param {Object} [ajaxOptions]
113 * @return {jQuery.Promise}
115 post: function ( parameters
, ajaxOptions
) {
116 ajaxOptions
= ajaxOptions
|| {};
117 ajaxOptions
.type
= 'POST';
118 return this.ajax( parameters
, ajaxOptions
);
122 * Perform the API call.
124 * @param {Object} parameters
125 * @param {Object} [ajaxOptions]
126 * @return {jQuery.Promise} Done: API response data and the jqXHR object.
129 ajax: function ( parameters
, ajaxOptions
) {
131 apiDeferred
= $.Deferred(),
134 parameters
= $.extend( {}, this.defaults
.parameters
, parameters
);
135 ajaxOptions
= $.extend( {}, this.defaults
.ajax
, ajaxOptions
);
137 // Ensure that token parameter is last (per [[mw:API:Edit#Token]]).
138 if ( parameters
.token
) {
139 token
= parameters
.token
;
140 delete parameters
.token
;
143 for ( key
in parameters
) {
144 if ( $.isArray( parameters
[key
] ) ) {
145 parameters
[key
] = parameters
[key
].join( '|' );
149 // If multipart/form-data has been requested and emulation is possible, emulate it
151 ajaxOptions
.type
=== 'POST' &&
153 ajaxOptions
.contentType
=== 'multipart/form-data'
156 formData
= new FormData();
158 for ( key
in parameters
) {
159 formData
.append( key
, parameters
[key
] );
161 // If we extracted a token parameter, add it back in.
163 formData
.append( 'token', token
);
166 ajaxOptions
.data
= formData
;
168 // Prevent jQuery from mangling our FormData object
169 ajaxOptions
.processData
= false;
170 // Prevent jQuery from overriding the Content-Type header
171 ajaxOptions
.contentType
= false;
173 // Some deployed MediaWiki >= 1.17 forbid periods in URLs, due to an IE XSS bug
174 // So let's escape them here. See bug #28235
175 // This works because jQuery accepts data as a query string or as an Object
176 ajaxOptions
.data
= $.param( parameters
).replace( /\./g, '%2E' );
178 // If we extracted a token parameter, add it back in.
180 ajaxOptions
.data
+= '&token=' + encodeURIComponent( token
);
183 if ( ajaxOptions
.contentType
=== 'multipart/form-data' ) {
184 // We were asked to emulate but can't, so drop the Content-Type header, otherwise
185 // it'll be wrong and the server will fail to decode the POST body
186 delete ajaxOptions
.contentType
;
190 // Make the AJAX request
191 xhr
= $.ajax( ajaxOptions
)
192 // If AJAX fails, reject API call with error code 'http'
193 // and details in second argument.
194 .fail( function ( xhr
, textStatus
, exception
) {
195 apiDeferred
.reject( 'http', {
197 textStatus
: textStatus
,
201 // AJAX success just means "200 OK" response, also check API error codes
202 .done( function ( result
, textStatus
, jqXHR
) {
203 if ( result
=== undefined || result
=== null || result
=== '' ) {
204 apiDeferred
.reject( 'ok-but-empty',
205 'OK response but empty result (check HTTP headers?)'
207 } else if ( result
.error
) {
208 var code
= result
.error
.code
=== undefined ? 'unknown' : result
.error
.code
;
209 apiDeferred
.reject( code
, result
);
211 apiDeferred
.resolve( result
, jqXHR
);
215 // Return the Promise
216 return apiDeferred
.promise( { abort
: xhr
.abort
} ).fail( function ( code
, details
) {
217 if ( !( code
=== 'http' && details
&& details
.textStatus
=== 'abort' ) ) {
218 mw
.log( 'mw.Api error: ', code
, details
);
224 * Post to API with specified type of token. If we have no token, get one and try to post.
225 * If we have a cached token try using that, and if it fails, blank out the
226 * cached token and start over. For example to change an user option you could do:
228 * new mw.Api().postWithToken( 'options', {
230 * optionname: 'gender',
231 * optionvalue: 'female'
234 * @param {string} tokenType The name of the token, like options or edit.
235 * @param {Object} params API parameters
236 * @param {Object} [ajaxOptions]
237 * @return {jQuery.Promise} See #post
240 postWithToken: function ( tokenType
, params
, ajaxOptions
) {
243 return api
.getToken( tokenType
, params
.assert
).then( function ( token
) {
244 params
.token
= token
;
245 return api
.post( params
, ajaxOptions
).then(
246 // If no error, return to caller as-is
250 if ( code
=== 'badtoken' ) {
252 promises
[ api
.defaults
.ajax
.url
][ tokenType
+ 'Token' ] =
253 params
.token
= undefined;
256 return api
.getToken( tokenType
, params
.assert
).then( function ( token
) {
257 params
.token
= token
;
258 return api
.post( params
, ajaxOptions
);
262 // Different error, pass on to let caller handle the error code
270 * Get a token for a certain action from the API.
272 * The assert parameter is only for internal use by postWithToken.
274 * @param {string} type Token type
275 * @return {jQuery.Promise}
276 * @return {Function} return.done
277 * @return {string} return.done.token Received token.
280 getToken: function ( action
, assert
) {
282 type
= getTokenType( action
),
283 promiseGroup
= promises
[ this.defaults
.ajax
.url
],
284 d
= promiseGroup
&& promiseGroup
[ action
+ 'Token' ];
287 apiPromise
= this.get( {
295 .then( function ( res
) {
296 // If token type is not available for this user,
297 // key '...token' is either missing or set to boolean false
298 if ( res
.query
&& res
.query
.tokens
&& res
.query
.tokens
[type
+ 'token'] ) {
299 return res
.query
.tokens
[type
+ 'token'];
302 return $.Deferred().reject( 'token-missing', res
);
304 // Clear promise. Do not cache errors.
305 delete promiseGroup
[ action
+ 'Token' ];
307 // Pass on to allow the caller to handle the error
310 // Attach abort handler
311 .promise( { abort
: apiPromise
.abort
} );
313 // Store deferred now so that we can use it again even if it isn't ready yet
314 if ( !promiseGroup
) {
315 promiseGroup
= promises
[ this.defaults
.ajax
.url
] = {};
317 promiseGroup
[ action
+ 'Token' ] = d
;
327 * List of errors we might receive from the API.
328 * For now, this just documents our expectation that there should be similar messages
332 // occurs when POST aborted
333 // jQuery 1.4 can't distinguish abort or lost connection from 200 OK + empty result
339 // really a warning, but we treat it like an error
343 // upload succeeded, but no image info.
344 // this is probably impossible, but might as well check for it
346 // remote errors, defined in API
354 'copyuploaddisabled',
360 'filetype-banned-type',
363 'verification-error',
370 'fileexists-shared-forbidden',
374 // Stash-specific errors - expanded
377 'stashedfilenotfound',
389 * List of warnings we might receive from the API.
390 * For now, this just documents our expectation that there should be similar messages
398 }( mediaWiki
, jQuery
) );