2 * JavaScript for Special:Upload
5 * @class mw.special.upload
9 /* eslint-disable no-use-before-define */
10 /* global Uint8Array */
12 ( function ( mw
, $ ) {
13 var uploadWarning
, uploadTemplatePreview
,
14 ajaxUploadDestCheck
= mw
.config
.get( 'wgAjaxUploadDestCheck' ),
15 $license
= $( '#wpLicense' );
17 window
.wgUploadWarningObj
= uploadWarning
= {
18 responseCache
: { '': ' ' },
24 keypress: function () {
25 if ( !ajaxUploadDestCheck
) {
29 // Find file to upload
30 if ( !$( '#wpDestFile' ).length
|| !$( '#wpDestFile-warning' ).length
) {
34 this.nameToCheck
= $( '#wpDestFile' ).val();
37 if ( this.timeoutID
) {
38 clearTimeout( this.timeoutID
);
40 // Check response cache
41 if ( this.responseCache
.hasOwnProperty( this.nameToCheck
) ) {
42 this.setWarning( this.responseCache
[ this.nameToCheck
] );
46 this.timeoutID
= setTimeout( function () {
47 uploadWarning
.timeout();
51 checkNow: function ( fname
) {
52 if ( !ajaxUploadDestCheck
) {
55 if ( this.timeoutID
) {
56 clearTimeout( this.timeoutID
);
58 this.nameToCheck
= fname
;
62 timeout: function () {
63 var $spinnerDestCheck
, title
;
64 if ( !ajaxUploadDestCheck
|| this.nameToCheck
=== '' ) {
67 $spinnerDestCheck
= $.createSpinner().insertAfter( '#wpDestFile' );
68 title
= mw
.Title
.newFromText( this.nameToCheck
, mw
.config
.get( 'wgNamespaceIds' ).file
);
70 ( new mw
.Api() ).get( {
73 // If title is empty, user input is invalid, the API call will produce details about why
74 titles
: title
? title
.getPrefixedText() : this.nameToCheck
,
76 iiprop
: 'uploadwarning'
77 } ).done( function ( result
) {
80 page
= result
.query
.pages
[ 0 ];
81 if ( page
.imageinfo
) {
82 resultOut
= page
.imageinfo
[ 0 ].html
;
83 } else if ( page
.invalidreason
) {
84 resultOut
= mw
.html
.escape( page
.invalidreason
);
86 uploadWarning
.processResult( resultOut
, uploadWarning
.nameToCheck
);
87 } ).always( function () {
88 $spinnerDestCheck
.remove();
92 processResult: function ( result
, fileName
) {
93 this.setWarning( result
);
94 this.responseCache
[ fileName
] = result
;
97 setWarning: function ( warning
) {
98 var $warningBox
= $( '#wpDestFile-warning' ),
99 $warning
= $( $.parseHTML( warning
) );
100 mw
.hook( 'wikipage.content' ).fire( $warning
);
101 $warningBox
.empty().append( $warning
);
103 // Set a value in the form indicating that the warning is acknowledged and
104 // doesn't need to be redisplayed post-upload
106 $( '#wpDestFileWarningAck' ).val( '' );
107 $warningBox
.removeAttr( 'class' );
109 $( '#wpDestFileWarningAck' ).val( '1' );
110 $warningBox
.attr( 'class', 'mw-destfile-warning' );
116 window
.wgUploadTemplatePreviewObj
= uploadTemplatePreview
= {
118 responseCache
: { '': '' },
121 * @param {jQuery} $element The element whose .val() will be previewed
122 * @param {jQuery} $previewContainer The container to display the preview in
124 getPreview: function ( $element
, $previewContainer
) {
125 var template
= $element
.val(),
128 if ( this.responseCache
.hasOwnProperty( template
) ) {
129 this.showPreview( this.responseCache
[ template
], $previewContainer
);
133 $spinner
= $.createSpinner().insertAfter( $element
);
135 ( new mw
.Api() ).get( {
138 text
: '{{' + template
+ '}}',
139 title
: $( '#wpDestFile' ).val() || 'File:Sample.jpg',
142 } ).done( function ( result
) {
143 uploadTemplatePreview
.processResult( result
, template
, $previewContainer
);
144 } ).always( function () {
149 processResult: function ( result
, template
, $previewContainer
) {
150 this.responseCache
[ template
] = result
.parse
.text
;
151 this.showPreview( this.responseCache
[ template
], $previewContainer
);
154 showPreview: function ( preview
, $previewContainer
) {
155 $previewContainer
.html( preview
);
161 // AJAX wpDestFile warnings
162 if ( ajaxUploadDestCheck
) {
163 // Insert an event handler that fetches upload warnings when wpDestFile
165 $( '#wpDestFile' ).change( function () {
166 uploadWarning
.checkNow( $( this ).val() );
168 // Insert a row where the warnings will be displayed just below the
170 $( '#mw-htmlform-description tbody' ).append(
173 .attr( 'id', 'wpDestFile-warning' )
174 .attr( 'colspan', 2 )
179 if ( mw
.config
.get( 'wgAjaxLicensePreview' ) && $license
.length
) {
180 // License selector check
181 $license
.change( function () {
182 // We might show a preview
183 uploadTemplatePreview
.getPreview( $license
, $( '#mw-license-preview' ) );
186 // License selector table row
187 $license
.closest( 'tr' ).after(
190 $( '<td>' ).attr( 'id', 'mw-license-preview' )
195 // fillDestFile setup
196 $.each( mw
.config
.get( 'wgUploadSourceIds' ), function ( index
, sourceId
) {
197 $( '#' + sourceId
).change( function () {
198 var path
, slash
, backslash
, fname
;
199 if ( !mw
.config
.get( 'wgUploadAutoFill' ) ) {
202 // Remove any previously flagged errors
203 $( '#mw-upload-permitted' ).attr( 'class', '' );
204 $( '#mw-upload-prohibited' ).attr( 'class', '' );
206 path
= $( this ).val();
207 // Find trailing part
208 slash
= path
.lastIndexOf( '/' );
209 backslash
= path
.lastIndexOf( '\\' );
210 if ( slash
=== -1 && backslash
=== -1 ) {
212 } else if ( slash
> backslash
) {
213 fname
= path
.slice( slash
+ 1 );
215 fname
= path
.slice( backslash
+ 1 );
218 // Clear the filename if it does not have a valid extension.
219 // URLs are less likely to have a useful extension, so don't include them in the
222 mw
.config
.get( 'wgCheckFileExtensions' ) &&
223 mw
.config
.get( 'wgStrictFileExtensions' ) &&
224 mw
.config
.get( 'wgFileExtensions' ) &&
225 $( this ).attr( 'id' ) !== 'wpUploadFileURL'
228 fname
.lastIndexOf( '.' ) === -1 ||
230 fname
.slice( fname
.lastIndexOf( '.' ) + 1 ).toLowerCase(),
231 $.map( mw
.config
.get( 'wgFileExtensions' ), function ( element
) {
232 return element
.toLowerCase();
236 // Not a valid extension
237 // Clear the upload and set mw-upload-permitted to error
239 $( '#mw-upload-permitted' ).attr( 'class', 'error' );
240 $( '#mw-upload-prohibited' ).attr( 'class', 'error' );
241 // Clear wpDestFile as well
242 $( '#wpDestFile' ).val( '' );
248 // Replace spaces by underscores
249 fname
= fname
.replace( / /g
, '_' );
250 // Capitalise first letter if needed
251 if ( mw
.config
.get( 'wgCapitalizeUploads' ) ) {
252 fname
= fname
[ 0 ].toUpperCase() + fname
.slice( 1 );
256 if ( $( '#wpDestFile' ).length
) {
257 // Call decodeURIComponent function to remove possible URL-encoded characters
258 // from the file name (T32390). Especially likely with upload-form-url.
259 // decodeURIComponent can throw an exception if input is invalid utf-8
261 $( '#wpDestFile' ).val( decodeURIComponent( fname
) );
263 $( '#wpDestFile' ).val( fname
);
265 uploadWarning
.checkNow( fname
);
271 // Add a preview to the upload form
274 * Is the FileAPI available with sufficient functionality?
278 function hasFileAPI() {
279 return window
.FileReader
!== undefined;
283 * Check if this is a recognizable image type...
284 * Also excludes files over 10M to avoid going insane on memory usage.
286 * TODO: Is there a way we can ask the browser what's supported in `<img>`s?
288 * TODO: Put SVG back after working around Firefox 7 bug <https://phabricator.wikimedia.org/T33643>
293 function fileIsPreviewable( file
) {
294 var known
= [ 'image/png', 'image/gif', 'image/jpeg', 'image/svg+xml' ],
295 tooHuge
= 10 * 1024 * 1024;
296 return ( $.inArray( file
.type
, known
) !== -1 ) && file
.size
> 0 && file
.size
< tooHuge
;
300 * Format a file size attractively.
302 * TODO: Match numeric formatting
307 function prettySize( s
) {
308 var sizeMsgs
= [ 'size-bytes', 'size-kilobytes', 'size-megabytes', 'size-gigabytes' ];
309 while ( s
>= 1024 && sizeMsgs
.length
> 1 ) {
311 sizeMsgs
= sizeMsgs
.slice( 1 );
313 return mw
.msg( sizeMsgs
[ 0 ], Math
.round( s
) );
317 * Show a thumbnail preview of PNG, JPEG, GIF, and SVG files prior to upload
318 * in browsers supporting HTML5 FileAPI.
320 * As of this writing, known good:
323 * - Chrome 7.something
325 * TODO: Check file size limits and warn of likely failures
329 function showPreview( file
) {
334 $spinner
= $.createSpinner( { size
: 'small', type
: 'block' } )
335 .css( { width
: previewSize
, height
: previewSize
} ),
336 thumb
= mw
.template
.get( 'mediawiki.special.upload', 'thumbnail.html' ).render();
339 .find( '.filename' ).text( file
.name
).end()
340 .find( '.fileinfo' ).text( prettySize( file
.size
) ).end()
341 .find( '.thumbinner' ).prepend( $spinner
).end();
343 $canvas
= $( '<canvas>' ).attr( { width
: previewSize
, height
: previewSize
} );
344 ctx
= $canvas
[ 0 ].getContext( '2d' );
345 $( '#mw-htmlform-source' ).parent().prepend( thumb
);
347 fetchPreview( file
, function ( dataURL
) {
348 var img
= new Image(),
351 if ( meta
&& meta
.tiff
&& meta
.tiff
.Orientation
) {
352 rotation
= ( 360 - ( function () {
353 // See includes/media/Bitmap.php
354 switch ( meta
.tiff
.Orientation
.value
) {
367 img
.onload = function () {
368 var info
, width
, height
, x
, y
, dx
, dy
, logicalWidth
, logicalHeight
;
370 // Fit the image within the previewSizexpreviewSize box
371 if ( img
.width
> img
.height
) {
373 height
= img
.height
/ img
.width
* previewSize
;
375 height
= previewSize
;
376 width
= img
.width
/ img
.height
* previewSize
;
378 // Determine the offset required to center the image
379 dx
= ( 180 - width
) / 2;
380 dy
= ( 180 - height
) / 2;
381 switch ( rotation
) {
382 // If a rotation is applied, the direction of the axis
383 // changes as well. You can derive the values below by
384 // drawing on paper an axis system, rotate it and see
385 // where the positive axis direction is
389 logicalWidth
= img
.width
;
390 logicalHeight
= img
.height
;
395 y
= dy
- previewSize
;
396 logicalWidth
= img
.height
;
397 logicalHeight
= img
.width
;
400 x
= dx
- previewSize
;
401 y
= dy
- previewSize
;
402 logicalWidth
= img
.width
;
403 logicalHeight
= img
.height
;
406 x
= dx
- previewSize
;
408 logicalWidth
= img
.height
;
409 logicalHeight
= img
.width
;
413 ctx
.clearRect( 0, 0, 180, 180 );
414 ctx
.rotate( rotation
/ 180 * Math
.PI
);
415 ctx
.drawImage( img
, x
, y
, width
, height
);
416 $spinner
.replaceWith( $canvas
);
419 info
= mw
.msg( 'widthheight', logicalWidth
, logicalHeight
) +
420 ', ' + prettySize( file
.size
);
422 $( '#mw-upload-thumbnail .fileinfo' ).text( info
);
424 img
.onerror = function () {
425 // Can happen for example for invalid SVG files
429 }, mw
.config
.get( 'wgFileCanRotate' ) ? function ( data
) {
431 meta
= mw
.libs
.jpegmeta( data
, file
.fileName
);
432 // eslint-disable-next-line no-underscore-dangle, camelcase
433 meta
._binary_data
= null;
441 * Start loading a file into memory; when complete, pass it as a
442 * data URL to the callback function. If the callbackBinary is set it will
443 * first be read as binary and afterwards as data URL. Useful if you want
444 * to do preprocessing on the binary data first.
447 * @param {Function} callback
448 * @param {Function} callbackBinary
450 function fetchPreview( file
, callback
, callbackBinary
) {
451 var reader
= new FileReader();
452 if ( callbackBinary
&& 'readAsBinaryString' in reader
) {
453 // To fetch JPEG metadata we need a binary string; start there.
455 reader
.onload = function () {
456 callbackBinary( reader
.result
);
458 // Now run back through the regular code path.
459 fetchPreview( file
, callback
);
461 reader
.readAsBinaryString( file
);
462 } else if ( callbackBinary
&& 'readAsArrayBuffer' in reader
) {
463 // readAsArrayBuffer replaces readAsBinaryString
464 // However, our JPEG metadata library wants a string.
465 // So, this is going to be an ugly conversion.
466 reader
.onload = function () {
468 buffer
= new Uint8Array( reader
.result
),
470 for ( i
= 0; i
< buffer
.byteLength
; i
++ ) {
471 string
+= String
.fromCharCode( buffer
[ i
] );
473 callbackBinary( string
);
475 // Now run back through the regular code path.
476 fetchPreview( file
, callback
);
478 reader
.readAsArrayBuffer( file
);
479 } else if ( 'URL' in window
&& 'createObjectURL' in window
.URL
) {
480 // Supported in Firefox 4.0 and above <https://developer.mozilla.org/en/DOM/window.URL.createObjectURL>
481 // WebKit has it in a namespace for now but that's ok. ;)
483 // Lifetime of this URL is until document close, which is fine
484 // for Special:Upload -- if this code gets used on longer-running
485 // pages, add a revokeObjectURL() when it's no longer needed.
487 // Prefer this over readAsDataURL for Firefox 7 due to bug reading
488 // some SVG files from data URIs <https://bugzilla.mozilla.org/show_bug.cgi?id=694165>
489 callback( window
.URL
.createObjectURL( file
) );
491 // This ends up decoding the file to base-64 and back again, which
492 // feels horribly inefficient.
493 reader
.onload = function () {
494 callback( reader
.result
);
496 reader
.readAsDataURL( file
);
501 * Clear the file upload preview area.
503 function clearPreview() {
504 $( '#mw-upload-thumbnail' ).remove();
508 * Check if the file does not exceed the maximum size
513 function checkMaxUploadSize( file
) {
516 function getMaxUploadSize( type
) {
517 var sizes
= mw
.config
.get( 'wgMaxUploadSize' );
519 if ( sizes
[ type
] !== undefined ) {
520 return sizes
[ type
];
525 $( '.mw-upload-source-error' ).remove();
527 maxSize
= getMaxUploadSize( 'file' );
528 if ( file
.size
> maxSize
) {
529 $error
= $( '<p class="error mw-upload-source-error" id="wpSourceTypeFile-error">' +
530 mw
.message( 'largefileserver', file
.size
, maxSize
).escaped() + '</p>' );
532 $( '#wpUploadFile' ).after( $error
);
541 if ( hasFileAPI() ) {
542 // Update thumbnail when the file selection control is updated.
543 $( '#wpUploadFile' ).change( function () {
546 if ( this.files
&& this.files
.length
) {
547 // Note: would need to be updated to handle multiple files.
548 file
= this.files
[ 0 ];
550 if ( !checkMaxUploadSize( file
) ) {
554 if ( fileIsPreviewable( file
) ) {
562 // Disable all upload source fields except the selected one
564 var $rows
= $( '.mw-htmlform-field-UploadSourceField' );
566 $rows
.on( 'change', 'input[type="radio"]', function ( e
) {
567 var currentRow
= e
.delegateTarget
;
569 if ( !this.checked
) {
573 $( '.mw-upload-source-error' ).remove();
575 // Enable selected upload method
576 $( currentRow
).find( 'input' ).prop( 'disabled', false );
578 // Disable inputs of other upload methods
579 // (except for the radio button to re-enable it)
582 .find( 'input[type!="radio"]' )
583 .prop( 'disabled', true );
587 if ( !$( '#wpSourceTypeurl' ).prop( 'checked' ) ) {
588 $( '#wpUploadFileURL' ).prop( 'disabled', true );
593 // Prevent losing work
594 var allowCloseWindow
,
595 $uploadForm
= $( '#mw-upload-form' );
597 if ( !mw
.user
.options
.get( 'useeditwarning' ) ) {
598 // If the user doesn't want edit warnings, don't set things up.
602 $uploadForm
.data( 'origtext', $uploadForm
.serialize() );
604 allowCloseWindow
= mw
.confirmCloseWindow( {
606 return $( '#wpUploadFile' ).get( 0 ).files
.length
!== 0 ||
607 $uploadForm
.data( 'origtext' ) !== $uploadForm
.serialize();
610 message
: mw
.msg( 'editwarning-warning' ),
611 namespace: 'uploadwarning'
614 $uploadForm
.submit( function () {
615 allowCloseWindow
.release();
619 // Add tabindex to mw-editTools
621 // Function to change tabindex for all links within mw-editTools
622 function setEditTabindex( $val
) {
623 $( '.mw-editTools' ).find( 'a' ).each( function () {
624 $( this ).attr( 'tabindex', $val
);
628 // Change tabindex to 0 if user pressed spaced or enter while focused
629 $( '.mw-editTools' ).on( 'keypress', function ( e
) {
630 // Don't continue if pressed key was not enter or spacebar
631 if ( e
.which
!== 13 && e
.which
!== 32 ) {
635 // Change tabindex only when main div has focus
636 if ( $( this ).is( ':focus' ) ) {
637 $( this ).find( 'a' ).first().focus();
638 setEditTabindex( '0' );
642 // Reset tabindex for elements when user focused out mw-editTools
643 $( '.mw-editTools' ).on( 'focusout', function ( e
) {
644 // Don't continue if relatedTarget is within mw-editTools
645 if ( e
.relatedTarget
!== null && $( e
.relatedTarget
).closest( '.mw-editTools' ).length
> 0 ) {
649 // Reset tabindex back to -1
650 setEditTabindex( '-1' );
653 // Set initial tabindex for mw-editTools to 0 and to -1 for all links
654 $( '.mw-editTools' ).attr( 'tabindex', '0' );
655 setEditTabindex( '-1' );
657 }( mediaWiki
, jQuery
) );