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