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