Merge "resourceloader: Simplify StringSet fallback"
[lhc/web/wiklou.git] / resources / src / mediawiki.api / index.js
1 ( function () {
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 * @property {boolean} defaultOptions.useUS Whether to use U+001F when joining multi-valued
13 * parameters (since 1.28). Default is true if ajax.url is not set, false otherwise for
14 * compatibility.
15 * @private
16 */
17 var defaultOptions = {
18 parameters: {
19 action: 'query',
20 format: 'json'
21 },
22 ajax: {
23 url: mw.util.wikiScript( 'api' ),
24 timeout: 30 * 1000, // 30 seconds
25 dataType: 'json'
26 }
27 },
28
29 // Keyed by ajax url and symbolic name for the individual request
30 promises = {};
31
32 function mapLegacyToken( action ) {
33 // Legacy types for backward-compatibility with API action=tokens.
34 var csrfActions = [
35 'edit',
36 'delete',
37 'protect',
38 'move',
39 'block',
40 'unblock',
41 'email',
42 'import',
43 'options'
44 ];
45 if ( csrfActions.indexOf( action ) !== -1 ) {
46 mw.track( 'mw.deprecate', 'apitoken_' + action );
47 mw.log.warn( 'Use of the "' + action + '" token is deprecated. Use "csrf" instead.' );
48 return 'csrf';
49 }
50 return action;
51 }
52
53 // Pre-populate with fake ajax promises to save http requests for tokens
54 // we already have on the page via the user.tokens module (T36733).
55 promises[ defaultOptions.ajax.url ] = {};
56 // eslint-disable-next-line no-restricted-properties
57 $.each( mw.user.tokens.get(), function ( key, value ) {
58 // This requires #getToken to use the same key as user.tokens.
59 // Format: token-type + "Token" (eg. csrfToken, patrolToken, watchToken).
60 promises[ defaultOptions.ajax.url ][ key ] = $.Deferred()
61 .resolve( value )
62 .promise( { abort: function () {} } );
63 } );
64
65 /**
66 * Constructor to create an object to interact with the API of a particular MediaWiki server.
67 * mw.Api objects represent the API of a particular MediaWiki server.
68 *
69 * var api = new mw.Api();
70 * api.get( {
71 * action: 'query',
72 * meta: 'userinfo'
73 * } ).done( function ( data ) {
74 * console.log( data );
75 * } );
76 *
77 * Since MW 1.25, multiple values for a parameter can be specified using an array:
78 *
79 * var api = new mw.Api();
80 * api.get( {
81 * action: 'query',
82 * meta: [ 'userinfo', 'siteinfo' ] // same effect as 'userinfo|siteinfo'
83 * } ).done( function ( data ) {
84 * console.log( data );
85 * } );
86 *
87 * Since MW 1.26, boolean values for a parameter can be specified directly. If the value is
88 * `false` or `undefined`, the parameter will be omitted from the request, as required by the API.
89 *
90 * @constructor
91 * @param {Object} [options] See #defaultOptions documentation above. Can also be overridden for
92 * each individual request by passing them to #get or #post (or directly #ajax) later on.
93 */
94 mw.Api = function ( options ) {
95 var defaults = $.extend( {}, options ),
96 setsUrl = options && options.ajax && options.ajax.url !== undefined;
97
98 defaults.parameters = $.extend( {}, defaultOptions.parameters, defaults.parameters );
99 defaults.ajax = $.extend( {}, defaultOptions.ajax, defaults.ajax );
100
101 // Force a string if we got a mw.Uri object
102 if ( setsUrl ) {
103 defaults.ajax.url = String( defaults.ajax.url );
104 }
105 if ( defaults.useUS === undefined ) {
106 defaults.useUS = !setsUrl;
107 }
108
109 this.defaults = defaults;
110 this.requests = [];
111 };
112
113 mw.Api.prototype = {
114 /**
115 * Abort all unfinished requests issued by this Api object.
116 *
117 * @method
118 */
119 abort: function () {
120 this.requests.forEach( function ( request ) {
121 if ( request ) {
122 request.abort();
123 }
124 } );
125 },
126
127 /**
128 * Perform API get request
129 *
130 * @param {Object} parameters
131 * @param {Object} [ajaxOptions]
132 * @return {jQuery.Promise}
133 */
134 get: function ( parameters, ajaxOptions ) {
135 ajaxOptions = ajaxOptions || {};
136 ajaxOptions.type = 'GET';
137 return this.ajax( parameters, ajaxOptions );
138 },
139
140 /**
141 * Perform API post request
142 *
143 * @param {Object} parameters
144 * @param {Object} [ajaxOptions]
145 * @return {jQuery.Promise}
146 */
147 post: function ( parameters, ajaxOptions ) {
148 ajaxOptions = ajaxOptions || {};
149 ajaxOptions.type = 'POST';
150 return this.ajax( parameters, ajaxOptions );
151 },
152
153 /**
154 * Massage parameters from the nice format we accept into a format suitable for the API.
155 *
156 * NOTE: A value of undefined/null in an array will be represented by Array#join()
157 * as the empty string. Should we filter silently? Warn? Leave as-is?
158 *
159 * @private
160 * @param {Object} parameters (modified in-place)
161 * @param {boolean} useUS Whether to use U+001F when joining multi-valued parameters.
162 */
163 preprocessParameters: function ( parameters, useUS ) {
164 var key;
165 // Handle common MediaWiki API idioms for passing parameters
166 for ( key in parameters ) {
167 // Multiple values are pipe-separated
168 if ( Array.isArray( parameters[ key ] ) ) {
169 if ( !useUS || parameters[ key ].join( '' ).indexOf( '|' ) === -1 ) {
170 parameters[ key ] = parameters[ key ].join( '|' );
171 } else {
172 parameters[ key ] = '\x1f' + parameters[ key ].join( '\x1f' );
173 }
174 } else if ( parameters[ key ] === false || parameters[ key ] === undefined ) {
175 // Boolean values are only false when not given at all
176 delete parameters[ key ];
177 }
178 }
179 },
180
181 /**
182 * Perform the API call.
183 *
184 * @param {Object} parameters
185 * @param {Object} [ajaxOptions]
186 * @return {jQuery.Promise} Done: API response data and the jqXHR object.
187 * Fail: Error code
188 */
189 ajax: function ( parameters, ajaxOptions ) {
190 var token, requestIndex,
191 api = this,
192 apiDeferred = $.Deferred(),
193 xhr, key, formData;
194
195 parameters = $.extend( {}, this.defaults.parameters, parameters );
196 ajaxOptions = $.extend( {}, this.defaults.ajax, ajaxOptions );
197
198 // Ensure that token parameter is last (per [[mw:API:Edit#Token]]).
199 if ( parameters.token ) {
200 token = parameters.token;
201 delete parameters.token;
202 }
203
204 this.preprocessParameters( parameters, this.defaults.useUS );
205
206 // If multipart/form-data has been requested and emulation is possible, emulate it
207 if (
208 ajaxOptions.type === 'POST' &&
209 window.FormData &&
210 ajaxOptions.contentType === 'multipart/form-data'
211 ) {
212
213 formData = new FormData();
214
215 for ( key in parameters ) {
216 formData.append( key, parameters[ key ] );
217 }
218 // If we extracted a token parameter, add it back in.
219 if ( token ) {
220 formData.append( 'token', token );
221 }
222
223 ajaxOptions.data = formData;
224
225 // Prevent jQuery from mangling our FormData object
226 ajaxOptions.processData = false;
227 // Prevent jQuery from overriding the Content-Type header
228 ajaxOptions.contentType = false;
229 } else {
230 // This works because jQuery accepts data as a query string or as an Object
231 ajaxOptions.data = $.param( parameters );
232 // If we extracted a token parameter, add it back in.
233 if ( token ) {
234 ajaxOptions.data += '&token=' + encodeURIComponent( token );
235 }
236
237 // Depending on server configuration, MediaWiki may forbid periods in URLs, due to an IE 6
238 // XSS bug. So let's escape them here. See WebRequest::checkUrlExtension() and T30235.
239 ajaxOptions.data = ajaxOptions.data.replace( /\./g, '%2E' );
240
241 if ( ajaxOptions.contentType === 'multipart/form-data' ) {
242 // We were asked to emulate but can't, so drop the Content-Type header, otherwise
243 // it'll be wrong and the server will fail to decode the POST body
244 delete ajaxOptions.contentType;
245 }
246 }
247
248 // Make the AJAX request
249 xhr = $.ajax( ajaxOptions )
250 // If AJAX fails, reject API call with error code 'http'
251 // and details in second argument.
252 .fail( function ( xhr, textStatus, exception ) {
253 apiDeferred.reject( 'http', {
254 xhr: xhr,
255 textStatus: textStatus,
256 exception: exception
257 } );
258 } )
259 // AJAX success just means "200 OK" response, also check API error codes
260 .done( function ( result, textStatus, jqXHR ) {
261 var code;
262 if ( result === undefined || result === null || result === '' ) {
263 apiDeferred.reject( 'ok-but-empty',
264 'OK response but empty result (check HTTP headers?)',
265 result,
266 jqXHR
267 );
268 } else if ( result.error ) {
269 // errorformat=bc
270 code = result.error.code === undefined ? 'unknown' : result.error.code;
271 apiDeferred.reject( code, result, result, jqXHR );
272 } else if ( result.errors ) {
273 // errorformat!=bc
274 code = result.errors[ 0 ].code === undefined ? 'unknown' : result.errors[ 0 ].code;
275 apiDeferred.reject( code, result, result, jqXHR );
276 } else {
277 apiDeferred.resolve( result, jqXHR );
278 }
279 } );
280
281 requestIndex = this.requests.length;
282 this.requests.push( xhr );
283 xhr.always( function () {
284 api.requests[ requestIndex ] = null;
285 } );
286 // Return the Promise
287 return apiDeferred.promise( { abort: xhr.abort } ).fail( function ( code, details ) {
288 if ( !( code === 'http' && details && details.textStatus === 'abort' ) ) {
289 mw.log( 'mw.Api error: ', code, details );
290 }
291 } );
292 },
293
294 /**
295 * Post to API with specified type of token. If we have no token, get one and try to post.
296 * If we have a cached token try using that, and if it fails, blank out the
297 * cached token and start over. For example to change an user option you could do:
298 *
299 * new mw.Api().postWithToken( 'csrf', {
300 * action: 'options',
301 * optionname: 'gender',
302 * optionvalue: 'female'
303 * } );
304 *
305 * @param {string} tokenType The name of the token, like options or edit.
306 * @param {Object} params API parameters
307 * @param {Object} [ajaxOptions]
308 * @return {jQuery.Promise} See #post
309 * @since 1.22
310 */
311 postWithToken: function ( tokenType, params, ajaxOptions ) {
312 var api = this,
313 abortedPromise = $.Deferred().reject( 'http',
314 { textStatus: 'abort', exception: 'abort' } ).promise(),
315 abortable,
316 aborted;
317
318 return api.getToken( tokenType, params.assert ).then( function ( token ) {
319 params.token = token;
320 // Request was aborted while token request was running, but we
321 // don't want to unnecessarily abort token requests, so abort
322 // a fake request instead
323 if ( aborted ) {
324 return abortedPromise;
325 }
326
327 return ( abortable = api.post( params, ajaxOptions ) ).catch(
328 // Error handler
329 function ( code ) {
330 if ( code === 'badtoken' ) {
331 api.badToken( tokenType );
332 // Try again, once
333 params.token = undefined;
334 abortable = null;
335 return api.getToken( tokenType, params.assert ).then( function ( token ) {
336 params.token = token;
337 if ( aborted ) {
338 return abortedPromise;
339 }
340
341 return ( abortable = api.post( params, ajaxOptions ) );
342 } );
343 }
344
345 // Let caller handle the error code
346 return $.Deferred().rejectWith( this, arguments );
347 }
348 );
349 } ).promise( { abort: function () {
350 if ( abortable ) {
351 abortable.abort();
352 } else {
353 aborted = true;
354 }
355 } } );
356 },
357
358 /**
359 * Get a token for a certain action from the API.
360 *
361 * The assert parameter is only for internal use by #postWithToken.
362 *
363 * @since 1.22
364 * @param {string} type Token type
365 * @param {string} [assert]
366 * @return {jQuery.Promise} Received token.
367 */
368 getToken: function ( type, assert ) {
369 var apiPromise, promiseGroup, d, reject;
370 type = mapLegacyToken( type );
371 promiseGroup = promises[ this.defaults.ajax.url ];
372 d = promiseGroup && promiseGroup[ type + 'Token' ];
373
374 if ( !promiseGroup ) {
375 promiseGroup = promises[ this.defaults.ajax.url ] = {};
376 }
377
378 if ( !d ) {
379 apiPromise = this.get( {
380 action: 'query',
381 meta: 'tokens',
382 type: type,
383 assert: assert
384 } );
385 reject = function () {
386 // Clear promise. Do not cache errors.
387 delete promiseGroup[ type + 'Token' ];
388
389 // Let caller handle the error code
390 return $.Deferred().rejectWith( this, arguments );
391 };
392 d = apiPromise
393 .then( function ( res ) {
394 if ( !res.query ) {
395 return reject( 'query-missing', res );
396 }
397 // If token type is unknown, it is omitted from the response
398 if ( !res.query.tokens[ type + 'token' ] ) {
399 return $.Deferred().reject( 'token-missing', res );
400 }
401 return res.query.tokens[ type + 'token' ];
402 }, reject )
403 // Attach abort handler
404 .promise( { abort: apiPromise.abort } );
405
406 // Store deferred now so that we can use it again even if it isn't ready yet
407 promiseGroup[ type + 'Token' ] = d;
408 }
409
410 return d;
411 },
412
413 /**
414 * Indicate that the cached token for a certain action of the API is bad.
415 *
416 * Call this if you get a 'badtoken' error when using the token returned by #getToken.
417 * You may also want to use #postWithToken instead, which invalidates bad cached tokens
418 * automatically.
419 *
420 * @param {string} type Token type
421 * @since 1.26
422 */
423 badToken: function ( type ) {
424 var promiseGroup = promises[ this.defaults.ajax.url ];
425
426 type = mapLegacyToken( type );
427 if ( promiseGroup ) {
428 delete promiseGroup[ type + 'Token' ];
429 }
430 }
431 };
432
433 /**
434 * @static
435 * @property {Array}
436 * Very incomplete and outdated list of errors we might receive from the API. Do not use.
437 * @deprecated since 1.29
438 */
439 mw.Api.errors = [
440 // occurs when POST aborted
441 // jQuery 1.4 can't distinguish abort or lost connection from 200 OK + empty result
442 'ok-but-empty',
443
444 // timeout
445 'timeout',
446
447 // really a warning, but we treat it like an error
448 'duplicate',
449 'duplicate-archive',
450
451 // upload succeeded, but no image info.
452 // this is probably impossible, but might as well check for it
453 'noimageinfo',
454 // remote errors, defined in API
455 'uploaddisabled',
456 'nomodule',
457 'mustbeposted',
458 'badaccess-groups',
459 'missingresult',
460 'missingparam',
461 'invalid-file-key',
462 'copyuploaddisabled',
463 'mustbeloggedin',
464 'empty-file',
465 'file-too-large',
466 'filetype-missing',
467 'filetype-banned',
468 'filetype-banned-type',
469 'filename-tooshort',
470 'illegal-filename',
471 'verification-error',
472 'hookaborted',
473 'unknown-error',
474 'internal-error',
475 'overwrite',
476 'badtoken',
477 'fetchfileerror',
478 'fileexists-shared-forbidden',
479 'invalidtitle',
480 'notloggedin',
481 'autoblocked',
482 'blocked',
483
484 // Stash-specific errors - expanded
485 'stashfailed',
486 'stasherror',
487 'stashedfilenotfound',
488 'stashpathinvalid',
489 'stashfilestorage',
490 'stashzerolength',
491 'stashnotloggedin',
492 'stashwrongowner',
493 'stashnosuchfilekey'
494 ];
495 mw.log.deprecate( mw.Api, 'errors', mw.Api.errors, null, 'mw.Api.errors' );
496
497 /**
498 * @static
499 * @property {Array}
500 * Very incomplete and outdated list of warnings we might receive from the API. Do not use.
501 * @deprecated since 1.29
502 */
503 mw.Api.warnings = [
504 'duplicate',
505 'exists'
506 ];
507 mw.log.deprecate( mw.Api, 'warnings', mw.Api.warnings, null, 'mw.Api.warnings' );
508
509 }() );