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
;
61 if ( !ajaxUploadDestCheck
|| this.nameToCheck
=== '' ) {
64 $spinnerDestCheck
= $.createSpinner().insertAfter( '#wpDestFile' );
66 ( new mw
.Api() ).get( {
68 titles
: ( new mw
.Title( this.nameToCheck
, mw
.config
.get( 'wgNamespaceIds' ).file
) ).getPrefixedText(),
70 iiprop
: 'uploadwarning',
72 } ).done( function ( result
) {
75 resultOut
= result
.query
.pages
[ result
.query
.pageids
[ 0 ] ].imageinfo
[ 0 ];
77 $spinnerDestCheck
.remove();
78 uploadWarning
.processResult( resultOut
, uploadWarning
.nameToCheck
);
82 processResult: function ( result
, fileName
) {
83 this.setWarning( result
.html
);
84 this.responseCache
[ fileName
] = result
.html
;
87 setWarning: function ( warning
) {
88 $( '#wpDestFile-warning' ).html( warning
);
90 // Set a value in the form indicating that the warning is acknowledged and
91 // doesn't need to be redisplayed post-upload
93 $( '#wpDestFileWarningAck' ).val( '' );
95 $( '#wpDestFileWarningAck' ).val( '1' );
103 responseCache
: { '': '' },
105 fetchPreview: function ( license
) {
107 if ( !mw
.config
.get( 'wgAjaxLicensePreview' ) ) {
110 if ( this.responseCache
.hasOwnProperty( license
) ) {
111 this.showPreview( this.responseCache
[ license
] );
115 $spinnerLicense
= $.createSpinner().insertAfter( '#wpLicense' );
117 ( new mw
.Api() ).get( {
119 text
: '{{' + license
+ '}}',
120 title
: $( '#wpDestFile' ).val() || 'File:Sample.jpg',
123 } ).done( function ( result
) {
124 $spinnerLicense
.remove();
125 uploadLicense
.processResult( result
, license
);
129 processResult: function ( result
, license
) {
130 this.responseCache
[ license
] = result
.parse
.text
[ '*' ];
131 this.showPreview( this.responseCache
[ license
] );
134 showPreview: function ( preview
) {
135 $( '#mw-license-preview' ).html( preview
);
141 // AJAX wpDestFile warnings
142 if ( ajaxUploadDestCheck
) {
143 // Insert an event handler that fetches upload warnings when wpDestFile
145 $( '#wpDestFile' ).change( function () {
146 uploadWarning
.checkNow( $( this ).val() );
148 // Insert a row where the warnings will be displayed just below the
150 $( '#mw-htmlform-description tbody' ).append(
153 .attr( 'id', 'wpDestFile-warning' )
154 .attr( 'colspan', 2 )
159 if ( mw
.config
.get( 'wgAjaxLicensePreview' ) && $license
.length
) {
160 // License selector check
161 $license
.change( function () {
162 // We might show a preview
163 uploadLicense
.fetchPreview( $license
.val() );
166 // License selector table row
167 $license
.closest( 'tr' ).after(
170 $( '<td>' ).attr( 'id', 'mw-license-preview' )
175 // fillDestFile setup
176 $.each( mw
.config
.get( 'wgUploadSourceIds' ), function ( index
, sourceId
) {
177 $( '#' + sourceId
).change( function () {
178 var path
, slash
, backslash
, fname
;
179 if ( !mw
.config
.get( 'wgUploadAutoFill' ) ) {
182 // Remove any previously flagged errors
183 $( '#mw-upload-permitted' ).attr( 'class', '' );
184 $( '#mw-upload-prohibited' ).attr( 'class', '' );
186 path
= $( this ).val();
187 // Find trailing part
188 slash
= path
.lastIndexOf( '/' );
189 backslash
= path
.lastIndexOf( '\\' );
190 if ( slash
=== -1 && backslash
=== -1 ) {
192 } else if ( slash
> backslash
) {
193 fname
= path
.slice( slash
+ 1 );
195 fname
= path
.slice( backslash
+ 1 );
198 // Clear the filename if it does not have a valid extension.
199 // URLs are less likely to have a useful extension, so don't include them in the
202 mw
.config
.get( 'wgCheckFileExtensions' ) &&
203 mw
.config
.get( 'wgStrictFileExtensions' ) &&
204 mw
.config
.get( 'wgFileExtensions' ) &&
205 $( this ).attr( 'id' ) !== 'wpUploadFileURL'
208 fname
.lastIndexOf( '.' ) === -1 ||
210 fname
.slice( fname
.lastIndexOf( '.' ) + 1 ).toLowerCase(),
211 $.map( mw
.config
.get( 'wgFileExtensions' ), function ( element
) {
212 return element
.toLowerCase();
216 // Not a valid extension
217 // Clear the upload and set mw-upload-permitted to error
219 $( '#mw-upload-permitted' ).attr( 'class', 'error' );
220 $( '#mw-upload-prohibited' ).attr( 'class', 'error' );
221 // Clear wpDestFile as well
222 $( '#wpDestFile' ).val( '' );
228 // Replace spaces by underscores
229 fname
= fname
.replace( / /g
, '_' );
230 // Capitalise first letter if needed
231 if ( mw
.config
.get( 'wgCapitalizeUploads' ) ) {
232 fname
= fname
[ 0 ].toUpperCase() + fname
.slice( 1 );
236 if ( $( '#wpDestFile' ).length
) {
237 // Call decodeURIComponent function to remove possible URL-encoded characters
238 // from the file name (bug 30390). Especially likely with upload-form-url.
239 // decodeURIComponent can throw an exception if input is invalid utf-8
241 $( '#wpDestFile' ).val( decodeURIComponent( fname
) );
243 $( '#wpDestFile' ).val( fname
);
245 uploadWarning
.checkNow( fname
);
251 // Add a preview to the upload form
254 * Is the FileAPI available with sufficient functionality?
256 function hasFileAPI() {
257 return window
.FileReader
!== undefined;
261 * Check if this is a recognizable image type...
262 * Also excludes files over 10M to avoid going insane on memory usage.
264 * TODO: Is there a way we can ask the browser what's supported in `<img>`s?
266 * TODO: Put SVG back after working around Firefox 7 bug <https://phabricator.wikimedia.org/T33643>
271 function fileIsPreviewable( file
) {
272 var known
= [ 'image/png', 'image/gif', 'image/jpeg', 'image/svg+xml' ],
273 tooHuge
= 10 * 1024 * 1024;
274 return ( $.inArray( file
.type
, known
) !== -1 ) && file
.size
> 0 && file
.size
< tooHuge
;
278 * Format a file size attractively.
280 * TODO: Match numeric formatting
285 function prettySize( s
) {
286 var sizeMsgs
= [ 'size-bytes', 'size-kilobytes', 'size-megabytes', 'size-gigabytes' ];
287 while ( s
>= 1024 && sizeMsgs
.length
> 1 ) {
289 sizeMsgs
= sizeMsgs
.slice( 1 );
291 return mw
.msg( sizeMsgs
[ 0 ], Math
.round( s
) );
295 * Show a thumbnail preview of PNG, JPEG, GIF, and SVG files prior to upload
296 * in browsers supporting HTML5 FileAPI.
298 * As of this writing, known good:
301 * - Chrome 7.something
303 * TODO: Check file size limits and warn of likely failures
307 function showPreview( file
) {
312 $spinner
= $.createSpinner( { size
: 'small', type
: 'block' } )
313 .css( { width
: previewSize
, height
: previewSize
} ),
314 thumb
= mw
.template
.get( 'mediawiki.special.upload', 'thumbnail.html' ).render();
317 .find( '.filename' ).text( file
.name
).end()
318 .find( '.fileinfo' ).text( prettySize( file
.size
) ).end()
319 .find( '.thumbinner' ).prepend( $spinner
).end();
321 $canvas
= $( '<canvas>' ).attr( { width
: previewSize
, height
: previewSize
} );
322 ctx
= $canvas
[ 0 ].getContext( '2d' );
323 $( '#mw-htmlform-source' ).parent().prepend( thumb
);
325 fetchPreview( file
, function ( dataURL
) {
326 var img
= new Image(),
329 if ( meta
&& meta
.tiff
&& meta
.tiff
.Orientation
) {
330 rotation
= ( 360 - ( function () {
331 // See includes/media/Bitmap.php
332 switch ( meta
.tiff
.Orientation
.value
) {
345 img
.onload = function () {
346 var info
, width
, height
, x
, y
, dx
, dy
, logicalWidth
, logicalHeight
;
348 // Fit the image within the previewSizexpreviewSize box
349 if ( img
.width
> img
.height
) {
351 height
= img
.height
/ img
.width
* previewSize
;
353 height
= previewSize
;
354 width
= img
.width
/ img
.height
* previewSize
;
356 // Determine the offset required to center the image
357 dx
= ( 180 - width
) / 2;
358 dy
= ( 180 - height
) / 2;
359 switch ( rotation
) {
360 // If a rotation is applied, the direction of the axis
361 // changes as well. You can derive the values below by
362 // drawing on paper an axis system, rotate it and see
363 // where the positive axis direction is
367 logicalWidth
= img
.width
;
368 logicalHeight
= img
.height
;
373 y
= dy
- previewSize
;
374 logicalWidth
= img
.height
;
375 logicalHeight
= img
.width
;
378 x
= dx
- previewSize
;
379 y
= dy
- previewSize
;
380 logicalWidth
= img
.width
;
381 logicalHeight
= img
.height
;
384 x
= dx
- previewSize
;
386 logicalWidth
= img
.height
;
387 logicalHeight
= img
.width
;
391 ctx
.clearRect( 0, 0, 180, 180 );
392 ctx
.rotate( rotation
/ 180 * Math
.PI
);
393 ctx
.drawImage( img
, x
, y
, width
, height
);
394 $spinner
.replaceWith( $canvas
);
397 info
= mw
.msg( 'widthheight', logicalWidth
, logicalHeight
) +
398 ', ' + prettySize( file
.size
);
400 $( '#mw-upload-thumbnail .fileinfo' ).text( info
);
403 }, mw
.config
.get( 'wgFileCanRotate' ) ? function ( data
) {
405 meta
= mw
.libs
.jpegmeta( data
, file
.fileName
);
406 // jscs:disable requireCamelCaseOrUpperCaseIdentifiers, disallowDanglingUnderscores
407 meta
._binary_data
= null;
416 * Start loading a file into memory; when complete, pass it as a
417 * data URL to the callback function. If the callbackBinary is set it will
418 * first be read as binary and afterwards as data URL. Useful if you want
419 * to do preprocessing on the binary data first.
422 * @param {Function} callback
423 * @param {Function} callbackBinary
425 function fetchPreview( file
, callback
, callbackBinary
) {
426 var reader
= new FileReader();
427 if ( callbackBinary
&& 'readAsBinaryString' in reader
) {
428 // To fetch JPEG metadata we need a binary string; start there.
430 reader
.onload = function () {
431 callbackBinary( reader
.result
);
433 // Now run back through the regular code path.
434 fetchPreview( file
, callback
);
436 reader
.readAsBinaryString( file
);
437 } else if ( callbackBinary
&& 'readAsArrayBuffer' in reader
) {
438 // readAsArrayBuffer replaces readAsBinaryString
439 // However, our JPEG metadata library wants a string.
440 // So, this is going to be an ugly conversion.
441 reader
.onload = function () {
443 buffer
= new Uint8Array( reader
.result
),
445 for ( i
= 0; i
< buffer
.byteLength
; i
++ ) {
446 string
+= String
.fromCharCode( buffer
[ i
] );
448 callbackBinary( string
);
450 // Now run back through the regular code path.
451 fetchPreview( file
, callback
);
453 reader
.readAsArrayBuffer( file
);
454 } else if ( 'URL' in window
&& 'createObjectURL' in window
.URL
) {
455 // Supported in Firefox 4.0 and above <https://developer.mozilla.org/en/DOM/window.URL.createObjectURL>
456 // WebKit has it in a namespace for now but that's ok. ;)
458 // Lifetime of this URL is until document close, which is fine
459 // for Special:Upload -- if this code gets used on longer-running
460 // pages, add a revokeObjectURL() when it's no longer needed.
462 // Prefer this over readAsDataURL for Firefox 7 due to bug reading
463 // some SVG files from data URIs <https://bugzilla.mozilla.org/show_bug.cgi?id=694165>
464 callback( window
.URL
.createObjectURL( file
) );
466 // This ends up decoding the file to base-64 and back again, which
467 // feels horribly inefficient.
468 reader
.onload = function () {
469 callback( reader
.result
);
471 reader
.readAsDataURL( file
);
476 * Clear the file upload preview area.
478 function clearPreview() {
479 $( '#mw-upload-thumbnail' ).remove();
483 * Check if the file does not exceed the maximum size
485 function checkMaxUploadSize( file
) {
488 function getMaxUploadSize( type
) {
489 var sizes
= mw
.config
.get( 'wgMaxUploadSize' );
491 if ( sizes
[ type
] !== undefined ) {
492 return sizes
[ type
];
497 $( '.mw-upload-source-error' ).remove();
499 maxSize
= getMaxUploadSize( 'file' );
500 if ( file
.size
> maxSize
) {
501 $error
= $( '<p class="error mw-upload-source-error" id="wpSourceTypeFile-error">' +
502 mw
.message( 'largefileserver', file
.size
, maxSize
).escaped() + '</p>' );
504 $( '#wpUploadFile' ).after( $error
);
513 if ( hasFileAPI() ) {
514 // Update thumbnail when the file selection control is updated.
515 $( '#wpUploadFile' ).change( function () {
517 if ( this.files
&& this.files
.length
) {
518 // Note: would need to be updated to handle multiple files.
519 var file
= this.files
[ 0 ];
521 if ( !checkMaxUploadSize( file
) ) {
525 if ( fileIsPreviewable( file
) ) {
533 // Disable all upload source fields except the selected one
535 var $rows
= $( '.mw-htmlform-field-UploadSourceField' );
537 $rows
.on( 'change', 'input[type="radio"]', function ( e
) {
538 var currentRow
= e
.delegateTarget
;
540 if ( !this.checked
) {
544 $( '.mw-upload-source-error' ).remove();
546 // Enable selected upload method
547 $( currentRow
).find( 'input' ).prop( 'disabled', false );
549 // Disable inputs of other upload methods
550 // (except for the radio button to re-enable it)
553 .find( 'input[type!="radio"]' )
554 .prop( 'disabled', true );
558 if ( !$( '#wpSourceTypeurl' ).prop( 'checked' ) ) {
559 $( '#wpUploadFileURL' ).prop( 'disabled', true );
564 // Prevent losing work
565 var allowCloseWindow
,
566 $uploadForm
= $( '#mw-upload-form' );
568 if ( !mw
.user
.options
.get( 'useeditwarning' ) ) {
569 // If the user doesn't want edit warnings, don't set things up.
573 $uploadForm
.data( 'origtext', $uploadForm
.serialize() );
575 allowCloseWindow
= mw
.confirmCloseWindow( {
577 return $( '#wpUploadFile' ).get( 0 ).files
.length
!== 0 ||
578 $uploadForm
.data( 'origtext' ) !== $uploadForm
.serialize();
581 message
: mw
.msg( 'editwarning-warning' ),
582 namespace: 'uploadwarning'
585 $uploadForm
.submit( function () {
586 allowCloseWindow
.release();
589 }( mediaWiki
, jQuery
) );