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 uploadWarning
.processResult( resultOut
, uploadWarning
.nameToCheck
);
84 } ).always( function () {
85 $spinnerDestCheck
.remove();
89 processResult: function ( result
, fileName
) {
90 this.setWarning( result
);
91 this.responseCache
[ fileName
] = result
;
94 setWarning: function ( warning
) {
95 var $warning
= $( $.parseHTML( warning
) );
96 mw
.hook( 'wikipage.content' ).fire( $warning
);
97 $( '#wpDestFile-warning' ).empty().append( $warning
);
99 // Set a value in the form indicating that the warning is acknowledged and
100 // doesn't need to be redisplayed post-upload
102 $( '#wpDestFileWarningAck' ).val( '' );
104 $( '#wpDestFileWarningAck' ).val( '1' );
112 responseCache
: { '': '' },
114 fetchPreview: function ( license
) {
116 if ( !mw
.config
.get( 'wgAjaxLicensePreview' ) ) {
119 if ( this.responseCache
.hasOwnProperty( license
) ) {
120 this.showPreview( this.responseCache
[ license
] );
124 $spinnerLicense
= $.createSpinner().insertAfter( '#wpLicense' );
126 ( new mw
.Api() ).get( {
129 text
: '{{' + license
+ '}}',
130 title
: $( '#wpDestFile' ).val() || 'File:Sample.jpg',
133 } ).done( function ( result
) {
134 uploadLicense
.processResult( result
, license
);
135 } ).always( function () {
136 $spinnerLicense
.remove();
140 processResult: function ( result
, license
) {
141 this.responseCache
[ license
] = result
.parse
.text
;
142 this.showPreview( this.responseCache
[ license
] );
145 showPreview: function ( preview
) {
146 $( '#mw-license-preview' ).html( preview
);
152 // AJAX wpDestFile warnings
153 if ( ajaxUploadDestCheck
) {
154 // Insert an event handler that fetches upload warnings when wpDestFile
156 $( '#wpDestFile' ).change( function () {
157 uploadWarning
.checkNow( $( this ).val() );
159 // Insert a row where the warnings will be displayed just below the
161 $( '#mw-htmlform-description tbody' ).append(
164 .attr( 'id', 'wpDestFile-warning' )
165 .attr( 'colspan', 2 )
170 if ( mw
.config
.get( 'wgAjaxLicensePreview' ) && $license
.length
) {
171 // License selector check
172 $license
.change( function () {
173 // We might show a preview
174 uploadLicense
.fetchPreview( $license
.val() );
177 // License selector table row
178 $license
.closest( 'tr' ).after(
181 $( '<td>' ).attr( 'id', 'mw-license-preview' )
186 // fillDestFile setup
187 $.each( mw
.config
.get( 'wgUploadSourceIds' ), function ( index
, sourceId
) {
188 $( '#' + sourceId
).change( function () {
189 var path
, slash
, backslash
, fname
;
190 if ( !mw
.config
.get( 'wgUploadAutoFill' ) ) {
193 // Remove any previously flagged errors
194 $( '#mw-upload-permitted' ).attr( 'class', '' );
195 $( '#mw-upload-prohibited' ).attr( 'class', '' );
197 path
= $( this ).val();
198 // Find trailing part
199 slash
= path
.lastIndexOf( '/' );
200 backslash
= path
.lastIndexOf( '\\' );
201 if ( slash
=== -1 && backslash
=== -1 ) {
203 } else if ( slash
> backslash
) {
204 fname
= path
.slice( slash
+ 1 );
206 fname
= path
.slice( backslash
+ 1 );
209 // Clear the filename if it does not have a valid extension.
210 // URLs are less likely to have a useful extension, so don't include them in the
213 mw
.config
.get( 'wgCheckFileExtensions' ) &&
214 mw
.config
.get( 'wgStrictFileExtensions' ) &&
215 mw
.config
.get( 'wgFileExtensions' ) &&
216 $( this ).attr( 'id' ) !== 'wpUploadFileURL'
219 fname
.lastIndexOf( '.' ) === -1 ||
221 fname
.slice( fname
.lastIndexOf( '.' ) + 1 ).toLowerCase(),
222 $.map( mw
.config
.get( 'wgFileExtensions' ), function ( element
) {
223 return element
.toLowerCase();
227 // Not a valid extension
228 // Clear the upload and set mw-upload-permitted to error
230 $( '#mw-upload-permitted' ).attr( 'class', 'error' );
231 $( '#mw-upload-prohibited' ).attr( 'class', 'error' );
232 // Clear wpDestFile as well
233 $( '#wpDestFile' ).val( '' );
239 // Replace spaces by underscores
240 fname
= fname
.replace( / /g
, '_' );
241 // Capitalise first letter if needed
242 if ( mw
.config
.get( 'wgCapitalizeUploads' ) ) {
243 fname
= fname
[ 0 ].toUpperCase() + fname
.slice( 1 );
247 if ( $( '#wpDestFile' ).length
) {
248 // Call decodeURIComponent function to remove possible URL-encoded characters
249 // from the file name (bug 30390). Especially likely with upload-form-url.
250 // decodeURIComponent can throw an exception if input is invalid utf-8
252 $( '#wpDestFile' ).val( decodeURIComponent( fname
) );
254 $( '#wpDestFile' ).val( fname
);
256 uploadWarning
.checkNow( fname
);
262 // Add a preview to the upload form
265 * Is the FileAPI available with sufficient functionality?
267 function hasFileAPI() {
268 return window
.FileReader
!== undefined;
272 * Check if this is a recognizable image type...
273 * Also excludes files over 10M to avoid going insane on memory usage.
275 * TODO: Is there a way we can ask the browser what's supported in `<img>`s?
277 * TODO: Put SVG back after working around Firefox 7 bug <https://phabricator.wikimedia.org/T33643>
282 function fileIsPreviewable( file
) {
283 var known
= [ 'image/png', 'image/gif', 'image/jpeg', 'image/svg+xml' ],
284 tooHuge
= 10 * 1024 * 1024;
285 return ( $.inArray( file
.type
, known
) !== -1 ) && file
.size
> 0 && file
.size
< tooHuge
;
289 * Format a file size attractively.
291 * TODO: Match numeric formatting
296 function prettySize( s
) {
297 var sizeMsgs
= [ 'size-bytes', 'size-kilobytes', 'size-megabytes', 'size-gigabytes' ];
298 while ( s
>= 1024 && sizeMsgs
.length
> 1 ) {
300 sizeMsgs
= sizeMsgs
.slice( 1 );
302 return mw
.msg( sizeMsgs
[ 0 ], Math
.round( s
) );
306 * Show a thumbnail preview of PNG, JPEG, GIF, and SVG files prior to upload
307 * in browsers supporting HTML5 FileAPI.
309 * As of this writing, known good:
312 * - Chrome 7.something
314 * TODO: Check file size limits and warn of likely failures
318 function showPreview( file
) {
323 $spinner
= $.createSpinner( { size
: 'small', type
: 'block' } )
324 .css( { width
: previewSize
, height
: previewSize
} ),
325 thumb
= mw
.template
.get( 'mediawiki.special.upload', 'thumbnail.html' ).render();
328 .find( '.filename' ).text( file
.name
).end()
329 .find( '.fileinfo' ).text( prettySize( file
.size
) ).end()
330 .find( '.thumbinner' ).prepend( $spinner
).end();
332 $canvas
= $( '<canvas>' ).attr( { width
: previewSize
, height
: previewSize
} );
333 ctx
= $canvas
[ 0 ].getContext( '2d' );
334 $( '#mw-htmlform-source' ).parent().prepend( thumb
);
336 fetchPreview( file
, function ( dataURL
) {
337 var img
= new Image(),
340 if ( meta
&& meta
.tiff
&& meta
.tiff
.Orientation
) {
341 rotation
= ( 360 - ( function () {
342 // See includes/media/Bitmap.php
343 switch ( meta
.tiff
.Orientation
.value
) {
356 img
.onload = function () {
357 var info
, width
, height
, x
, y
, dx
, dy
, logicalWidth
, logicalHeight
;
359 // Fit the image within the previewSizexpreviewSize box
360 if ( img
.width
> img
.height
) {
362 height
= img
.height
/ img
.width
* previewSize
;
364 height
= previewSize
;
365 width
= img
.width
/ img
.height
* previewSize
;
367 // Determine the offset required to center the image
368 dx
= ( 180 - width
) / 2;
369 dy
= ( 180 - height
) / 2;
370 switch ( rotation
) {
371 // If a rotation is applied, the direction of the axis
372 // changes as well. You can derive the values below by
373 // drawing on paper an axis system, rotate it and see
374 // where the positive axis direction is
378 logicalWidth
= img
.width
;
379 logicalHeight
= img
.height
;
384 y
= dy
- previewSize
;
385 logicalWidth
= img
.height
;
386 logicalHeight
= img
.width
;
389 x
= dx
- previewSize
;
390 y
= dy
- previewSize
;
391 logicalWidth
= img
.width
;
392 logicalHeight
= img
.height
;
395 x
= dx
- previewSize
;
397 logicalWidth
= img
.height
;
398 logicalHeight
= img
.width
;
402 ctx
.clearRect( 0, 0, 180, 180 );
403 ctx
.rotate( rotation
/ 180 * Math
.PI
);
404 ctx
.drawImage( img
, x
, y
, width
, height
);
405 $spinner
.replaceWith( $canvas
);
408 info
= mw
.msg( 'widthheight', logicalWidth
, logicalHeight
) +
409 ', ' + prettySize( file
.size
);
411 $( '#mw-upload-thumbnail .fileinfo' ).text( info
);
413 img
.onerror = function () {
414 // Can happen for example for invalid SVG files
418 }, mw
.config
.get( 'wgFileCanRotate' ) ? function ( data
) {
420 meta
= mw
.libs
.jpegmeta( data
, file
.fileName
);
421 // jscs:disable requireCamelCaseOrUpperCaseIdentifiers, disallowDanglingUnderscores
422 meta
._binary_data
= null;
431 * Start loading a file into memory; when complete, pass it as a
432 * data URL to the callback function. If the callbackBinary is set it will
433 * first be read as binary and afterwards as data URL. Useful if you want
434 * to do preprocessing on the binary data first.
437 * @param {Function} callback
438 * @param {Function} callbackBinary
440 function fetchPreview( file
, callback
, callbackBinary
) {
441 var reader
= new FileReader();
442 if ( callbackBinary
&& 'readAsBinaryString' in reader
) {
443 // To fetch JPEG metadata we need a binary string; start there.
445 reader
.onload = function () {
446 callbackBinary( reader
.result
);
448 // Now run back through the regular code path.
449 fetchPreview( file
, callback
);
451 reader
.readAsBinaryString( file
);
452 } else if ( callbackBinary
&& 'readAsArrayBuffer' in reader
) {
453 // readAsArrayBuffer replaces readAsBinaryString
454 // However, our JPEG metadata library wants a string.
455 // So, this is going to be an ugly conversion.
456 reader
.onload = function () {
458 buffer
= new Uint8Array( reader
.result
),
460 for ( i
= 0; i
< buffer
.byteLength
; i
++ ) {
461 string
+= String
.fromCharCode( buffer
[ i
] );
463 callbackBinary( string
);
465 // Now run back through the regular code path.
466 fetchPreview( file
, callback
);
468 reader
.readAsArrayBuffer( file
);
469 } else if ( 'URL' in window
&& 'createObjectURL' in window
.URL
) {
470 // Supported in Firefox 4.0 and above <https://developer.mozilla.org/en/DOM/window.URL.createObjectURL>
471 // WebKit has it in a namespace for now but that's ok. ;)
473 // Lifetime of this URL is until document close, which is fine
474 // for Special:Upload -- if this code gets used on longer-running
475 // pages, add a revokeObjectURL() when it's no longer needed.
477 // Prefer this over readAsDataURL for Firefox 7 due to bug reading
478 // some SVG files from data URIs <https://bugzilla.mozilla.org/show_bug.cgi?id=694165>
479 callback( window
.URL
.createObjectURL( file
) );
481 // This ends up decoding the file to base-64 and back again, which
482 // feels horribly inefficient.
483 reader
.onload = function () {
484 callback( reader
.result
);
486 reader
.readAsDataURL( file
);
491 * Clear the file upload preview area.
493 function clearPreview() {
494 $( '#mw-upload-thumbnail' ).remove();
498 * Check if the file does not exceed the maximum size
500 function checkMaxUploadSize( file
) {
503 function getMaxUploadSize( type
) {
504 var sizes
= mw
.config
.get( 'wgMaxUploadSize' );
506 if ( sizes
[ type
] !== undefined ) {
507 return sizes
[ type
];
512 $( '.mw-upload-source-error' ).remove();
514 maxSize
= getMaxUploadSize( 'file' );
515 if ( file
.size
> maxSize
) {
516 $error
= $( '<p class="error mw-upload-source-error" id="wpSourceTypeFile-error">' +
517 mw
.message( 'largefileserver', file
.size
, maxSize
).escaped() + '</p>' );
519 $( '#wpUploadFile' ).after( $error
);
528 if ( hasFileAPI() ) {
529 // Update thumbnail when the file selection control is updated.
530 $( '#wpUploadFile' ).change( function () {
532 if ( this.files
&& this.files
.length
) {
533 // Note: would need to be updated to handle multiple files.
534 var file
= this.files
[ 0 ];
536 if ( !checkMaxUploadSize( file
) ) {
540 if ( fileIsPreviewable( file
) ) {
548 // Disable all upload source fields except the selected one
550 var $rows
= $( '.mw-htmlform-field-UploadSourceField' );
552 $rows
.on( 'change', 'input[type="radio"]', function ( e
) {
553 var currentRow
= e
.delegateTarget
;
555 if ( !this.checked
) {
559 $( '.mw-upload-source-error' ).remove();
561 // Enable selected upload method
562 $( currentRow
).find( 'input' ).prop( 'disabled', false );
564 // Disable inputs of other upload methods
565 // (except for the radio button to re-enable it)
568 .find( 'input[type!="radio"]' )
569 .prop( 'disabled', true );
573 if ( !$( '#wpSourceTypeurl' ).prop( 'checked' ) ) {
574 $( '#wpUploadFileURL' ).prop( 'disabled', true );
579 // Prevent losing work
580 var allowCloseWindow
,
581 $uploadForm
= $( '#mw-upload-form' );
583 if ( !mw
.user
.options
.get( 'useeditwarning' ) ) {
584 // If the user doesn't want edit warnings, don't set things up.
588 $uploadForm
.data( 'origtext', $uploadForm
.serialize() );
590 allowCloseWindow
= mw
.confirmCloseWindow( {
592 return $( '#wpUploadFile' ).get( 0 ).files
.length
!== 0 ||
593 $uploadForm
.data( 'origtext' ) !== $uploadForm
.serialize();
596 message
: mw
.msg( 'editwarning-warning' ),
597 namespace: 'uploadwarning'
600 $uploadForm
.submit( function () {
601 allowCloseWindow
.release();
604 }( mediaWiki
, jQuery
) );