1a9c1b555a3ec1382cb495a461f5e26f1a5e42ac
[lhc/web/wiklou.git] / resources / src / mediawiki.api / mediawiki.api.js
1 ( function ( mw, $ ) {
2
3 function getTokenType( action ) {
4 // Token types from `action=tokens` that need to be mapped to the 'csrf' token type for backward-compatibility.
5 var csrfActions = [ 'block', 'delete', 'edit', 'email', 'import', 'move', 'options', 'protect', 'unblock' ];
6 return $.inArray( action, csrfActions ) === -1 ? action : 'csrf';
7 }
8
9 // We allow people to omit these default parameters from API requests
10 // there is very customizable error handling here, on a per-call basis
11 // wondering, would it be simpler to make it easy to clone the api object,
12 // change error handling, and use that instead?
13 var defaultOptions = {
14
15 // Query parameters for API requests
16 parameters: {
17 action: 'query',
18 format: 'json'
19 },
20
21 // Ajax options for jQuery.ajax()
22 ajax: {
23 url: mw.util.wikiScript( 'api' ),
24
25 timeout: 30 * 1000, // 30 seconds
26
27 dataType: 'json'
28 }
29 },
30 // Keyed by ajax url and symbolic name for the individual request
31 promises = {};
32
33 // Pre-populate with fake ajax promises to save http requests for tokens
34 // we already have on the page via the user.tokens module (bug 34733).
35 promises[ defaultOptions.ajax.url ] = {};
36 $.each( mw.user.tokens.get(), function ( key, value ) {
37 // This requires #getToken to use the same key as user.tokens.
38 // Format: token-type + "Token" (eg. editToken, patrolToken, watchToken).
39 promises[ defaultOptions.ajax.url ][ key ] = $.Deferred()
40 .resolve( value )
41 .promise( { abort: function () {} } );
42 } );
43
44 /**
45 * Constructor to create an object to interact with the API of a particular MediaWiki server.
46 * mw.Api objects represent the API of a particular MediaWiki server.
47 *
48 * TODO: Share API objects with exact same config.
49 *
50 * var api = new mw.Api();
51 * api.get( {
52 * action: 'query',
53 * meta: 'userinfo'
54 * } ).done ( function ( data ) {
55 * console.log( data );
56 * } );
57 *
58 * Multiple values for a parameter can be specified using an array (since MW 1.25):
59 *
60 * var api = new mw.Api();
61 * api.get( {
62 * action: 'query',
63 * meta: [ 'userinfo', 'siteinfo' ] // same effect as 'userinfo|siteinfo'
64 * } ).done ( function ( data ) {
65 * console.log( data );
66 * } );
67 *
68 * @class
69 *
70 * @constructor
71 * @param {Object} options See defaultOptions documentation above. Ajax options can also be
72 * overridden for each individual request to {@link jQuery#ajax} later on.
73 */
74 mw.Api = function ( options ) {
75
76 if ( options === undefined ) {
77 options = {};
78 }
79
80 // Force a string if we got a mw.Uri object
81 if ( options.ajax && options.ajax.url !== undefined ) {
82 options.ajax.url = String( options.ajax.url );
83 }
84
85 options.parameters = $.extend( {}, defaultOptions.parameters, options.parameters );
86 options.ajax = $.extend( {}, defaultOptions.ajax, options.ajax );
87
88 this.defaults = options;
89 };
90
91 mw.Api.prototype = {
92
93 /**
94 * Perform API get request
95 *
96 * @param {Object} parameters
97 * @param {Object} [ajaxOptions]
98 * @return {jQuery.Promise}
99 */
100 get: function ( parameters, ajaxOptions ) {
101 ajaxOptions = ajaxOptions || {};
102 ajaxOptions.type = 'GET';
103 return this.ajax( parameters, ajaxOptions );
104 },
105
106 /**
107 * Perform API post request
108 *
109 * TODO: Post actions for non-local hostnames will need proxy.
110 *
111 * @param {Object} parameters
112 * @param {Object} [ajaxOptions]
113 * @return {jQuery.Promise}
114 */
115 post: function ( parameters, ajaxOptions ) {
116 ajaxOptions = ajaxOptions || {};
117 ajaxOptions.type = 'POST';
118 return this.ajax( parameters, ajaxOptions );
119 },
120
121 /**
122 * Perform the API call.
123 *
124 * @param {Object} parameters
125 * @param {Object} [ajaxOptions]
126 * @return {jQuery.Promise} Done: API response data and the jqXHR object.
127 * Fail: Error code
128 */
129 ajax: function ( parameters, ajaxOptions ) {
130 var token,
131 apiDeferred = $.Deferred(),
132 xhr, key, formData;
133
134 parameters = $.extend( {}, this.defaults.parameters, parameters );
135 ajaxOptions = $.extend( {}, this.defaults.ajax, ajaxOptions );
136
137 // Ensure that token parameter is last (per [[mw:API:Edit#Token]]).
138 if ( parameters.token ) {
139 token = parameters.token;
140 delete parameters.token;
141 }
142
143 for ( key in parameters ) {
144 if ( $.isArray( parameters[key] ) ) {
145 parameters[key] = parameters[key].join( '|' );
146 }
147 }
148
149 // If multipart/form-data has been requested and emulation is possible, emulate it
150 if (
151 ajaxOptions.type === 'POST' &&
152 window.FormData &&
153 ajaxOptions.contentType === 'multipart/form-data'
154 ) {
155
156 formData = new FormData();
157
158 for ( key in parameters ) {
159 formData.append( key, parameters[key] );
160 }
161 // If we extracted a token parameter, add it back in.
162 if ( token ) {
163 formData.append( 'token', token );
164 }
165
166 ajaxOptions.data = formData;
167
168 // Prevent jQuery from mangling our FormData object
169 ajaxOptions.processData = false;
170 // Prevent jQuery from overriding the Content-Type header
171 ajaxOptions.contentType = false;
172 } else {
173 // Some deployed MediaWiki >= 1.17 forbid periods in URLs, due to an IE XSS bug
174 // So let's escape them here. See bug #28235
175 // This works because jQuery accepts data as a query string or as an Object
176 ajaxOptions.data = $.param( parameters ).replace( /\./g, '%2E' );
177
178 // If we extracted a token parameter, add it back in.
179 if ( token ) {
180 ajaxOptions.data += '&token=' + encodeURIComponent( token );
181 }
182
183 if ( ajaxOptions.contentType === 'multipart/form-data' ) {
184 // We were asked to emulate but can't, so drop the Content-Type header, otherwise
185 // it'll be wrong and the server will fail to decode the POST body
186 delete ajaxOptions.contentType;
187 }
188 }
189
190 // Make the AJAX request
191 xhr = $.ajax( ajaxOptions )
192 // If AJAX fails, reject API call with error code 'http'
193 // and details in second argument.
194 .fail( function ( xhr, textStatus, exception ) {
195 apiDeferred.reject( 'http', {
196 xhr: xhr,
197 textStatus: textStatus,
198 exception: exception
199 } );
200 } )
201 // AJAX success just means "200 OK" response, also check API error codes
202 .done( function ( result, textStatus, jqXHR ) {
203 if ( result === undefined || result === null || result === '' ) {
204 apiDeferred.reject( 'ok-but-empty',
205 'OK response but empty result (check HTTP headers?)'
206 );
207 } else if ( result.error ) {
208 var code = result.error.code === undefined ? 'unknown' : result.error.code;
209 apiDeferred.reject( code, result );
210 } else {
211 apiDeferred.resolve( result, jqXHR );
212 }
213 } );
214
215 // Return the Promise
216 return apiDeferred.promise( { abort: xhr.abort } ).fail( function ( code, details ) {
217 if ( !( code === 'http' && details && details.textStatus === 'abort' ) ) {
218 mw.log( 'mw.Api error: ', code, details );
219 }
220 } );
221 },
222
223 /**
224 * Post to API with specified type of token. If we have no token, get one and try to post.
225 * If we have a cached token try using that, and if it fails, blank out the
226 * cached token and start over. For example to change an user option you could do:
227 *
228 * new mw.Api().postWithToken( 'options', {
229 * action: 'options',
230 * optionname: 'gender',
231 * optionvalue: 'female'
232 * } );
233 *
234 * @param {string} tokenType The name of the token, like options or edit.
235 * @param {Object} params API parameters
236 * @param {Object} [ajaxOptions]
237 * @return {jQuery.Promise} See #post
238 * @since 1.22
239 */
240 postWithToken: function ( tokenType, params, ajaxOptions ) {
241 var api = this;
242
243 return api.getToken( tokenType, params.assert ).then( function ( token ) {
244 params.token = token;
245 return api.post( params, ajaxOptions ).then(
246 // If no error, return to caller as-is
247 null,
248 // Error handler
249 function ( code ) {
250 if ( code === 'badtoken' ) {
251 // Clear from cache
252 promises[ api.defaults.ajax.url ][ tokenType + 'Token' ] =
253 params.token = undefined;
254
255 // Try again, once
256 return api.getToken( tokenType, params.assert ).then( function ( token ) {
257 params.token = token;
258 return api.post( params, ajaxOptions );
259 } );
260 }
261
262 // Different error, pass on to let caller handle the error code
263 return this;
264 }
265 );
266 } );
267 },
268
269 /**
270 * Get a token for a certain action from the API.
271 *
272 * The assert parameter is only for internal use by postWithToken.
273 *
274 * @param {string} type Token type
275 * @return {jQuery.Promise}
276 * @return {Function} return.done
277 * @return {string} return.done.token Received token.
278 * @since 1.22
279 */
280 getToken: function ( action, assert ) {
281 var apiPromise,
282 type = getTokenType( action ),
283 promiseGroup = promises[ this.defaults.ajax.url ],
284 d = promiseGroup && promiseGroup[ action + 'Token' ];
285
286 if ( !d ) {
287 apiPromise = this.get( {
288 action: 'query',
289 meta: 'tokens',
290 type: type,
291 assert: assert
292 } );
293
294 d = apiPromise
295 .then( function ( res ) {
296 // If token type is not available for this user,
297 // key '...token' is either missing or set to boolean false
298 if ( res.query && res.query.tokens && res.query.tokens[type + 'token'] ) {
299 return res.query.tokens[type + 'token'];
300 }
301
302 return $.Deferred().reject( 'token-missing', res );
303 }, function () {
304 // Clear promise. Do not cache errors.
305 delete promiseGroup[ action + 'Token' ];
306
307 // Pass on to allow the caller to handle the error
308 return this;
309 } )
310 // Attach abort handler
311 .promise( { abort: apiPromise.abort } );
312
313 // Store deferred now so that we can use it again even if it isn't ready yet
314 if ( !promiseGroup ) {
315 promiseGroup = promises[ this.defaults.ajax.url ] = {};
316 }
317 promiseGroup[ action + 'Token' ] = d;
318 }
319
320 return d;
321 }
322 };
323
324 /**
325 * @static
326 * @property {Array}
327 * List of errors we might receive from the API.
328 * For now, this just documents our expectation that there should be similar messages
329 * available.
330 */
331 mw.Api.errors = [
332 // occurs when POST aborted
333 // jQuery 1.4 can't distinguish abort or lost connection from 200 OK + empty result
334 'ok-but-empty',
335
336 // timeout
337 'timeout',
338
339 // really a warning, but we treat it like an error
340 'duplicate',
341 'duplicate-archive',
342
343 // upload succeeded, but no image info.
344 // this is probably impossible, but might as well check for it
345 'noimageinfo',
346 // remote errors, defined in API
347 'uploaddisabled',
348 'nomodule',
349 'mustbeposted',
350 'badaccess-groups',
351 'missingresult',
352 'missingparam',
353 'invalid-file-key',
354 'copyuploaddisabled',
355 'mustbeloggedin',
356 'empty-file',
357 'file-too-large',
358 'filetype-missing',
359 'filetype-banned',
360 'filetype-banned-type',
361 'filename-tooshort',
362 'illegal-filename',
363 'verification-error',
364 'hookaborted',
365 'unknown-error',
366 'internal-error',
367 'overwrite',
368 'badtoken',
369 'fetchfileerror',
370 'fileexists-shared-forbidden',
371 'invalidtitle',
372 'notloggedin',
373
374 // Stash-specific errors - expanded
375 'stashfailed',
376 'stasherror',
377 'stashedfilenotfound',
378 'stashpathinvalid',
379 'stashfilestorage',
380 'stashzerolength',
381 'stashnotloggedin',
382 'stashwrongowner',
383 'stashnosuchfilekey'
384 ];
385
386 /**
387 * @static
388 * @property {Array}
389 * List of warnings 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.warnings = [
394 'duplicate',
395 'exists'
396 ];
397
398 }( mediaWiki, jQuery ) );