2 * JavaScript for Special:Upload
5 * @class mw.special.upload
10 let uploadWarning, uploadTemplatePreview, $warningBox;
11 const NS_FILE = mw.config.get( 'wgNamespaceIds' ).file;
13 window.wgUploadWarningObj = uploadWarning = {
15 checkNow: function ( nameToCheck ) {
16 if ( nameToCheck.trim() === '' ) {
19 const $spinnerDestCheck = $.createSpinner().insertAfter( '#wpDestFile' );
20 const title = mw.Title.newFromText( nameToCheck, NS_FILE );
21 // If title is null, user input is invalid, the API call will produce details about why,
22 // but it needs the namespace to produce errors related to files (when starts with interwiki)
24 if ( !title || title.getNamespaceId() !== NS_FILE ) {
25 requestTitle = mw.config.get( 'wgFormattedNamespaces' )[ NS_FILE ] + ':' + nameToCheck;
27 requestTitle = title.getPrefixedText();
30 ( new mw.Api() ).get( {
35 iiprop: 'uploadwarning',
37 errorlang: mw.config.get( 'wgUserLanguage' )
38 } ).then( ( result ) => {
40 const page = result.query.pages[ 0 ];
41 if ( page.imageinfo ) {
42 resultOut = page.imageinfo[ 0 ].html;
43 } else if ( page.invalidreason ) {
44 resultOut = page.invalidreason.html;
46 uploadWarning.setWarning( resultOut );
47 $spinnerDestCheck.remove();
49 $spinnerDestCheck.remove();
53 setWarning: function ( warning ) {
54 $warningBox.empty().append( $.parseHTML( warning ) );
55 mw.hook( 'wikipage.content' ).fire( $warningBox );
57 // Set a value in the form indicating that the warning is acknowledged and
58 // doesn't need to be redisplayed post-upload
60 $( '#wpDestFileWarningAck' ).val( '' );
61 $warningBox.removeAttr( 'class' );
63 $( '#wpDestFileWarningAck' ).val( '1' );
64 $warningBox.attr( 'class', 'mw-destfile-warning' );
70 window.wgUploadTemplatePreviewObj = uploadTemplatePreview = {
72 responseCache: { '': '' },
75 * @param {jQuery} $element The element whose .val() will be previewed
76 * @param {jQuery} $previewContainer The container to display the preview in
78 getPreview: function ( $element, $previewContainer ) {
79 const template = $element.val();
81 if ( Object.prototype.hasOwnProperty.call( this.responseCache, template ) ) {
82 this.showPreview( this.responseCache[ template ], $previewContainer );
86 const $spinner = $.createSpinner().insertAfter( $element );
88 ( new mw.Api() ).parse( '{{' + template + '}}', {
89 title: $( '#wpDestFile' ).val() || 'File:Sample.jpg',
92 uselang: mw.config.get( 'wgUserLanguage' )
93 } ).done( ( result ) => {
94 uploadTemplatePreview.processResult( result, template, $previewContainer );
100 processResult: function ( result, template, $previewContainer ) {
101 this.responseCache[ template ] = result;
102 this.showPreview( this.responseCache[ template ], $previewContainer );
105 showPreview: function ( preview, $previewContainer ) {
106 $previewContainer.html( preview );
112 // Insert an event handler that fetches upload warnings when wpDestFile
114 $( '#wpDestFile' ).on( 'change', function () {
115 uploadWarning.checkNow( $( this ).val() );
117 // Insert a row where the warnings will be displayed just below the
119 $warningBox = $( '<td>' )
120 .attr( 'id', 'wpDestFile-warning' )
121 .attr( 'colspan', 2 );
122 $( '#mw-htmlform-description tbody' ).append(
123 $( '<tr>' ).append( $warningBox )
126 const $license = $( '#wpLicense' );
127 if ( mw.config.get( 'wgAjaxLicensePreview' ) && $license.length ) {
128 // License selector check
129 $license.on( 'change', () => {
130 // We might show a preview
131 uploadTemplatePreview.getPreview( $license, $( '#mw-license-preview' ) );
134 // License selector table row
135 $license.closest( 'tr' ).after(
138 $( '<td>' ).attr( 'id', 'mw-license-preview' )
143 // fillDestFile setup. Note if the upload wiki does not allow uploads,
144 // e.g. Polish Wikipedia - this code still runs amnd this will be undefined,
145 // so fallback to empty array.
146 mw.config.get( 'wgUploadSourceIds', [] ).forEach( ( sourceId ) => {
147 $( '#' + sourceId ).on( 'change', function () {
148 if ( !mw.config.get( 'wgUploadAutoFill' ) ) {
151 // Remove any previously flagged errors
152 $( '#mw-upload-permitted, #mw-upload-prohibited' ).removeClass();
154 const path = $( this ).val();
155 // Find trailing part
156 const slash = path.lastIndexOf( '/' );
157 const backslash = path.lastIndexOf( '\\' );
159 if ( slash === -1 && backslash === -1 ) {
161 } else if ( slash > backslash ) {
162 fname = path.slice( slash + 1 );
164 fname = path.slice( backslash + 1 );
167 // Clear the filename if it does not have a valid extension.
168 // URLs are less likely to have a useful extension, so don't include them in the
171 mw.config.get( 'wgCheckFileExtensions' ) &&
172 mw.config.get( 'wgStrictFileExtensions' ) &&
173 Array.isArray( mw.config.get( 'wgFileExtensions' ) ) &&
174 $( this ).attr( 'id' ) !== 'wpUploadFileURL'
177 fname.lastIndexOf( '.' ) === -1 ||
178 mw.config.get( 'wgFileExtensions' ).map( ( element ) => element.toLowerCase() ).indexOf( fname.slice( fname.lastIndexOf( '.' ) + 1 ).toLowerCase() ) === -1
180 // Not a valid extension
181 // Clear the upload and set mw-upload-permitted to error
183 $( '#mw-upload-permitted' ).attr( 'class', 'error' );
184 $( '#mw-upload-prohibited' ).attr( 'class', 'error' );
185 // Clear wpDestFile as well
186 $( '#wpDestFile' ).val( '' );
192 // Replace spaces by underscores and capitalise first letter if needed.
193 const title = mw.Title.makeTitle( NS_FILE, fname );
195 // This happens on invalid characters like <, >, [, ]
198 fname = title.getMain();
201 if ( $( '#wpDestFile' ).length ) {
202 // Call decodeURIComponent function to remove possible URL-encoded characters
203 // from the file name (T32390). Especially likely with upload-form-url.
204 // decodeURIComponent can throw an exception if input is invalid utf-8
206 $( '#wpDestFile' ).val( decodeURIComponent( fname ) );
208 $( '#wpDestFile' ).val( fname );
210 uploadWarning.checkNow( fname );
216 // Add a preview to the upload form
219 * Is the FileAPI available with sufficient functionality?
223 function hasFileAPI() {
224 return window.FileReader !== undefined;
228 * Check if this is a recognizable image type...
229 * Also excludes files over 10 MiB to avoid excessive memory usage.
231 * TODO: Is there a way we can ask the browser what's supported in `<img>`s?
236 function fileIsPreviewable( file ) {
237 const known = [ 'image/png', 'image/gif', 'image/jpeg', 'image/svg+xml', 'image/webp' ],
238 tooHuge = 10 * 1024 * 1024;
239 return ( known.indexOf( file.type ) !== -1 ) && file.size > 0 && file.size < tooHuge;
243 * Format a file size attractively.
245 * TODO: Match numeric formatting
250 function prettySize( s ) {
251 let sizeMsgs = [ 'size-bytes', 'size-kilobytes', 'size-megabytes', 'size-gigabytes' ];
252 while ( s >= 1024 && sizeMsgs.length > 1 ) {
254 sizeMsgs = sizeMsgs.slice( 1 );
256 // The following messages are used here:
261 return mw.msg( sizeMsgs[ 0 ], Math.round( s ) );
265 * Start loading a file into memory; when complete, pass it as a
266 * data URL to the callback function. If the callbackBinary is set it will
267 * first be read as binary and afterwards as data URL. Useful if you want
268 * to do preprocessing on the binary data first.
271 * @param {Function} callback
272 * @param {Function} callbackBinary
274 function fetchPreview( file, callback, callbackBinary ) {
275 const reader = new FileReader();
276 if ( callbackBinary && 'readAsBinaryString' in reader ) {
277 // To fetch JPEG metadata we need a binary string; start there.
279 reader.onload = function () {
280 callbackBinary( reader.result );
282 // Now run back through the regular code path.
283 fetchPreview( file, callback );
285 reader.readAsBinaryString( file );
286 } else if ( callbackBinary && 'readAsArrayBuffer' in reader ) {
287 // readAsArrayBuffer replaces readAsBinaryString
288 // However, our JPEG metadata library wants a string.
289 // So, this is going to be an ugly conversion.
290 reader.onload = function () {
291 const buffer = new Uint8Array( reader.result );
293 for ( let i = 0; i < buffer.byteLength; i++ ) {
294 string += String.fromCharCode( buffer[ i ] );
296 callbackBinary( string );
298 // Now run back through the regular code path.
299 fetchPreview( file, callback );
301 reader.readAsArrayBuffer( file );
302 } else if ( 'URL' in window && 'createObjectURL' in window.URL ) {
303 // Supported in Firefox 4.0 and above <https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL>
304 // WebKit has it in a namespace for now but that's ok. ;)
306 // Lifetime of this URL is until document close, which is fine
307 // for Special:Upload -- if this code gets used on longer-running
308 // pages, add a revokeObjectURL() when it's no longer needed.
310 // Prefer this over readAsDataURL for Firefox 7 due to bug reading
311 // some SVG files from data URIs <https://bugzilla.mozilla.org/show_bug.cgi?id=694165>
312 callback( window.URL.createObjectURL( file ) );
314 // This ends up decoding the file to base-64 and back again, which
315 // feels horribly inefficient.
316 reader.onload = function () {
317 callback( reader.result );
319 reader.readAsDataURL( file );
324 * Clear the file upload preview area.
326 function clearPreview() {
327 $( '#mw-upload-thumbnail' ).remove();
331 * Show a thumbnail preview of PNG, JPEG, GIF, and SVG files prior to upload
332 * in browsers supporting HTML5 FileAPI.
334 * As of this writing, known good:
337 * - Chrome 7.something
339 * TODO: Check file size limits and warn of likely failures
343 function showPreview( file ) {
345 const previewSize = 180,
346 $spinner = $.createSpinner( { size: 'small', type: 'block' } )
347 .css( { width: previewSize, height: previewSize } ),
348 thumb = mw.template.get( 'mediawiki.special.upload', 'thumbnail.html' ).render();
351 .find( '.filename' ).text( file.name ).end()
352 .find( '.fileinfo' ).text( prettySize( file.size ) ).end()
353 .find( '.thumbinner' ).prepend( $spinner ).end();
355 const $canvas = $( '<canvas>' ).attr( { width: previewSize, height: previewSize } );
356 const ctx = $canvas[ 0 ].getContext( '2d' );
357 $( '#mw-htmlform-source' ).parent().prepend( thumb );
359 fetchPreview( file, ( dataURL ) => {
360 const img = new Image();
363 if ( meta && meta.tiff && meta.tiff.Orientation ) {
364 rotation = ( 360 - ( function () {
365 // See BitmapHandler class in PHP
366 switch ( meta.tiff.Orientation.value ) {
379 img.onload = function () {
381 // Fit the image within the previewSizexpreviewSize box
382 if ( img.width > img.height ) {
384 height = img.height / img.width * previewSize;
386 height = previewSize;
387 width = img.width / img.height * previewSize;
389 // Determine the offset required to center the image
390 const dx = ( 180 - width ) / 2;
391 const dy = ( 180 - height ) / 2;
392 let x, y, logicalWidth, logicalHeight;
393 switch ( rotation ) {
394 // If a rotation is applied, the direction of the axis
395 // changes as well. You can derive the values below by
396 // drawing on paper an axis system, rotate it and see
397 // where the positive axis direction is
401 logicalWidth = img.width;
402 logicalHeight = img.height;
407 y = dy - previewSize;
408 logicalWidth = img.height;
409 logicalHeight = img.width;
412 x = dx - previewSize;
413 y = dy - previewSize;
414 logicalWidth = img.width;
415 logicalHeight = img.height;
418 x = dx - previewSize;
420 logicalWidth = img.height;
421 logicalHeight = img.width;
424 ctx.clearRect( 0, 0, 180, 180 );
425 ctx.rotate( rotation / 180 * Math.PI );
426 ctx.drawImage( img, x, y, width, height );
427 $spinner.replaceWith( $canvas );
430 const info = mw.msg( 'widthheight', logicalWidth, logicalHeight ) +
431 ', ' + prettySize( file.size );
433 $( '#mw-upload-thumbnail .fileinfo' ).text( info );
435 img.onerror = function () {
436 // Can happen for example for invalid SVG files
440 }, mw.config.get( 'wgFileCanRotate' ) && !CSS.supports( 'image-orientation', 'from-image' ) ? ( data ) => {
441 const jpegmeta = require( 'mediawiki.libs.jpegmeta' );
443 meta = jpegmeta( data, file.fileName );
444 // eslint-disable-next-line no-underscore-dangle, camelcase
445 meta._binary_data = null;
453 * Check if the file does not exceed the maximum size
458 function checkMaxUploadSize( file ) {
459 function getMaxUploadSize( type ) {
460 const sizes = mw.config.get( 'wgMaxUploadSize' );
462 if ( sizes[ type ] !== undefined ) {
463 return sizes[ type ];
468 $( '.mw-upload-source-error' ).remove();
470 const maxSize = getMaxUploadSize( 'file' );
471 if ( file.size > maxSize ) {
472 const $error = $( '<p>' )
473 .addClass( 'error mw-upload-source-error' )
474 .attr( 'id', 'wpSourceTypeFile-error' )
475 .text( mw.msg( 'largefileserver' ) );
477 $( '#wpUploadFile' ).after( $error );
486 if ( hasFileAPI() ) {
487 // Update thumbnail when the file selection control is updated.
488 $( '#wpUploadFile' ).on( 'change', function () {
491 if ( this.files && this.files.length ) {
492 // Note: would need to be updated to handle multiple files.
493 file = this.files[ 0 ];
495 if ( !checkMaxUploadSize( file ) ) {
499 if ( fileIsPreviewable( file ) ) {
507 // Disable all upload source fields except the selected one
509 const $rows = $( '.mw-htmlform-field-UploadSourceField' );
511 $rows.on( 'change', 'input[type="radio"]', function ( e ) {
512 const currentRow = e.delegateTarget;
514 if ( !this.checked ) {
518 $( '.mw-upload-source-error' ).remove();
520 // Enable selected upload method
521 $( currentRow ).find( 'input' ).prop( 'disabled', false );
523 // Disable inputs of other upload methods
524 // (except for the radio button to re-enable it)
527 .find( 'input[type!="radio"]' )
528 .prop( 'disabled', true );
532 if ( !$( '#wpSourceTypeurl' ).prop( 'checked' ) ) {
533 $( '#wpUploadFileURL' ).prop( 'disabled', true );
538 // Prevent losing work
539 const $uploadForm = $( '#mw-upload-form' );
541 if ( !mw.user.options.get( 'useeditwarning' ) ) {
542 // If the user doesn't want edit warnings, don't set things up.
546 $uploadForm.data( 'origtext', $uploadForm.serialize() );
548 const allowCloseWindow = mw.confirmCloseWindow( {
550 const $wpUploadFile = $( '#wpUploadFile' );
551 // check for existence of #wpUploadFile in case a gadget removed it (T262844)
553 $wpUploadFile.length && $wpUploadFile.get( 0 ).files.length !== 0
554 ) || $uploadForm.data( 'origtext' ) !== $uploadForm.serialize();
558 $uploadForm.on( 'submit', () => {
559 allowCloseWindow.release();
563 // Add tabindex to mw-editTools
565 // Function to change tabindex for all links within mw-editTools
566 function setEditTabindex( $val ) {
567 $( '.mw-editTools' ).find( 'a' ).each( function () {
568 $( this ).attr( 'tabindex', $val );
572 // Change tabindex to 0 if user pressed spaced or enter while focused
573 $( '.mw-editTools' ).on( 'keypress', function ( e ) {
574 // Don't continue if pressed key was not enter or spacebar
575 if ( e.which !== 13 && e.which !== 32 ) {
579 // Change tabindex only when main div has focus
580 if ( $( this ).is( ':focus' ) ) {
581 $( this ).find( 'a' ).first().trigger( 'focus' );
582 setEditTabindex( '0' );
586 // Reset tabindex for elements when user focused out mw-editTools
587 $( '.mw-editTools' ).on( 'focusout', ( e ) => {
588 // Don't continue if relatedTarget is within mw-editTools
589 if ( e.relatedTarget !== null && $( e.relatedTarget ).closest( '.mw-editTools' ).length > 0 ) {
593 // Reset tabindex back to -1
594 setEditTabindex( '-1' );
597 // Set initial tabindex for mw-editTools to 0 and to -1 for all links
598 $( '.mw-editTools' ).attr( 'tabindex', '0' );
599 setEditTabindex( '-1' );