2 * JavaScript for Special:Upload
5 * @class mw.special.upload
9 /* global Uint8Array */
12 var uploadWarning
, uploadTemplatePreview
,
13 ajaxUploadDestCheck
= mw
.config
.get( 'wgAjaxUploadDestCheck' ),
14 $license
= $( '#wpLicense' );
16 window
.wgUploadWarningObj
= uploadWarning
= {
17 responseCache
: { '': ' ' },
23 checkNow: function ( fname
) {
24 if ( !ajaxUploadDestCheck
) {
27 if ( this.timeoutID
) {
28 clearTimeout( this.timeoutID
);
30 this.nameToCheck
= fname
;
34 timeout: function () {
35 var $spinnerDestCheck
, title
;
36 if ( !ajaxUploadDestCheck
|| this.nameToCheck
.trim() === '' ) {
39 $spinnerDestCheck
= $.createSpinner().insertAfter( '#wpDestFile' );
40 title
= mw
.Title
.newFromText( this.nameToCheck
, mw
.config
.get( 'wgNamespaceIds' ).file
);
42 ( new mw
.Api() ).get( {
45 // If title is empty, user input is invalid, the API call will produce details about why
46 titles
: [ title
? title
.getPrefixedText() : this.nameToCheck
],
48 iiprop
: 'uploadwarning',
50 errorlang
: mw
.config
.get( 'wgUserLanguage' )
51 } ).done( function ( result
) {
54 page
= result
.query
.pages
[ 0 ];
55 if ( page
.imageinfo
) {
56 resultOut
= page
.imageinfo
[ 0 ].html
;
57 } else if ( page
.invalidreason
) {
58 resultOut
= page
.invalidreason
.html
;
60 uploadWarning
.processResult( resultOut
, uploadWarning
.nameToCheck
);
61 } ).always( function () {
62 $spinnerDestCheck
.remove();
66 processResult: function ( result
, fileName
) {
67 this.setWarning( result
);
68 this.responseCache
[ fileName
] = result
;
71 setWarning: function ( warning
) {
72 var $warningBox
= $( '#wpDestFile-warning' ),
73 $warning
= $( $.parseHTML( warning
) );
74 mw
.hook( 'wikipage.content' ).fire( $warning
);
75 $warningBox
.empty().append( $warning
);
77 // Set a value in the form indicating that the warning is acknowledged and
78 // doesn't need to be redisplayed post-upload
80 $( '#wpDestFileWarningAck' ).val( '' );
81 $warningBox
.removeAttr( 'class' );
83 $( '#wpDestFileWarningAck' ).val( '1' );
84 $warningBox
.attr( 'class', 'mw-destfile-warning' );
90 window
.wgUploadTemplatePreviewObj
= uploadTemplatePreview
= {
92 responseCache
: { '': '' },
95 * @param {jQuery} $element The element whose .val() will be previewed
96 * @param {jQuery} $previewContainer The container to display the preview in
98 getPreview: function ( $element
, $previewContainer
) {
99 var template
= $element
.val(),
102 if ( Object
.prototype.hasOwnProperty
.call( this.responseCache
, template
) ) {
103 this.showPreview( this.responseCache
[ template
], $previewContainer
);
107 $spinner
= $.createSpinner().insertAfter( $element
);
109 ( new mw
.Api() ).parse( '{{' + template
+ '}}', {
110 title
: $( '#wpDestFile' ).val() || 'File:Sample.jpg',
113 uselang
: mw
.config
.get( 'wgUserLanguage' )
114 } ).done( function ( result
) {
115 uploadTemplatePreview
.processResult( result
, template
, $previewContainer
);
116 } ).always( function () {
121 processResult: function ( result
, template
, $previewContainer
) {
122 this.responseCache
[ template
] = result
;
123 this.showPreview( this.responseCache
[ template
], $previewContainer
);
126 showPreview: function ( preview
, $previewContainer
) {
127 $previewContainer
.html( preview
);
133 // AJAX wpDestFile warnings
134 if ( ajaxUploadDestCheck
) {
135 // Insert an event handler that fetches upload warnings when wpDestFile
137 $( '#wpDestFile' ).on( 'change', function () {
138 uploadWarning
.checkNow( $( this ).val() );
140 // Insert a row where the warnings will be displayed just below the
142 $( '#mw-htmlform-description tbody' ).append(
145 .attr( 'id', 'wpDestFile-warning' )
146 .attr( 'colspan', 2 )
151 if ( mw
.config
.get( 'wgAjaxLicensePreview' ) && $license
.length
) {
152 // License selector check
153 $license
.on( 'change', function () {
154 // We might show a preview
155 uploadTemplatePreview
.getPreview( $license
, $( '#mw-license-preview' ) );
158 // License selector table row
159 $license
.closest( 'tr' ).after(
162 $( '<td>' ).attr( 'id', 'mw-license-preview' )
167 // fillDestFile setup
168 mw
.config
.get( 'wgUploadSourceIds' ).forEach( function ( sourceId
) {
169 $( '#' + sourceId
).on( 'change', function () {
170 var path
, slash
, backslash
, fname
;
171 if ( !mw
.config
.get( 'wgUploadAutoFill' ) ) {
174 // Remove any previously flagged errors
175 $( '#mw-upload-permitted' ).attr( 'class', '' );
176 $( '#mw-upload-prohibited' ).attr( 'class', '' );
178 path
= $( this ).val();
179 // Find trailing part
180 slash
= path
.lastIndexOf( '/' );
181 backslash
= path
.lastIndexOf( '\\' );
182 if ( slash
=== -1 && backslash
=== -1 ) {
184 } else if ( slash
> backslash
) {
185 fname
= path
.slice( slash
+ 1 );
187 fname
= path
.slice( backslash
+ 1 );
190 // Clear the filename if it does not have a valid extension.
191 // URLs are less likely to have a useful extension, so don't include them in the
194 mw
.config
.get( 'wgCheckFileExtensions' ) &&
195 mw
.config
.get( 'wgStrictFileExtensions' ) &&
196 Array
.isArray( mw
.config
.get( 'wgFileExtensions' ) ) &&
197 $( this ).attr( 'id' ) !== 'wpUploadFileURL'
200 fname
.lastIndexOf( '.' ) === -1 ||
201 mw
.config
.get( 'wgFileExtensions' ).map( function ( element
) {
202 return element
.toLowerCase();
203 } ).indexOf( fname
.slice( fname
.lastIndexOf( '.' ) + 1 ).toLowerCase() ) === -1
205 // Not a valid extension
206 // Clear the upload and set mw-upload-permitted to error
208 $( '#mw-upload-permitted' ).attr( 'class', 'error' );
209 $( '#mw-upload-prohibited' ).attr( 'class', 'error' );
210 // Clear wpDestFile as well
211 $( '#wpDestFile' ).val( '' );
217 // Replace spaces by underscores
218 fname
= fname
.replace( / /g
, '_' );
219 // Capitalise first letter if needed
220 if ( mw
.config
.get( 'wgCapitalizeUploads' ) ) {
221 fname
= fname
[ 0 ].toUpperCase() + fname
.slice( 1 );
225 if ( $( '#wpDestFile' ).length
) {
226 // Call decodeURIComponent function to remove possible URL-encoded characters
227 // from the file name (T32390). Especially likely with upload-form-url.
228 // decodeURIComponent can throw an exception if input is invalid utf-8
230 $( '#wpDestFile' ).val( decodeURIComponent( fname
) );
232 $( '#wpDestFile' ).val( fname
);
234 uploadWarning
.checkNow( fname
);
240 // Add a preview to the upload form
243 * Is the FileAPI available with sufficient functionality?
247 function hasFileAPI() {
248 return window
.FileReader
!== undefined;
252 * Check if this is a recognizable image type...
253 * Also excludes files over 10M to avoid going insane on memory usage.
255 * TODO: Is there a way we can ask the browser what's supported in `<img>`s?
257 * TODO: Put SVG back after working around Firefox 7 bug <https://phabricator.wikimedia.org/T33643>
262 function fileIsPreviewable( file
) {
263 var known
= [ 'image/png', 'image/gif', 'image/jpeg', 'image/svg+xml' ],
264 tooHuge
= 10 * 1024 * 1024;
265 return ( known
.indexOf( file
.type
) !== -1 ) && file
.size
> 0 && file
.size
< tooHuge
;
269 * Format a file size attractively.
271 * TODO: Match numeric formatting
276 function prettySize( s
) {
277 var sizeMsgs
= [ 'size-bytes', 'size-kilobytes', 'size-megabytes', 'size-gigabytes' ];
278 while ( s
>= 1024 && sizeMsgs
.length
> 1 ) {
280 sizeMsgs
= sizeMsgs
.slice( 1 );
282 return mw
.msg( sizeMsgs
[ 0 ], Math
.round( s
) );
286 * Start loading a file into memory; when complete, pass it as a
287 * data URL to the callback function. If the callbackBinary is set it will
288 * first be read as binary and afterwards as data URL. Useful if you want
289 * to do preprocessing on the binary data first.
292 * @param {Function} callback
293 * @param {Function} callbackBinary
295 function fetchPreview( file
, callback
, callbackBinary
) {
296 var reader
= new FileReader();
297 if ( callbackBinary
&& 'readAsBinaryString' in reader
) {
298 // To fetch JPEG metadata we need a binary string; start there.
300 reader
.onload = function () {
301 callbackBinary( reader
.result
);
303 // Now run back through the regular code path.
304 fetchPreview( file
, callback
);
306 reader
.readAsBinaryString( file
);
307 } else if ( callbackBinary
&& 'readAsArrayBuffer' in reader
) {
308 // readAsArrayBuffer replaces readAsBinaryString
309 // However, our JPEG metadata library wants a string.
310 // So, this is going to be an ugly conversion.
311 reader
.onload = function () {
313 buffer
= new Uint8Array( reader
.result
),
315 for ( i
= 0; i
< buffer
.byteLength
; i
++ ) {
316 string
+= String
.fromCharCode( buffer
[ i
] );
318 callbackBinary( string
);
320 // Now run back through the regular code path.
321 fetchPreview( file
, callback
);
323 reader
.readAsArrayBuffer( file
);
324 } else if ( 'URL' in window
&& 'createObjectURL' in window
.URL
) {
325 // Supported in Firefox 4.0 and above <https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL>
326 // WebKit has it in a namespace for now but that's ok. ;)
328 // Lifetime of this URL is until document close, which is fine
329 // for Special:Upload -- if this code gets used on longer-running
330 // pages, add a revokeObjectURL() when it's no longer needed.
332 // Prefer this over readAsDataURL for Firefox 7 due to bug reading
333 // some SVG files from data URIs <https://bugzilla.mozilla.org/show_bug.cgi?id=694165>
334 callback( window
.URL
.createObjectURL( file
) );
336 // This ends up decoding the file to base-64 and back again, which
337 // feels horribly inefficient.
338 reader
.onload = function () {
339 callback( reader
.result
);
341 reader
.readAsDataURL( file
);
346 * Clear the file upload preview area.
348 function clearPreview() {
349 $( '#mw-upload-thumbnail' ).remove();
353 * Show a thumbnail preview of PNG, JPEG, GIF, and SVG files prior to upload
354 * in browsers supporting HTML5 FileAPI.
356 * As of this writing, known good:
359 * - Chrome 7.something
361 * TODO: Check file size limits and warn of likely failures
365 function showPreview( file
) {
370 $spinner
= $.createSpinner( { size
: 'small', type
: 'block' } )
371 .css( { width
: previewSize
, height
: previewSize
} ),
372 thumb
= mw
.template
.get( 'mediawiki.special.upload', 'thumbnail.html' ).render();
375 .find( '.filename' ).text( file
.name
).end()
376 .find( '.fileinfo' ).text( prettySize( file
.size
) ).end()
377 .find( '.thumbinner' ).prepend( $spinner
).end();
379 $canvas
= $( '<canvas>' ).attr( { width
: previewSize
, height
: previewSize
} );
380 ctx
= $canvas
[ 0 ].getContext( '2d' );
381 $( '#mw-htmlform-source' ).parent().prepend( thumb
);
383 fetchPreview( file
, function ( dataURL
) {
384 var img
= new Image(),
387 if ( meta
&& meta
.tiff
&& meta
.tiff
.Orientation
) {
388 rotation
= ( 360 - ( function () {
389 // See BitmapHandler class in PHP
390 switch ( meta
.tiff
.Orientation
.value
) {
403 img
.onload = function () {
404 var info
, width
, height
, x
, y
, dx
, dy
, logicalWidth
, logicalHeight
;
406 // Fit the image within the previewSizexpreviewSize box
407 if ( img
.width
> img
.height
) {
409 height
= img
.height
/ img
.width
* previewSize
;
411 height
= previewSize
;
412 width
= img
.width
/ img
.height
* previewSize
;
414 // Determine the offset required to center the image
415 dx
= ( 180 - width
) / 2;
416 dy
= ( 180 - height
) / 2;
417 switch ( rotation
) {
418 // If a rotation is applied, the direction of the axis
419 // changes as well. You can derive the values below by
420 // drawing on paper an axis system, rotate it and see
421 // where the positive axis direction is
425 logicalWidth
= img
.width
;
426 logicalHeight
= img
.height
;
431 y
= dy
- previewSize
;
432 logicalWidth
= img
.height
;
433 logicalHeight
= img
.width
;
436 x
= dx
- previewSize
;
437 y
= dy
- previewSize
;
438 logicalWidth
= img
.width
;
439 logicalHeight
= img
.height
;
442 x
= dx
- previewSize
;
444 logicalWidth
= img
.height
;
445 logicalHeight
= img
.width
;
449 ctx
.clearRect( 0, 0, 180, 180 );
450 ctx
.rotate( rotation
/ 180 * Math
.PI
);
451 ctx
.drawImage( img
, x
, y
, width
, height
);
452 $spinner
.replaceWith( $canvas
);
455 info
= mw
.msg( 'widthheight', logicalWidth
, logicalHeight
) +
456 ', ' + prettySize( file
.size
);
458 $( '#mw-upload-thumbnail .fileinfo' ).text( info
);
460 img
.onerror = function () {
461 // Can happen for example for invalid SVG files
465 }, mw
.config
.get( 'wgFileCanRotate' ) ? function ( data
) {
466 var jpegmeta
= require( 'mediawiki.libs.jpegmeta' );
468 meta
= jpegmeta( data
, file
.fileName
);
469 // eslint-disable-next-line no-underscore-dangle, camelcase
470 meta
._binary_data
= null;
478 * Check if the file does not exceed the maximum size
483 function checkMaxUploadSize( file
) {
486 function getMaxUploadSize( type
) {
487 var sizes
= mw
.config
.get( 'wgMaxUploadSize' );
489 if ( sizes
[ type
] !== undefined ) {
490 return sizes
[ type
];
495 $( '.mw-upload-source-error' ).remove();
497 maxSize
= getMaxUploadSize( 'file' );
498 if ( file
.size
> maxSize
) {
499 $error
= $( '<p class="error mw-upload-source-error" id="wpSourceTypeFile-error">' +
500 mw
.message( 'largefileserver', file
.size
, maxSize
).escaped() + '</p>' );
502 $( '#wpUploadFile' ).after( $error
);
511 if ( hasFileAPI() ) {
512 // Update thumbnail when the file selection control is updated.
513 $( '#wpUploadFile' ).on( 'change', function () {
516 if ( this.files
&& this.files
.length
) {
517 // Note: would need to be updated to handle multiple files.
518 file
= this.files
[ 0 ];
520 if ( !checkMaxUploadSize( file
) ) {
524 if ( fileIsPreviewable( file
) ) {
532 // Disable all upload source fields except the selected one
534 var $rows
= $( '.mw-htmlform-field-UploadSourceField' );
536 $rows
.on( 'change', 'input[type="radio"]', function ( e
) {
537 var currentRow
= e
.delegateTarget
;
539 if ( !this.checked
) {
543 $( '.mw-upload-source-error' ).remove();
545 // Enable selected upload method
546 $( currentRow
).find( 'input' ).prop( 'disabled', false );
548 // Disable inputs of other upload methods
549 // (except for the radio button to re-enable it)
552 .find( 'input[type!="radio"]' )
553 .prop( 'disabled', true );
557 if ( !$( '#wpSourceTypeurl' ).prop( 'checked' ) ) {
558 $( '#wpUploadFileURL' ).prop( 'disabled', true );
563 // Prevent losing work
564 var allowCloseWindow
,
565 $uploadForm
= $( '#mw-upload-form' );
567 if ( !mw
.user
.options
.get( 'useeditwarning' ) ) {
568 // If the user doesn't want edit warnings, don't set things up.
572 $uploadForm
.data( 'origtext', $uploadForm
.serialize() );
574 allowCloseWindow
= mw
.confirmCloseWindow( {
576 return $( '#wpUploadFile' ).get( 0 ).files
.length
!== 0 ||
577 $uploadForm
.data( 'origtext' ) !== $uploadForm
.serialize();
580 message
: mw
.msg( 'editwarning-warning' ),
581 namespace: 'uploadwarning'
584 $uploadForm
.on( 'submit', function () {
585 allowCloseWindow
.release();
589 // Add tabindex to mw-editTools
591 // Function to change tabindex for all links within mw-editTools
592 function setEditTabindex( $val
) {
593 $( '.mw-editTools' ).find( 'a' ).each( function () {
594 $( this ).attr( 'tabindex', $val
);
598 // Change tabindex to 0 if user pressed spaced or enter while focused
599 $( '.mw-editTools' ).on( 'keypress', function ( e
) {
600 // Don't continue if pressed key was not enter or spacebar
601 if ( e
.which
!== 13 && e
.which
!== 32 ) {
605 // Change tabindex only when main div has focus
606 if ( $( this ).is( ':focus' ) ) {
607 $( this ).find( 'a' ).first().trigger( 'focus' );
608 setEditTabindex( '0' );
612 // Reset tabindex for elements when user focused out mw-editTools
613 $( '.mw-editTools' ).on( 'focusout', function ( e
) {
614 // Don't continue if relatedTarget is within mw-editTools
615 if ( e
.relatedTarget
!== null && $( e
.relatedTarget
).closest( '.mw-editTools' ).length
> 0 ) {
619 // Reset tabindex back to -1
620 setEditTabindex( '-1' );
623 // Set initial tabindex for mw-editTools to 0 and to -1 for all links
624 $( '.mw-editTools' ).attr( 'tabindex', '0' );
625 setEditTabindex( '-1' );