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