Merge "Bug 35623 - createAndPromote.php: Change to allow promotion only"
[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
120 parameters = $.extend( {}, this.defaults.parameters, parameters );
121 ajaxOptions = $.extend( {}, this.defaults.ajax, ajaxOptions );
122
123 // Ensure that token parameter is last (per [[mw:API:Edit#Token]]).
124 if ( parameters.token ) {
125 token = parameters.token;
126 delete parameters.token;
127 }
128 // Some deployed MediaWiki >= 1.17 forbid periods in URLs, due to an IE XSS bug
129 // So let's escape them here. See bug #28235
130 // This works because jQuery accepts data as a query string or as an Object
131 ajaxOptions.data = $.param( parameters ).replace( /\./g, '%2E' );
132
133 // If we extracted a token parameter, add it back in.
134 if ( token ) {
135 ajaxOptions.data += '&token=' + encodeURIComponent( token );
136 }
137
138 // Backwards compatibility: Before MediaWiki 1.20,
139 // callbacks were done with the 'ok' and 'err' property in ajaxOptions.
140 if ( ajaxOptions.ok ) {
141 apiDeferred.done( ajaxOptions.ok );
142 delete ajaxOptions.ok;
143 }
144 if ( ajaxOptions.err ) {
145 apiDeferred.fail( ajaxOptions.err );
146 delete ajaxOptions.err;
147 }
148
149 // Make the AJAX request
150 $.ajax( ajaxOptions )
151 // If AJAX fails, reject API call with error code 'http'
152 // and details in second argument.
153 .fail( function ( xhr, textStatus, exception ) {
154 apiDeferred.reject( 'http', {
155 xhr: xhr,
156 textStatus: textStatus,
157 exception: exception
158 } );
159 } )
160 // AJAX success just means "200 OK" response, also check API error codes
161 .done( function ( result ) {
162 if ( result === undefined || result === null || result === '' ) {
163 apiDeferred.reject( 'ok-but-empty',
164 'OK response but empty result (check HTTP headers?)'
165 );
166 } else if ( result.error ) {
167 var code = result.error.code === undefined ? 'unknown' : result.error.code;
168 apiDeferred.reject( code, result );
169 } else {
170 apiDeferred.resolve( result );
171 }
172 } );
173
174 // Return the Promise
175 return apiDeferred.promise().fail( function ( code, details ) {
176 mw.log( 'mw.Api error: ', code, details );
177 });
178 }
179
180 };
181
182 /**
183 * @static
184 * @property {Array}
185 * List of errors we might receive from the API.
186 * For now, this just documents our expectation that there should be similar messages
187 * available.
188 */
189 mw.Api.errors = [
190 // occurs when POST aborted
191 // jQuery 1.4 can't distinguish abort or lost connection from 200 OK + empty result
192 'ok-but-empty',
193
194 // timeout
195 'timeout',
196
197 // really a warning, but we treat it like an error
198 'duplicate',
199 'duplicate-archive',
200
201 // upload succeeded, but no image info.
202 // this is probably impossible, but might as well check for it
203 'noimageinfo',
204 // remote errors, defined in API
205 'uploaddisabled',
206 'nomodule',
207 'mustbeposted',
208 'badaccess-groups',
209 'stashfailed',
210 'missingresult',
211 'missingparam',
212 'invalid-file-key',
213 'copyuploaddisabled',
214 'mustbeloggedin',
215 'empty-file',
216 'file-too-large',
217 'filetype-missing',
218 'filetype-banned',
219 'filetype-banned-type',
220 'filename-tooshort',
221 'illegal-filename',
222 'verification-error',
223 'hookaborted',
224 'unknown-error',
225 'internal-error',
226 'overwrite',
227 'badtoken',
228 'fetchfileerror',
229 'fileexists-shared-forbidden',
230 'invalidtitle',
231 'notloggedin'
232 ];
233
234 /**
235 * @static
236 * @property {Array}
237 * List of warnings we might receive from the API.
238 * For now, this just documents our expectation that there should be similar messages
239 * available.
240 */
241 mw.Api.warnings = [
242 'duplicate',
243 'exists'
244 ];
245
246 }( mediaWiki, jQuery ) );