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 $warningBox
= $( '#wpDestFile-warning' ),
96 $warning
= $( $.parseHTML( warning
) );
97 mw
.hook( 'wikipage.content' ).fire( $warning
);
98 $warningBox
.empty().append( $warning
);
100 // Set a value in the form indicating that the warning is acknowledged and
101 // doesn't need to be redisplayed post-upload
103 $( '#wpDestFileWarningAck' ).val( '' );
104 $warningBox
.removeAttr( 'class' );
106 $( '#wpDestFileWarningAck' ).val( '1' );
107 $warningBox
.attr( 'class', 'mw-destfile-warning' );
115 responseCache
: { '': '' },
117 fetchPreview: function ( license
) {
119 if ( !mw
.config
.get( 'wgAjaxLicensePreview' ) ) {
122 if ( this.responseCache
.hasOwnProperty( license
) ) {
123 this.showPreview( this.responseCache
[ license
] );
127 $spinnerLicense
= $.createSpinner().insertAfter( '#wpLicense' );
129 ( new mw
.Api() ).get( {
132 text
: '{{' + license
+ '}}',
133 title
: $( '#wpDestFile' ).val() || 'File:Sample.jpg',
136 } ).done( function ( result
) {
137 uploadLicense
.processResult( result
, license
);
138 } ).always( function () {
139 $spinnerLicense
.remove();
143 processResult: function ( result
, license
) {
144 this.responseCache
[ license
] = result
.parse
.text
;
145 this.showPreview( this.responseCache
[ license
] );
148 showPreview: function ( preview
) {
149 $( '#mw-license-preview' ).html( preview
);
155 // AJAX wpDestFile warnings
156 if ( ajaxUploadDestCheck
) {
157 // Insert an event handler that fetches upload warnings when wpDestFile
159 $( '#wpDestFile' ).change( function () {
160 uploadWarning
.checkNow( $( this ).val() );
162 // Insert a row where the warnings will be displayed just below the
164 $( '#mw-htmlform-description tbody' ).append(
167 .attr( 'id', 'wpDestFile-warning' )
168 .attr( 'colspan', 2 )
173 if ( mw
.config
.get( 'wgAjaxLicensePreview' ) && $license
.length
) {
174 // License selector check
175 $license
.change( function () {
176 // We might show a preview
177 uploadLicense
.fetchPreview( $license
.val() );
180 // License selector table row
181 $license
.closest( 'tr' ).after(
184 $( '<td>' ).attr( 'id', 'mw-license-preview' )
189 // fillDestFile setup
190 $.each( mw
.config
.get( 'wgUploadSourceIds' ), function ( index
, sourceId
) {
191 $( '#' + sourceId
).change( function () {
192 var path
, slash
, backslash
, fname
;
193 if ( !mw
.config
.get( 'wgUploadAutoFill' ) ) {
196 // Remove any previously flagged errors
197 $( '#mw-upload-permitted' ).attr( 'class', '' );
198 $( '#mw-upload-prohibited' ).attr( 'class', '' );
200 path
= $( this ).val();
201 // Find trailing part
202 slash
= path
.lastIndexOf( '/' );
203 backslash
= path
.lastIndexOf( '\\' );
204 if ( slash
=== -1 && backslash
=== -1 ) {
206 } else if ( slash
> backslash
) {
207 fname
= path
.slice( slash
+ 1 );
209 fname
= path
.slice( backslash
+ 1 );
212 // Clear the filename if it does not have a valid extension.
213 // URLs are less likely to have a useful extension, so don't include them in the
216 mw
.config
.get( 'wgCheckFileExtensions' ) &&
217 mw
.config
.get( 'wgStrictFileExtensions' ) &&
218 mw
.config
.get( 'wgFileExtensions' ) &&
219 $( this ).attr( 'id' ) !== 'wpUploadFileURL'
222 fname
.lastIndexOf( '.' ) === -1 ||
224 fname
.slice( fname
.lastIndexOf( '.' ) + 1 ).toLowerCase(),
225 $.map( mw
.config
.get( 'wgFileExtensions' ), function ( element
) {
226 return element
.toLowerCase();
230 // Not a valid extension
231 // Clear the upload and set mw-upload-permitted to error
233 $( '#mw-upload-permitted' ).attr( 'class', 'error' );
234 $( '#mw-upload-prohibited' ).attr( 'class', 'error' );
235 // Clear wpDestFile as well
236 $( '#wpDestFile' ).val( '' );
242 // Replace spaces by underscores
243 fname
= fname
.replace( / /g
, '_' );
244 // Capitalise first letter if needed
245 if ( mw
.config
.get( 'wgCapitalizeUploads' ) ) {
246 fname
= fname
[ 0 ].toUpperCase() + fname
.slice( 1 );
250 if ( $( '#wpDestFile' ).length
) {
251 // Call decodeURIComponent function to remove possible URL-encoded characters
252 // from the file name (bug 30390). Especially likely with upload-form-url.
253 // decodeURIComponent can throw an exception if input is invalid utf-8
255 $( '#wpDestFile' ).val( decodeURIComponent( fname
) );
257 $( '#wpDestFile' ).val( fname
);
259 uploadWarning
.checkNow( fname
);
265 // Add a preview to the upload form
268 * Is the FileAPI available with sufficient functionality?
270 function hasFileAPI() {
271 return window
.FileReader
!== undefined;
275 * Check if this is a recognizable image type...
276 * Also excludes files over 10M to avoid going insane on memory usage.
278 * TODO: Is there a way we can ask the browser what's supported in `<img>`s?
280 * TODO: Put SVG back after working around Firefox 7 bug <https://phabricator.wikimedia.org/T33643>
285 function fileIsPreviewable( file
) {
286 var known
= [ 'image/png', 'image/gif', 'image/jpeg', 'image/svg+xml' ],
287 tooHuge
= 10 * 1024 * 1024;
288 return ( $.inArray( file
.type
, known
) !== -1 ) && file
.size
> 0 && file
.size
< tooHuge
;
292 * Format a file size attractively.
294 * TODO: Match numeric formatting
299 function prettySize( s
) {
300 var sizeMsgs
= [ 'size-bytes', 'size-kilobytes', 'size-megabytes', 'size-gigabytes' ];
301 while ( s
>= 1024 && sizeMsgs
.length
> 1 ) {
303 sizeMsgs
= sizeMsgs
.slice( 1 );
305 return mw
.msg( sizeMsgs
[ 0 ], Math
.round( s
) );
309 * Show a thumbnail preview of PNG, JPEG, GIF, and SVG files prior to upload
310 * in browsers supporting HTML5 FileAPI.
312 * As of this writing, known good:
315 * - Chrome 7.something
317 * TODO: Check file size limits and warn of likely failures
321 function showPreview( file
) {
326 $spinner
= $.createSpinner( { size
: 'small', type
: 'block' } )
327 .css( { width
: previewSize
, height
: previewSize
} ),
328 thumb
= mw
.template
.get( 'mediawiki.special.upload', 'thumbnail.html' ).render();
331 .find( '.filename' ).text( file
.name
).end()
332 .find( '.fileinfo' ).text( prettySize( file
.size
) ).end()
333 .find( '.thumbinner' ).prepend( $spinner
).end();
335 $canvas
= $( '<canvas>' ).attr( { width
: previewSize
, height
: previewSize
} );
336 ctx
= $canvas
[ 0 ].getContext( '2d' );
337 $( '#mw-htmlform-source' ).parent().prepend( thumb
);
339 fetchPreview( file
, function ( dataURL
) {
340 var img
= new Image(),
343 if ( meta
&& meta
.tiff
&& meta
.tiff
.Orientation
) {
344 rotation
= ( 360 - ( function () {
345 // See includes/media/Bitmap.php
346 switch ( meta
.tiff
.Orientation
.value
) {
359 img
.onload = function () {
360 var info
, width
, height
, x
, y
, dx
, dy
, logicalWidth
, logicalHeight
;
362 // Fit the image within the previewSizexpreviewSize box
363 if ( img
.width
> img
.height
) {
365 height
= img
.height
/ img
.width
* previewSize
;
367 height
= previewSize
;
368 width
= img
.width
/ img
.height
* previewSize
;
370 // Determine the offset required to center the image
371 dx
= ( 180 - width
) / 2;
372 dy
= ( 180 - height
) / 2;
373 switch ( rotation
) {
374 // If a rotation is applied, the direction of the axis
375 // changes as well. You can derive the values below by
376 // drawing on paper an axis system, rotate it and see
377 // where the positive axis direction is
381 logicalWidth
= img
.width
;
382 logicalHeight
= img
.height
;
387 y
= dy
- previewSize
;
388 logicalWidth
= img
.height
;
389 logicalHeight
= img
.width
;
392 x
= dx
- previewSize
;
393 y
= dy
- previewSize
;
394 logicalWidth
= img
.width
;
395 logicalHeight
= img
.height
;
398 x
= dx
- previewSize
;
400 logicalWidth
= img
.height
;
401 logicalHeight
= img
.width
;
405 ctx
.clearRect( 0, 0, 180, 180 );
406 ctx
.rotate( rotation
/ 180 * Math
.PI
);
407 ctx
.drawImage( img
, x
, y
, width
, height
);
408 $spinner
.replaceWith( $canvas
);
411 info
= mw
.msg( 'widthheight', logicalWidth
, logicalHeight
) +
412 ', ' + prettySize( file
.size
);
414 $( '#mw-upload-thumbnail .fileinfo' ).text( info
);
416 img
.onerror = function () {
417 // Can happen for example for invalid SVG files
421 }, mw
.config
.get( 'wgFileCanRotate' ) ? function ( data
) {
423 meta
= mw
.libs
.jpegmeta( data
, file
.fileName
);
424 // jscs:disable requireCamelCaseOrUpperCaseIdentifiers, disallowDanglingUnderscores
425 meta
._binary_data
= null;
434 * Start loading a file into memory; when complete, pass it as a
435 * data URL to the callback function. If the callbackBinary is set it will
436 * first be read as binary and afterwards as data URL. Useful if you want
437 * to do preprocessing on the binary data first.
440 * @param {Function} callback
441 * @param {Function} callbackBinary
443 function fetchPreview( file
, callback
, callbackBinary
) {
444 var reader
= new FileReader();
445 if ( callbackBinary
&& 'readAsBinaryString' in reader
) {
446 // To fetch JPEG metadata we need a binary string; start there.
448 reader
.onload = function () {
449 callbackBinary( reader
.result
);
451 // Now run back through the regular code path.
452 fetchPreview( file
, callback
);
454 reader
.readAsBinaryString( file
);
455 } else if ( callbackBinary
&& 'readAsArrayBuffer' in reader
) {
456 // readAsArrayBuffer replaces readAsBinaryString
457 // However, our JPEG metadata library wants a string.
458 // So, this is going to be an ugly conversion.
459 reader
.onload = function () {
461 buffer
= new Uint8Array( reader
.result
),
463 for ( i
= 0; i
< buffer
.byteLength
; i
++ ) {
464 string
+= String
.fromCharCode( buffer
[ i
] );
466 callbackBinary( string
);
468 // Now run back through the regular code path.
469 fetchPreview( file
, callback
);
471 reader
.readAsArrayBuffer( file
);
472 } else if ( 'URL' in window
&& 'createObjectURL' in window
.URL
) {
473 // Supported in Firefox 4.0 and above <https://developer.mozilla.org/en/DOM/window.URL.createObjectURL>
474 // WebKit has it in a namespace for now but that's ok. ;)
476 // Lifetime of this URL is until document close, which is fine
477 // for Special:Upload -- if this code gets used on longer-running
478 // pages, add a revokeObjectURL() when it's no longer needed.
480 // Prefer this over readAsDataURL for Firefox 7 due to bug reading
481 // some SVG files from data URIs <https://bugzilla.mozilla.org/show_bug.cgi?id=694165>
482 callback( window
.URL
.createObjectURL( file
) );
484 // This ends up decoding the file to base-64 and back again, which
485 // feels horribly inefficient.
486 reader
.onload = function () {
487 callback( reader
.result
);
489 reader
.readAsDataURL( file
);
494 * Clear the file upload preview area.
496 function clearPreview() {
497 $( '#mw-upload-thumbnail' ).remove();
501 * Check if the file does not exceed the maximum size
503 function checkMaxUploadSize( file
) {
506 function getMaxUploadSize( type
) {
507 var sizes
= mw
.config
.get( 'wgMaxUploadSize' );
509 if ( sizes
[ type
] !== undefined ) {
510 return sizes
[ type
];
515 $( '.mw-upload-source-error' ).remove();
517 maxSize
= getMaxUploadSize( 'file' );
518 if ( file
.size
> maxSize
) {
519 $error
= $( '<p class="error mw-upload-source-error" id="wpSourceTypeFile-error">' +
520 mw
.message( 'largefileserver', file
.size
, maxSize
).escaped() + '</p>' );
522 $( '#wpUploadFile' ).after( $error
);
531 if ( hasFileAPI() ) {
532 // Update thumbnail when the file selection control is updated.
533 $( '#wpUploadFile' ).change( function () {
535 if ( this.files
&& this.files
.length
) {
536 // Note: would need to be updated to handle multiple files.
537 var file
= this.files
[ 0 ];
539 if ( !checkMaxUploadSize( file
) ) {
543 if ( fileIsPreviewable( file
) ) {
551 // Disable all upload source fields except the selected one
553 var $rows
= $( '.mw-htmlform-field-UploadSourceField' );
555 $rows
.on( 'change', 'input[type="radio"]', function ( e
) {
556 var currentRow
= e
.delegateTarget
;
558 if ( !this.checked
) {
562 $( '.mw-upload-source-error' ).remove();
564 // Enable selected upload method
565 $( currentRow
).find( 'input' ).prop( 'disabled', false );
567 // Disable inputs of other upload methods
568 // (except for the radio button to re-enable it)
571 .find( 'input[type!="radio"]' )
572 .prop( 'disabled', true );
576 if ( !$( '#wpSourceTypeurl' ).prop( 'checked' ) ) {
577 $( '#wpUploadFileURL' ).prop( 'disabled', true );
582 // Prevent losing work
583 var allowCloseWindow
,
584 $uploadForm
= $( '#mw-upload-form' );
586 if ( !mw
.user
.options
.get( 'useeditwarning' ) ) {
587 // If the user doesn't want edit warnings, don't set things up.
591 $uploadForm
.data( 'origtext', $uploadForm
.serialize() );
593 allowCloseWindow
= mw
.confirmCloseWindow( {
595 return $( '#wpUploadFile' ).get( 0 ).files
.length
!== 0 ||
596 $uploadForm
.data( 'origtext' ) !== $uploadForm
.serialize();
599 message
: mw
.msg( 'editwarning-warning' ),
600 namespace: 'uploadwarning'
603 $uploadForm
.submit( function () {
604 allowCloseWindow
.release();
607 }( mediaWiki
, jQuery
) );