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 uploadWarning
.processResult( resultOut
, uploadWarning
.nameToCheck
);
78 } ).always( function () {
79 $spinnerDestCheck
.remove();
83 processResult: function ( result
, fileName
) {
84 this.setWarning( result
.html
);
85 this.responseCache
[ fileName
] = result
.html
;
88 setWarning: function ( warning
) {
89 var $warning
= $( $.parseHTML( warning
) );
90 mw
.hook( 'wikipage.content' ).fire( $warning
);
91 $( '#wpDestFile-warning' ).empty().append( $warning
);
93 // Set a value in the form indicating that the warning is acknowledged and
94 // doesn't need to be redisplayed post-upload
96 $( '#wpDestFileWarningAck' ).val( '' );
98 $( '#wpDestFileWarningAck' ).val( '1' );
106 responseCache
: { '': '' },
108 fetchPreview: function ( license
) {
110 if ( !mw
.config
.get( 'wgAjaxLicensePreview' ) ) {
113 if ( this.responseCache
.hasOwnProperty( license
) ) {
114 this.showPreview( this.responseCache
[ license
] );
118 $spinnerLicense
= $.createSpinner().insertAfter( '#wpLicense' );
120 ( new mw
.Api() ).get( {
122 text
: '{{' + license
+ '}}',
123 title
: $( '#wpDestFile' ).val() || 'File:Sample.jpg',
126 } ).done( function ( result
) {
127 uploadLicense
.processResult( result
, license
);
128 } ).always( function () {
129 $spinnerLicense
.remove();
133 processResult: function ( result
, license
) {
134 this.responseCache
[ license
] = result
.parse
.text
[ '*' ];
135 this.showPreview( this.responseCache
[ license
] );
138 showPreview: function ( preview
) {
139 $( '#mw-license-preview' ).html( preview
);
145 // AJAX wpDestFile warnings
146 if ( ajaxUploadDestCheck
) {
147 // Insert an event handler that fetches upload warnings when wpDestFile
149 $( '#wpDestFile' ).change( function () {
150 uploadWarning
.checkNow( $( this ).val() );
152 // Insert a row where the warnings will be displayed just below the
154 $( '#mw-htmlform-description tbody' ).append(
157 .attr( 'id', 'wpDestFile-warning' )
158 .attr( 'colspan', 2 )
163 if ( mw
.config
.get( 'wgAjaxLicensePreview' ) && $license
.length
) {
164 // License selector check
165 $license
.change( function () {
166 // We might show a preview
167 uploadLicense
.fetchPreview( $license
.val() );
170 // License selector table row
171 $license
.closest( 'tr' ).after(
174 $( '<td>' ).attr( 'id', 'mw-license-preview' )
179 // fillDestFile setup
180 $.each( mw
.config
.get( 'wgUploadSourceIds' ), function ( index
, sourceId
) {
181 $( '#' + sourceId
).change( function () {
182 var path
, slash
, backslash
, fname
;
183 if ( !mw
.config
.get( 'wgUploadAutoFill' ) ) {
186 // Remove any previously flagged errors
187 $( '#mw-upload-permitted' ).attr( 'class', '' );
188 $( '#mw-upload-prohibited' ).attr( 'class', '' );
190 path
= $( this ).val();
191 // Find trailing part
192 slash
= path
.lastIndexOf( '/' );
193 backslash
= path
.lastIndexOf( '\\' );
194 if ( slash
=== -1 && backslash
=== -1 ) {
196 } else if ( slash
> backslash
) {
197 fname
= path
.slice( slash
+ 1 );
199 fname
= path
.slice( backslash
+ 1 );
202 // Clear the filename if it does not have a valid extension.
203 // URLs are less likely to have a useful extension, so don't include them in the
206 mw
.config
.get( 'wgCheckFileExtensions' ) &&
207 mw
.config
.get( 'wgStrictFileExtensions' ) &&
208 mw
.config
.get( 'wgFileExtensions' ) &&
209 $( this ).attr( 'id' ) !== 'wpUploadFileURL'
212 fname
.lastIndexOf( '.' ) === -1 ||
214 fname
.slice( fname
.lastIndexOf( '.' ) + 1 ).toLowerCase(),
215 $.map( mw
.config
.get( 'wgFileExtensions' ), function ( element
) {
216 return element
.toLowerCase();
220 // Not a valid extension
221 // Clear the upload and set mw-upload-permitted to error
223 $( '#mw-upload-permitted' ).attr( 'class', 'error' );
224 $( '#mw-upload-prohibited' ).attr( 'class', 'error' );
225 // Clear wpDestFile as well
226 $( '#wpDestFile' ).val( '' );
232 // Replace spaces by underscores
233 fname
= fname
.replace( / /g
, '_' );
234 // Capitalise first letter if needed
235 if ( mw
.config
.get( 'wgCapitalizeUploads' ) ) {
236 fname
= fname
[ 0 ].toUpperCase() + fname
.slice( 1 );
240 if ( $( '#wpDestFile' ).length
) {
241 // Call decodeURIComponent function to remove possible URL-encoded characters
242 // from the file name (bug 30390). Especially likely with upload-form-url.
243 // decodeURIComponent can throw an exception if input is invalid utf-8
245 $( '#wpDestFile' ).val( decodeURIComponent( fname
) );
247 $( '#wpDestFile' ).val( fname
);
249 uploadWarning
.checkNow( fname
);
255 // Add a preview to the upload form
258 * Is the FileAPI available with sufficient functionality?
260 function hasFileAPI() {
261 return window
.FileReader
!== undefined;
265 * Check if this is a recognizable image type...
266 * Also excludes files over 10M to avoid going insane on memory usage.
268 * TODO: Is there a way we can ask the browser what's supported in `<img>`s?
270 * TODO: Put SVG back after working around Firefox 7 bug <https://phabricator.wikimedia.org/T33643>
275 function fileIsPreviewable( file
) {
276 var known
= [ 'image/png', 'image/gif', 'image/jpeg', 'image/svg+xml' ],
277 tooHuge
= 10 * 1024 * 1024;
278 return ( $.inArray( file
.type
, known
) !== -1 ) && file
.size
> 0 && file
.size
< tooHuge
;
282 * Format a file size attractively.
284 * TODO: Match numeric formatting
289 function prettySize( s
) {
290 var sizeMsgs
= [ 'size-bytes', 'size-kilobytes', 'size-megabytes', 'size-gigabytes' ];
291 while ( s
>= 1024 && sizeMsgs
.length
> 1 ) {
293 sizeMsgs
= sizeMsgs
.slice( 1 );
295 return mw
.msg( sizeMsgs
[ 0 ], Math
.round( s
) );
299 * Show a thumbnail preview of PNG, JPEG, GIF, and SVG files prior to upload
300 * in browsers supporting HTML5 FileAPI.
302 * As of this writing, known good:
305 * - Chrome 7.something
307 * TODO: Check file size limits and warn of likely failures
311 function showPreview( file
) {
316 $spinner
= $.createSpinner( { size
: 'small', type
: 'block' } )
317 .css( { width
: previewSize
, height
: previewSize
} ),
318 thumb
= mw
.template
.get( 'mediawiki.special.upload', 'thumbnail.html' ).render();
321 .find( '.filename' ).text( file
.name
).end()
322 .find( '.fileinfo' ).text( prettySize( file
.size
) ).end()
323 .find( '.thumbinner' ).prepend( $spinner
).end();
325 $canvas
= $( '<canvas>' ).attr( { width
: previewSize
, height
: previewSize
} );
326 ctx
= $canvas
[ 0 ].getContext( '2d' );
327 $( '#mw-htmlform-source' ).parent().prepend( thumb
);
329 fetchPreview( file
, function ( dataURL
) {
330 var img
= new Image(),
333 if ( meta
&& meta
.tiff
&& meta
.tiff
.Orientation
) {
334 rotation
= ( 360 - ( function () {
335 // See includes/media/Bitmap.php
336 switch ( meta
.tiff
.Orientation
.value
) {
349 img
.onload = function () {
350 var info
, width
, height
, x
, y
, dx
, dy
, logicalWidth
, logicalHeight
;
352 // Fit the image within the previewSizexpreviewSize box
353 if ( img
.width
> img
.height
) {
355 height
= img
.height
/ img
.width
* previewSize
;
357 height
= previewSize
;
358 width
= img
.width
/ img
.height
* previewSize
;
360 // Determine the offset required to center the image
361 dx
= ( 180 - width
) / 2;
362 dy
= ( 180 - height
) / 2;
363 switch ( rotation
) {
364 // If a rotation is applied, the direction of the axis
365 // changes as well. You can derive the values below by
366 // drawing on paper an axis system, rotate it and see
367 // where the positive axis direction is
371 logicalWidth
= img
.width
;
372 logicalHeight
= img
.height
;
377 y
= dy
- previewSize
;
378 logicalWidth
= img
.height
;
379 logicalHeight
= img
.width
;
382 x
= dx
- previewSize
;
383 y
= dy
- previewSize
;
384 logicalWidth
= img
.width
;
385 logicalHeight
= img
.height
;
388 x
= dx
- previewSize
;
390 logicalWidth
= img
.height
;
391 logicalHeight
= img
.width
;
395 ctx
.clearRect( 0, 0, 180, 180 );
396 ctx
.rotate( rotation
/ 180 * Math
.PI
);
397 ctx
.drawImage( img
, x
, y
, width
, height
);
398 $spinner
.replaceWith( $canvas
);
401 info
= mw
.msg( 'widthheight', logicalWidth
, logicalHeight
) +
402 ', ' + prettySize( file
.size
);
404 $( '#mw-upload-thumbnail .fileinfo' ).text( info
);
407 }, mw
.config
.get( 'wgFileCanRotate' ) ? function ( data
) {
409 meta
= mw
.libs
.jpegmeta( data
, file
.fileName
);
410 // jscs:disable requireCamelCaseOrUpperCaseIdentifiers, disallowDanglingUnderscores
411 meta
._binary_data
= null;
420 * Start loading a file into memory; when complete, pass it as a
421 * data URL to the callback function. If the callbackBinary is set it will
422 * first be read as binary and afterwards as data URL. Useful if you want
423 * to do preprocessing on the binary data first.
426 * @param {Function} callback
427 * @param {Function} callbackBinary
429 function fetchPreview( file
, callback
, callbackBinary
) {
430 var reader
= new FileReader();
431 if ( callbackBinary
&& 'readAsBinaryString' in reader
) {
432 // To fetch JPEG metadata we need a binary string; start there.
434 reader
.onload = function () {
435 callbackBinary( reader
.result
);
437 // Now run back through the regular code path.
438 fetchPreview( file
, callback
);
440 reader
.readAsBinaryString( file
);
441 } else if ( callbackBinary
&& 'readAsArrayBuffer' in reader
) {
442 // readAsArrayBuffer replaces readAsBinaryString
443 // However, our JPEG metadata library wants a string.
444 // So, this is going to be an ugly conversion.
445 reader
.onload = function () {
447 buffer
= new Uint8Array( reader
.result
),
449 for ( i
= 0; i
< buffer
.byteLength
; i
++ ) {
450 string
+= String
.fromCharCode( buffer
[ i
] );
452 callbackBinary( string
);
454 // Now run back through the regular code path.
455 fetchPreview( file
, callback
);
457 reader
.readAsArrayBuffer( file
);
458 } else if ( 'URL' in window
&& 'createObjectURL' in window
.URL
) {
459 // Supported in Firefox 4.0 and above <https://developer.mozilla.org/en/DOM/window.URL.createObjectURL>
460 // WebKit has it in a namespace for now but that's ok. ;)
462 // Lifetime of this URL is until document close, which is fine
463 // for Special:Upload -- if this code gets used on longer-running
464 // pages, add a revokeObjectURL() when it's no longer needed.
466 // Prefer this over readAsDataURL for Firefox 7 due to bug reading
467 // some SVG files from data URIs <https://bugzilla.mozilla.org/show_bug.cgi?id=694165>
468 callback( window
.URL
.createObjectURL( file
) );
470 // This ends up decoding the file to base-64 and back again, which
471 // feels horribly inefficient.
472 reader
.onload = function () {
473 callback( reader
.result
);
475 reader
.readAsDataURL( file
);
480 * Clear the file upload preview area.
482 function clearPreview() {
483 $( '#mw-upload-thumbnail' ).remove();
487 * Check if the file does not exceed the maximum size
489 function checkMaxUploadSize( file
) {
492 function getMaxUploadSize( type
) {
493 var sizes
= mw
.config
.get( 'wgMaxUploadSize' );
495 if ( sizes
[ type
] !== undefined ) {
496 return sizes
[ type
];
501 $( '.mw-upload-source-error' ).remove();
503 maxSize
= getMaxUploadSize( 'file' );
504 if ( file
.size
> maxSize
) {
505 $error
= $( '<p class="error mw-upload-source-error" id="wpSourceTypeFile-error">' +
506 mw
.message( 'largefileserver', file
.size
, maxSize
).escaped() + '</p>' );
508 $( '#wpUploadFile' ).after( $error
);
517 if ( hasFileAPI() ) {
518 // Update thumbnail when the file selection control is updated.
519 $( '#wpUploadFile' ).change( function () {
521 if ( this.files
&& this.files
.length
) {
522 // Note: would need to be updated to handle multiple files.
523 var file
= this.files
[ 0 ];
525 if ( !checkMaxUploadSize( file
) ) {
529 if ( fileIsPreviewable( file
) ) {
537 // Disable all upload source fields except the selected one
539 var $rows
= $( '.mw-htmlform-field-UploadSourceField' );
541 $rows
.on( 'change', 'input[type="radio"]', function ( e
) {
542 var currentRow
= e
.delegateTarget
;
544 if ( !this.checked
) {
548 $( '.mw-upload-source-error' ).remove();
550 // Enable selected upload method
551 $( currentRow
).find( 'input' ).prop( 'disabled', false );
553 // Disable inputs of other upload methods
554 // (except for the radio button to re-enable it)
557 .find( 'input[type!="radio"]' )
558 .prop( 'disabled', true );
562 if ( !$( '#wpSourceTypeurl' ).prop( 'checked' ) ) {
563 $( '#wpUploadFileURL' ).prop( 'disabled', true );
568 // Prevent losing work
569 var allowCloseWindow
,
570 $uploadForm
= $( '#mw-upload-form' );
572 if ( !mw
.user
.options
.get( 'useeditwarning' ) ) {
573 // If the user doesn't want edit warnings, don't set things up.
577 $uploadForm
.data( 'origtext', $uploadForm
.serialize() );
579 allowCloseWindow
= mw
.confirmCloseWindow( {
581 return $( '#wpUploadFile' ).get( 0 ).files
.length
!== 0 ||
582 $uploadForm
.data( 'origtext' ) !== $uploadForm
.serialize();
585 message
: mw
.msg( 'editwarning-warning' ),
586 namespace: 'uploadwarning'
589 $uploadForm
.submit( function () {
590 allowCloseWindow
.release();
593 }( mediaWiki
, jQuery
) );