Merge "Use setMwGlobals in ApiEditPageTest"
[lhc/web/wiklou.git] / resources / 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 tokenCache = {};
25
26 /**
27 * Constructor to create an object to interact with the API of a particular MediaWiki server.
28 * mw.Api objects represent the API of a particular MediaWiki server.
29 *
30 * TODO: Share API objects with exact same config.
31 *
32 * var api = new mw.Api();
33 * api.get( {
34 * action: 'query',
35 * meta: 'userinfo'
36 * } ).done ( function ( data ) {
37 * console.log( data );
38 * } );
39 *
40 * @class
41 *
42 * @constructor
43 * @param {Object} options See defaultOptions documentation above. Ajax options can also be
44 * overridden for each individual request to {@link jQuery#ajax} later on.
45 */
46 mw.Api = function ( options ) {
47
48 if ( options === undefined ) {
49 options = {};
50 }
51
52 // Force toString if we got a mw.Uri object
53 if ( options.ajax && options.ajax.url !== undefined ) {
54 options.ajax.url = String( options.ajax.url );
55 }
56
57 options.parameters = $.extend( {}, defaultOptions.parameters, options.parameters );
58 options.ajax = $.extend( {}, defaultOptions.ajax, options.ajax );
59
60 this.defaults = options;
61 };
62
63 mw.Api.prototype = {
64
65 /**
66 * Normalize the ajax options for compatibility and/or convenience methods.
67 *
68 * @param {Object} [arg] An object contaning one or more of options.ajax.
69 * @return {Object} Normalized ajax options.
70 */
71 normalizeAjaxOptions: function ( arg ) {
72 // Arg argument is usually empty
73 // (before MW 1.20 it was used to pass ok callbacks)
74 var opts = arg || {};
75 // Options can also be a success callback handler
76 if ( typeof arg === 'function' ) {
77 opts = { ok: arg };
78 }
79 return opts;
80 },
81
82 /**
83 * Perform API get request
84 *
85 * @param {Object} parameters
86 * @param {Object|Function} [ajaxOptions]
87 * @return {jQuery.Promise}
88 */
89 get: function ( parameters, ajaxOptions ) {
90 ajaxOptions = this.normalizeAjaxOptions( ajaxOptions );
91 ajaxOptions.type = 'GET';
92 return this.ajax( parameters, ajaxOptions );
93 },
94
95 /**
96 * Perform API post request
97 *
98 * TODO: Post actions for non-local hostnames will need proxy.
99 *
100 * @param {Object} parameters
101 * @param {Object|Function} [ajaxOptions]
102 * @return {jQuery.Promise}
103 */
104 post: function ( parameters, ajaxOptions ) {
105 ajaxOptions = this.normalizeAjaxOptions( ajaxOptions );
106 ajaxOptions.type = 'POST';
107 return this.ajax( parameters, ajaxOptions );
108 },
109
110 /**
111 * Perform the API call.
112 *
113 * @param {Object} parameters
114 * @param {Object} [ajaxOptions]
115 * @return {jQuery.Promise} Done: API response data and the jqXHR object.
116 * Fail: Error code
117 */
118 ajax: function ( parameters, ajaxOptions ) {
119 var token,
120 apiDeferred = $.Deferred(),
121 msg = 'Use of mediawiki.api callback params is deprecated. Use the Promise instead.',
122 xhr;
123
124 parameters = $.extend( {}, this.defaults.parameters, parameters );
125 ajaxOptions = $.extend( {}, this.defaults.ajax, ajaxOptions );
126
127 // Ensure that token parameter is last (per [[mw:API:Edit#Token]]).
128 if ( parameters.token ) {
129 token = parameters.token;
130 delete parameters.token;
131 }
132 // Some deployed MediaWiki >= 1.17 forbid periods in URLs, due to an IE XSS bug
133 // So let's escape them here. See bug #28235
134 // This works because jQuery accepts data as a query string or as an Object
135 ajaxOptions.data = $.param( parameters ).replace( /\./g, '%2E' );
136
137 // If we extracted a token parameter, add it back in.
138 if ( token ) {
139 ajaxOptions.data += '&token=' + encodeURIComponent( token );
140 }
141
142 // Backwards compatibility: Before MediaWiki 1.20,
143 // callbacks were done with the 'ok' and 'err' property in ajaxOptions.
144 if ( ajaxOptions.ok ) {
145 mw.track( 'mw.deprecate', 'api.cbParam' );
146 mw.log.warn( msg );
147 apiDeferred.done( ajaxOptions.ok );
148 delete ajaxOptions.ok;
149 }
150 if ( ajaxOptions.err ) {
151 mw.track( 'mw.deprecate', 'api.cbParam' );
152 mw.log.warn( msg );
153 apiDeferred.fail( ajaxOptions.err );
154 delete ajaxOptions.err;
155 }
156
157 // Make the AJAX request
158 xhr = $.ajax( ajaxOptions )
159 // If AJAX fails, reject API call with error code 'http'
160 // and details in second argument.
161 .fail( function ( xhr, textStatus, exception ) {
162 apiDeferred.reject( 'http', {
163 xhr: xhr,
164 textStatus: textStatus,
165 exception: exception
166 } );
167 } )
168 // AJAX success just means "200 OK" response, also check API error codes
169 .done( function ( result, textStatus, jqXHR ) {
170 if ( result === undefined || result === null || result === '' ) {
171 apiDeferred.reject( 'ok-but-empty',
172 'OK response but empty result (check HTTP headers?)'
173 );
174 } else if ( result.error ) {
175 var code = result.error.code === undefined ? 'unknown' : result.error.code;
176 apiDeferred.reject( code, result );
177 } else {
178 apiDeferred.resolve( result, jqXHR );
179 }
180 } );
181
182 // Return the Promise
183 return apiDeferred.promise( { abort: xhr.abort } ).fail( function ( code, details ) {
184 mw.log( 'mw.Api error: ', code, details );
185 } );
186 },
187
188 /**
189 * Post to API with specified type of token. If we have no token, get one and try to post.
190 * If we have a cached token try using that, and if it fails, blank out the
191 * cached token and start over. For example to change an user option you could do:
192 *
193 * new mw.Api().postWithToken( 'options', {
194 * action: 'options',
195 * optionname: 'gender',
196 * optionvalue: 'female'
197 * } );
198 *
199 * @param {string} tokenType The name of the token, like options or edit.
200 * @param {Object} params API parameters
201 * @return {jQuery.Promise} See #post
202 */
203 postWithToken: function ( tokenType, params ) {
204 var api = this, hasOwn = tokenCache.hasOwnProperty;
205 if ( hasOwn.call( tokenCache, tokenType ) && tokenCache[tokenType] !== undefined ) {
206 params.token = tokenCache[tokenType];
207 return api.post( params ).then(
208 null,
209 function ( code ) {
210 if ( code === 'badtoken' ) {
211 // force a new token, clear any old one
212 tokenCache[tokenType] = params.token = undefined;
213 return api.post( params );
214 }
215 // Pass the promise forward, so the caller gets error codes
216 return this;
217 }
218 );
219 } else {
220 return api.getToken( tokenType ).then( function ( token ) {
221 tokenCache[tokenType] = params.token = token;
222 return api.post( params );
223 } );
224 }
225 },
226
227 /**
228 * Api helper to grab any token.
229 *
230 * @param {string} type Token type.
231 * @return {jQuery.Promise}
232 * @return {Function} return.done
233 * @return {string} return.done.token Received token.
234 */
235 getToken: function ( type ) {
236 var apiPromise,
237 d = $.Deferred();
238
239 apiPromise = this.get( {
240 action: 'tokens',
241 type: type
242 } )
243 .done( function ( data ) {
244 // If token type is not available for this user,
245 // key '...token' is missing or can contain Boolean false
246 if ( data.tokens && data.tokens[type + 'token'] ) {
247 d.resolve( data.tokens[type + 'token'] );
248 } else {
249 d.reject( 'token-missing', data );
250 }
251 } )
252 .fail( d.reject );
253
254 return d.promise( { abort: apiPromise.abort } );
255 }
256 };
257
258 /**
259 * @static
260 * @property {Array}
261 * List of errors we might receive from the API.
262 * For now, this just documents our expectation that there should be similar messages
263 * available.
264 */
265 mw.Api.errors = [
266 // occurs when POST aborted
267 // jQuery 1.4 can't distinguish abort or lost connection from 200 OK + empty result
268 'ok-but-empty',
269
270 // timeout
271 'timeout',
272
273 // really a warning, but we treat it like an error
274 'duplicate',
275 'duplicate-archive',
276
277 // upload succeeded, but no image info.
278 // this is probably impossible, but might as well check for it
279 'noimageinfo',
280 // remote errors, defined in API
281 'uploaddisabled',
282 'nomodule',
283 'mustbeposted',
284 'badaccess-groups',
285 'stashfailed',
286 'missingresult',
287 'missingparam',
288 'invalid-file-key',
289 'copyuploaddisabled',
290 'mustbeloggedin',
291 'empty-file',
292 'file-too-large',
293 'filetype-missing',
294 'filetype-banned',
295 'filetype-banned-type',
296 'filename-tooshort',
297 'illegal-filename',
298 'verification-error',
299 'hookaborted',
300 'unknown-error',
301 'internal-error',
302 'overwrite',
303 'badtoken',
304 'fetchfileerror',
305 'fileexists-shared-forbidden',
306 'invalidtitle',
307 'notloggedin'
308 ];
309
310 /**
311 * @static
312 * @property {Array}
313 * List of warnings we might receive from the API.
314 * For now, this just documents our expectation that there should be similar messages
315 * available.
316 */
317 mw.Api.warnings = [
318 'duplicate',
319 'exists'
320 ];
321
322 }( mediaWiki, jQuery ) );