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
, uploadLicense
,
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' );
118 responseCache
: { '': '' },
120 fetchPreview: function ( license
) {
122 if ( !mw
.config
.get( 'wgAjaxLicensePreview' ) ) {
125 if ( this.responseCache
.hasOwnProperty( license
) ) {
126 this.showPreview( this.responseCache
[ license
] );
130 $spinnerLicense
= $.createSpinner().insertAfter( '#wpLicense' );
132 ( new mw
.Api() ).get( {
135 text
: '{{' + license
+ '}}',
136 title
: $( '#wpDestFile' ).val() || 'File:Sample.jpg',
139 uselang
: mw
.config
.get( 'wgUserLanguage' )
140 } ).done( function ( result
) {
141 uploadLicense
.processResult( result
, license
);
142 } ).always( function () {
143 $spinnerLicense
.remove();
147 processResult: function ( result
, license
) {
148 this.responseCache
[ license
] = result
.parse
.text
;
149 this.showPreview( this.responseCache
[ license
] );
152 showPreview: function ( preview
) {
153 $( '#mw-license-preview' ).html( preview
);
159 // AJAX wpDestFile warnings
160 if ( ajaxUploadDestCheck
) {
161 // Insert an event handler that fetches upload warnings when wpDestFile
163 $( '#wpDestFile' ).change( function () {
164 uploadWarning
.checkNow( $( this ).val() );
166 // Insert a row where the warnings will be displayed just below the
168 $( '#mw-htmlform-description tbody' ).append(
171 .attr( 'id', 'wpDestFile-warning' )
172 .attr( 'colspan', 2 )
177 if ( mw
.config
.get( 'wgAjaxLicensePreview' ) && $license
.length
) {
178 // License selector check
179 $license
.change( function () {
180 // We might show a preview
181 uploadLicense
.fetchPreview( $license
.val() );
184 // License selector table row
185 $license
.closest( 'tr' ).after(
188 $( '<td>' ).attr( 'id', 'mw-license-preview' )
193 // fillDestFile setup
194 $.each( mw
.config
.get( 'wgUploadSourceIds' ), function ( index
, sourceId
) {
195 $( '#' + sourceId
).change( function () {
196 var path
, slash
, backslash
, fname
;
197 if ( !mw
.config
.get( 'wgUploadAutoFill' ) ) {
200 // Remove any previously flagged errors
201 $( '#mw-upload-permitted' ).attr( 'class', '' );
202 $( '#mw-upload-prohibited' ).attr( 'class', '' );
204 path
= $( this ).val();
205 // Find trailing part
206 slash
= path
.lastIndexOf( '/' );
207 backslash
= path
.lastIndexOf( '\\' );
208 if ( slash
=== -1 && backslash
=== -1 ) {
210 } else if ( slash
> backslash
) {
211 fname
= path
.slice( slash
+ 1 );
213 fname
= path
.slice( backslash
+ 1 );
216 // Clear the filename if it does not have a valid extension.
217 // URLs are less likely to have a useful extension, so don't include them in the
220 mw
.config
.get( 'wgCheckFileExtensions' ) &&
221 mw
.config
.get( 'wgStrictFileExtensions' ) &&
222 mw
.config
.get( 'wgFileExtensions' ) &&
223 $( this ).attr( 'id' ) !== 'wpUploadFileURL'
226 fname
.lastIndexOf( '.' ) === -1 ||
228 fname
.slice( fname
.lastIndexOf( '.' ) + 1 ).toLowerCase(),
229 $.map( mw
.config
.get( 'wgFileExtensions' ), function ( element
) {
230 return element
.toLowerCase();
234 // Not a valid extension
235 // Clear the upload and set mw-upload-permitted to error
237 $( '#mw-upload-permitted' ).attr( 'class', 'error' );
238 $( '#mw-upload-prohibited' ).attr( 'class', 'error' );
239 // Clear wpDestFile as well
240 $( '#wpDestFile' ).val( '' );
246 // Replace spaces by underscores
247 fname
= fname
.replace( / /g
, '_' );
248 // Capitalise first letter if needed
249 if ( mw
.config
.get( 'wgCapitalizeUploads' ) ) {
250 fname
= fname
[ 0 ].toUpperCase() + fname
.slice( 1 );
254 if ( $( '#wpDestFile' ).length
) {
255 // Call decodeURIComponent function to remove possible URL-encoded characters
256 // from the file name (T32390). Especially likely with upload-form-url.
257 // decodeURIComponent can throw an exception if input is invalid utf-8
259 $( '#wpDestFile' ).val( decodeURIComponent( fname
) );
261 $( '#wpDestFile' ).val( fname
);
263 uploadWarning
.checkNow( fname
);
269 // Add a preview to the upload form
272 * Is the FileAPI available with sufficient functionality?
276 function hasFileAPI() {
277 return window
.FileReader
!== undefined;
281 * Check if this is a recognizable image type...
282 * Also excludes files over 10M to avoid going insane on memory usage.
284 * TODO: Is there a way we can ask the browser what's supported in `<img>`s?
286 * TODO: Put SVG back after working around Firefox 7 bug <https://phabricator.wikimedia.org/T33643>
291 function fileIsPreviewable( file
) {
292 var known
= [ 'image/png', 'image/gif', 'image/jpeg', 'image/svg+xml' ],
293 tooHuge
= 10 * 1024 * 1024;
294 return ( $.inArray( file
.type
, known
) !== -1 ) && file
.size
> 0 && file
.size
< tooHuge
;
298 * Format a file size attractively.
300 * TODO: Match numeric formatting
305 function prettySize( s
) {
306 var sizeMsgs
= [ 'size-bytes', 'size-kilobytes', 'size-megabytes', 'size-gigabytes' ];
307 while ( s
>= 1024 && sizeMsgs
.length
> 1 ) {
309 sizeMsgs
= sizeMsgs
.slice( 1 );
311 return mw
.msg( sizeMsgs
[ 0 ], Math
.round( s
) );
315 * Show a thumbnail preview of PNG, JPEG, GIF, and SVG files prior to upload
316 * in browsers supporting HTML5 FileAPI.
318 * As of this writing, known good:
321 * - Chrome 7.something
323 * TODO: Check file size limits and warn of likely failures
327 function showPreview( file
) {
332 $spinner
= $.createSpinner( { size
: 'small', type
: 'block' } )
333 .css( { width
: previewSize
, height
: previewSize
} ),
334 thumb
= mw
.template
.get( 'mediawiki.special.upload', 'thumbnail.html' ).render();
337 .find( '.filename' ).text( file
.name
).end()
338 .find( '.fileinfo' ).text( prettySize( file
.size
) ).end()
339 .find( '.thumbinner' ).prepend( $spinner
).end();
341 $canvas
= $( '<canvas>' ).attr( { width
: previewSize
, height
: previewSize
} );
342 ctx
= $canvas
[ 0 ].getContext( '2d' );
343 $( '#mw-htmlform-source' ).parent().prepend( thumb
);
345 fetchPreview( file
, function ( dataURL
) {
346 var img
= new Image(),
349 if ( meta
&& meta
.tiff
&& meta
.tiff
.Orientation
) {
350 rotation
= ( 360 - ( function () {
351 // See includes/media/Bitmap.php
352 switch ( meta
.tiff
.Orientation
.value
) {
365 img
.onload = function () {
366 var info
, width
, height
, x
, y
, dx
, dy
, logicalWidth
, logicalHeight
;
368 // Fit the image within the previewSizexpreviewSize box
369 if ( img
.width
> img
.height
) {
371 height
= img
.height
/ img
.width
* previewSize
;
373 height
= previewSize
;
374 width
= img
.width
/ img
.height
* previewSize
;
376 // Determine the offset required to center the image
377 dx
= ( 180 - width
) / 2;
378 dy
= ( 180 - height
) / 2;
379 switch ( rotation
) {
380 // If a rotation is applied, the direction of the axis
381 // changes as well. You can derive the values below by
382 // drawing on paper an axis system, rotate it and see
383 // where the positive axis direction is
387 logicalWidth
= img
.width
;
388 logicalHeight
= img
.height
;
393 y
= dy
- previewSize
;
394 logicalWidth
= img
.height
;
395 logicalHeight
= img
.width
;
398 x
= dx
- previewSize
;
399 y
= dy
- previewSize
;
400 logicalWidth
= img
.width
;
401 logicalHeight
= img
.height
;
404 x
= dx
- previewSize
;
406 logicalWidth
= img
.height
;
407 logicalHeight
= img
.width
;
411 ctx
.clearRect( 0, 0, 180, 180 );
412 ctx
.rotate( rotation
/ 180 * Math
.PI
);
413 ctx
.drawImage( img
, x
, y
, width
, height
);
414 $spinner
.replaceWith( $canvas
);
417 info
= mw
.msg( 'widthheight', logicalWidth
, logicalHeight
) +
418 ', ' + prettySize( file
.size
);
420 $( '#mw-upload-thumbnail .fileinfo' ).text( info
);
422 img
.onerror = function () {
423 // Can happen for example for invalid SVG files
427 }, mw
.config
.get( 'wgFileCanRotate' ) ? function ( data
) {
429 meta
= mw
.libs
.jpegmeta( data
, file
.fileName
);
430 // eslint-disable-next-line no-underscore-dangle, camelcase
431 meta
._binary_data
= null;
439 * Start loading a file into memory; when complete, pass it as a
440 * data URL to the callback function. If the callbackBinary is set it will
441 * first be read as binary and afterwards as data URL. Useful if you want
442 * to do preprocessing on the binary data first.
445 * @param {Function} callback
446 * @param {Function} callbackBinary
448 function fetchPreview( file
, callback
, callbackBinary
) {
449 var reader
= new FileReader();
450 if ( callbackBinary
&& 'readAsBinaryString' in reader
) {
451 // To fetch JPEG metadata we need a binary string; start there.
453 reader
.onload = function () {
454 callbackBinary( reader
.result
);
456 // Now run back through the regular code path.
457 fetchPreview( file
, callback
);
459 reader
.readAsBinaryString( file
);
460 } else if ( callbackBinary
&& 'readAsArrayBuffer' in reader
) {
461 // readAsArrayBuffer replaces readAsBinaryString
462 // However, our JPEG metadata library wants a string.
463 // So, this is going to be an ugly conversion.
464 reader
.onload = function () {
466 buffer
= new Uint8Array( reader
.result
),
468 for ( i
= 0; i
< buffer
.byteLength
; i
++ ) {
469 string
+= String
.fromCharCode( buffer
[ i
] );
471 callbackBinary( string
);
473 // Now run back through the regular code path.
474 fetchPreview( file
, callback
);
476 reader
.readAsArrayBuffer( file
);
477 } else if ( 'URL' in window
&& 'createObjectURL' in window
.URL
) {
478 // Supported in Firefox 4.0 and above <https://developer.mozilla.org/en/DOM/window.URL.createObjectURL>
479 // WebKit has it in a namespace for now but that's ok. ;)
481 // Lifetime of this URL is until document close, which is fine
482 // for Special:Upload -- if this code gets used on longer-running
483 // pages, add a revokeObjectURL() when it's no longer needed.
485 // Prefer this over readAsDataURL for Firefox 7 due to bug reading
486 // some SVG files from data URIs <https://bugzilla.mozilla.org/show_bug.cgi?id=694165>
487 callback( window
.URL
.createObjectURL( file
) );
489 // This ends up decoding the file to base-64 and back again, which
490 // feels horribly inefficient.
491 reader
.onload = function () {
492 callback( reader
.result
);
494 reader
.readAsDataURL( file
);
499 * Clear the file upload preview area.
501 function clearPreview() {
502 $( '#mw-upload-thumbnail' ).remove();
506 * Check if the file does not exceed the maximum size
511 function checkMaxUploadSize( file
) {
514 function getMaxUploadSize( type
) {
515 var sizes
= mw
.config
.get( 'wgMaxUploadSize' );
517 if ( sizes
[ type
] !== undefined ) {
518 return sizes
[ type
];
523 $( '.mw-upload-source-error' ).remove();
525 maxSize
= getMaxUploadSize( 'file' );
526 if ( file
.size
> maxSize
) {
527 $error
= $( '<p class="error mw-upload-source-error" id="wpSourceTypeFile-error">' +
528 mw
.message( 'largefileserver', file
.size
, maxSize
).escaped() + '</p>' );
530 $( '#wpUploadFile' ).after( $error
);
539 if ( hasFileAPI() ) {
540 // Update thumbnail when the file selection control is updated.
541 $( '#wpUploadFile' ).change( function () {
544 if ( this.files
&& this.files
.length
) {
545 // Note: would need to be updated to handle multiple files.
546 file
= this.files
[ 0 ];
548 if ( !checkMaxUploadSize( file
) ) {
552 if ( fileIsPreviewable( file
) ) {
560 // Disable all upload source fields except the selected one
562 var $rows
= $( '.mw-htmlform-field-UploadSourceField' );
564 $rows
.on( 'change', 'input[type="radio"]', function ( e
) {
565 var currentRow
= e
.delegateTarget
;
567 if ( !this.checked
) {
571 $( '.mw-upload-source-error' ).remove();
573 // Enable selected upload method
574 $( currentRow
).find( 'input' ).prop( 'disabled', false );
576 // Disable inputs of other upload methods
577 // (except for the radio button to re-enable it)
580 .find( 'input[type!="radio"]' )
581 .prop( 'disabled', true );
585 if ( !$( '#wpSourceTypeurl' ).prop( 'checked' ) ) {
586 $( '#wpUploadFileURL' ).prop( 'disabled', true );
591 // Prevent losing work
592 var allowCloseWindow
,
593 $uploadForm
= $( '#mw-upload-form' );
595 if ( !mw
.user
.options
.get( 'useeditwarning' ) ) {
596 // If the user doesn't want edit warnings, don't set things up.
600 $uploadForm
.data( 'origtext', $uploadForm
.serialize() );
602 allowCloseWindow
= mw
.confirmCloseWindow( {
604 return $( '#wpUploadFile' ).get( 0 ).files
.length
!== 0 ||
605 $uploadForm
.data( 'origtext' ) !== $uploadForm
.serialize();
608 message
: mw
.msg( 'editwarning-warning' ),
609 namespace: 'uploadwarning'
612 $uploadForm
.submit( function () {
613 allowCloseWindow
.release();
617 // Add tabindex to mw-editTools
619 // Function to change tabindex for all links within mw-editTools
620 function setEditTabindex( $val
) {
621 $( '.mw-editTools' ).find( 'a' ).each( function () {
622 $( this ).attr( 'tabindex', $val
);
626 // Change tabindex to 0 if user pressed spaced or enter while focused
627 $( '.mw-editTools' ).on( 'keypress', function ( e
) {
628 // Don't continue if pressed key was not enter or spacebar
629 if ( e
.which
!== 13 && e
.which
!== 32 ) {
633 // Change tabindex only when main div has focus
634 if ( $( this ).is( ':focus' ) ) {
635 $( this ).find( 'a' ).first().focus();
636 setEditTabindex( '0' );
640 // Reset tabindex for elements when user focused out mw-editTools
641 $( '.mw-editTools' ).on( 'focusout', function ( e
) {
642 // Don't continue if relatedTarget is within mw-editTools
643 if ( e
.relatedTarget
!== null && $( e
.relatedTarget
).closest( '.mw-editTools' ).length
> 0 ) {
647 // Reset tabindex back to -1
648 setEditTabindex( '-1' );
651 // Set initial tabindex for mw-editTools to 0 and to -1 for all links
652 $( '.mw-editTools' ).attr( 'tabindex', '0' );
653 setEditTabindex( '-1' );
655 }( mediaWiki
, jQuery
) );