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