2 * JavaScript for Special:Upload
5 * @class mw.special.upload
9 /*jshint latedef:false */
10 var uploadWarning, uploadLicense,
11 ajaxUploadDestCheck = mw.config.get( 'wgAjaxUploadDestCheck' ),
12 $license = $( '#wpLicense' );
14 window.wgUploadWarningObj = uploadWarning = {
15 responseCache: { '': ' ' },
21 keypress: function () {
22 if ( !ajaxUploadDestCheck ) {
26 // Find file to upload
27 if ( !$( '#wpDestFile' ).length || !$( '#wpDestFile-warning' ).length ) {
31 this.nameToCheck = $( '#wpDestFile' ).val();
34 if ( this.timeoutID ) {
35 clearTimeout( this.timeoutID );
37 // Check response cache
38 if ( this.responseCache.hasOwnProperty( this.nameToCheck ) ) {
39 this.setWarning( this.responseCache[ this.nameToCheck ] );
43 this.timeoutID = setTimeout( function () {
44 uploadWarning.timeout();
48 checkNow: function ( fname ) {
49 if ( !ajaxUploadDestCheck ) {
52 if ( this.timeoutID ) {
53 clearTimeout( this.timeoutID );
55 this.nameToCheck = fname;
59 timeout: function () {
60 var $spinnerDestCheck;
61 if ( !ajaxUploadDestCheck || this.nameToCheck === '' ) {
64 $spinnerDestCheck = $.createSpinner().insertAfter( '#wpDestFile' );
66 ( new mw.Api() ).get( {
68 titles: ( new mw.Title( this.nameToCheck, mw.config.get( 'wgNamespaceIds' ).file ) ).getPrefixedText(),
70 iiprop: 'uploadwarning',
72 } ).done( function ( result ) {
75 resultOut = result.query.pages[ result.query.pageids[ 0 ] ].imageinfo[ 0 ];
77 $spinnerDestCheck.remove();
78 uploadWarning.processResult( resultOut, uploadWarning.nameToCheck );
82 processResult: function ( result, fileName ) {
83 this.setWarning( result.html );
84 this.responseCache[ fileName ] = result.html;
87 setWarning: function ( warning ) {
88 var $warning = $( $.parseHTML( warning ) );
89 mw.hook( 'wikipage.content' ).fire( $warning );
90 $( '#wpDestFile-warning' ).empty().append( $warning );
92 // Set a value in the form indicating that the warning is acknowledged and
93 // doesn't need to be redisplayed post-upload
95 $( '#wpDestFileWarningAck' ).val( '' );
97 $( '#wpDestFileWarningAck' ).val( '1' );
105 responseCache: { '': '' },
107 fetchPreview: function ( license ) {
109 if ( !mw.config.get( 'wgAjaxLicensePreview' ) ) {
112 if ( this.responseCache.hasOwnProperty( license ) ) {
113 this.showPreview( this.responseCache[ license ] );
117 $spinnerLicense = $.createSpinner().insertAfter( '#wpLicense' );
119 ( new mw.Api() ).get( {
121 text: '{{' + license + '}}',
122 title: $( '#wpDestFile' ).val() || 'File:Sample.jpg',
125 } ).done( function ( result ) {
126 $spinnerLicense.remove();
127 uploadLicense.processResult( result, license );
131 processResult: function ( result, license ) {
132 this.responseCache[ license ] = result.parse.text[ '*' ];
133 this.showPreview( this.responseCache[ license ] );
136 showPreview: function ( preview ) {
137 $( '#mw-license-preview' ).html( preview );
143 // AJAX wpDestFile warnings
144 if ( ajaxUploadDestCheck ) {
145 // Insert an event handler that fetches upload warnings when wpDestFile
147 $( '#wpDestFile' ).change( function () {
148 uploadWarning.checkNow( $( this ).val() );
150 // Insert a row where the warnings will be displayed just below the
152 $( '#mw-htmlform-description tbody' ).append(
155 .attr( 'id', 'wpDestFile-warning' )
156 .attr( 'colspan', 2 )
161 if ( mw.config.get( 'wgAjaxLicensePreview' ) && $license.length ) {
162 // License selector check
163 $license.change( function () {
164 // We might show a preview
165 uploadLicense.fetchPreview( $license.val() );
168 // License selector table row
169 $license.closest( 'tr' ).after(
172 $( '<td>' ).attr( 'id', 'mw-license-preview' )
177 // fillDestFile setup
178 $.each( mw.config.get( 'wgUploadSourceIds' ), function ( index, sourceId ) {
179 $( '#' + sourceId ).change( function () {
180 var path, slash, backslash, fname;
181 if ( !mw.config.get( 'wgUploadAutoFill' ) ) {
184 // Remove any previously flagged errors
185 $( '#mw-upload-permitted' ).attr( 'class', '' );
186 $( '#mw-upload-prohibited' ).attr( 'class', '' );
188 path = $( this ).val();
189 // Find trailing part
190 slash = path.lastIndexOf( '/' );
191 backslash = path.lastIndexOf( '\\' );
192 if ( slash === -1 && backslash === -1 ) {
194 } else if ( slash > backslash ) {
195 fname = path.slice( slash + 1 );
197 fname = path.slice( backslash + 1 );
200 // Clear the filename if it does not have a valid extension.
201 // URLs are less likely to have a useful extension, so don't include them in the
204 mw.config.get( 'wgCheckFileExtensions' ) &&
205 mw.config.get( 'wgStrictFileExtensions' ) &&
206 mw.config.get( 'wgFileExtensions' ) &&
207 $( this ).attr( 'id' ) !== 'wpUploadFileURL'
210 fname.lastIndexOf( '.' ) === -1 ||
212 fname.slice( fname.lastIndexOf( '.' ) + 1 ).toLowerCase(),
213 $.map( mw.config.get( 'wgFileExtensions' ), function ( element ) {
214 return element.toLowerCase();
218 // Not a valid extension
219 // Clear the upload and set mw-upload-permitted to error
221 $( '#mw-upload-permitted' ).attr( 'class', 'error' );
222 $( '#mw-upload-prohibited' ).attr( 'class', 'error' );
223 // Clear wpDestFile as well
224 $( '#wpDestFile' ).val( '' );
230 // Replace spaces by underscores
231 fname = fname.replace( / /g, '_' );
232 // Capitalise first letter if needed
233 if ( mw.config.get( 'wgCapitalizeUploads' ) ) {
234 fname = fname[ 0 ].toUpperCase() + fname.slice( 1 );
238 if ( $( '#wpDestFile' ).length ) {
239 // Call decodeURIComponent function to remove possible URL-encoded characters
240 // from the file name (bug 30390). Especially likely with upload-form-url.
241 // decodeURIComponent can throw an exception if input is invalid utf-8
243 $( '#wpDestFile' ).val( decodeURIComponent( fname ) );
245 $( '#wpDestFile' ).val( fname );
247 uploadWarning.checkNow( fname );
253 // Add a preview to the upload form
256 * Is the FileAPI available with sufficient functionality?
258 function hasFileAPI() {
259 return window.FileReader !== undefined;
263 * Check if this is a recognizable image type...
264 * Also excludes files over 10M to avoid going insane on memory usage.
266 * TODO: Is there a way we can ask the browser what's supported in `<img>`s?
268 * TODO: Put SVG back after working around Firefox 7 bug <https://phabricator.wikimedia.org/T33643>
273 function fileIsPreviewable( file ) {
274 var known = [ 'image/png', 'image/gif', 'image/jpeg', 'image/svg+xml' ],
275 tooHuge = 10 * 1024 * 1024;
276 return ( $.inArray( file.type, known ) !== -1 ) && file.size > 0 && file.size < tooHuge;
280 * Format a file size attractively.
282 * TODO: Match numeric formatting
287 function prettySize( s ) {
288 var sizeMsgs = [ 'size-bytes', 'size-kilobytes', 'size-megabytes', 'size-gigabytes' ];
289 while ( s >= 1024 && sizeMsgs.length > 1 ) {
291 sizeMsgs = sizeMsgs.slice( 1 );
293 return mw.msg( sizeMsgs[ 0 ], Math.round( s ) );
297 * Show a thumbnail preview of PNG, JPEG, GIF, and SVG files prior to upload
298 * in browsers supporting HTML5 FileAPI.
300 * As of this writing, known good:
303 * - Chrome 7.something
305 * TODO: Check file size limits and warn of likely failures
309 function showPreview( file ) {
314 $spinner = $.createSpinner( { size: 'small', type: 'block' } )
315 .css( { width: previewSize, height: previewSize } ),
316 thumb = mw.template.get( 'mediawiki.special.upload', 'thumbnail.html' ).render();
319 .find( '.filename' ).text( file.name ).end()
320 .find( '.fileinfo' ).text( prettySize( file.size ) ).end()
321 .find( '.thumbinner' ).prepend( $spinner ).end();
323 $canvas = $( '<canvas>' ).attr( { width: previewSize, height: previewSize } );
324 ctx = $canvas[ 0 ].getContext( '2d' );
325 $( '#mw-htmlform-source' ).parent().prepend( thumb );
327 fetchPreview( file, function ( dataURL ) {
328 var img = new Image(),
331 if ( meta && meta.tiff && meta.tiff.Orientation ) {
332 rotation = ( 360 - ( function () {
333 // See includes/media/Bitmap.php
334 switch ( meta.tiff.Orientation.value ) {
347 img.onload = function () {
348 var info, width, height, x, y, dx, dy, logicalWidth, logicalHeight;
350 // Fit the image within the previewSizexpreviewSize box
351 if ( img.width > img.height ) {
353 height = img.height / img.width * previewSize;
355 height = previewSize;
356 width = img.width / img.height * previewSize;
358 // Determine the offset required to center the image
359 dx = ( 180 - width ) / 2;
360 dy = ( 180 - height ) / 2;
361 switch ( rotation ) {
362 // If a rotation is applied, the direction of the axis
363 // changes as well. You can derive the values below by
364 // drawing on paper an axis system, rotate it and see
365 // where the positive axis direction is
369 logicalWidth = img.width;
370 logicalHeight = img.height;
375 y = dy - previewSize;
376 logicalWidth = img.height;
377 logicalHeight = img.width;
380 x = dx - previewSize;
381 y = dy - previewSize;
382 logicalWidth = img.width;
383 logicalHeight = img.height;
386 x = dx - previewSize;
388 logicalWidth = img.height;
389 logicalHeight = img.width;
393 ctx.clearRect( 0, 0, 180, 180 );
394 ctx.rotate( rotation / 180 * Math.PI );
395 ctx.drawImage( img, x, y, width, height );
396 $spinner.replaceWith( $canvas );
399 info = mw.msg( 'widthheight', logicalWidth, logicalHeight ) +
400 ', ' + prettySize( file.size );
402 $( '#mw-upload-thumbnail .fileinfo' ).text( info );
405 }, mw.config.get( 'wgFileCanRotate' ) ? function ( data ) {
407 meta = mw.libs.jpegmeta( data, file.fileName );
408 // jscs:disable requireCamelCaseOrUpperCaseIdentifiers, disallowDanglingUnderscores
409 meta._binary_data = null;
418 * Start loading a file into memory; when complete, pass it as a
419 * data URL to the callback function. If the callbackBinary is set it will
420 * first be read as binary and afterwards as data URL. Useful if you want
421 * to do preprocessing on the binary data first.
424 * @param {Function} callback
425 * @param {Function} callbackBinary
427 function fetchPreview( file, callback, callbackBinary ) {
428 var reader = new FileReader();
429 if ( callbackBinary && 'readAsBinaryString' in reader ) {
430 // To fetch JPEG metadata we need a binary string; start there.
432 reader.onload = function () {
433 callbackBinary( reader.result );
435 // Now run back through the regular code path.
436 fetchPreview( file, callback );
438 reader.readAsBinaryString( file );
439 } else if ( callbackBinary && 'readAsArrayBuffer' in reader ) {
440 // readAsArrayBuffer replaces readAsBinaryString
441 // However, our JPEG metadata library wants a string.
442 // So, this is going to be an ugly conversion.
443 reader.onload = function () {
445 buffer = new Uint8Array( reader.result ),
447 for ( i = 0; i < buffer.byteLength; i++ ) {
448 string += String.fromCharCode( buffer[ i ] );
450 callbackBinary( string );
452 // Now run back through the regular code path.
453 fetchPreview( file, callback );
455 reader.readAsArrayBuffer( file );
456 } else if ( 'URL' in window && 'createObjectURL' in window.URL ) {
457 // Supported in Firefox 4.0 and above <https://developer.mozilla.org/en/DOM/window.URL.createObjectURL>
458 // WebKit has it in a namespace for now but that's ok. ;)
460 // Lifetime of this URL is until document close, which is fine
461 // for Special:Upload -- if this code gets used on longer-running
462 // pages, add a revokeObjectURL() when it's no longer needed.
464 // Prefer this over readAsDataURL for Firefox 7 due to bug reading
465 // some SVG files from data URIs <https://bugzilla.mozilla.org/show_bug.cgi?id=694165>
466 callback( window.URL.createObjectURL( file ) );
468 // This ends up decoding the file to base-64 and back again, which
469 // feels horribly inefficient.
470 reader.onload = function () {
471 callback( reader.result );
473 reader.readAsDataURL( file );
478 * Clear the file upload preview area.
480 function clearPreview() {
481 $( '#mw-upload-thumbnail' ).remove();
485 * Check if the file does not exceed the maximum size
487 function checkMaxUploadSize( file ) {
490 function getMaxUploadSize( type ) {
491 var sizes = mw.config.get( 'wgMaxUploadSize' );
493 if ( sizes[ type ] !== undefined ) {
494 return sizes[ type ];
499 $( '.mw-upload-source-error' ).remove();
501 maxSize = getMaxUploadSize( 'file' );
502 if ( file.size > maxSize ) {
503 $error = $( '<p class="error mw-upload-source-error" id="wpSourceTypeFile-error">' +
504 mw.message( 'largefileserver', file.size, maxSize ).escaped() + '</p>' );
506 $( '#wpUploadFile' ).after( $error );
515 if ( hasFileAPI() ) {
516 // Update thumbnail when the file selection control is updated.
517 $( '#wpUploadFile' ).change( function () {
519 if ( this.files && this.files.length ) {
520 // Note: would need to be updated to handle multiple files.
521 var file = this.files[ 0 ];
523 if ( !checkMaxUploadSize( file ) ) {
527 if ( fileIsPreviewable( file ) ) {
535 // Disable all upload source fields except the selected one
537 var $rows = $( '.mw-htmlform-field-UploadSourceField' );
539 $rows.on( 'change', 'input[type="radio"]', function ( e ) {
540 var currentRow = e.delegateTarget;
542 if ( !this.checked ) {
546 $( '.mw-upload-source-error' ).remove();
548 // Enable selected upload method
549 $( currentRow ).find( 'input' ).prop( 'disabled', false );
551 // Disable inputs of other upload methods
552 // (except for the radio button to re-enable it)
555 .find( 'input[type!="radio"]' )
556 .prop( 'disabled', true );
560 if ( !$( '#wpSourceTypeurl' ).prop( 'checked' ) ) {
561 $( '#wpUploadFileURL' ).prop( 'disabled', true );
566 // Prevent losing work
567 var allowCloseWindow,
568 $uploadForm = $( '#mw-upload-form' );
570 if ( !mw.user.options.get( 'useeditwarning' ) ) {
571 // If the user doesn't want edit warnings, don't set things up.
575 $uploadForm.data( 'origtext', $uploadForm.serialize() );
577 allowCloseWindow = mw.confirmCloseWindow( {
579 return $( '#wpUploadFile' ).get( 0 ).files.length !== 0 ||
580 $uploadForm.data( 'origtext' ) !== $uploadForm.serialize();
583 message: mw.msg( 'editwarning-warning' ),
584 namespace: 'uploadwarning'
587 $uploadForm.submit( function () {
588 allowCloseWindow.release();
591 }( mediaWiki, jQuery ) );