Merge "Added a few more trx sanity checks to DatabaseBase"
[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. Fail: Error code
116 */
117 ajax: function ( parameters, ajaxOptions ) {
118 var token,
119 apiDeferred = $.Deferred(),
120 xhr;
121
122 parameters = $.extend( {}, this.defaults.parameters, parameters );
123 ajaxOptions = $.extend( {}, this.defaults.ajax, ajaxOptions );
124
125 // Ensure that token parameter is last (per [[mw:API:Edit#Token]]).
126 if ( parameters.token ) {
127 token = parameters.token;
128 delete parameters.token;
129 }
130 // Some deployed MediaWiki >= 1.17 forbid periods in URLs, due to an IE XSS bug
131 // So let's escape them here. See bug #28235
132 // This works because jQuery accepts data as a query string or as an Object
133 ajaxOptions.data = $.param( parameters ).replace( /\./g, '%2E' );
134
135 // If we extracted a token parameter, add it back in.
136 if ( token ) {
137 ajaxOptions.data += '&token=' + encodeURIComponent( token );
138 }
139
140 // Backwards compatibility: Before MediaWiki 1.20,
141 // callbacks were done with the 'ok' and 'err' property in ajaxOptions.
142 if ( ajaxOptions.ok ) {
143 apiDeferred.done( ajaxOptions.ok );
144 delete ajaxOptions.ok;
145 }
146 if ( ajaxOptions.err ) {
147 apiDeferred.fail( ajaxOptions.err );
148 delete ajaxOptions.err;
149 }
150
151 // Make the AJAX request
152 xhr = $.ajax( ajaxOptions )
153 // If AJAX fails, reject API call with error code 'http'
154 // and details in second argument.
155 .fail( function ( xhr, textStatus, exception ) {
156 apiDeferred.reject( 'http', {
157 xhr: xhr,
158 textStatus: textStatus,
159 exception: exception
160 } );
161 } )
162 // AJAX success just means "200 OK" response, also check API error codes
163 .done( function ( result ) {
164 if ( result === undefined || result === null || result === '' ) {
165 apiDeferred.reject( 'ok-but-empty',
166 'OK response but empty result (check HTTP headers?)'
167 );
168 } else if ( result.error ) {
169 var code = result.error.code === undefined ? 'unknown' : result.error.code;
170 apiDeferred.reject( code, result );
171 } else {
172 apiDeferred.resolve( result );
173 }
174 } );
175
176 // Return the Promise
177 return apiDeferred.promise( { abort: xhr.abort } ).fail( function ( code, details ) {
178 mw.log( 'mw.Api error: ', code, details );
179 } );
180 },
181
182 /**
183 * Post to API with specified type of token. If we have no token, get one and try to post.
184 * If we have a cached token try using that, and if it fails, blank out the
185 * cached token and start over. For example to change an user option you could do:
186 *
187 * new mw.Api().postWithToken( 'options', {
188 * action: 'options',
189 * optionname: 'gender',
190 * optionvalue: 'female'
191 * } );
192 *
193 * @param {string} tokenType The name of the token, like options or edit.
194 * @param {Object} params API parameters
195 * @return {jQuery.Promise} See #post
196 */
197 postWithToken: function ( tokenType, params ) {
198 var api = this, hasOwn = tokenCache.hasOwnProperty;
199 if ( hasOwn.call( tokenCache, tokenType ) && tokenCache[tokenType] !== undefined ) {
200 params.token = tokenCache[tokenType];
201 return api.post( params ).then(
202 null,
203 function ( code ) {
204 if ( code === 'badtoken' ) {
205 // force a new token, clear any old one
206 tokenCache[tokenType] = params.token = undefined;
207 return api.post( params );
208 }
209 }
210 );
211 } else {
212 return api.getToken( tokenType ).then( function ( token ) {
213 tokenCache[tokenType] = params.token = token;
214 return api.post( params );
215 } );
216 }
217 },
218
219 /**
220 * Api helper to grab any token.
221 *
222 * @param {string} type Token type.
223 * @return {jQuery.Promise}
224 * @return {Function} return.done
225 * @return {string} return.done.token Received token.
226 */
227 getToken: function ( type ) {
228 var apiPromise,
229 d = $.Deferred();
230
231 apiPromise = this.get( {
232 action: 'tokens',
233 type: type
234 }, {
235 // Due to the API assuming we're logged out if we pass the callback-parameter,
236 // we have to disable jQuery's callback system, and instead parse JSON string,
237 // by setting 'jsonp' to false.
238 // TODO: This concern seems genuine but no other module has it. Is it still
239 // needed and/or should we pass this by default?
240 } )
241 .done( function ( data ) {
242 // If token type is not available for this user,
243 // key '...token' is missing or can contain Boolean false
244 if ( data.tokens && data.tokens[type + 'token'] ) {
245 d.resolve( data.tokens[type + 'token'] );
246 } else {
247 d.reject( 'token-missing', data );
248 }
249 } )
250 .fail( d.reject );
251
252 return d.promise( { abort: apiPromise.abort } );
253 }
254 };
255
256 /**
257 * @static
258 * @property {Array}
259 * List of errors we might receive from the API.
260 * For now, this just documents our expectation that there should be similar messages
261 * available.
262 */
263 mw.Api.errors = [
264 // occurs when POST aborted
265 // jQuery 1.4 can't distinguish abort or lost connection from 200 OK + empty result
266 'ok-but-empty',
267
268 // timeout
269 'timeout',
270
271 // really a warning, but we treat it like an error
272 'duplicate',
273 'duplicate-archive',
274
275 // upload succeeded, but no image info.
276 // this is probably impossible, but might as well check for it
277 'noimageinfo',
278 // remote errors, defined in API
279 'uploaddisabled',
280 'nomodule',
281 'mustbeposted',
282 'badaccess-groups',
283 'stashfailed',
284 'missingresult',
285 'missingparam',
286 'invalid-file-key',
287 'copyuploaddisabled',
288 'mustbeloggedin',
289 'empty-file',
290 'file-too-large',
291 'filetype-missing',
292 'filetype-banned',
293 'filetype-banned-type',
294 'filename-tooshort',
295 'illegal-filename',
296 'verification-error',
297 'hookaborted',
298 'unknown-error',
299 'internal-error',
300 'overwrite',
301 'badtoken',
302 'fetchfileerror',
303 'fileexists-shared-forbidden',
304 'invalidtitle',
305 'notloggedin'
306 ];
307
308 /**
309 * @static
310 * @property {Array}
311 * List of warnings we might receive from the API.
312 * For now, this just documents our expectation that there should be similar messages
313 * available.
314 */
315 mw.Api.warnings = [
316 'duplicate',
317 'exists'
318 ];
319
320 }( mediaWiki, jQuery ) );