mediawiki.api: Add #badToken for invalidating bad cached tokens
[lhc/web/wiklou.git] / resources / src / mediawiki.api / mediawiki.api.js
1 ( function ( mw, $ ) {
2
3 // We allow people to omit these default parameters from API requests
4 // there is very customizable error handling here, on a per-call basis
5 // wondering, would it be simpler to make it easy to clone the api object,
6 // change error handling, and use that instead?
7 var defaultOptions = {
8
9 // Query parameters for API requests
10 parameters: {
11 action: 'query',
12 format: 'json'
13 },
14
15 // Ajax options for jQuery.ajax()
16 ajax: {
17 url: mw.util.wikiScript( 'api' ),
18
19 timeout: 30 * 1000, // 30 seconds
20
21 dataType: 'json'
22 }
23 },
24 // Keyed by ajax url and symbolic name for the individual request
25 promises = {};
26
27 // Pre-populate with fake ajax promises to save http requests for tokens
28 // we already have on the page via the user.tokens module (bug 34733).
29 promises[ defaultOptions.ajax.url ] = {};
30 $.each( mw.user.tokens.get(), function ( key, value ) {
31 // This requires #getToken to use the same key as user.tokens.
32 // Format: token-type + "Token" (eg. editToken, patrolToken, watchToken).
33 promises[ defaultOptions.ajax.url ][ key ] = $.Deferred()
34 .resolve( value )
35 .promise( { abort: function () {} } );
36 } );
37
38 /**
39 * Constructor to create an object to interact with the API of a particular MediaWiki server.
40 * mw.Api objects represent the API of a particular MediaWiki server.
41 *
42 * TODO: Share API objects with exact same config.
43 *
44 * var api = new mw.Api();
45 * api.get( {
46 * action: 'query',
47 * meta: 'userinfo'
48 * } ).done ( function ( data ) {
49 * console.log( data );
50 * } );
51 *
52 * Multiple values for a parameter can be specified using an array (since MW 1.25):
53 *
54 * var api = new mw.Api();
55 * api.get( {
56 * action: 'query',
57 * meta: [ 'userinfo', 'siteinfo' ] // same effect as 'userinfo|siteinfo'
58 * } ).done ( function ( data ) {
59 * console.log( data );
60 * } );
61 *
62 * @class
63 *
64 * @constructor
65 * @param {Object} options See defaultOptions documentation above. Ajax options can also be
66 * overridden for each individual request to {@link jQuery#ajax} later on.
67 */
68 mw.Api = function ( options ) {
69
70 if ( options === undefined ) {
71 options = {};
72 }
73
74 // Force a string if we got a mw.Uri object
75 if ( options.ajax && options.ajax.url !== undefined ) {
76 options.ajax.url = String( options.ajax.url );
77 }
78
79 options.parameters = $.extend( {}, defaultOptions.parameters, options.parameters );
80 options.ajax = $.extend( {}, defaultOptions.ajax, options.ajax );
81
82 this.defaults = options;
83 };
84
85 mw.Api.prototype = {
86
87 /**
88 * Perform API get request
89 *
90 * @param {Object} parameters
91 * @param {Object} [ajaxOptions]
92 * @return {jQuery.Promise}
93 */
94 get: function ( parameters, ajaxOptions ) {
95 ajaxOptions = ajaxOptions || {};
96 ajaxOptions.type = 'GET';
97 return this.ajax( parameters, ajaxOptions );
98 },
99
100 /**
101 * Perform API post request
102 *
103 * TODO: Post actions for non-local hostnames will need proxy.
104 *
105 * @param {Object} parameters
106 * @param {Object} [ajaxOptions]
107 * @return {jQuery.Promise}
108 */
109 post: function ( parameters, ajaxOptions ) {
110 ajaxOptions = ajaxOptions || {};
111 ajaxOptions.type = 'POST';
112 return this.ajax( parameters, ajaxOptions );
113 },
114
115 /**
116 * Perform the API call.
117 *
118 * @param {Object} parameters
119 * @param {Object} [ajaxOptions]
120 * @return {jQuery.Promise} Done: API response data and the jqXHR object.
121 * Fail: Error code
122 */
123 ajax: function ( parameters, ajaxOptions ) {
124 var token,
125 apiDeferred = $.Deferred(),
126 xhr, key, formData;
127
128 parameters = $.extend( {}, this.defaults.parameters, parameters );
129 ajaxOptions = $.extend( {}, this.defaults.ajax, ajaxOptions );
130
131 // Ensure that token parameter is last (per [[mw:API:Edit#Token]]).
132 if ( parameters.token ) {
133 token = parameters.token;
134 delete parameters.token;
135 }
136
137 for ( key in parameters ) {
138 if ( $.isArray( parameters[key] ) ) {
139 parameters[key] = parameters[key].join( '|' );
140 }
141 }
142
143 // If multipart/form-data has been requested and emulation is possible, emulate it
144 if (
145 ajaxOptions.type === 'POST' &&
146 window.FormData &&
147 ajaxOptions.contentType === 'multipart/form-data'
148 ) {
149
150 formData = new FormData();
151
152 for ( key in parameters ) {
153 formData.append( key, parameters[key] );
154 }
155 // If we extracted a token parameter, add it back in.
156 if ( token ) {
157 formData.append( 'token', token );
158 }
159
160 ajaxOptions.data = formData;
161
162 // Prevent jQuery from mangling our FormData object
163 ajaxOptions.processData = false;
164 // Prevent jQuery from overriding the Content-Type header
165 ajaxOptions.contentType = false;
166 } else {
167 // Some deployed MediaWiki >= 1.17 forbid periods in URLs, due to an IE XSS bug
168 // So let's escape them here. See bug #28235
169 // This works because jQuery accepts data as a query string or as an Object
170 ajaxOptions.data = $.param( parameters ).replace( /\./g, '%2E' );
171
172 // If we extracted a token parameter, add it back in.
173 if ( token ) {
174 ajaxOptions.data += '&token=' + encodeURIComponent( token );
175 }
176
177 if ( ajaxOptions.contentType === 'multipart/form-data' ) {
178 // We were asked to emulate but can't, so drop the Content-Type header, otherwise
179 // it'll be wrong and the server will fail to decode the POST body
180 delete ajaxOptions.contentType;
181 }
182 }
183
184 // Make the AJAX request
185 xhr = $.ajax( ajaxOptions )
186 // If AJAX fails, reject API call with error code 'http'
187 // and details in second argument.
188 .fail( function ( xhr, textStatus, exception ) {
189 apiDeferred.reject( 'http', {
190 xhr: xhr,
191 textStatus: textStatus,
192 exception: exception
193 } );
194 } )
195 // AJAX success just means "200 OK" response, also check API error codes
196 .done( function ( result, textStatus, jqXHR ) {
197 if ( result === undefined || result === null || result === '' ) {
198 apiDeferred.reject( 'ok-but-empty',
199 'OK response but empty result (check HTTP headers?)'
200 );
201 } else if ( result.error ) {
202 var code = result.error.code === undefined ? 'unknown' : result.error.code;
203 apiDeferred.reject( code, result );
204 } else {
205 apiDeferred.resolve( result, jqXHR );
206 }
207 } );
208
209 // Return the Promise
210 return apiDeferred.promise( { abort: xhr.abort } ).fail( function ( code, details ) {
211 if ( !( code === 'http' && details && details.textStatus === 'abort' ) ) {
212 mw.log( 'mw.Api error: ', code, details );
213 }
214 } );
215 },
216
217 /**
218 * Post to API with specified type of token. If we have no token, get one and try to post.
219 * If we have a cached token try using that, and if it fails, blank out the
220 * cached token and start over. For example to change an user option you could do:
221 *
222 * new mw.Api().postWithToken( 'options', {
223 * action: 'options',
224 * optionname: 'gender',
225 * optionvalue: 'female'
226 * } );
227 *
228 * @param {string} tokenType The name of the token, like options or edit.
229 * @param {Object} params API parameters
230 * @param {Object} [ajaxOptions]
231 * @return {jQuery.Promise} See #post
232 * @since 1.22
233 */
234 postWithToken: function ( tokenType, params, ajaxOptions ) {
235 var api = this;
236
237 return api.getToken( tokenType, params.assert ).then( function ( token ) {
238 params.token = token;
239 return api.post( params, ajaxOptions ).then(
240 // If no error, return to caller as-is
241 null,
242 // Error handler
243 function ( code ) {
244 if ( code === 'badtoken' ) {
245 api.badToken( tokenType );
246 // Try again, once
247 params.token = undefined;
248 return api.getToken( tokenType, params.assert ).then( function ( token ) {
249 params.token = token;
250 return api.post( params, ajaxOptions );
251 } );
252 }
253
254 // Different error, pass on to let caller handle the error code
255 return this;
256 }
257 );
258 } );
259 },
260
261 /**
262 * Get a token for a certain action from the API.
263 *
264 * The assert parameter is only for internal use by postWithToken.
265 *
266 * @param {string} type Token type
267 * @return {jQuery.Promise}
268 * @return {Function} return.done
269 * @return {string} return.done.token Received token.
270 * @since 1.22
271 */
272 getToken: function ( type, assert ) {
273 var apiPromise,
274 promiseGroup = promises[ this.defaults.ajax.url ],
275 d = promiseGroup && promiseGroup[ type + 'Token' ];
276
277 if ( !d ) {
278 apiPromise = this.get( { action: 'tokens', type: type, assert: assert } );
279
280 d = apiPromise
281 .then( function ( data ) {
282 if ( data.tokens && data.tokens[type + 'token'] ) {
283 return data.tokens[type + 'token'];
284 }
285
286 // If token type is not available for this user,
287 // key '...token' is either missing or set to boolean false
288 return $.Deferred().reject( 'token-missing', data );
289 }, function () {
290 // Clear promise. Do not cache errors.
291 delete promiseGroup[ type + 'Token' ];
292 // Pass on to allow the caller to handle the error
293 return this;
294 } )
295 // Attach abort handler
296 .promise( { abort: apiPromise.abort } );
297
298 // Store deferred now so that we can use it again even if it isn't ready yet
299 if ( !promiseGroup ) {
300 promiseGroup = promises[ this.defaults.ajax.url ] = {};
301 }
302 promiseGroup[ type + 'Token' ] = d;
303 }
304
305 return d;
306 },
307
308 /**
309 * Indicate that the cached token for a certain action of the API is bad.
310 *
311 * Call this if you get a 'badtoken' error when using the token returned by #getToken.
312 * You may also want to use #postWithToken instead, which invalidates bad cached tokens
313 * automatically.
314 *
315 * @param {string} type Token type
316 * @since 1.26
317 */
318 badToken: function ( type ) {
319 var promiseGroup = promises[ this.defaults.ajax.url ];
320 if ( promiseGroup ) {
321 delete promiseGroup[ type + 'Token' ];
322 }
323 }
324 };
325
326 /**
327 * @static
328 * @property {Array}
329 * List of errors we might receive from the API.
330 * For now, this just documents our expectation that there should be similar messages
331 * available.
332 */
333 mw.Api.errors = [
334 // occurs when POST aborted
335 // jQuery 1.4 can't distinguish abort or lost connection from 200 OK + empty result
336 'ok-but-empty',
337
338 // timeout
339 'timeout',
340
341 // really a warning, but we treat it like an error
342 'duplicate',
343 'duplicate-archive',
344
345 // upload succeeded, but no image info.
346 // this is probably impossible, but might as well check for it
347 'noimageinfo',
348 // remote errors, defined in API
349 'uploaddisabled',
350 'nomodule',
351 'mustbeposted',
352 'badaccess-groups',
353 'missingresult',
354 'missingparam',
355 'invalid-file-key',
356 'copyuploaddisabled',
357 'mustbeloggedin',
358 'empty-file',
359 'file-too-large',
360 'filetype-missing',
361 'filetype-banned',
362 'filetype-banned-type',
363 'filename-tooshort',
364 'illegal-filename',
365 'verification-error',
366 'hookaborted',
367 'unknown-error',
368 'internal-error',
369 'overwrite',
370 'badtoken',
371 'fetchfileerror',
372 'fileexists-shared-forbidden',
373 'invalidtitle',
374 'notloggedin',
375
376 // Stash-specific errors - expanded
377 'stashfailed',
378 'stasherror',
379 'stashedfilenotfound',
380 'stashpathinvalid',
381 'stashfilestorage',
382 'stashzerolength',
383 'stashnotloggedin',
384 'stashwrongowner',
385 'stashnosuchfilekey'
386 ];
387
388 /**
389 * @static
390 * @property {Array}
391 * List of warnings we might receive from the API.
392 * For now, this just documents our expectation that there should be similar messages
393 * available.
394 */
395 mw.Api.warnings = [
396 'duplicate',
397 'exists'
398 ];
399
400 }( mediaWiki, jQuery ) );