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