Merge "Switched FileBackendStore to use ProfileSection when possible."
[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
25 /**
26 * Constructor to create an object to interact with the API of a particular MediaWiki server.
27 * mw.Api objects represent the API of a particular MediaWiki server.
28 *
29 * TODO: Share API objects with exact same config.
30 *
31 * var api = new mw.Api();
32 * api.get( {
33 * action: 'query',
34 * meta: 'userinfo'
35 * } ).done ( function ( data ) {
36 * console.log( data );
37 * } );
38 *
39 * @class
40 *
41 * @constructor
42 * @param {Object} options See defaultOptions documentation above. Ajax options can also be
43 * overridden for each individual request to {@link jQuery#ajax} later on.
44 */
45 mw.Api = function ( options ) {
46
47 if ( options === undefined ) {
48 options = {};
49 }
50
51 // Force toString if we got a mw.Uri object
52 if ( options.ajax && options.ajax.url !== undefined ) {
53 options.ajax.url = String( options.ajax.url );
54 }
55
56 options.parameters = $.extend( {}, defaultOptions.parameters, options.parameters );
57 options.ajax = $.extend( {}, defaultOptions.ajax, options.ajax );
58
59 this.defaults = options;
60 };
61
62 mw.Api.prototype = {
63
64 /**
65 * Normalize the ajax options for compatibility and/or convenience methods.
66 *
67 * @param {Object} [arg] An object contaning one or more of options.ajax.
68 * @return {Object} Normalized ajax options.
69 */
70 normalizeAjaxOptions: function ( arg ) {
71 // Arg argument is usually empty
72 // (before MW 1.20 it was used to pass ok callbacks)
73 var opts = arg || {};
74 // Options can also be a success callback handler
75 if ( typeof arg === 'function' ) {
76 opts = { ok: arg };
77 }
78 return opts;
79 },
80
81 /**
82 * Perform API get request
83 *
84 * @param {Object} parameters
85 * @param {Object|Function} [ajaxOptions]
86 * @return {jQuery.Promise}
87 */
88 get: function ( parameters, ajaxOptions ) {
89 ajaxOptions = this.normalizeAjaxOptions( ajaxOptions );
90 ajaxOptions.type = 'GET';
91 return this.ajax( parameters, ajaxOptions );
92 },
93
94 /**
95 * Perform API post request
96 *
97 * TODO: Post actions for non-local hostnames will need proxy.
98 *
99 * @param {Object} parameters
100 * @param {Object|Function} [ajaxOptions]
101 * @return {jQuery.Promise}
102 */
103 post: function ( parameters, ajaxOptions ) {
104 ajaxOptions = this.normalizeAjaxOptions( ajaxOptions );
105 ajaxOptions.type = 'POST';
106 return this.ajax( parameters, ajaxOptions );
107 },
108
109 /**
110 * Perform the API call.
111 *
112 * @param {Object} parameters
113 * @param {Object} [ajaxOptions]
114 * @return {jQuery.Promise} Done: API response data. Fail: Error code
115 */
116 ajax: function ( parameters, ajaxOptions ) {
117 var token,
118 apiDeferred = $.Deferred(),
119 xhr;
120
121 parameters = $.extend( {}, this.defaults.parameters, parameters );
122 ajaxOptions = $.extend( {}, this.defaults.ajax, ajaxOptions );
123
124 // Ensure that token parameter is last (per [[mw:API:Edit#Token]]).
125 if ( parameters.token ) {
126 token = parameters.token;
127 delete parameters.token;
128 }
129 // Some deployed MediaWiki >= 1.17 forbid periods in URLs, due to an IE XSS bug
130 // So let's escape them here. See bug #28235
131 // This works because jQuery accepts data as a query string or as an Object
132 ajaxOptions.data = $.param( parameters ).replace( /\./g, '%2E' );
133
134 // If we extracted a token parameter, add it back in.
135 if ( token ) {
136 ajaxOptions.data += '&token=' + encodeURIComponent( token );
137 }
138
139 // Backwards compatibility: Before MediaWiki 1.20,
140 // callbacks were done with the 'ok' and 'err' property in ajaxOptions.
141 if ( ajaxOptions.ok ) {
142 apiDeferred.done( ajaxOptions.ok );
143 delete ajaxOptions.ok;
144 }
145 if ( ajaxOptions.err ) {
146 apiDeferred.fail( ajaxOptions.err );
147 delete ajaxOptions.err;
148 }
149
150 // Make the AJAX request
151 xhr = $.ajax( ajaxOptions )
152 // If AJAX fails, reject API call with error code 'http'
153 // and details in second argument.
154 .fail( function ( xhr, textStatus, exception ) {
155 apiDeferred.reject( 'http', {
156 xhr: xhr,
157 textStatus: textStatus,
158 exception: exception
159 } );
160 } )
161 // AJAX success just means "200 OK" response, also check API error codes
162 .done( function ( result ) {
163 if ( result === undefined || result === null || result === '' ) {
164 apiDeferred.reject( 'ok-but-empty',
165 'OK response but empty result (check HTTP headers?)'
166 );
167 } else if ( result.error ) {
168 var code = result.error.code === undefined ? 'unknown' : result.error.code;
169 apiDeferred.reject( code, result );
170 } else {
171 apiDeferred.resolve( result );
172 }
173 } );
174
175 // Return the Promise
176 return apiDeferred.promise( { abort: xhr.abort } ).fail( function ( code, details ) {
177 mw.log( 'mw.Api error: ', code, details );
178 } );
179 }
180
181 };
182
183 /**
184 * @static
185 * @property {Array}
186 * List of errors we might receive from the API.
187 * For now, this just documents our expectation that there should be similar messages
188 * available.
189 */
190 mw.Api.errors = [
191 // occurs when POST aborted
192 // jQuery 1.4 can't distinguish abort or lost connection from 200 OK + empty result
193 'ok-but-empty',
194
195 // timeout
196 'timeout',
197
198 // really a warning, but we treat it like an error
199 'duplicate',
200 'duplicate-archive',
201
202 // upload succeeded, but no image info.
203 // this is probably impossible, but might as well check for it
204 'noimageinfo',
205 // remote errors, defined in API
206 'uploaddisabled',
207 'nomodule',
208 'mustbeposted',
209 'badaccess-groups',
210 'stashfailed',
211 'missingresult',
212 'missingparam',
213 'invalid-file-key',
214 'copyuploaddisabled',
215 'mustbeloggedin',
216 'empty-file',
217 'file-too-large',
218 'filetype-missing',
219 'filetype-banned',
220 'filetype-banned-type',
221 'filename-tooshort',
222 'illegal-filename',
223 'verification-error',
224 'hookaborted',
225 'unknown-error',
226 'internal-error',
227 'overwrite',
228 'badtoken',
229 'fetchfileerror',
230 'fileexists-shared-forbidden',
231 'invalidtitle',
232 'notloggedin'
233 ];
234
235 /**
236 * @static
237 * @property {Array}
238 * List of warnings we might receive from the API.
239 * For now, this just documents our expectation that there should be similar messages
240 * available.
241 */
242 mw.Api.warnings = [
243 'duplicate',
244 'exists'
245 ];
246
247 }( mediaWiki, jQuery ) );