2 * JavaScript for Special:Upload
5 * @class mw.special.upload
9 /*jshint latedef:false */
10 var uploadWarning
, uploadLicense
,
11 ajaxUploadDestCheck
= mw
.config
.get( 'wgAjaxUploadDestCheck' ),
12 $license
= $( '#wpLicense' );
14 window
.wgUploadWarningObj
= uploadWarning
= {
15 responseCache
: { '': ' ' },
21 keypress: function () {
22 if ( !ajaxUploadDestCheck
) {
26 // Find file to upload
27 if ( !$( '#wpDestFile' ).length
|| !$( '#wpDestFile-warning' ).length
) {
31 this.nameToCheck
= $( '#wpDestFile' ).val();
34 if ( this.timeoutID
) {
35 clearTimeout( this.timeoutID
);
37 // Check response cache
38 if ( this.responseCache
.hasOwnProperty( this.nameToCheck
) ) {
39 this.setWarning( this.responseCache
[ this.nameToCheck
] );
43 this.timeoutID
= setTimeout( function () {
44 uploadWarning
.timeout();
48 checkNow: function ( fname
) {
49 if ( !ajaxUploadDestCheck
) {
52 if ( this.timeoutID
) {
53 clearTimeout( this.timeoutID
);
55 this.nameToCheck
= fname
;
59 timeout: function () {
60 var $spinnerDestCheck
, title
;
61 if ( !ajaxUploadDestCheck
|| this.nameToCheck
=== '' ) {
64 $spinnerDestCheck
= $.createSpinner().insertAfter( '#wpDestFile' );
65 title
= mw
.Title
.newFromText( this.nameToCheck
, mw
.config
.get( 'wgNamespaceIds' ).file
);
67 ( new mw
.Api() ).get( {
70 // If title is empty, user input is invalid, the API call will produce details about why
71 titles
: title
? title
.getPrefixedText() : this.nameToCheck
,
73 iiprop
: 'uploadwarning'
74 } ).done( function ( result
) {
77 page
= result
.query
.pages
[ 0 ];
78 if ( page
.imageinfo
) {
79 resultOut
= page
.imageinfo
[ 0 ].html
;
80 } else if ( page
.invalidreason
) {
81 resultOut
= mw
.html
.escape( page
.invalidreason
);
83 $spinnerDestCheck
.remove();
84 uploadWarning
.processResult( resultOut
, uploadWarning
.nameToCheck
);
88 processResult: function ( result
, fileName
) {
89 this.setWarning( result
);
90 this.responseCache
[ fileName
] = result
;
93 setWarning: function ( warning
) {
94 var $warning
= $( $.parseHTML( warning
) );
95 mw
.hook( 'wikipage.content' ).fire( $warning
);
96 $( '#wpDestFile-warning' ).empty().append( $warning
);
98 // Set a value in the form indicating that the warning is acknowledged and
99 // doesn't need to be redisplayed post-upload
101 $( '#wpDestFileWarningAck' ).val( '' );
103 $( '#wpDestFileWarningAck' ).val( '1' );
111 responseCache
: { '': '' },
113 fetchPreview: function ( license
) {
115 if ( !mw
.config
.get( 'wgAjaxLicensePreview' ) ) {
118 if ( this.responseCache
.hasOwnProperty( license
) ) {
119 this.showPreview( this.responseCache
[ license
] );
123 $spinnerLicense
= $.createSpinner().insertAfter( '#wpLicense' );
125 ( new mw
.Api() ).get( {
128 text
: '{{' + license
+ '}}',
129 title
: $( '#wpDestFile' ).val() || 'File:Sample.jpg',
132 } ).done( function ( result
) {
133 $spinnerLicense
.remove();
134 uploadLicense
.processResult( result
, license
);
138 processResult: function ( result
, license
) {
139 this.responseCache
[ license
] = result
.parse
.text
;
140 this.showPreview( this.responseCache
[ license
] );
143 showPreview: function ( preview
) {
144 $( '#mw-license-preview' ).html( preview
);
150 // AJAX wpDestFile warnings
151 if ( ajaxUploadDestCheck
) {
152 // Insert an event handler that fetches upload warnings when wpDestFile
154 $( '#wpDestFile' ).change( function () {
155 uploadWarning
.checkNow( $( this ).val() );
157 // Insert a row where the warnings will be displayed just below the
159 $( '#mw-htmlform-description tbody' ).append(
162 .attr( 'id', 'wpDestFile-warning' )
163 .attr( 'colspan', 2 )
168 if ( mw
.config
.get( 'wgAjaxLicensePreview' ) && $license
.length
) {
169 // License selector check
170 $license
.change( function () {
171 // We might show a preview
172 uploadLicense
.fetchPreview( $license
.val() );
175 // License selector table row
176 $license
.closest( 'tr' ).after(
179 $( '<td>' ).attr( 'id', 'mw-license-preview' )
184 // fillDestFile setup
185 $.each( mw
.config
.get( 'wgUploadSourceIds' ), function ( index
, sourceId
) {
186 $( '#' + sourceId
).change( function () {
187 var path
, slash
, backslash
, fname
;
188 if ( !mw
.config
.get( 'wgUploadAutoFill' ) ) {
191 // Remove any previously flagged errors
192 $( '#mw-upload-permitted' ).attr( 'class', '' );
193 $( '#mw-upload-prohibited' ).attr( 'class', '' );
195 path
= $( this ).val();
196 // Find trailing part
197 slash
= path
.lastIndexOf( '/' );
198 backslash
= path
.lastIndexOf( '\\' );
199 if ( slash
=== -1 && backslash
=== -1 ) {
201 } else if ( slash
> backslash
) {
202 fname
= path
.slice( slash
+ 1 );
204 fname
= path
.slice( backslash
+ 1 );
207 // Clear the filename if it does not have a valid extension.
208 // URLs are less likely to have a useful extension, so don't include them in the
211 mw
.config
.get( 'wgCheckFileExtensions' ) &&
212 mw
.config
.get( 'wgStrictFileExtensions' ) &&
213 mw
.config
.get( 'wgFileExtensions' ) &&
214 $( this ).attr( 'id' ) !== 'wpUploadFileURL'
217 fname
.lastIndexOf( '.' ) === -1 ||
219 fname
.slice( fname
.lastIndexOf( '.' ) + 1 ).toLowerCase(),
220 $.map( mw
.config
.get( 'wgFileExtensions' ), function ( element
) {
221 return element
.toLowerCase();
225 // Not a valid extension
226 // Clear the upload and set mw-upload-permitted to error
228 $( '#mw-upload-permitted' ).attr( 'class', 'error' );
229 $( '#mw-upload-prohibited' ).attr( 'class', 'error' );
230 // Clear wpDestFile as well
231 $( '#wpDestFile' ).val( '' );
237 // Replace spaces by underscores
238 fname
= fname
.replace( / /g
, '_' );
239 // Capitalise first letter if needed
240 if ( mw
.config
.get( 'wgCapitalizeUploads' ) ) {
241 fname
= fname
[ 0 ].toUpperCase() + fname
.slice( 1 );
245 if ( $( '#wpDestFile' ).length
) {
246 // Call decodeURIComponent function to remove possible URL-encoded characters
247 // from the file name (bug 30390). Especially likely with upload-form-url.
248 // decodeURIComponent can throw an exception if input is invalid utf-8
250 $( '#wpDestFile' ).val( decodeURIComponent( fname
) );
252 $( '#wpDestFile' ).val( fname
);
254 uploadWarning
.checkNow( fname
);
260 // Add a preview to the upload form
263 * Is the FileAPI available with sufficient functionality?
265 function hasFileAPI() {
266 return window
.FileReader
!== undefined;
270 * Check if this is a recognizable image type...
271 * Also excludes files over 10M to avoid going insane on memory usage.
273 * TODO: Is there a way we can ask the browser what's supported in `<img>`s?
275 * TODO: Put SVG back after working around Firefox 7 bug <https://phabricator.wikimedia.org/T33643>
280 function fileIsPreviewable( file
) {
281 var known
= [ 'image/png', 'image/gif', 'image/jpeg', 'image/svg+xml' ],
282 tooHuge
= 10 * 1024 * 1024;
283 return ( $.inArray( file
.type
, known
) !== -1 ) && file
.size
> 0 && file
.size
< tooHuge
;
287 * Format a file size attractively.
289 * TODO: Match numeric formatting
294 function prettySize( s
) {
295 var sizeMsgs
= [ 'size-bytes', 'size-kilobytes', 'size-megabytes', 'size-gigabytes' ];
296 while ( s
>= 1024 && sizeMsgs
.length
> 1 ) {
298 sizeMsgs
= sizeMsgs
.slice( 1 );
300 return mw
.msg( sizeMsgs
[ 0 ], Math
.round( s
) );
304 * Show a thumbnail preview of PNG, JPEG, GIF, and SVG files prior to upload
305 * in browsers supporting HTML5 FileAPI.
307 * As of this writing, known good:
310 * - Chrome 7.something
312 * TODO: Check file size limits and warn of likely failures
316 function showPreview( file
) {
321 $spinner
= $.createSpinner( { size
: 'small', type
: 'block' } )
322 .css( { width
: previewSize
, height
: previewSize
} ),
323 thumb
= mw
.template
.get( 'mediawiki.special.upload', 'thumbnail.html' ).render();
326 .find( '.filename' ).text( file
.name
).end()
327 .find( '.fileinfo' ).text( prettySize( file
.size
) ).end()
328 .find( '.thumbinner' ).prepend( $spinner
).end();
330 $canvas
= $( '<canvas>' ).attr( { width
: previewSize
, height
: previewSize
} );
331 ctx
= $canvas
[ 0 ].getContext( '2d' );
332 $( '#mw-htmlform-source' ).parent().prepend( thumb
);
334 fetchPreview( file
, function ( dataURL
) {
335 var img
= new Image(),
338 if ( meta
&& meta
.tiff
&& meta
.tiff
.Orientation
) {
339 rotation
= ( 360 - ( function () {
340 // See includes/media/Bitmap.php
341 switch ( meta
.tiff
.Orientation
.value
) {
354 img
.onload = function () {
355 var info
, width
, height
, x
, y
, dx
, dy
, logicalWidth
, logicalHeight
;
357 // Fit the image within the previewSizexpreviewSize box
358 if ( img
.width
> img
.height
) {
360 height
= img
.height
/ img
.width
* previewSize
;
362 height
= previewSize
;
363 width
= img
.width
/ img
.height
* previewSize
;
365 // Determine the offset required to center the image
366 dx
= ( 180 - width
) / 2;
367 dy
= ( 180 - height
) / 2;
368 switch ( rotation
) {
369 // If a rotation is applied, the direction of the axis
370 // changes as well. You can derive the values below by
371 // drawing on paper an axis system, rotate it and see
372 // where the positive axis direction is
376 logicalWidth
= img
.width
;
377 logicalHeight
= img
.height
;
382 y
= dy
- previewSize
;
383 logicalWidth
= img
.height
;
384 logicalHeight
= img
.width
;
387 x
= dx
- previewSize
;
388 y
= dy
- previewSize
;
389 logicalWidth
= img
.width
;
390 logicalHeight
= img
.height
;
393 x
= dx
- previewSize
;
395 logicalWidth
= img
.height
;
396 logicalHeight
= img
.width
;
400 ctx
.clearRect( 0, 0, 180, 180 );
401 ctx
.rotate( rotation
/ 180 * Math
.PI
);
402 ctx
.drawImage( img
, x
, y
, width
, height
);
403 $spinner
.replaceWith( $canvas
);
406 info
= mw
.msg( 'widthheight', logicalWidth
, logicalHeight
) +
407 ', ' + prettySize( file
.size
);
409 $( '#mw-upload-thumbnail .fileinfo' ).text( info
);
411 img
.onerror = function () {
412 // Can happen for example for invalid SVG files
416 }, mw
.config
.get( 'wgFileCanRotate' ) ? function ( data
) {
418 meta
= mw
.libs
.jpegmeta( data
, file
.fileName
);
419 // jscs:disable requireCamelCaseOrUpperCaseIdentifiers, disallowDanglingUnderscores
420 meta
._binary_data
= null;
429 * Start loading a file into memory; when complete, pass it as a
430 * data URL to the callback function. If the callbackBinary is set it will
431 * first be read as binary and afterwards as data URL. Useful if you want
432 * to do preprocessing on the binary data first.
435 * @param {Function} callback
436 * @param {Function} callbackBinary
438 function fetchPreview( file
, callback
, callbackBinary
) {
439 var reader
= new FileReader();
440 if ( callbackBinary
&& 'readAsBinaryString' in reader
) {
441 // To fetch JPEG metadata we need a binary string; start there.
443 reader
.onload = function () {
444 callbackBinary( reader
.result
);
446 // Now run back through the regular code path.
447 fetchPreview( file
, callback
);
449 reader
.readAsBinaryString( file
);
450 } else if ( callbackBinary
&& 'readAsArrayBuffer' in reader
) {
451 // readAsArrayBuffer replaces readAsBinaryString
452 // However, our JPEG metadata library wants a string.
453 // So, this is going to be an ugly conversion.
454 reader
.onload = function () {
456 buffer
= new Uint8Array( reader
.result
),
458 for ( i
= 0; i
< buffer
.byteLength
; i
++ ) {
459 string
+= String
.fromCharCode( buffer
[ i
] );
461 callbackBinary( string
);
463 // Now run back through the regular code path.
464 fetchPreview( file
, callback
);
466 reader
.readAsArrayBuffer( file
);
467 } else if ( 'URL' in window
&& 'createObjectURL' in window
.URL
) {
468 // Supported in Firefox 4.0 and above <https://developer.mozilla.org/en/DOM/window.URL.createObjectURL>
469 // WebKit has it in a namespace for now but that's ok. ;)
471 // Lifetime of this URL is until document close, which is fine
472 // for Special:Upload -- if this code gets used on longer-running
473 // pages, add a revokeObjectURL() when it's no longer needed.
475 // Prefer this over readAsDataURL for Firefox 7 due to bug reading
476 // some SVG files from data URIs <https://bugzilla.mozilla.org/show_bug.cgi?id=694165>
477 callback( window
.URL
.createObjectURL( file
) );
479 // This ends up decoding the file to base-64 and back again, which
480 // feels horribly inefficient.
481 reader
.onload = function () {
482 callback( reader
.result
);
484 reader
.readAsDataURL( file
);
489 * Clear the file upload preview area.
491 function clearPreview() {
492 $( '#mw-upload-thumbnail' ).remove();
496 * Check if the file does not exceed the maximum size
498 function checkMaxUploadSize( file
) {
501 function getMaxUploadSize( type
) {
502 var sizes
= mw
.config
.get( 'wgMaxUploadSize' );
504 if ( sizes
[ type
] !== undefined ) {
505 return sizes
[ type
];
510 $( '.mw-upload-source-error' ).remove();
512 maxSize
= getMaxUploadSize( 'file' );
513 if ( file
.size
> maxSize
) {
514 $error
= $( '<p class="error mw-upload-source-error" id="wpSourceTypeFile-error">' +
515 mw
.message( 'largefileserver', file
.size
, maxSize
).escaped() + '</p>' );
517 $( '#wpUploadFile' ).after( $error
);
526 if ( hasFileAPI() ) {
527 // Update thumbnail when the file selection control is updated.
528 $( '#wpUploadFile' ).change( function () {
530 if ( this.files
&& this.files
.length
) {
531 // Note: would need to be updated to handle multiple files.
532 var file
= this.files
[ 0 ];
534 if ( !checkMaxUploadSize( file
) ) {
538 if ( fileIsPreviewable( file
) ) {
546 // Disable all upload source fields except the selected one
548 var $rows
= $( '.mw-htmlform-field-UploadSourceField' );
550 $rows
.on( 'change', 'input[type="radio"]', function ( e
) {
551 var currentRow
= e
.delegateTarget
;
553 if ( !this.checked
) {
557 $( '.mw-upload-source-error' ).remove();
559 // Enable selected upload method
560 $( currentRow
).find( 'input' ).prop( 'disabled', false );
562 // Disable inputs of other upload methods
563 // (except for the radio button to re-enable it)
566 .find( 'input[type!="radio"]' )
567 .prop( 'disabled', true );
571 if ( !$( '#wpSourceTypeurl' ).prop( 'checked' ) ) {
572 $( '#wpUploadFileURL' ).prop( 'disabled', true );
577 // Prevent losing work
578 var allowCloseWindow
,
579 $uploadForm
= $( '#mw-upload-form' );
581 if ( !mw
.user
.options
.get( 'useeditwarning' ) ) {
582 // If the user doesn't want edit warnings, don't set things up.
586 $uploadForm
.data( 'origtext', $uploadForm
.serialize() );
588 allowCloseWindow
= mw
.confirmCloseWindow( {
590 return $( '#wpUploadFile' ).get( 0 ).files
.length
!== 0 ||
591 $uploadForm
.data( 'origtext' ) !== $uploadForm
.serialize();
594 message
: mw
.msg( 'editwarning-warning' ),
595 namespace: 'uploadwarning'
598 $uploadForm
.submit( function () {
599 allowCloseWindow
.release();
602 }( mediaWiki
, jQuery
) );