Merge "Special:RC 'hidemajor' filter"
[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 (bug 34733).
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 $.each( this.requests, function ( index, 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 * @private
154 * @param {Object} parameters (modified in-place)
155 * @param {boolean} useUS Whether to use U+001F when joining multi-valued parameters.
156 */
157 preprocessParameters: function ( parameters, useUS ) {
158 var key;
159 // Handle common MediaWiki API idioms for passing parameters
160 for ( key in parameters ) {
161 // Multiple values are pipe-separated
162 if ( $.isArray( parameters[ key ] ) ) {
163 if ( !useUS || parameters[ key ].join( '' ).indexOf( '|' ) === -1 ) {
164 parameters[ key ] = parameters[ key ].join( '|' );
165 } else {
166 parameters[ key ] = '\x1f' + parameters[ key ].join( '\x1f' );
167 }
168 }
169 // Boolean values are only false when not given at all
170 if ( parameters[ key ] === false || parameters[ key ] === undefined ) {
171 delete parameters[ key ];
172 }
173 }
174 },
175
176 /**
177 * Perform the API call.
178 *
179 * @param {Object} parameters
180 * @param {Object} [ajaxOptions]
181 * @return {jQuery.Promise} Done: API response data and the jqXHR object.
182 * Fail: Error code
183 */
184 ajax: function ( parameters, ajaxOptions ) {
185 var token, requestIndex,
186 api = this,
187 apiDeferred = $.Deferred(),
188 xhr, key, formData;
189
190 parameters = $.extend( {}, this.defaults.parameters, parameters );
191 ajaxOptions = $.extend( {}, this.defaults.ajax, ajaxOptions );
192
193 // Ensure that token parameter is last (per [[mw:API:Edit#Token]]).
194 if ( parameters.token ) {
195 token = parameters.token;
196 delete parameters.token;
197 }
198
199 this.preprocessParameters( parameters, this.defaults.useUS );
200
201 // If multipart/form-data has been requested and emulation is possible, emulate it
202 if (
203 ajaxOptions.type === 'POST' &&
204 window.FormData &&
205 ajaxOptions.contentType === 'multipart/form-data'
206 ) {
207
208 formData = new FormData();
209
210 for ( key in parameters ) {
211 formData.append( key, parameters[ key ] );
212 }
213 // If we extracted a token parameter, add it back in.
214 if ( token ) {
215 formData.append( 'token', token );
216 }
217
218 ajaxOptions.data = formData;
219
220 // Prevent jQuery from mangling our FormData object
221 ajaxOptions.processData = false;
222 // Prevent jQuery from overriding the Content-Type header
223 ajaxOptions.contentType = false;
224 } else {
225 // This works because jQuery accepts data as a query string or as an Object
226 ajaxOptions.data = $.param( parameters );
227 // If we extracted a token parameter, add it back in.
228 if ( token ) {
229 ajaxOptions.data += '&token=' + encodeURIComponent( token );
230 }
231
232 // Depending on server configuration, MediaWiki may forbid periods in URLs, due to an IE 6
233 // XSS bug. So let's escape them here. See WebRequest::checkUrlExtension() and T30235.
234 ajaxOptions.data = ajaxOptions.data.replace( /\./g, '%2E' );
235
236 if ( ajaxOptions.contentType === 'multipart/form-data' ) {
237 // We were asked to emulate but can't, so drop the Content-Type header, otherwise
238 // it'll be wrong and the server will fail to decode the POST body
239 delete ajaxOptions.contentType;
240 }
241 }
242
243 // Make the AJAX request
244 xhr = $.ajax( ajaxOptions )
245 // If AJAX fails, reject API call with error code 'http'
246 // and details in second argument.
247 .fail( function ( xhr, textStatus, exception ) {
248 apiDeferred.reject( 'http', {
249 xhr: xhr,
250 textStatus: textStatus,
251 exception: exception
252 } );
253 } )
254 // AJAX success just means "200 OK" response, also check API error codes
255 .done( function ( result, textStatus, jqXHR ) {
256 var code;
257 if ( result === undefined || result === null || result === '' ) {
258 apiDeferred.reject( 'ok-but-empty',
259 'OK response but empty result (check HTTP headers?)',
260 result,
261 jqXHR
262 );
263 } else if ( result.error ) {
264 code = result.error.code === undefined ? 'unknown' : result.error.code;
265 apiDeferred.reject( code, result, result, jqXHR );
266 } else if ( result.errors ) {
267 code = result.errors[ 0 ].code === undefined ? 'unknown' : result.errors[ 0 ].code;
268 apiDeferred.reject( code, result, result, jqXHR );
269 } else {
270 apiDeferred.resolve( result, jqXHR );
271 }
272 } );
273
274 requestIndex = this.requests.length;
275 this.requests.push( xhr );
276 xhr.always( function () {
277 api.requests[ requestIndex ] = null;
278 } );
279 // Return the Promise
280 return apiDeferred.promise( { abort: xhr.abort } ).fail( function ( code, details ) {
281 if ( !( code === 'http' && details && details.textStatus === 'abort' ) ) {
282 mw.log( 'mw.Api error: ', code, details );
283 }
284 } );
285 },
286
287 /**
288 * Post to API with specified type of token. If we have no token, get one and try to post.
289 * If we have a cached token try using that, and if it fails, blank out the
290 * cached token and start over. For example to change an user option you could do:
291 *
292 * new mw.Api().postWithToken( 'csrf', {
293 * action: 'options',
294 * optionname: 'gender',
295 * optionvalue: 'female'
296 * } );
297 *
298 * @param {string} tokenType The name of the token, like options or edit.
299 * @param {Object} params API parameters
300 * @param {Object} [ajaxOptions]
301 * @return {jQuery.Promise} See #post
302 * @since 1.22
303 */
304 postWithToken: function ( tokenType, params, ajaxOptions ) {
305 var api = this,
306 abortedPromise = $.Deferred().reject( 'http',
307 { textStatus: 'abort', exception: 'abort' } ).promise(),
308 abortable,
309 aborted;
310
311 return api.getToken( tokenType, params.assert ).then( function ( token ) {
312 params.token = token;
313 // Request was aborted while token request was running, but we
314 // don't want to unnecessarily abort token requests, so abort
315 // a fake request instead
316 if ( aborted ) {
317 return abortedPromise;
318 }
319
320 return ( abortable = api.post( params, ajaxOptions ) ).then(
321 // If no error, return to caller as-is
322 null,
323 // Error handler
324 function ( code ) {
325 if ( code === 'badtoken' ) {
326 api.badToken( tokenType );
327 // Try again, once
328 params.token = undefined;
329 abortable = null;
330 return api.getToken( tokenType, params.assert ).then( function ( token ) {
331 params.token = token;
332 if ( aborted ) {
333 return abortedPromise;
334 }
335
336 return ( abortable = api.post( params, ajaxOptions ) );
337 } );
338 }
339
340 // Let caller handle the error code
341 return $.Deferred().rejectWith( this, arguments );
342 }
343 );
344 } ).promise( { abort: function () {
345 if ( abortable ) {
346 abortable.abort();
347 } else {
348 aborted = true;
349 }
350 } } );
351 },
352
353 /**
354 * Get a token for a certain action from the API.
355 *
356 * The assert parameter is only for internal use by #postWithToken.
357 *
358 * @since 1.22
359 * @param {string} type Token type
360 * @param {string} [assert]
361 * @return {jQuery.Promise} Received token.
362 */
363 getToken: function ( type, assert ) {
364 var apiPromise, promiseGroup, d;
365 type = mapLegacyToken( type );
366 promiseGroup = promises[ this.defaults.ajax.url ];
367 d = promiseGroup && promiseGroup[ type + 'Token' ];
368
369 if ( !promiseGroup ) {
370 promiseGroup = promises[ this.defaults.ajax.url ] = {};
371 }
372
373 if ( !d ) {
374 apiPromise = this.get( {
375 action: 'query',
376 meta: 'tokens',
377 type: type,
378 assert: assert
379 } );
380 d = apiPromise
381 .then( function ( res ) {
382 // If token type is unknown, it is omitted from the response
383 if ( !res.query.tokens[ type + 'token' ] ) {
384 return $.Deferred().reject( 'token-missing', res );
385 }
386
387 return res.query.tokens[ type + 'token' ];
388 }, function () {
389 // Clear promise. Do not cache errors.
390 delete promiseGroup[ type + 'Token' ];
391
392 // Let caller handle the error code
393 return $.Deferred().rejectWith( this, arguments );
394 } )
395 // Attach abort handler
396 .promise( { abort: apiPromise.abort } );
397
398 // Store deferred now so that we can use it again even if it isn't ready yet
399 promiseGroup[ type + 'Token' ] = d;
400 }
401
402 return d;
403 },
404
405 /**
406 * Indicate that the cached token for a certain action of the API is bad.
407 *
408 * Call this if you get a 'badtoken' error when using the token returned by #getToken.
409 * You may also want to use #postWithToken instead, which invalidates bad cached tokens
410 * automatically.
411 *
412 * @param {string} type Token type
413 * @since 1.26
414 */
415 badToken: function ( type ) {
416 var promiseGroup = promises[ this.defaults.ajax.url ];
417
418 type = mapLegacyToken( type );
419 if ( promiseGroup ) {
420 delete promiseGroup[ type + 'Token' ];
421 }
422 }
423 };
424
425 /**
426 * @static
427 * @property {Array}
428 * List of errors we might receive from the API.
429 * For now, this just documents our expectation that there should be similar messages
430 * available.
431 */
432 mw.Api.errors = [
433 // occurs when POST aborted
434 // jQuery 1.4 can't distinguish abort or lost connection from 200 OK + empty result
435 'ok-but-empty',
436
437 // timeout
438 'timeout',
439
440 // really a warning, but we treat it like an error
441 'duplicate',
442 'duplicate-archive',
443
444 // upload succeeded, but no image info.
445 // this is probably impossible, but might as well check for it
446 'noimageinfo',
447 // remote errors, defined in API
448 'uploaddisabled',
449 'nomodule',
450 'mustbeposted',
451 'badaccess-groups',
452 'missingresult',
453 'missingparam',
454 'invalid-file-key',
455 'copyuploaddisabled',
456 'mustbeloggedin',
457 'empty-file',
458 'file-too-large',
459 'filetype-missing',
460 'filetype-banned',
461 'filetype-banned-type',
462 'filename-tooshort',
463 'illegal-filename',
464 'verification-error',
465 'hookaborted',
466 'unknown-error',
467 'internal-error',
468 'overwrite',
469 'badtoken',
470 'fetchfileerror',
471 'fileexists-shared-forbidden',
472 'invalidtitle',
473 'notloggedin',
474 'autoblocked',
475 'blocked',
476
477 // Stash-specific errors - expanded
478 'stashfailed',
479 'stasherror',
480 'stashedfilenotfound',
481 'stashpathinvalid',
482 'stashfilestorage',
483 'stashzerolength',
484 'stashnotloggedin',
485 'stashwrongowner',
486 'stashnosuchfilekey'
487 ];
488
489 /**
490 * @static
491 * @property {Array}
492 * List of warnings we might receive from the API.
493 * For now, this just documents our expectation that there should be similar messages
494 * available.
495 */
496 mw.Api.warnings = [
497 'duplicate',
498 'exists'
499 ];
500
501 }( mediaWiki, jQuery ) );