2 * JavaScript for Special:Upload
5 * @class mw.special.upload
9 var uploadWarning
, uploadLicense
,
10 ajaxUploadDestCheck
= mw
.config
.get( 'wgAjaxUploadDestCheck' ),
11 $license
= $( '#wpLicense' );
13 window
.wgUploadWarningObj
= uploadWarning
= {
14 responseCache
: { '': ' ' },
20 keypress: function () {
21 if ( !ajaxUploadDestCheck
) {
25 // Find file to upload
26 if ( !$( '#wpDestFile' ).length
|| !$( '#wpDestFile-warning' ).length
) {
30 this.nameToCheck
= $( '#wpDestFile' ).val();
33 if ( this.timeoutID
) {
34 clearTimeout( this.timeoutID
);
36 // Check response cache
37 if ( this.responseCache
.hasOwnProperty( this.nameToCheck
) ) {
38 this.setWarning( this.responseCache
[this.nameToCheck
] );
42 this.timeoutID
= setTimeout( function () {
43 uploadWarning
.timeout();
47 checkNow: function ( fname
) {
48 if ( !ajaxUploadDestCheck
) {
51 if ( this.timeoutID
) {
52 clearTimeout( this.timeoutID
);
54 this.nameToCheck
= fname
;
58 timeout: function () {
59 var $spinnerDestCheck
;
60 if ( !ajaxUploadDestCheck
|| this.nameToCheck
=== '' ) {
63 $spinnerDestCheck
= $.createSpinner().insertAfter( '#wpDestFile' );
65 ( new mw
.Api() ).get( {
67 titles
: ( new mw
.Title( this.nameToCheck
, mw
.config
.get( 'wgNamespaceIds' ).file
) ).getPrefixedText(),
69 iiprop
: 'uploadwarning',
71 } ).done( function ( result
) {
74 resultOut
= result
.query
.pages
[result
.query
.pageids
[0]].imageinfo
[0];
76 $spinnerDestCheck
.remove();
77 uploadWarning
.processResult( resultOut
, uploadWarning
.nameToCheck
);
81 processResult: function ( result
, fileName
) {
82 this.setWarning( result
.html
);
83 this.responseCache
[fileName
] = result
.html
;
86 setWarning: function ( warning
) {
87 $( '#wpDestFile-warning' ).html( warning
);
89 // Set a value in the form indicating that the warning is acknowledged and
90 // doesn't need to be redisplayed post-upload
92 $( '#wpDestFileWarningAck' ).val( '' );
94 $( '#wpDestFileWarningAck' ).val( '1' );
102 responseCache
: { '': '' },
104 fetchPreview: function ( license
) {
106 if ( !mw
.config
.get( 'wgAjaxLicensePreview' ) ) {
109 if ( this.responseCache
.hasOwnProperty( license
) ) {
110 this.showPreview( this.responseCache
[license
] );
114 $spinnerLicense
= $.createSpinner().insertAfter( '#wpLicense' );
116 ( new mw
.Api() ).get( {
118 text
: '{{' + license
+ '}}',
119 title
: $( '#wpDestFile' ).val() || 'File:Sample.jpg',
122 } ).done( function ( result
) {
123 $spinnerLicense
.remove();
124 uploadLicense
.processResult( result
, license
);
128 processResult: function ( result
, license
) {
129 this.responseCache
[license
] = result
.parse
.text
['*'];
130 this.showPreview( this.responseCache
[license
] );
133 showPreview: function ( preview
) {
134 $( '#mw-license-preview' ).html( preview
);
140 // AJAX wpDestFile warnings
141 if ( ajaxUploadDestCheck
) {
142 // Insert an event handler that fetches upload warnings when wpDestFile
144 $( '#wpDestFile' ).change( function () {
145 uploadWarning
.checkNow( $( this ).val() );
147 // Insert a row where the warnings will be displayed just below the
149 $( '#mw-htmlform-description tbody' ).append(
152 .attr( 'id', 'wpDestFile-warning' )
153 .attr( 'colspan', 2 )
158 if ( mw
.config
.get( 'wgAjaxLicensePreview' ) && $license
.length
) {
159 // License selector check
160 $license
.change( function () {
161 // We might show a preview
162 uploadLicense
.fetchPreview( $license
.val() );
165 // License selector table row
166 $license
.closest( 'tr' ).after(
169 $( '<td>' ).attr( 'id', 'mw-license-preview' )
174 // fillDestFile setup
175 $.each( mw
.config
.get( 'wgUploadSourceIds' ), function ( index
, sourceId
) {
176 $( '#' + sourceId
).change( function () {
177 var path
, slash
, backslash
, fname
;
178 if ( !mw
.config
.get( 'wgUploadAutoFill' ) ) {
181 // Remove any previously flagged errors
182 $( '#mw-upload-permitted' ).attr( 'class', '' );
183 $( '#mw-upload-prohibited' ).attr( 'class', '' );
185 path
= $( this ).val();
186 // Find trailing part
187 slash
= path
.lastIndexOf( '/' );
188 backslash
= path
.lastIndexOf( '\\' );
189 if ( slash
=== -1 && backslash
=== -1 ) {
191 } else if ( slash
> backslash
) {
192 fname
= path
.slice( slash
+ 1 );
194 fname
= path
.slice( backslash
+ 1 );
197 // Clear the filename if it does not have a valid extension.
198 // URLs are less likely to have a useful extension, so don't include them in the
201 mw
.config
.get( 'wgCheckFileExtensions' ) &&
202 mw
.config
.get( 'wgStrictFileExtensions' ) &&
203 mw
.config
.get( 'wgFileExtensions' ) &&
204 $( this ).attr( 'id' ) !== 'wpUploadFileURL'
207 fname
.lastIndexOf( '.' ) === -1 ||
209 fname
.slice( fname
.lastIndexOf( '.' ) + 1 ).toLowerCase(),
210 $.map( mw
.config
.get( 'wgFileExtensions' ), function ( element
) {
211 return element
.toLowerCase();
215 // Not a valid extension
216 // Clear the upload and set mw-upload-permitted to error
218 $( '#mw-upload-permitted' ).attr( 'class', 'error' );
219 $( '#mw-upload-prohibited' ).attr( 'class', 'error' );
220 // Clear wpDestFile as well
221 $( '#wpDestFile' ).val( '' );
227 // Replace spaces by underscores
228 fname
= fname
.replace( / /g
, '_' );
229 // Capitalise first letter if needed
230 if ( mw
.config
.get( 'wgCapitalizeUploads' ) ) {
231 fname
= fname
[0].toUpperCase() + fname
.slice( 1 );
235 if ( $( '#wpDestFile' ).length
) {
236 // Call decodeURIComponent function to remove possible URL-encoded characters
237 // from the file name (bug 30390). Especially likely with upload-form-url.
238 // decodeURIComponent can throw an exception if input is invalid utf-8
240 $( '#wpDestFile' ).val( decodeURIComponent( fname
) );
242 $( '#wpDestFile' ).val( fname
);
244 uploadWarning
.checkNow( fname
);
250 // Add a preview to the upload form
253 * Is the FileAPI available with sufficient functionality?
255 function hasFileAPI() {
256 return window
.FileReader
!== undefined;
260 * Check if this is a recognizable image type...
261 * Also excludes files over 10M to avoid going insane on memory usage.
263 * TODO: Is there a way we can ask the browser what's supported in `<img>`s?
265 * TODO: Put SVG back after working around Firefox 7 bug <https://bugzilla.wikimedia.org/show_bug.cgi?id=31643>
270 function fileIsPreviewable( file
) {
271 var known
= ['image/png', 'image/gif', 'image/jpeg', 'image/svg+xml'],
272 tooHuge
= 10 * 1024 * 1024;
273 return ( $.inArray( file
.type
, known
) !== -1 ) && file
.size
> 0 && file
.size
< tooHuge
;
277 * Show a thumbnail preview of PNG, JPEG, GIF, and SVG files prior to upload
278 * in browsers supporting HTML5 FileAPI.
280 * As of this writing, known good:
283 * - Chrome 7.something
285 * TODO: Check file size limits and warn of likely failures
289 function showPreview( file
) {
294 $spinner
= $.createSpinner( { size
: 'small', type
: 'block' } )
295 .css( { width
: previewSize
, height
: previewSize
} ),
296 thumb
= mw
.template
.get( 'mediawiki.special.upload', 'thumbnail.html' ).render();
299 .find( '.filename' ).text( file
.name
).end()
300 .find( '.fileinfo' ).text( prettySize( file
.size
) ).end()
301 .find( '.thumbinner' ).prepend( $spinner
).end();
303 $canvas
= $( '<canvas>' ).attr( { width
: previewSize
, height
: previewSize
} );
304 ctx
= $canvas
[0].getContext( '2d' );
305 $( '#mw-htmlform-source' ).parent().prepend( thumb
);
307 fetchPreview( file
, function ( dataURL
) {
308 var img
= new Image(),
311 if ( meta
&& meta
.tiff
&& meta
.tiff
.Orientation
) {
312 rotation
= ( 360 - ( function () {
313 // See includes/media/Bitmap.php
314 switch ( meta
.tiff
.Orientation
.value
) {
327 img
.onload = function () {
328 var info
, width
, height
, x
, y
, dx
, dy
, logicalWidth
, logicalHeight
;
330 // Fit the image within the previewSizexpreviewSize box
331 if ( img
.width
> img
.height
) {
333 height
= img
.height
/ img
.width
* previewSize
;
335 height
= previewSize
;
336 width
= img
.width
/ img
.height
* previewSize
;
338 // Determine the offset required to center the image
339 dx
= ( 180 - width
) / 2;
340 dy
= ( 180 - height
) / 2;
341 switch ( rotation
) {
342 // If a rotation is applied, the direction of the axis
343 // changes as well. You can derive the values below by
344 // drawing on paper an axis system, rotate it and see
345 // where the positive axis direction is
349 logicalWidth
= img
.width
;
350 logicalHeight
= img
.height
;
355 y
= dy
- previewSize
;
356 logicalWidth
= img
.height
;
357 logicalHeight
= img
.width
;
360 x
= dx
- previewSize
;
361 y
= dy
- previewSize
;
362 logicalWidth
= img
.width
;
363 logicalHeight
= img
.height
;
366 x
= dx
- previewSize
;
368 logicalWidth
= img
.height
;
369 logicalHeight
= img
.width
;
373 ctx
.clearRect( 0, 0, 180, 180 );
374 ctx
.rotate( rotation
/ 180 * Math
.PI
);
375 ctx
.drawImage( img
, x
, y
, width
, height
);
376 $spinner
.replaceWith( $canvas
);
379 info
= mw
.msg( 'widthheight', logicalWidth
, logicalHeight
) +
380 ', ' + prettySize( file
.size
);
382 $( '#mw-upload-thumbnail .fileinfo' ).text( info
);
385 }, mw
.config
.get( 'wgFileCanRotate' ) ? function ( data
) {
387 meta
= mw
.libs
.jpegmeta( data
, file
.fileName
);
388 // jscs:disable requireCamelCaseOrUpperCaseIdentifiers, disallowDanglingUnderscores
389 meta
._binary_data
= null;
398 * Start loading a file into memory; when complete, pass it as a
399 * data URL to the callback function. If the callbackBinary is set it will
400 * first be read as binary and afterwards as data URL. Useful if you want
401 * to do preprocessing on the binary data first.
404 * @param {Function} callback
405 * @param {Function} callbackBinary
407 function fetchPreview( file
, callback
, callbackBinary
) {
408 var reader
= new FileReader();
409 if ( callbackBinary
&& 'readAsBinaryString' in reader
) {
410 // To fetch JPEG metadata we need a binary string; start there.
412 reader
.onload = function () {
413 callbackBinary( reader
.result
);
415 // Now run back through the regular code path.
416 fetchPreview( file
, callback
);
418 reader
.readAsBinaryString( file
);
419 } else if ( callbackBinary
&& 'readAsArrayBuffer' in reader
) {
420 // readAsArrayBuffer replaces readAsBinaryString
421 // However, our JPEG metadata library wants a string.
422 // So, this is going to be an ugly conversion.
423 reader
.onload = function () {
425 buffer
= new Uint8Array( reader
.result
),
427 for ( i
= 0; i
< buffer
.byteLength
; i
++ ) {
428 string
+= String
.fromCharCode( buffer
[i
] );
430 callbackBinary( string
);
432 // Now run back through the regular code path.
433 fetchPreview( file
, callback
);
435 reader
.readAsArrayBuffer( file
);
436 } else if ( 'URL' in window
&& 'createObjectURL' in window
.URL
) {
437 // Supported in Firefox 4.0 and above <https://developer.mozilla.org/en/DOM/window.URL.createObjectURL>
438 // WebKit has it in a namespace for now but that's ok. ;)
440 // Lifetime of this URL is until document close, which is fine
441 // for Special:Upload -- if this code gets used on longer-running
442 // pages, add a revokeObjectURL() when it's no longer needed.
444 // Prefer this over readAsDataURL for Firefox 7 due to bug reading
445 // some SVG files from data URIs <https://bugzilla.mozilla.org/show_bug.cgi?id=694165>
446 callback( window
.URL
.createObjectURL( file
) );
448 // This ends up decoding the file to base-64 and back again, which
449 // feels horribly inefficient.
450 reader
.onload = function () {
451 callback( reader
.result
);
453 reader
.readAsDataURL( file
);
458 * Format a file size attractively.
460 * TODO: Match numeric formatting
465 function prettySize( s
) {
466 var sizeMsgs
= ['size-bytes', 'size-kilobytes', 'size-megabytes', 'size-gigabytes'];
467 while ( s
>= 1024 && sizeMsgs
.length
> 1 ) {
469 sizeMsgs
= sizeMsgs
.slice( 1 );
471 return mw
.msg( sizeMsgs
[0], Math
.round( s
) );
475 * Clear the file upload preview area.
477 function clearPreview() {
478 $( '#mw-upload-thumbnail' ).remove();
482 * Check if the file does not exceed the maximum size
484 function checkMaxUploadSize( file
) {
487 function getMaxUploadSize( type
) {
488 var sizes
= mw
.config
.get( 'wgMaxUploadSize' );
490 if ( sizes
[type
] !== undefined ) {
496 $( '.mw-upload-source-error' ).remove();
498 maxSize
= getMaxUploadSize( 'file' );
499 if ( file
.size
> maxSize
) {
500 $error
= $( '<p class="error mw-upload-source-error" id="wpSourceTypeFile-error">' +
501 mw
.message( 'largefileserver', file
.size
, maxSize
).escaped() + '</p>' );
503 $( '#wpUploadFile' ).after( $error
);
512 if ( hasFileAPI() ) {
513 // Update thumbnail when the file selection control is updated.
514 $( '#wpUploadFile' ).change( function () {
516 if ( this.files
&& this.files
.length
) {
517 // Note: would need to be updated to handle multiple files.
518 var 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
.submit( function () {
585 allowCloseWindow
.release();
588 }( mediaWiki
, jQuery
) );