Merge "Add mediastatistics-header-3d"
[lhc/web/wiklou.git] / resources / src / mediawiki / api / upload.js
1 /**
2 * Provides an interface for uploading files to MediaWiki.
3 *
4 * @class mw.Api.plugin.upload
5 * @singleton
6 */
7 ( function ( mw, $ ) {
8 var nonce = 0,
9 fieldsAllowed = {
10 stash: true,
11 filekey: true,
12 filename: true,
13 comment: true,
14 text: true,
15 watchlist: true,
16 ignorewarnings: true,
17 chunk: true,
18 offset: true,
19 filesize: true,
20 async: true
21 };
22
23 /**
24 * Get nonce for iframe IDs on the page.
25 *
26 * @private
27 * @return {number}
28 */
29 function getNonce() {
30 return nonce++;
31 }
32
33 /**
34 * Given a non-empty object, return one of its keys.
35 *
36 * @private
37 * @param {Object} obj
38 * @return {string}
39 */
40 function getFirstKey( obj ) {
41 var key;
42 for ( key in obj ) {
43 if ( obj.hasOwnProperty( key ) ) {
44 return key;
45 }
46 }
47 }
48
49 /**
50 * Get new iframe object for an upload.
51 *
52 * @private
53 * @param {string} id
54 * @return {HTMLIframeElement}
55 */
56 function getNewIframe( id ) {
57 var frame = document.createElement( 'iframe' );
58 frame.id = id;
59 frame.name = id;
60 return frame;
61 }
62
63 /**
64 * Shortcut for getting hidden inputs
65 *
66 * @private
67 * @param {string} name
68 * @param {string} val
69 * @return {jQuery}
70 */
71 function getHiddenInput( name, val ) {
72 return $( '<input>' ).attr( 'type', 'hidden' )
73 .attr( 'name', name )
74 .val( val );
75 }
76
77 /**
78 * Process the result of the form submission, returned to an iframe.
79 * This is the iframe's onload event.
80 *
81 * @param {HTMLIframeElement} iframe Iframe to extract result from
82 * @return {Object} Response from the server. The return value may or may
83 * not be an XMLDocument, this code was copied from elsewhere, so if you
84 * see an unexpected return type, please file a bug.
85 */
86 function processIframeResult( iframe ) {
87 var json,
88 doc = iframe.contentDocument || frames[ iframe.id ].document;
89
90 if ( doc.XMLDocument ) {
91 // The response is a document property in IE
92 return doc.XMLDocument;
93 }
94
95 if ( doc.body ) {
96 // Get the json string
97 // We're actually searching through an HTML doc here --
98 // according to mdale we need to do this
99 // because IE does not load JSON properly in an iframe
100 json = $( doc.body ).find( 'pre' ).text();
101
102 return JSON.parse( json );
103 }
104
105 // Response is a xml document
106 return doc;
107 }
108
109 function formDataAvailable() {
110 return window.FormData !== undefined &&
111 window.File !== undefined &&
112 window.File.prototype.slice !== undefined;
113 }
114
115 $.extend( mw.Api.prototype, {
116 /**
117 * Upload a file to MediaWiki.
118 *
119 * The file will be uploaded using AJAX and FormData, if the browser supports it, or via an
120 * iframe if it doesn't.
121 *
122 * Caveats of iframe upload:
123 * - The returned jQuery.Promise will not receive `progress` notifications during the upload
124 * - It is incompatible with uploads to a foreign wiki using mw.ForeignApi
125 * - You must pass a HTMLInputElement and not a File for it to be possible
126 *
127 * @param {HTMLInputElement|File|Blob} file HTML input type=file element with a file already inside
128 * of it, or a File object.
129 * @param {Object} data Other upload options, see action=upload API docs for more
130 * @return {jQuery.Promise}
131 */
132 upload: function ( file, data ) {
133 var isFileInput, canUseFormData;
134
135 isFileInput = file && file.nodeType === Node.ELEMENT_NODE;
136
137 if ( formDataAvailable() && isFileInput && file.files ) {
138 file = file.files[ 0 ];
139 }
140
141 if ( !file ) {
142 throw new Error( 'No file' );
143 }
144
145 // Blobs are allowed in formdata uploads, it turns out
146 canUseFormData = formDataAvailable() && ( file instanceof window.File || file instanceof window.Blob );
147
148 if ( !isFileInput && !canUseFormData ) {
149 throw new Error( 'Unsupported argument type passed to mw.Api.upload' );
150 }
151
152 if ( canUseFormData ) {
153 return this.uploadWithFormData( file, data );
154 }
155
156 return this.uploadWithIframe( file, data );
157 },
158
159 /**
160 * Upload a file to MediaWiki with an iframe and a form.
161 *
162 * This method is necessary for browsers without the File/FormData
163 * APIs, and continues to work in browsers with those APIs.
164 *
165 * The rough sketch of how this method works is as follows:
166 * 1. An iframe is loaded with no content.
167 * 2. A form is submitted with the passed-in file input and some extras.
168 * 3. The MediaWiki API receives that form data, and sends back a response.
169 * 4. The response is sent to the iframe, because we set target=(iframe id)
170 * 5. The response is parsed out of the iframe's document, and passed back
171 * through the promise.
172 *
173 * @private
174 * @param {HTMLInputElement} file The file input with a file in it.
175 * @param {Object} data Other upload options, see action=upload API docs for more
176 * @return {jQuery.Promise}
177 */
178 uploadWithIframe: function ( file, data ) {
179 var key,
180 tokenPromise = $.Deferred(),
181 api = this,
182 deferred = $.Deferred(),
183 nonce = getNonce(),
184 id = 'uploadframe-' + nonce,
185 $form = $( '<form>' ),
186 iframe = getNewIframe( id ),
187 $iframe = $( iframe );
188
189 for ( key in data ) {
190 if ( !fieldsAllowed[ key ] ) {
191 delete data[ key ];
192 }
193 }
194
195 data = $.extend( {}, this.defaults.parameters, { action: 'upload' }, data );
196 $form.addClass( 'mw-api-upload-form' );
197
198 $form.css( 'display', 'none' )
199 .attr( {
200 action: this.defaults.ajax.url,
201 method: 'POST',
202 target: id,
203 enctype: 'multipart/form-data'
204 } );
205
206 $iframe.one( 'load', function () {
207 $iframe.one( 'load', function () {
208 var result = processIframeResult( iframe );
209 deferred.notify( 1 );
210
211 if ( !result ) {
212 deferred.reject( 'ok-but-empty', 'No response from API on upload attempt.' );
213 } else if ( result.error ) {
214 if ( result.error.code === 'badtoken' ) {
215 api.badToken( 'csrf' );
216 }
217
218 deferred.reject( result.error.code, result );
219 } else if ( result.upload && result.upload.warnings ) {
220 deferred.reject( getFirstKey( result.upload.warnings ), result );
221 } else {
222 deferred.resolve( result );
223 }
224 } );
225 tokenPromise.done( function () {
226 $form.submit();
227 } );
228 } );
229
230 $iframe.on( 'error', function ( error ) {
231 deferred.reject( 'http', error );
232 } );
233
234 $iframe.prop( 'src', 'about:blank' ).hide();
235
236 file.name = 'file';
237
238 $.each( data, function ( key, val ) {
239 $form.append( getHiddenInput( key, val ) );
240 } );
241
242 if ( !data.filename && !data.stash ) {
243 throw new Error( 'Filename not included in file data.' );
244 }
245
246 if ( this.needToken() ) {
247 this.getEditToken().then( function ( token ) {
248 $form.append( getHiddenInput( 'token', token ) );
249 tokenPromise.resolve();
250 }, tokenPromise.reject );
251 } else {
252 tokenPromise.resolve();
253 }
254
255 $( 'body' ).append( $form, $iframe );
256
257 deferred.always( function () {
258 $form.remove();
259 $iframe.remove();
260 } );
261
262 return deferred.promise();
263 },
264
265 /**
266 * Uploads a file using the FormData API.
267 *
268 * @private
269 * @param {File} file
270 * @param {Object} data Other upload options, see action=upload API docs for more
271 * @return {jQuery.Promise}
272 */
273 uploadWithFormData: function ( file, data ) {
274 var key, request,
275 deferred = $.Deferred();
276
277 for ( key in data ) {
278 if ( !fieldsAllowed[ key ] ) {
279 delete data[ key ];
280 }
281 }
282
283 data = $.extend( {}, this.defaults.parameters, { action: 'upload' }, data );
284 if ( !data.chunk ) {
285 data.file = file;
286 }
287
288 if ( !data.filename && !data.stash ) {
289 throw new Error( 'Filename not included in file data.' );
290 }
291
292 // Use this.postWithEditToken() or this.post()
293 request = this[ this.needToken() ? 'postWithEditToken' : 'post' ]( data, {
294 // Use FormData (if we got here, we know that it's available)
295 contentType: 'multipart/form-data',
296 // No timeout (default from mw.Api is 30 seconds)
297 timeout: 0,
298 // Provide upload progress notifications
299 xhr: function () {
300 var xhr = $.ajaxSettings.xhr();
301 if ( xhr.upload ) {
302 // need to bind this event before we open the connection (see note at
303 // https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest#Monitoring_progress)
304 xhr.upload.addEventListener( 'progress', function ( ev ) {
305 if ( ev.lengthComputable ) {
306 deferred.notify( ev.loaded / ev.total );
307 }
308 } );
309 }
310 return xhr;
311 }
312 } )
313 .done( function ( result ) {
314 deferred.notify( 1 );
315 if ( result.upload && result.upload.warnings ) {
316 deferred.reject( getFirstKey( result.upload.warnings ), result );
317 } else {
318 deferred.resolve( result );
319 }
320 } )
321 .fail( function ( errorCode, result ) {
322 deferred.notify( 1 );
323 deferred.reject( errorCode, result );
324 } );
325
326 return deferred.promise( { abort: request.abort } );
327 },
328
329 /**
330 * Upload a file in several chunks.
331 *
332 * @param {File} file
333 * @param {Object} data Other upload options, see action=upload API docs for more
334 * @param {number} [chunkSize] Size (in bytes) per chunk (default: 5MB)
335 * @param {number} [chunkRetries] Amount of times to retry a failed chunk (default: 1)
336 * @returns {jQuery.Promise}
337 */
338 chunkedUpload: function ( file, data, chunkSize, chunkRetries ) {
339 var start, end, promise, next, active,
340 deferred = $.Deferred();
341
342 chunkSize = chunkSize === undefined ? 5 * 1024 * 1024 : chunkSize;
343 chunkRetries = chunkRetries === undefined ? 1 : chunkRetries;
344
345 if ( !data.filename ) {
346 throw new Error( 'Filename not included in file data.' );
347 }
348
349 // Submit first chunk to get the filekey
350 active = promise = this.uploadChunk( file, data, 0, chunkSize, '', chunkRetries )
351 .fail( deferred.reject )
352 .progress( deferred.notify );
353
354 // Now iteratively submit the rest of the chunks
355 for ( start = chunkSize; start < file.size; start += chunkSize ) {
356 end = Math.min( start + chunkSize, file.size );
357 next = $.Deferred();
358
359 // We could simply chain one this.uploadChunk after another with
360 // .then(), but then we'd hit an `Uncaught RangeError: Maximum
361 // call stack size exceeded` at as low as 1024 calls in Firefox
362 // 47. This'll work around it, but comes with the drawback of
363 // having to properly relay the results to the returned promise.
364 // eslint-disable-next-line no-loop-func
365 promise.done( function ( start, end, next, result ) {
366 var filekey = result.upload.filekey;
367 active = this.uploadChunk( file, data, start, end, filekey, chunkRetries )
368 .done( end === file.size ? deferred.resolve : next.resolve )
369 .fail( deferred.reject )
370 .progress( deferred.notify );
371 // start, end & next must be bound to closure, or they'd have
372 // changed by the time the promises are resolved
373 }.bind( this, start, end, next ) );
374
375 promise = next;
376 }
377
378 return deferred.promise( { abort: active.abort } );
379 },
380
381 /**
382 * Uploads 1 chunk.
383 *
384 * @private
385 * @param {File} file
386 * @param {Object} data Other upload options, see action=upload API docs for more
387 * @param {number} start Chunk start position
388 * @param {number} end Chunk end position
389 * @param {string} [filekey] File key, for follow-up chunks
390 * @param {number} [retries] Amount of times to retry request
391 * @return {jQuery.Promise}
392 */
393 uploadChunk: function ( file, data, start, end, filekey, retries ) {
394 var upload, retry,
395 api = this,
396 chunk = this.slice( file, start, end );
397
398 // When uploading in chunks, we're going to be issuing a lot more
399 // requests and there's always a chance of 1 getting dropped.
400 // In such case, it could be useful to try again: a network hickup
401 // doesn't necessarily have to result in upload failure...
402 retries = retries === undefined ? 1 : retries;
403 retry = function ( code, result ) {
404 var deferred = $.Deferred(),
405 callback = function () {
406 api.uploadChunk( file, data, start, end, filekey, retries - 1 )
407 .then( deferred.resolve, deferred.reject );
408 };
409
410 // Don't retry if the request failed because we aborted it (or
411 // if it's another kind of request failure)
412 if ( code !== 'http' || result.textStatus === 'abort' ) {
413 return deferred.reject( code, result );
414 }
415
416 setTimeout( callback, 1000 );
417 return deferred.promise();
418 };
419
420 data.filesize = file.size;
421 data.chunk = chunk;
422 data.offset = start;
423
424 // filekey must only be added when uploading follow-up chunks; the
425 // first chunk should never have a filekey (it'll be generated)
426 if ( filekey && start !== 0 ) {
427 data.filekey = filekey;
428 }
429
430 upload = this.uploadWithFormData( file, data );
431 return upload.then(
432 null,
433 // If the call fails, we may want to try again...
434 retries === 0 ? null : retry,
435 function ( fraction ) {
436 // Since we're only uploading small parts of a file, we
437 // need to adjust the reported progress to reflect where
438 // we actually are in the combined upload
439 return ( start + fraction * ( end - start ) ) / file.size;
440 }
441 ).promise( { abort: upload.abort } );
442 },
443
444 /**
445 * Slice a chunk out of a File object.
446 *
447 * @private
448 * @param {File} file
449 * @param {number} start
450 * @param {number} stop
451 * @returns {Blob}
452 */
453 slice: function ( file, start, stop ) {
454 if ( file.mozSlice ) {
455 // FF <= 12
456 return file.mozSlice( start, stop, file.type );
457 } else if ( file.webkitSlice ) {
458 // Chrome <= 20
459 return file.webkitSlice( start, stop, file.type );
460 } else {
461 // On really old browser versions (before slice was prefixed),
462 // slice() would take (start, length) instead of (start, end)
463 // We'll ignore that here...
464 return file.slice( start, stop, file.type );
465 }
466 },
467
468 /**
469 * Upload a file to the stash.
470 *
471 * This function will return a promise, which when resolved, will pass back a function
472 * to finish the stash upload. You can call that function with an argument containing
473 * more, or conflicting, data to pass to the server. For example:
474 *
475 * // upload a file to the stash with a placeholder filename
476 * api.uploadToStash( file, { filename: 'testing.png' } ).done( function ( finish ) {
477 * // finish is now the function we can use to finalize the upload
478 * // pass it a new filename from user input to override the initial value
479 * finish( { filename: getFilenameFromUser() } ).done( function ( data ) {
480 * // the upload is complete, data holds the API response
481 * } );
482 * } );
483 *
484 * @param {File|HTMLInputElement} file
485 * @param {Object} [data]
486 * @return {jQuery.Promise}
487 * @return {Function} return.finishStashUpload Call this function to finish the upload.
488 * @return {Object} return.finishStashUpload.data Additional data for the upload.
489 * @return {jQuery.Promise} return.finishStashUpload.return API promise for the final upload
490 * @return {Object} return.finishStashUpload.return.data API return value for the final upload
491 */
492 uploadToStash: function ( file, data ) {
493 var filekey,
494 api = this;
495
496 if ( !data.filename ) {
497 throw new Error( 'Filename not included in file data.' );
498 }
499
500 function finishUpload( moreData ) {
501 return api.uploadFromStash( filekey, $.extend( data, moreData ) );
502 }
503
504 return this.upload( file, { stash: true, filename: data.filename } ).then(
505 function ( result ) {
506 filekey = result.upload.filekey;
507 return finishUpload;
508 },
509 function ( errorCode, result ) {
510 if ( result && result.upload && result.upload.filekey ) {
511 // Ignore any warnings if 'filekey' was returned, that's all we care about
512 filekey = result.upload.filekey;
513 return $.Deferred().resolve( finishUpload );
514 }
515 return $.Deferred().reject( errorCode, result );
516 }
517 );
518 },
519
520 /**
521 * Finish an upload in the stash.
522 *
523 * @param {string} filekey
524 * @param {Object} data
525 * @return {jQuery.Promise}
526 */
527 uploadFromStash: function ( filekey, data ) {
528 data.filekey = filekey;
529 data.action = 'upload';
530 data.format = 'json';
531
532 if ( !data.filename ) {
533 throw new Error( 'Filename not included in file data.' );
534 }
535
536 return this.postWithEditToken( data ).then( function ( result ) {
537 if ( result.upload && result.upload.warnings ) {
538 return $.Deferred().reject( getFirstKey( result.upload.warnings ), result ).promise();
539 }
540 return result;
541 } );
542 },
543
544 needToken: function () {
545 return true;
546 }
547 } );
548
549 /**
550 * @class mw.Api
551 * @mixins mw.Api.plugin.upload
552 */
553 }( mediaWiki, jQuery ) );