2 * JavaScript for Special:Upload
5 * @class mw.special.upload
9 var uploadWarning
, uploadLicense
,
10 ajaxUploadDestCheck
= mw
.config
.get( 'wgAjaxUploadDestCheck' ),
11 $license
= $( '#wpLicense' );
13 window
.wgUploadWarningObj
= uploadWarning
= {
14 responseCache
: { '': ' ' },
20 keypress: function () {
21 if ( !ajaxUploadDestCheck
) {
25 // Find file to upload
26 if ( !$( '#wpDestFile' ).length
|| !$( '#wpDestFile-warning' ).length
) {
30 this.nameToCheck
= $( '#wpDestFile' ).val();
33 if ( this.timeoutID
) {
34 clearTimeout( this.timeoutID
);
36 // Check response cache
37 if ( this.responseCache
.hasOwnProperty( this.nameToCheck
) ) {
38 this.setWarning( this.responseCache
[this.nameToCheck
] );
42 this.timeoutID
= setTimeout( function () {
43 uploadWarning
.timeout();
47 checkNow: function ( fname
) {
48 if ( !ajaxUploadDestCheck
) {
51 if ( this.timeoutID
) {
52 clearTimeout( this.timeoutID
);
54 this.nameToCheck
= fname
;
58 timeout: function () {
59 var $spinnerDestCheck
;
60 if ( !ajaxUploadDestCheck
|| this.nameToCheck
=== '' ) {
63 $spinnerDestCheck
= $.createSpinner().insertAfter( '#wpDestFile' );
65 ( new mw
.Api() ).get( {
67 titles
: ( new mw
.Title( this.nameToCheck
, mw
.config
.get( 'wgNamespaceIds' ).file
) ).getPrefixedText(),
69 iiprop
: 'uploadwarning',
71 } ).done( function ( result
) {
74 resultOut
= result
.query
.pages
[result
.query
.pageids
[0]].imageinfo
[0];
76 $spinnerDestCheck
.remove();
77 uploadWarning
.processResult( resultOut
, uploadWarning
.nameToCheck
);
81 processResult: function ( result
, fileName
) {
82 this.setWarning( result
.html
);
83 this.responseCache
[fileName
] = result
.html
;
86 setWarning: function ( warning
) {
87 $( '#wpDestFile-warning' ).html( warning
);
89 // Set a value in the form indicating that the warning is acknowledged and
90 // doesn't need to be redisplayed post-upload
92 $( '#wpDestFileWarningAck' ).val( '' );
94 $( '#wpDestFileWarningAck' ).val( '1' );
102 responseCache
: { '': '' },
104 fetchPreview: function ( license
) {
106 if ( !mw
.config
.get( 'wgAjaxLicensePreview' ) ) {
109 if ( this.responseCache
.hasOwnProperty( license
) ) {
110 this.showPreview( this.responseCache
[license
] );
114 $spinnerLicense
= $.createSpinner().insertAfter( '#wpLicense' );
116 ( new mw
.Api() ).get( {
118 text
: '{{' + license
+ '}}',
119 title
: $( '#wpDestFile' ).val() || 'File:Sample.jpg',
122 } ).done( function ( result
) {
123 $spinnerLicense
.remove();
124 uploadLicense
.processResult( result
, license
);
128 processResult: function ( result
, license
) {
129 this.responseCache
[license
] = result
.parse
.text
['*'];
130 this.showPreview( this.responseCache
[license
] );
133 showPreview: function ( preview
) {
134 $( '#mw-license-preview' ).html( preview
);
140 // Disable URL box if the URL copy upload source type is not selected
141 if ( !$( '#wpSourceTypeurl' ).prop( 'checked' ) ) {
142 $( '#wpUploadFileURL' ).prop( 'disabled', true );
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
.charAt( 0 ).toUpperCase().concat( 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://bugzilla.wikimedia.org/show_bug.cgi?id=31643>
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 * Show a thumbnail preview of PNG, JPEG, GIF, and SVG files prior to upload
283 * in browsers supporting HTML5 FileAPI.
285 * As of this writing, known good:
288 * - Chrome 7.something
290 * TODO: Check file size limits and warn of likely failures
294 function showPreview( file
) {
299 thumb
= mw
.template
.get( 'mediawiki.special.upload', 'thumbnail.html' ).render();
301 thumb
.find( '.filename' ).text( file
.name
).end()
302 .find( '.fileinfo' ).text( prettySize( file
.size
) ).end();
304 $canvas
= $( '<canvas width="' + previewSize
+ '" height="' + previewSize
+ '" ></canvas>' );
305 ctx
= $canvas
[0].getContext( '2d' );
306 $( '#mw-htmlform-source' ).parent().prepend( thumb
);
308 fetchPreview( file
, function ( dataURL
) {
309 var img
= new Image(),
312 if ( meta
&& meta
.tiff
&& meta
.tiff
.Orientation
) {
313 rotation
= ( 360 - ( function () {
314 // See includes/media/Bitmap.php
315 switch ( meta
.tiff
.Orientation
.value
) {
328 img
.onload = function () {
329 var info
, width
, height
, x
, y
, dx
, dy
, logicalWidth
, logicalHeight
;
331 // Fit the image within the previewSizexpreviewSize box
332 if ( img
.width
> img
.height
) {
334 height
= img
.height
/ img
.width
* previewSize
;
336 height
= previewSize
;
337 width
= img
.width
/ img
.height
* previewSize
;
339 // Determine the offset required to center the image
340 dx
= ( 180 - width
) / 2;
341 dy
= ( 180 - height
) / 2;
342 switch ( rotation
) {
343 // If a rotation is applied, the direction of the axis
344 // changes as well. You can derive the values below by
345 // drawing on paper an axis system, rotate it and see
346 // where the positive axis direction is
350 logicalWidth
= img
.width
;
351 logicalHeight
= img
.height
;
356 y
= dy
- previewSize
;
357 logicalWidth
= img
.height
;
358 logicalHeight
= img
.width
;
361 x
= dx
- previewSize
;
362 y
= dy
- previewSize
;
363 logicalWidth
= img
.width
;
364 logicalHeight
= img
.height
;
367 x
= dx
- previewSize
;
369 logicalWidth
= img
.height
;
370 logicalHeight
= img
.width
;
374 ctx
.clearRect( 0, 0, 180, 180 );
375 ctx
.rotate( rotation
/ 180 * Math
.PI
);
376 ctx
.drawImage( img
, x
, y
, width
, height
);
377 thumb
.find( '.mw-small-spinner' ).replaceWith( $canvas
);
380 info
= mw
.msg( 'widthheight', logicalWidth
, logicalHeight
) +
381 ', ' + prettySize( file
.size
);
383 $( '#mw-upload-thumbnail .fileinfo' ).text( info
);
386 }, mw
.config
.get( 'wgFileCanRotate' ) ? function ( data
) {
388 meta
= mw
.libs
.jpegmeta( data
, file
.fileName
);
389 // jscs:disable requireCamelCaseOrUpperCaseIdentifiers, disallowDanglingUnderscores
390 meta
._binary_data
= null;
399 * Start loading a file into memory; when complete, pass it as a
400 * data URL to the callback function. If the callbackBinary is set it will
401 * first be read as binary and afterwards as data URL. Useful if you want
402 * to do preprocessing on the binary data first.
405 * @param {Function} callback
406 * @param {Function} callbackBinary
408 function fetchPreview( file
, callback
, callbackBinary
) {
409 var reader
= new FileReader();
410 if ( callbackBinary
&& 'readAsBinaryString' in reader
) {
411 // To fetch JPEG metadata we need a binary string; start there.
413 reader
.onload = function () {
414 callbackBinary( reader
.result
);
416 // Now run back through the regular code path.
417 fetchPreview( file
, callback
);
419 reader
.readAsBinaryString( file
);
420 } else if ( callbackBinary
&& 'readAsArrayBuffer' in reader
) {
421 // readAsArrayBuffer replaces readAsBinaryString
422 // However, our JPEG metadata library wants a string.
423 // So, this is going to be an ugly conversion.
424 reader
.onload = function () {
426 buffer
= new Uint8Array( reader
.result
),
428 for ( i
= 0; i
< buffer
.byteLength
; i
++ ) {
429 string
+= String
.fromCharCode( buffer
[i
] );
431 callbackBinary( string
);
433 // Now run back through the regular code path.
434 fetchPreview( file
, callback
);
436 reader
.readAsArrayBuffer( file
);
437 } else if ( 'URL' in window
&& 'createObjectURL' in window
.URL
) {
438 // Supported in Firefox 4.0 and above <https://developer.mozilla.org/en/DOM/window.URL.createObjectURL>
439 // WebKit has it in a namespace for now but that's ok. ;)
441 // Lifetime of this URL is until document close, which is fine
442 // for Special:Upload -- if this code gets used on longer-running
443 // pages, add a revokeObjectURL() when it's no longer needed.
445 // Prefer this over readAsDataURL for Firefox 7 due to bug reading
446 // some SVG files from data URIs <https://bugzilla.mozilla.org/show_bug.cgi?id=694165>
447 callback( window
.URL
.createObjectURL( file
) );
449 // This ends up decoding the file to base-64 and back again, which
450 // feels horribly inefficient.
451 reader
.onload = function () {
452 callback( reader
.result
);
454 reader
.readAsDataURL( file
);
459 * Format a file size attractively.
461 * TODO: Match numeric formatting
466 function prettySize( s
) {
467 var sizeMsgs
= ['size-bytes', 'size-kilobytes', 'size-megabytes', 'size-gigabytes'];
468 while ( s
>= 1024 && sizeMsgs
.length
> 1 ) {
470 sizeMsgs
= sizeMsgs
.slice( 1 );
472 return mw
.msg( sizeMsgs
[0], Math
.round( s
) );
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 ) {
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
536 $rows
= $( '.mw-htmlform-field-UploadSourceField' );
539 * @param {jQuery} $currentRow
540 * @return {Function} Handler
541 * @return {jQuery.Event} return.e
543 function createHandler( $currentRow
) {
545 $( '.mw-upload-source-error' ).remove();
546 if ( this.checked
) {
547 // Disable all inputs
548 $rows
.find( 'input[name!="wpSourceType"]' ).prop( 'disabled', true );
549 // Re-enable the current one
550 $currentRow
.find( 'input' ).prop( 'disabled', false );
555 for ( i
= $rows
.length
; i
; i
-- ) {
556 $row
= $rows
.eq( i
- 1 );
558 .find( 'input[name="wpSourceType"]' )
559 .change( createHandler( $row
) );
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 () {
589 }( mediaWiki
, jQuery
) );