Revert "Split editcascadeprotected permission from protect permission"
[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 // This works because jQuery accepts data as a query string or as an Object
216 ajaxOptions.data = $.param( parameters );
217 // If we extracted a token parameter, add it back in.
218 if ( token ) {
219 ajaxOptions.data += '&token=' + encodeURIComponent( token );
220 }
221
222 // Depending on server configuration, MediaWiki may forbid periods in URLs, due to an IE 6
223 // XSS bug. So let's escape them here. See WebRequest::checkUrlExtension() and T30235.
224 ajaxOptions.data = ajaxOptions.data.replace( /\./g, '%2E' );
225
226 if ( ajaxOptions.contentType === 'multipart/form-data' ) {
227 // We were asked to emulate but can't, so drop the Content-Type header, otherwise
228 // it'll be wrong and the server will fail to decode the POST body
229 delete ajaxOptions.contentType;
230 }
231 }
232
233 // Make the AJAX request
234 xhr = $.ajax( ajaxOptions )
235 // If AJAX fails, reject API call with error code 'http'
236 // and details in second argument.
237 .fail( function ( xhr, textStatus, exception ) {
238 apiDeferred.reject( 'http', {
239 xhr: xhr,
240 textStatus: textStatus,
241 exception: exception
242 } );
243 } )
244 // AJAX success just means "200 OK" response, also check API error codes
245 .done( function ( result, textStatus, jqXHR ) {
246 if ( result === undefined || result === null || result === '' ) {
247 apiDeferred.reject( 'ok-but-empty',
248 'OK response but empty result (check HTTP headers?)',
249 result,
250 jqXHR
251 );
252 } else if ( result.error ) {
253 var code = result.error.code === undefined ? 'unknown' : result.error.code;
254 apiDeferred.reject( code, result, result, jqXHR );
255 } else {
256 apiDeferred.resolve( result, jqXHR );
257 }
258 } );
259
260 requestIndex = this.requests.length;
261 this.requests.push( xhr );
262 xhr.always( function () {
263 api.requests[ requestIndex ] = null;
264 } );
265 // Return the Promise
266 return apiDeferred.promise( { abort: xhr.abort } ).fail( function ( code, details ) {
267 if ( !( code === 'http' && details && details.textStatus === 'abort' ) ) {
268 mw.log( 'mw.Api error: ', code, details );
269 }
270 } );
271 },
272
273 /**
274 * Post to API with specified type of token. If we have no token, get one and try to post.
275 * If we have a cached token try using that, and if it fails, blank out the
276 * cached token and start over. For example to change an user option you could do:
277 *
278 * new mw.Api().postWithToken( 'csrf', {
279 * action: 'options',
280 * optionname: 'gender',
281 * optionvalue: 'female'
282 * } );
283 *
284 * @param {string} tokenType The name of the token, like options or edit.
285 * @param {Object} params API parameters
286 * @param {Object} [ajaxOptions]
287 * @return {jQuery.Promise} See #post
288 * @since 1.22
289 */
290 postWithToken: function ( tokenType, params, ajaxOptions ) {
291 var api = this;
292
293 return api.getToken( tokenType, params.assert ).then( function ( token ) {
294 params.token = token;
295 return api.post( params, ajaxOptions ).then(
296 // If no error, return to caller as-is
297 null,
298 // Error handler
299 function ( code ) {
300 if ( code === 'badtoken' ) {
301 api.badToken( tokenType );
302 // Try again, once
303 params.token = undefined;
304 return api.getToken( tokenType, params.assert ).then( function ( token ) {
305 params.token = token;
306 return api.post( params, ajaxOptions );
307 } );
308 }
309
310 // Different error, pass on to let caller handle the error code
311 return this;
312 }
313 );
314 } );
315 },
316
317 /**
318 * Get a token for a certain action from the API.
319 *
320 * The assert parameter is only for internal use by #postWithToken.
321 *
322 * @since 1.22
323 * @param {string} type Token type
324 * @return {jQuery.Promise} Received token.
325 */
326 getToken: function ( type, assert ) {
327 var apiPromise, promiseGroup, d;
328 type = mapLegacyToken( type );
329 promiseGroup = promises[ this.defaults.ajax.url ];
330 d = promiseGroup && promiseGroup[ type + 'Token' ];
331
332 if ( !d ) {
333 apiPromise = this.get( {
334 action: 'query',
335 meta: 'tokens',
336 type: type,
337 assert: assert
338 } );
339 d = apiPromise
340 .then( function ( res ) {
341 // If token type is unknown, it is omitted from the response
342 if ( !res.query.tokens[ type + 'token' ] ) {
343 return $.Deferred().reject( 'token-missing', res );
344 }
345
346 return res.query.tokens[ type + 'token' ];
347 }, function () {
348 // Clear promise. Do not cache errors.
349 delete promiseGroup[ type + 'Token' ];
350
351 // Pass on to allow the caller to handle the error
352 return this;
353 } )
354 // Attach abort handler
355 .promise( { abort: apiPromise.abort } );
356
357 // Store deferred now so that we can use it again even if it isn't ready yet
358 if ( !promiseGroup ) {
359 promiseGroup = promises[ this.defaults.ajax.url ] = {};
360 }
361 promiseGroup[ type + 'Token' ] = d;
362 }
363
364 return d;
365 },
366
367 /**
368 * Indicate that the cached token for a certain action of the API is bad.
369 *
370 * Call this if you get a 'badtoken' error when using the token returned by #getToken.
371 * You may also want to use #postWithToken instead, which invalidates bad cached tokens
372 * automatically.
373 *
374 * @param {string} type Token type
375 * @since 1.26
376 */
377 badToken: function ( type ) {
378 var promiseGroup = promises[ this.defaults.ajax.url ];
379
380 type = mapLegacyToken( type );
381 if ( promiseGroup ) {
382 delete promiseGroup[ type + 'Token' ];
383 }
384 }
385 };
386
387 /**
388 * @static
389 * @property {Array}
390 * List of errors we might receive from the API.
391 * For now, this just documents our expectation that there should be similar messages
392 * available.
393 */
394 mw.Api.errors = [
395 // occurs when POST aborted
396 // jQuery 1.4 can't distinguish abort or lost connection from 200 OK + empty result
397 'ok-but-empty',
398
399 // timeout
400 'timeout',
401
402 // really a warning, but we treat it like an error
403 'duplicate',
404 'duplicate-archive',
405
406 // upload succeeded, but no image info.
407 // this is probably impossible, but might as well check for it
408 'noimageinfo',
409 // remote errors, defined in API
410 'uploaddisabled',
411 'nomodule',
412 'mustbeposted',
413 'badaccess-groups',
414 'missingresult',
415 'missingparam',
416 'invalid-file-key',
417 'copyuploaddisabled',
418 'mustbeloggedin',
419 'empty-file',
420 'file-too-large',
421 'filetype-missing',
422 'filetype-banned',
423 'filetype-banned-type',
424 'filename-tooshort',
425 'illegal-filename',
426 'verification-error',
427 'hookaborted',
428 'unknown-error',
429 'internal-error',
430 'overwrite',
431 'badtoken',
432 'fetchfileerror',
433 'fileexists-shared-forbidden',
434 'invalidtitle',
435 'notloggedin',
436 'autoblocked',
437 'blocked',
438
439 // Stash-specific errors - expanded
440 'stashfailed',
441 'stasherror',
442 'stashedfilenotfound',
443 'stashpathinvalid',
444 'stashfilestorage',
445 'stashzerolength',
446 'stashnotloggedin',
447 'stashwrongowner',
448 'stashnosuchfilekey'
449 ];
450
451 /**
452 * @static
453 * @property {Array}
454 * List of warnings we might receive from the API.
455 * For now, this just documents our expectation that there should be similar messages
456 * available.
457 */
458 mw.Api.warnings = [
459 'duplicate',
460 'exists'
461 ];
462
463 }( mediaWiki, jQuery ) );