2 * JavaScript for Special:Upload
5 * @class mw.special.upload
9 /* global Uint8Array */
11 ( function ( mw
, $ ) {
12 var uploadWarning
, uploadTemplatePreview
,
13 ajaxUploadDestCheck
= mw
.config
.get( 'wgAjaxUploadDestCheck' ),
14 $license
= $( '#wpLicense' );
16 window
.wgUploadWarningObj
= uploadWarning
= {
17 responseCache
: { '': ' ' },
23 keypress: function () {
24 if ( !ajaxUploadDestCheck
) {
28 // Find file to upload
29 if ( !$( '#wpDestFile' ).length
|| !$( '#wpDestFile-warning' ).length
) {
33 this.nameToCheck
= $( '#wpDestFile' ).val();
36 if ( this.timeoutID
) {
37 clearTimeout( this.timeoutID
);
39 // Check response cache
40 if ( this.responseCache
.hasOwnProperty( this.nameToCheck
) ) {
41 this.setWarning( this.responseCache
[ this.nameToCheck
] );
45 this.timeoutID
= setTimeout( function () {
46 uploadWarning
.timeout();
50 checkNow: function ( fname
) {
51 if ( !ajaxUploadDestCheck
) {
54 if ( this.timeoutID
) {
55 clearTimeout( this.timeoutID
);
57 this.nameToCheck
= fname
;
61 timeout: function () {
62 var $spinnerDestCheck
, title
;
63 if ( !ajaxUploadDestCheck
|| this.nameToCheck
.trim() === '' ) {
66 $spinnerDestCheck
= $.createSpinner().insertAfter( '#wpDestFile' );
67 title
= mw
.Title
.newFromText( this.nameToCheck
, mw
.config
.get( 'wgNamespaceIds' ).file
);
69 ( new mw
.Api() ).get( {
72 // If title is empty, user input is invalid, the API call will produce details about why
73 titles
: [ title
? title
.getPrefixedText() : this.nameToCheck
],
75 iiprop
: 'uploadwarning',
77 errorlang
: mw
.config
.get( 'wgUserLanguage' )
78 } ).done( function ( result
) {
81 page
= result
.query
.pages
[ 0 ];
82 if ( page
.imageinfo
) {
83 resultOut
= page
.imageinfo
[ 0 ].html
;
84 } else if ( page
.invalidreason
) {
85 resultOut
= page
.invalidreason
.html
;
87 uploadWarning
.processResult( resultOut
, uploadWarning
.nameToCheck
);
88 } ).always( function () {
89 $spinnerDestCheck
.remove();
93 processResult: function ( result
, fileName
) {
94 this.setWarning( result
);
95 this.responseCache
[ fileName
] = result
;
98 setWarning: function ( warning
) {
99 var $warningBox
= $( '#wpDestFile-warning' ),
100 $warning
= $( $.parseHTML( warning
) );
101 mw
.hook( 'wikipage.content' ).fire( $warning
);
102 $warningBox
.empty().append( $warning
);
104 // Set a value in the form indicating that the warning is acknowledged and
105 // doesn't need to be redisplayed post-upload
107 $( '#wpDestFileWarningAck' ).val( '' );
108 $warningBox
.removeAttr( 'class' );
110 $( '#wpDestFileWarningAck' ).val( '1' );
111 $warningBox
.attr( 'class', 'mw-destfile-warning' );
117 window
.wgUploadTemplatePreviewObj
= uploadTemplatePreview
= {
119 responseCache
: { '': '' },
122 * @param {jQuery} $element The element whose .val() will be previewed
123 * @param {jQuery} $previewContainer The container to display the preview in
125 getPreview: function ( $element
, $previewContainer
) {
126 var template
= $element
.val(),
129 if ( this.responseCache
.hasOwnProperty( template
) ) {
130 this.showPreview( this.responseCache
[ template
], $previewContainer
);
134 $spinner
= $.createSpinner().insertAfter( $element
);
136 ( new mw
.Api() ).parse( '{{' + template
+ '}}', {
137 title
: $( '#wpDestFile' ).val() || 'File:Sample.jpg',
140 uselang
: mw
.config
.get( 'wgUserLanguage' )
141 } ).done( function ( result
) {
142 uploadTemplatePreview
.processResult( result
, template
, $previewContainer
);
143 } ).always( function () {
148 processResult: function ( result
, template
, $previewContainer
) {
149 this.responseCache
[ template
] = result
;
150 this.showPreview( this.responseCache
[ template
], $previewContainer
);
153 showPreview: function ( preview
, $previewContainer
) {
154 $previewContainer
.html( preview
);
160 // AJAX wpDestFile warnings
161 if ( ajaxUploadDestCheck
) {
162 // Insert an event handler that fetches upload warnings when wpDestFile
164 $( '#wpDestFile' ).change( function () {
165 uploadWarning
.checkNow( $( this ).val() );
167 // Insert a row where the warnings will be displayed just below the
169 $( '#mw-htmlform-description tbody' ).append(
172 .attr( 'id', 'wpDestFile-warning' )
173 .attr( 'colspan', 2 )
178 if ( mw
.config
.get( 'wgAjaxLicensePreview' ) && $license
.length
) {
179 // License selector check
180 $license
.change( function () {
181 // We might show a preview
182 uploadTemplatePreview
.getPreview( $license
, $( '#mw-license-preview' ) );
185 // License selector table row
186 $license
.closest( 'tr' ).after(
189 $( '<td>' ).attr( 'id', 'mw-license-preview' )
194 // fillDestFile setup
195 mw
.config
.get( 'wgUploadSourceIds' ).forEach( function ( sourceId
) {
196 $( '#' + sourceId
).change( function () {
197 var path
, slash
, backslash
, fname
;
198 if ( !mw
.config
.get( 'wgUploadAutoFill' ) ) {
201 // Remove any previously flagged errors
202 $( '#mw-upload-permitted' ).attr( 'class', '' );
203 $( '#mw-upload-prohibited' ).attr( 'class', '' );
205 path
= $( this ).val();
206 // Find trailing part
207 slash
= path
.lastIndexOf( '/' );
208 backslash
= path
.lastIndexOf( '\\' );
209 if ( slash
=== -1 && backslash
=== -1 ) {
211 } else if ( slash
> backslash
) {
212 fname
= path
.slice( slash
+ 1 );
214 fname
= path
.slice( backslash
+ 1 );
217 // Clear the filename if it does not have a valid extension.
218 // URLs are less likely to have a useful extension, so don't include them in the
221 mw
.config
.get( 'wgCheckFileExtensions' ) &&
222 mw
.config
.get( 'wgStrictFileExtensions' ) &&
223 Array
.isArray( mw
.config
.get( 'wgFileExtensions' ) ) &&
224 $( this ).attr( 'id' ) !== 'wpUploadFileURL'
227 fname
.lastIndexOf( '.' ) === -1 ||
228 mw
.config
.get( 'wgFileExtensions' ).map( function ( element
) {
229 return element
.toLowerCase();
230 } ).indexOf( fname
.slice( fname
.lastIndexOf( '.' ) + 1 ).toLowerCase() ) === -1
232 // Not a valid extension
233 // Clear the upload and set mw-upload-permitted to error
235 $( '#mw-upload-permitted' ).attr( 'class', 'error' );
236 $( '#mw-upload-prohibited' ).attr( 'class', 'error' );
237 // Clear wpDestFile as well
238 $( '#wpDestFile' ).val( '' );
244 // Replace spaces by underscores
245 fname
= fname
.replace( / /g
, '_' );
246 // Capitalise first letter if needed
247 if ( mw
.config
.get( 'wgCapitalizeUploads' ) ) {
248 fname
= fname
[ 0 ].toUpperCase() + fname
.slice( 1 );
252 if ( $( '#wpDestFile' ).length
) {
253 // Call decodeURIComponent function to remove possible URL-encoded characters
254 // from the file name (T32390). Especially likely with upload-form-url.
255 // decodeURIComponent can throw an exception if input is invalid utf-8
257 $( '#wpDestFile' ).val( decodeURIComponent( fname
) );
259 $( '#wpDestFile' ).val( fname
);
261 uploadWarning
.checkNow( fname
);
267 // Add a preview to the upload form
270 * Is the FileAPI available with sufficient functionality?
274 function hasFileAPI() {
275 return window
.FileReader
!== undefined;
279 * Check if this is a recognizable image type...
280 * Also excludes files over 10M to avoid going insane on memory usage.
282 * TODO: Is there a way we can ask the browser what's supported in `<img>`s?
284 * TODO: Put SVG back after working around Firefox 7 bug <https://phabricator.wikimedia.org/T33643>
289 function fileIsPreviewable( file
) {
290 var known
= [ 'image/png', 'image/gif', 'image/jpeg', 'image/svg+xml' ],
291 tooHuge
= 10 * 1024 * 1024;
292 return ( known
.indexOf( file
.type
) !== -1 ) && file
.size
> 0 && file
.size
< tooHuge
;
296 * Format a file size attractively.
298 * TODO: Match numeric formatting
303 function prettySize( s
) {
304 var sizeMsgs
= [ 'size-bytes', 'size-kilobytes', 'size-megabytes', 'size-gigabytes' ];
305 while ( s
>= 1024 && sizeMsgs
.length
> 1 ) {
307 sizeMsgs
= sizeMsgs
.slice( 1 );
309 return mw
.msg( sizeMsgs
[ 0 ], Math
.round( s
) );
313 * Start loading a file into memory; when complete, pass it as a
314 * data URL to the callback function. If the callbackBinary is set it will
315 * first be read as binary and afterwards as data URL. Useful if you want
316 * to do preprocessing on the binary data first.
319 * @param {Function} callback
320 * @param {Function} callbackBinary
322 function fetchPreview( file
, callback
, callbackBinary
) {
323 var reader
= new FileReader();
324 if ( callbackBinary
&& 'readAsBinaryString' in reader
) {
325 // To fetch JPEG metadata we need a binary string; start there.
327 reader
.onload = function () {
328 callbackBinary( reader
.result
);
330 // Now run back through the regular code path.
331 fetchPreview( file
, callback
);
333 reader
.readAsBinaryString( file
);
334 } else if ( callbackBinary
&& 'readAsArrayBuffer' in reader
) {
335 // readAsArrayBuffer replaces readAsBinaryString
336 // However, our JPEG metadata library wants a string.
337 // So, this is going to be an ugly conversion.
338 reader
.onload = function () {
340 buffer
= new Uint8Array( reader
.result
),
342 for ( i
= 0; i
< buffer
.byteLength
; i
++ ) {
343 string
+= String
.fromCharCode( buffer
[ i
] );
345 callbackBinary( string
);
347 // Now run back through the regular code path.
348 fetchPreview( file
, callback
);
350 reader
.readAsArrayBuffer( file
);
351 } else if ( 'URL' in window
&& 'createObjectURL' in window
.URL
) {
352 // Supported in Firefox 4.0 and above <https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL>
353 // WebKit has it in a namespace for now but that's ok. ;)
355 // Lifetime of this URL is until document close, which is fine
356 // for Special:Upload -- if this code gets used on longer-running
357 // pages, add a revokeObjectURL() when it's no longer needed.
359 // Prefer this over readAsDataURL for Firefox 7 due to bug reading
360 // some SVG files from data URIs <https://bugzilla.mozilla.org/show_bug.cgi?id=694165>
361 callback( window
.URL
.createObjectURL( file
) );
363 // This ends up decoding the file to base-64 and back again, which
364 // feels horribly inefficient.
365 reader
.onload = function () {
366 callback( reader
.result
);
368 reader
.readAsDataURL( file
);
373 * Clear the file upload preview area.
375 function clearPreview() {
376 $( '#mw-upload-thumbnail' ).remove();
380 * Show a thumbnail preview of PNG, JPEG, GIF, and SVG files prior to upload
381 * in browsers supporting HTML5 FileAPI.
383 * As of this writing, known good:
386 * - Chrome 7.something
388 * TODO: Check file size limits and warn of likely failures
392 function showPreview( file
) {
397 $spinner
= $.createSpinner( { size
: 'small', type
: 'block' } )
398 .css( { width
: previewSize
, height
: previewSize
} ),
399 thumb
= mw
.template
.get( 'mediawiki.special.upload', 'thumbnail.html' ).render();
402 .find( '.filename' ).text( file
.name
).end()
403 .find( '.fileinfo' ).text( prettySize( file
.size
) ).end()
404 .find( '.thumbinner' ).prepend( $spinner
).end();
406 $canvas
= $( '<canvas>' ).attr( { width
: previewSize
, height
: previewSize
} );
407 ctx
= $canvas
[ 0 ].getContext( '2d' );
408 $( '#mw-htmlform-source' ).parent().prepend( thumb
);
410 fetchPreview( file
, function ( dataURL
) {
411 var img
= new Image(),
414 if ( meta
&& meta
.tiff
&& meta
.tiff
.Orientation
) {
415 rotation
= ( 360 - ( function () {
416 // See includes/media/Bitmap.php
417 switch ( meta
.tiff
.Orientation
.value
) {
430 img
.onload = function () {
431 var info
, width
, height
, x
, y
, dx
, dy
, logicalWidth
, logicalHeight
;
433 // Fit the image within the previewSizexpreviewSize box
434 if ( img
.width
> img
.height
) {
436 height
= img
.height
/ img
.width
* previewSize
;
438 height
= previewSize
;
439 width
= img
.width
/ img
.height
* previewSize
;
441 // Determine the offset required to center the image
442 dx
= ( 180 - width
) / 2;
443 dy
= ( 180 - height
) / 2;
444 switch ( rotation
) {
445 // If a rotation is applied, the direction of the axis
446 // changes as well. You can derive the values below by
447 // drawing on paper an axis system, rotate it and see
448 // where the positive axis direction is
452 logicalWidth
= img
.width
;
453 logicalHeight
= img
.height
;
458 y
= dy
- previewSize
;
459 logicalWidth
= img
.height
;
460 logicalHeight
= img
.width
;
463 x
= dx
- previewSize
;
464 y
= dy
- previewSize
;
465 logicalWidth
= img
.width
;
466 logicalHeight
= img
.height
;
469 x
= dx
- previewSize
;
471 logicalWidth
= img
.height
;
472 logicalHeight
= img
.width
;
476 ctx
.clearRect( 0, 0, 180, 180 );
477 ctx
.rotate( rotation
/ 180 * Math
.PI
);
478 ctx
.drawImage( img
, x
, y
, width
, height
);
479 $spinner
.replaceWith( $canvas
);
482 info
= mw
.msg( 'widthheight', logicalWidth
, logicalHeight
) +
483 ', ' + prettySize( file
.size
);
485 $( '#mw-upload-thumbnail .fileinfo' ).text( info
);
487 img
.onerror = function () {
488 // Can happen for example for invalid SVG files
492 }, mw
.config
.get( 'wgFileCanRotate' ) ? function ( data
) {
493 var jpegmeta
= mw
.loader
.require( 'mediawiki.libs.jpegmeta' );
495 meta
= jpegmeta( data
, file
.fileName
);
496 // eslint-disable-next-line no-underscore-dangle, camelcase
497 meta
._binary_data
= null;
505 * Check if the file does not exceed the maximum size
510 function checkMaxUploadSize( file
) {
513 function getMaxUploadSize( type
) {
514 var sizes
= mw
.config
.get( 'wgMaxUploadSize' );
516 if ( sizes
[ type
] !== undefined ) {
517 return sizes
[ type
];
522 $( '.mw-upload-source-error' ).remove();
524 maxSize
= getMaxUploadSize( 'file' );
525 if ( file
.size
> maxSize
) {
526 $error
= $( '<p class="error mw-upload-source-error" id="wpSourceTypeFile-error">' +
527 mw
.message( 'largefileserver', file
.size
, maxSize
).escaped() + '</p>' );
529 $( '#wpUploadFile' ).after( $error
);
538 if ( hasFileAPI() ) {
539 // Update thumbnail when the file selection control is updated.
540 $( '#wpUploadFile' ).change( function () {
543 if ( this.files
&& this.files
.length
) {
544 // Note: would need to be updated to handle multiple files.
545 file
= this.files
[ 0 ];
547 if ( !checkMaxUploadSize( file
) ) {
551 if ( fileIsPreviewable( file
) ) {
559 // Disable all upload source fields except the selected one
561 var $rows
= $( '.mw-htmlform-field-UploadSourceField' );
563 $rows
.on( 'change', 'input[type="radio"]', function ( e
) {
564 var currentRow
= e
.delegateTarget
;
566 if ( !this.checked
) {
570 $( '.mw-upload-source-error' ).remove();
572 // Enable selected upload method
573 $( currentRow
).find( 'input' ).prop( 'disabled', false );
575 // Disable inputs of other upload methods
576 // (except for the radio button to re-enable it)
579 .find( 'input[type!="radio"]' )
580 .prop( 'disabled', true );
584 if ( !$( '#wpSourceTypeurl' ).prop( 'checked' ) ) {
585 $( '#wpUploadFileURL' ).prop( 'disabled', true );
590 // Prevent losing work
591 var allowCloseWindow
,
592 $uploadForm
= $( '#mw-upload-form' );
594 if ( !mw
.user
.options
.get( 'useeditwarning' ) ) {
595 // If the user doesn't want edit warnings, don't set things up.
599 $uploadForm
.data( 'origtext', $uploadForm
.serialize() );
601 allowCloseWindow
= mw
.confirmCloseWindow( {
603 return $( '#wpUploadFile' ).get( 0 ).files
.length
!== 0 ||
604 $uploadForm
.data( 'origtext' ) !== $uploadForm
.serialize();
607 message
: mw
.msg( 'editwarning-warning' ),
608 namespace: 'uploadwarning'
611 $uploadForm
.submit( function () {
612 allowCloseWindow
.release();
616 // Add tabindex to mw-editTools
618 // Function to change tabindex for all links within mw-editTools
619 function setEditTabindex( $val
) {
620 $( '.mw-editTools' ).find( 'a' ).each( function () {
621 $( this ).attr( 'tabindex', $val
);
625 // Change tabindex to 0 if user pressed spaced or enter while focused
626 $( '.mw-editTools' ).on( 'keypress', function ( e
) {
627 // Don't continue if pressed key was not enter or spacebar
628 if ( e
.which
!== 13 && e
.which
!== 32 ) {
632 // Change tabindex only when main div has focus
633 if ( $( this ).is( ':focus' ) ) {
634 $( this ).find( 'a' ).first().focus();
635 setEditTabindex( '0' );
639 // Reset tabindex for elements when user focused out mw-editTools
640 $( '.mw-editTools' ).on( 'focusout', function ( e
) {
641 // Don't continue if relatedTarget is within mw-editTools
642 if ( e
.relatedTarget
!== null && $( e
.relatedTarget
).closest( '.mw-editTools' ).length
> 0 ) {
646 // Reset tabindex back to -1
647 setEditTabindex( '-1' );
650 // Set initial tabindex for mw-editTools to 0 and to -1 for all links
651 $( '.mw-editTools' ).attr( 'tabindex', '0' );
652 setEditTabindex( '-1' );
654 }( mediaWiki
, jQuery
) );