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