2 * JavaScript for Special:Upload
5 * @class mw.special.upload
9 var ajaxUploadDestCheck
= mw
.config
.get( 'wgAjaxUploadDestCheck' ),
10 $license
= $( '#wpLicense' ), uploadWarning
, uploadLicense
;
12 window
.wgUploadWarningObj
= uploadWarning
= {
13 responseCache
: { '': ' ' },
19 keypress: function () {
20 if ( !ajaxUploadDestCheck
) {
24 // Find file to upload
25 if ( !$( '#wpDestFile' ).length
|| !$( '#wpDestFile-warning' ).length
) {
29 this.nameToCheck
= $( '#wpDestFile' ).val();
32 if ( this.timeoutID
) {
33 clearTimeout( this.timeoutID
);
35 // Check response cache
36 if ( this.responseCache
.hasOwnProperty( this.nameToCheck
) ) {
37 this.setWarning( this.responseCache
[this.nameToCheck
] );
41 this.timeoutID
= setTimeout( function () {
42 uploadWarning
.timeout();
46 checkNow: function ( fname
) {
47 if ( !ajaxUploadDestCheck
) {
50 if ( this.timeoutID
) {
51 clearTimeout( this.timeoutID
);
53 this.nameToCheck
= fname
;
57 timeout: function () {
58 var $spinnerDestCheck
;
59 if ( !ajaxUploadDestCheck
|| this.nameToCheck
=== '' ) {
62 $spinnerDestCheck
= $.createSpinner().insertAfter( '#wpDestFile' );
64 ( new mw
.Api() ).get( {
66 titles
: ( new mw
.Title( this.nameToCheck
, mw
.config
.get( 'wgNamespaceIds' ).file
) ).getPrefixedText(),
68 iiprop
: 'uploadwarning',
70 } ).done( function ( result
) {
73 resultOut
= result
.query
.pages
[result
.query
.pageids
[0]].imageinfo
[0];
75 $spinnerDestCheck
.remove();
76 uploadWarning
.processResult( resultOut
, uploadWarning
.nameToCheck
);
80 processResult: function ( result
, fileName
) {
81 this.setWarning( result
.html
);
82 this.responseCache
[fileName
] = result
.html
;
85 setWarning: function ( warning
) {
86 $( '#wpDestFile-warning' ).html( warning
);
88 // Set a value in the form indicating that the warning is acknowledged and
89 // doesn't need to be redisplayed post-upload
91 $( '#wpDestFileWarningAck' ).val( '' );
93 $( '#wpDestFileWarningAck' ).val( '1' );
101 responseCache
: { '': '' },
103 fetchPreview: function ( license
) {
105 if ( !mw
.config
.get( 'wgAjaxLicensePreview' ) ) {
108 if ( this.responseCache
.hasOwnProperty( license
) ) {
109 this.showPreview( this.responseCache
[license
] );
113 $spinnerLicense
= $.createSpinner().insertAfter( '#wpLicense' );
115 ( new mw
.Api() ).get( {
117 text
: '{{' + license
+ '}}',
118 title
: $( '#wpDestFile' ).val() || 'File:Sample.jpg',
121 } ).done( function ( result
) {
122 $spinnerLicense
.remove();
123 uploadLicense
.processResult( result
, license
);
127 processResult: function ( result
, license
) {
128 this.responseCache
[license
] = result
.parse
.text
['*'];
129 this.showPreview( this.responseCache
[license
] );
132 showPreview: function ( preview
) {
133 $( '#mw-license-preview' ).html( preview
);
139 // Disable URL box if the URL copy upload source type is not selected
140 if ( !$( '#wpSourceTypeurl' ).prop( 'checked' ) ) {
141 $( '#wpUploadFileURL' ).prop( 'disabled', true );
144 // AJAX wpDestFile warnings
145 if ( ajaxUploadDestCheck
) {
146 // Insert an event handler that fetches upload warnings when wpDestFile
148 $( '#wpDestFile' ).change( function () {
149 uploadWarning
.checkNow( $( this ).val() );
151 // Insert a row where the warnings will be displayed just below the
153 $( '#mw-htmlform-description tbody' ).append(
156 .attr( 'id', 'wpDestFile-warning' )
157 .attr( 'colspan', 2 )
162 if ( mw
.config
.get( 'wgAjaxLicensePreview' ) && $license
.length
) {
163 // License selector check
164 $license
.change( function () {
165 // We might show a preview
166 uploadLicense
.fetchPreview( $license
.val() );
169 // License selector table row
170 $license
.closest( 'tr' ).after(
173 $( '<td>' ).attr( 'id', 'mw-license-preview' )
178 // fillDestFile setup
179 $.each( mw
.config
.get( 'wgUploadSourceIds' ), function ( index
, sourceId
) {
180 $( '#' + sourceId
).change( function () {
181 var path
, slash
, backslash
, fname
;
182 if ( !mw
.config
.get( 'wgUploadAutoFill' ) ) {
185 // Remove any previously flagged errors
186 $( '#mw-upload-permitted' ).attr( 'class', '' );
187 $( '#mw-upload-prohibited' ).attr( 'class', '' );
189 path
= $( this ).val();
190 // Find trailing part
191 slash
= path
.lastIndexOf( '/' );
192 backslash
= path
.lastIndexOf( '\\' );
193 if ( slash
=== -1 && backslash
=== -1 ) {
195 } else if ( slash
> backslash
) {
196 fname
= path
.slice( slash
+ 1 );
198 fname
= path
.slice( backslash
+ 1 );
201 // Clear the filename if it does not have a valid extension.
202 // URLs are less likely to have a useful extension, so don't include them in the
205 mw
.config
.get( 'wgStrictFileExtensions' ) &&
206 mw
.config
.get( 'wgFileExtensions' ) &&
207 $( this ).attr( 'id' ) !== 'wpUploadFileURL'
210 fname
.lastIndexOf( '.' ) === -1 ||
212 fname
.slice( fname
.lastIndexOf( '.' ) + 1 ).toLowerCase(),
213 $.map( mw
.config
.get( 'wgFileExtensions' ), function ( element
) {
214 return element
.toLowerCase();
218 // Not a valid extension
219 // Clear the upload and set mw-upload-permitted to error
221 $( '#mw-upload-permitted' ).attr( 'class', 'error' );
222 $( '#mw-upload-prohibited' ).attr( 'class', 'error' );
223 // Clear wpDestFile as well
224 $( '#wpDestFile' ).val( '' );
230 // Replace spaces by underscores
231 fname
= fname
.replace( / /g
, '_' );
232 // Capitalise first letter if needed
233 if ( mw
.config
.get( 'wgCapitalizeUploads' ) ) {
234 fname
= fname
.charAt( 0 ).toUpperCase().concat( fname
.slice( 1 ) );
238 if ( $( '#wpDestFile' ).length
) {
239 // Call decodeURIComponent function to remove possible URL-encoded characters
240 // from the file name (bug 30390). Especially likely with upload-form-url.
241 // decodeURIComponent can throw an exception if input is invalid utf-8
243 $( '#wpDestFile' ).val( decodeURIComponent( fname
) );
245 $( '#wpDestFile' ).val( fname
);
247 uploadWarning
.checkNow( fname
);
253 // Add a preview to the upload form
256 * Is the FileAPI available with sufficient functionality?
258 function hasFileAPI() {
259 return window
.FileReader
!== undefined;
263 * Check if this is a recognizable image type...
264 * Also excludes files over 10M to avoid going insane on memory usage.
266 * TODO: Is there a way we can ask the browser what's supported in `<img>`s?
268 * TODO: Put SVG back after working around Firefox 7 bug <https://bugzilla.wikimedia.org/show_bug.cgi?id=31643>
273 function fileIsPreviewable( file
) {
274 var known
= ['image/png', 'image/gif', 'image/jpeg', 'image/svg+xml'],
275 tooHuge
= 10 * 1024 * 1024;
276 return ( $.inArray( file
.type
, known
) !== -1 ) && file
.size
> 0 && file
.size
< tooHuge
;
280 * Show a thumbnail preview of PNG, JPEG, GIF, and SVG files prior to upload
281 * in browsers supporting HTML5 FileAPI.
283 * As of this writing, known good:
286 * - Chrome 7.something
288 * TODO: Check file size limits and warn of likely failures
292 function showPreview( file
) {
297 thumb
= mw
.template
.get( 'mediawiki.special.upload', 'thumbnail.html' ).render();
299 thumb
.find( '.filename' ).text( file
.name
).end()
300 .find( '.fileinfo' ).text( prettySize( file
.size
) ).end();
302 $canvas
= $( '<canvas width="' + previewSize
+ '" height="' + previewSize
+ '" ></canvas>' );
303 ctx
= $canvas
[0].getContext( '2d' );
304 $( '#mw-htmlform-source' ).parent().prepend( thumb
);
306 fetchPreview( file
, function ( dataURL
) {
307 var img
= new Image(),
310 if ( meta
&& meta
.tiff
&& meta
.tiff
.Orientation
) {
311 rotation
= ( 360 - ( function () {
312 // See includes/media/Bitmap.php
313 switch ( meta
.tiff
.Orientation
.value
) {
326 img
.onload = function () {
327 var info
, width
, height
, x
, y
, dx
, dy
, logicalWidth
, logicalHeight
;
329 // Fit the image within the previewSizexpreviewSize box
330 if ( img
.width
> img
.height
) {
332 height
= img
.height
/ img
.width
* previewSize
;
334 height
= previewSize
;
335 width
= img
.width
/ img
.height
* previewSize
;
337 // Determine the offset required to center the image
338 dx
= ( 180 - width
) / 2;
339 dy
= ( 180 - height
) / 2;
340 switch ( rotation
) {
341 // If a rotation is applied, the direction of the axis
342 // changes as well. You can derive the values below by
343 // drawing on paper an axis system, rotate it and see
344 // where the positive axis direction is
348 logicalWidth
= img
.width
;
349 logicalHeight
= img
.height
;
354 y
= dy
- previewSize
;
355 logicalWidth
= img
.height
;
356 logicalHeight
= img
.width
;
359 x
= dx
- previewSize
;
360 y
= dy
- previewSize
;
361 logicalWidth
= img
.width
;
362 logicalHeight
= img
.height
;
365 x
= dx
- previewSize
;
367 logicalWidth
= img
.height
;
368 logicalHeight
= img
.width
;
372 ctx
.clearRect( 0, 0, 180, 180 );
373 ctx
.rotate( rotation
/ 180 * Math
.PI
);
374 ctx
.drawImage( img
, x
, y
, width
, height
);
375 thumb
.find( '.mw-small-spinner' ).replaceWith( $canvas
);
378 info
= mw
.msg( 'widthheight', logicalWidth
, logicalHeight
) +
379 ', ' + prettySize( file
.size
);
381 $( '#mw-upload-thumbnail .fileinfo' ).text( info
);
384 }, mw
.config
.get( 'wgFileCanRotate' ) ? function ( data
) {
385 /*jshint camelcase:false, nomen:false */
387 meta
= mw
.libs
.jpegmeta( data
, file
.fileName
);
388 meta
._binary_data
= null;
396 * Start loading a file into memory; when complete, pass it as a
397 * data URL to the callback function. If the callbackBinary is set it will
398 * first be read as binary and afterwards as data URL. Useful if you want
399 * to do preprocessing on the binary data first.
402 * @param {Function} callback
403 * @param {Function} callbackBinary
405 function fetchPreview( file
, callback
, callbackBinary
) {
406 var reader
= new FileReader();
407 if ( callbackBinary
&& 'readAsBinaryString' in reader
) {
408 // To fetch JPEG metadata we need a binary string; start there.
410 reader
.onload = function () {
411 callbackBinary( reader
.result
);
413 // Now run back through the regular code path.
414 fetchPreview( file
, callback
);
416 reader
.readAsBinaryString( file
);
417 } else if ( callbackBinary
&& 'readAsArrayBuffer' in reader
) {
418 // readAsArrayBuffer replaces readAsBinaryString
419 // However, our JPEG metadata library wants a string.
420 // So, this is going to be an ugly conversion.
421 reader
.onload = function () {
423 buffer
= new Uint8Array( reader
.result
),
425 for ( i
= 0; i
< buffer
.byteLength
; i
++ ) {
426 string
+= String
.fromCharCode( buffer
[i
] );
428 callbackBinary( string
);
430 // Now run back through the regular code path.
431 fetchPreview( file
, callback
);
433 reader
.readAsArrayBuffer( file
);
434 } else if ( 'URL' in window
&& 'createObjectURL' in window
.URL
) {
435 // Supported in Firefox 4.0 and above <https://developer.mozilla.org/en/DOM/window.URL.createObjectURL>
436 // WebKit has it in a namespace for now but that's ok. ;)
438 // Lifetime of this URL is until document close, which is fine
439 // for Special:Upload -- if this code gets used on longer-running
440 // pages, add a revokeObjectURL() when it's no longer needed.
442 // Prefer this over readAsDataURL for Firefox 7 due to bug reading
443 // some SVG files from data URIs <https://bugzilla.mozilla.org/show_bug.cgi?id=694165>
444 callback( window
.URL
.createObjectURL( file
) );
446 // This ends up decoding the file to base-64 and back again, which
447 // feels horribly inefficient.
448 reader
.onload = function () {
449 callback( reader
.result
);
451 reader
.readAsDataURL( file
);
456 * Format a file size attractively.
458 * TODO: Match numeric formatting
463 function prettySize( s
) {
464 var sizeMsgs
= ['size-bytes', 'size-kilobytes', 'size-megabytes', 'size-gigabytes'];
465 while ( s
>= 1024 && sizeMsgs
.length
> 1 ) {
467 sizeMsgs
= sizeMsgs
.slice( 1 );
469 return mw
.msg( sizeMsgs
[0], Math
.round( s
) );
473 * Clear the file upload preview area.
475 function clearPreview() {
476 $( '#mw-upload-thumbnail' ).remove();
480 * Check if the file does not exceed the maximum size
482 function checkMaxUploadSize( file
) {
485 function getMaxUploadSize( type
) {
486 var sizes
= mw
.config
.get( 'wgMaxUploadSize' );
488 if ( sizes
[type
] !== undefined ) {
494 $( '.mw-upload-source-error' ).remove();
496 maxSize
= getMaxUploadSize( 'file' );
497 if ( file
.size
> maxSize
) {
498 $error
= $( '<p class="error mw-upload-source-error" id="wpSourceTypeFile-error">' +
499 mw
.message( 'largefileserver', file
.size
, maxSize
).escaped() + '</p>' );
501 $( '#wpUploadFile' ).after( $error
);
510 if ( hasFileAPI() ) {
511 // Update thumbnail when the file selection control is updated.
512 $( '#wpUploadFile' ).change( function () {
514 if ( this.files
&& this.files
.length
) {
515 // Note: would need to be updated to handle multiple files.
516 var file
= this.files
[0];
518 if ( !checkMaxUploadSize( file
) ) {
522 if ( fileIsPreviewable( file
) ) {
530 // Disable all upload source fields except the selected one
533 $rows
= $( '.mw-htmlform-field-UploadSourceField' );
536 * @param {jQuery} $currentRow
537 * @return {Function} Handler
538 * @return {jQuery.Event} return.e
540 function createHandler( $currentRow
) {
542 $( '.mw-upload-source-error' ).remove();
543 if ( this.checked
) {
544 // Disable all inputs
545 $rows
.find( 'input[name!="wpSourceType"]' ).prop( 'disabled', true );
546 // Re-enable the current one
547 $currentRow
.find( 'input' ).prop( 'disabled', false );
552 for ( i
= $rows
.length
; i
; i
-- ) {
553 $row
= $rows
.eq( i
- 1 );
555 .find( 'input[name="wpSourceType"]' )
556 .change( createHandler( $row
) );
561 // Prevent losing work
562 var allowCloseWindow
,
563 $uploadForm
= $( '#mw-upload-form' );
565 if ( !mw
.user
.options
.get( 'useeditwarning' ) ) {
566 // If the user doesn't want edit warnings, don't set things up.
570 $uploadForm
.data( 'origtext', $uploadForm
.serialize() );
572 allowCloseWindow
= mw
.confirmCloseWindow( {
574 return $( '#wpUploadFile' ).get( 0 ).files
.length
!== 0 ||
575 $uploadForm
.data( 'origtext' ) !== $uploadForm
.serialize();
578 message
: mw
.msg( 'editwarning-warning' ),
579 namespace: 'uploadwarning'
582 $uploadForm
.submit( function () {
586 }( mediaWiki
, jQuery
) );