Merge "mw.ForeignApi: Percent-encode dots in the 'origin' parameter"
[lhc/web/wiklou.git] / resources / src / mediawiki.special / mediawiki.special.upload.js
1 /**
2 * JavaScript for Special:Upload
3 *
4 * @private
5 * @class mw.special.upload
6 * @singleton
7 */
8 ( function ( mw, $ ) {
9 /*jshint latedef:false */
10 var uploadWarning, uploadLicense,
11 ajaxUploadDestCheck = mw.config.get( 'wgAjaxUploadDestCheck' ),
12 $license = $( '#wpLicense' );
13
14 window.wgUploadWarningObj = uploadWarning = {
15 responseCache: { '': ' ' },
16 nameToCheck: '',
17 typing: false,
18 delay: 500, // ms
19 timeoutID: false,
20
21 keypress: function () {
22 if ( !ajaxUploadDestCheck ) {
23 return;
24 }
25
26 // Find file to upload
27 if ( !$( '#wpDestFile' ).length || !$( '#wpDestFile-warning' ).length ) {
28 return;
29 }
30
31 this.nameToCheck = $( '#wpDestFile' ).val();
32
33 // Clear timer
34 if ( this.timeoutID ) {
35 clearTimeout( this.timeoutID );
36 }
37 // Check response cache
38 if ( this.responseCache.hasOwnProperty( this.nameToCheck ) ) {
39 this.setWarning( this.responseCache[ this.nameToCheck ] );
40 return;
41 }
42
43 this.timeoutID = setTimeout( function () {
44 uploadWarning.timeout();
45 }, this.delay );
46 },
47
48 checkNow: function ( fname ) {
49 if ( !ajaxUploadDestCheck ) {
50 return;
51 }
52 if ( this.timeoutID ) {
53 clearTimeout( this.timeoutID );
54 }
55 this.nameToCheck = fname;
56 this.timeout();
57 },
58
59 timeout: function () {
60 var $spinnerDestCheck, title;
61 if ( !ajaxUploadDestCheck || this.nameToCheck === '' ) {
62 return;
63 }
64 $spinnerDestCheck = $.createSpinner().insertAfter( '#wpDestFile' );
65 title = mw.Title.newFromText( this.nameToCheck, mw.config.get( 'wgNamespaceIds' ).file );
66
67 ( new mw.Api() ).get( {
68 formatversion: 2,
69 action: 'query',
70 // If title is empty, user input is invalid, the API call will produce details about why
71 titles: title ? title.getPrefixedText() : this.nameToCheck,
72 prop: 'imageinfo',
73 iiprop: 'uploadwarning'
74 } ).done( function ( result ) {
75 var
76 resultOut = '',
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 );
82 }
83 uploadWarning.processResult( resultOut, uploadWarning.nameToCheck );
84 } ).always( function () {
85 $spinnerDestCheck.remove();
86 } );
87 },
88
89 processResult: function ( result, fileName ) {
90 this.setWarning( result );
91 this.responseCache[ fileName ] = result;
92 },
93
94 setWarning: function ( warning ) {
95 var $warning = $( $.parseHTML( warning ) );
96 mw.hook( 'wikipage.content' ).fire( $warning );
97 $( '#wpDestFile-warning' ).empty().append( $warning );
98
99 // Set a value in the form indicating that the warning is acknowledged and
100 // doesn't need to be redisplayed post-upload
101 if ( !warning ) {
102 $( '#wpDestFileWarningAck' ).val( '' );
103 } else {
104 $( '#wpDestFileWarningAck' ).val( '1' );
105 }
106
107 }
108 };
109
110 uploadLicense = {
111
112 responseCache: { '': '' },
113
114 fetchPreview: function ( license ) {
115 var $spinnerLicense;
116 if ( !mw.config.get( 'wgAjaxLicensePreview' ) ) {
117 return;
118 }
119 if ( this.responseCache.hasOwnProperty( license ) ) {
120 this.showPreview( this.responseCache[ license ] );
121 return;
122 }
123
124 $spinnerLicense = $.createSpinner().insertAfter( '#wpLicense' );
125
126 ( new mw.Api() ).get( {
127 formatversion: 2,
128 action: 'parse',
129 text: '{{' + license + '}}',
130 title: $( '#wpDestFile' ).val() || 'File:Sample.jpg',
131 prop: 'text',
132 pst: true
133 } ).done( function ( result ) {
134 uploadLicense.processResult( result, license );
135 } ).always( function () {
136 $spinnerLicense.remove();
137 } );
138 },
139
140 processResult: function ( result, license ) {
141 this.responseCache[ license ] = result.parse.text;
142 this.showPreview( this.responseCache[ license ] );
143 },
144
145 showPreview: function ( preview ) {
146 $( '#mw-license-preview' ).html( preview );
147 }
148
149 };
150
151 $( function () {
152 // AJAX wpDestFile warnings
153 if ( ajaxUploadDestCheck ) {
154 // Insert an event handler that fetches upload warnings when wpDestFile
155 // has been changed
156 $( '#wpDestFile' ).change( function () {
157 uploadWarning.checkNow( $( this ).val() );
158 } );
159 // Insert a row where the warnings will be displayed just below the
160 // wpDestFile row
161 $( '#mw-htmlform-description tbody' ).append(
162 $( '<tr>' ).append(
163 $( '<td>' )
164 .attr( 'id', 'wpDestFile-warning' )
165 .attr( 'colspan', 2 )
166 )
167 );
168 }
169
170 if ( mw.config.get( 'wgAjaxLicensePreview' ) && $license.length ) {
171 // License selector check
172 $license.change( function () {
173 // We might show a preview
174 uploadLicense.fetchPreview( $license.val() );
175 } );
176
177 // License selector table row
178 $license.closest( 'tr' ).after(
179 $( '<tr>' ).append(
180 $( '<td>' ),
181 $( '<td>' ).attr( 'id', 'mw-license-preview' )
182 )
183 );
184 }
185
186 // fillDestFile setup
187 $.each( mw.config.get( 'wgUploadSourceIds' ), function ( index, sourceId ) {
188 $( '#' + sourceId ).change( function () {
189 var path, slash, backslash, fname;
190 if ( !mw.config.get( 'wgUploadAutoFill' ) ) {
191 return;
192 }
193 // Remove any previously flagged errors
194 $( '#mw-upload-permitted' ).attr( 'class', '' );
195 $( '#mw-upload-prohibited' ).attr( 'class', '' );
196
197 path = $( this ).val();
198 // Find trailing part
199 slash = path.lastIndexOf( '/' );
200 backslash = path.lastIndexOf( '\\' );
201 if ( slash === -1 && backslash === -1 ) {
202 fname = path;
203 } else if ( slash > backslash ) {
204 fname = path.slice( slash + 1 );
205 } else {
206 fname = path.slice( backslash + 1 );
207 }
208
209 // Clear the filename if it does not have a valid extension.
210 // URLs are less likely to have a useful extension, so don't include them in the
211 // extension check.
212 if (
213 mw.config.get( 'wgCheckFileExtensions' ) &&
214 mw.config.get( 'wgStrictFileExtensions' ) &&
215 mw.config.get( 'wgFileExtensions' ) &&
216 $( this ).attr( 'id' ) !== 'wpUploadFileURL'
217 ) {
218 if (
219 fname.lastIndexOf( '.' ) === -1 ||
220 $.inArray(
221 fname.slice( fname.lastIndexOf( '.' ) + 1 ).toLowerCase(),
222 $.map( mw.config.get( 'wgFileExtensions' ), function ( element ) {
223 return element.toLowerCase();
224 } )
225 ) === -1
226 ) {
227 // Not a valid extension
228 // Clear the upload and set mw-upload-permitted to error
229 $( this ).val( '' );
230 $( '#mw-upload-permitted' ).attr( 'class', 'error' );
231 $( '#mw-upload-prohibited' ).attr( 'class', 'error' );
232 // Clear wpDestFile as well
233 $( '#wpDestFile' ).val( '' );
234
235 return false;
236 }
237 }
238
239 // Replace spaces by underscores
240 fname = fname.replace( / /g, '_' );
241 // Capitalise first letter if needed
242 if ( mw.config.get( 'wgCapitalizeUploads' ) ) {
243 fname = fname[ 0 ].toUpperCase() + fname.slice( 1 );
244 }
245
246 // Output result
247 if ( $( '#wpDestFile' ).length ) {
248 // Call decodeURIComponent function to remove possible URL-encoded characters
249 // from the file name (bug 30390). Especially likely with upload-form-url.
250 // decodeURIComponent can throw an exception if input is invalid utf-8
251 try {
252 $( '#wpDestFile' ).val( decodeURIComponent( fname ) );
253 } catch ( err ) {
254 $( '#wpDestFile' ).val( fname );
255 }
256 uploadWarning.checkNow( fname );
257 }
258 } );
259 } );
260 } );
261
262 // Add a preview to the upload form
263 $( function () {
264 /**
265 * Is the FileAPI available with sufficient functionality?
266 */
267 function hasFileAPI() {
268 return window.FileReader !== undefined;
269 }
270
271 /**
272 * Check if this is a recognizable image type...
273 * Also excludes files over 10M to avoid going insane on memory usage.
274 *
275 * TODO: Is there a way we can ask the browser what's supported in `<img>`s?
276 *
277 * TODO: Put SVG back after working around Firefox 7 bug <https://phabricator.wikimedia.org/T33643>
278 *
279 * @param {File} file
280 * @return {boolean}
281 */
282 function fileIsPreviewable( file ) {
283 var known = [ 'image/png', 'image/gif', 'image/jpeg', 'image/svg+xml' ],
284 tooHuge = 10 * 1024 * 1024;
285 return ( $.inArray( file.type, known ) !== -1 ) && file.size > 0 && file.size < tooHuge;
286 }
287
288 /**
289 * Format a file size attractively.
290 *
291 * TODO: Match numeric formatting
292 *
293 * @param {number} s
294 * @return {string}
295 */
296 function prettySize( s ) {
297 var sizeMsgs = [ 'size-bytes', 'size-kilobytes', 'size-megabytes', 'size-gigabytes' ];
298 while ( s >= 1024 && sizeMsgs.length > 1 ) {
299 s /= 1024;
300 sizeMsgs = sizeMsgs.slice( 1 );
301 }
302 return mw.msg( sizeMsgs[ 0 ], Math.round( s ) );
303 }
304
305 /**
306 * Show a thumbnail preview of PNG, JPEG, GIF, and SVG files prior to upload
307 * in browsers supporting HTML5 FileAPI.
308 *
309 * As of this writing, known good:
310 *
311 * - Firefox 3.6+
312 * - Chrome 7.something
313 *
314 * TODO: Check file size limits and warn of likely failures
315 *
316 * @param {File} file
317 */
318 function showPreview( file ) {
319 var $canvas,
320 ctx,
321 meta,
322 previewSize = 180,
323 $spinner = $.createSpinner( { size: 'small', type: 'block' } )
324 .css( { width: previewSize, height: previewSize } ),
325 thumb = mw.template.get( 'mediawiki.special.upload', 'thumbnail.html' ).render();
326
327 thumb
328 .find( '.filename' ).text( file.name ).end()
329 .find( '.fileinfo' ).text( prettySize( file.size ) ).end()
330 .find( '.thumbinner' ).prepend( $spinner ).end();
331
332 $canvas = $( '<canvas>' ).attr( { width: previewSize, height: previewSize } );
333 ctx = $canvas[ 0 ].getContext( '2d' );
334 $( '#mw-htmlform-source' ).parent().prepend( thumb );
335
336 fetchPreview( file, function ( dataURL ) {
337 var img = new Image(),
338 rotation = 0;
339
340 if ( meta && meta.tiff && meta.tiff.Orientation ) {
341 rotation = ( 360 - ( function () {
342 // See includes/media/Bitmap.php
343 switch ( meta.tiff.Orientation.value ) {
344 case 8:
345 return 90;
346 case 3:
347 return 180;
348 case 6:
349 return 270;
350 default:
351 return 0;
352 }
353 }() ) ) % 360;
354 }
355
356 img.onload = function () {
357 var info, width, height, x, y, dx, dy, logicalWidth, logicalHeight;
358
359 // Fit the image within the previewSizexpreviewSize box
360 if ( img.width > img.height ) {
361 width = previewSize;
362 height = img.height / img.width * previewSize;
363 } else {
364 height = previewSize;
365 width = img.width / img.height * previewSize;
366 }
367 // Determine the offset required to center the image
368 dx = ( 180 - width ) / 2;
369 dy = ( 180 - height ) / 2;
370 switch ( rotation ) {
371 // If a rotation is applied, the direction of the axis
372 // changes as well. You can derive the values below by
373 // drawing on paper an axis system, rotate it and see
374 // where the positive axis direction is
375 case 0:
376 x = dx;
377 y = dy;
378 logicalWidth = img.width;
379 logicalHeight = img.height;
380 break;
381 case 90:
382
383 x = dx;
384 y = dy - previewSize;
385 logicalWidth = img.height;
386 logicalHeight = img.width;
387 break;
388 case 180:
389 x = dx - previewSize;
390 y = dy - previewSize;
391 logicalWidth = img.width;
392 logicalHeight = img.height;
393 break;
394 case 270:
395 x = dx - previewSize;
396 y = dy;
397 logicalWidth = img.height;
398 logicalHeight = img.width;
399 break;
400 }
401
402 ctx.clearRect( 0, 0, 180, 180 );
403 ctx.rotate( rotation / 180 * Math.PI );
404 ctx.drawImage( img, x, y, width, height );
405 $spinner.replaceWith( $canvas );
406
407 // Image size
408 info = mw.msg( 'widthheight', logicalWidth, logicalHeight ) +
409 ', ' + prettySize( file.size );
410
411 $( '#mw-upload-thumbnail .fileinfo' ).text( info );
412 };
413 img.onerror = function () {
414 // Can happen for example for invalid SVG files
415 clearPreview();
416 };
417 img.src = dataURL;
418 }, mw.config.get( 'wgFileCanRotate' ) ? function ( data ) {
419 try {
420 meta = mw.libs.jpegmeta( data, file.fileName );
421 // jscs:disable requireCamelCaseOrUpperCaseIdentifiers, disallowDanglingUnderscores
422 meta._binary_data = null;
423 // jscs:enable
424 } catch ( e ) {
425 meta = null;
426 }
427 } : null );
428 }
429
430 /**
431 * Start loading a file into memory; when complete, pass it as a
432 * data URL to the callback function. If the callbackBinary is set it will
433 * first be read as binary and afterwards as data URL. Useful if you want
434 * to do preprocessing on the binary data first.
435 *
436 * @param {File} file
437 * @param {Function} callback
438 * @param {Function} callbackBinary
439 */
440 function fetchPreview( file, callback, callbackBinary ) {
441 var reader = new FileReader();
442 if ( callbackBinary && 'readAsBinaryString' in reader ) {
443 // To fetch JPEG metadata we need a binary string; start there.
444 // TODO
445 reader.onload = function () {
446 callbackBinary( reader.result );
447
448 // Now run back through the regular code path.
449 fetchPreview( file, callback );
450 };
451 reader.readAsBinaryString( file );
452 } else if ( callbackBinary && 'readAsArrayBuffer' in reader ) {
453 // readAsArrayBuffer replaces readAsBinaryString
454 // However, our JPEG metadata library wants a string.
455 // So, this is going to be an ugly conversion.
456 reader.onload = function () {
457 var i,
458 buffer = new Uint8Array( reader.result ),
459 string = '';
460 for ( i = 0; i < buffer.byteLength; i++ ) {
461 string += String.fromCharCode( buffer[ i ] );
462 }
463 callbackBinary( string );
464
465 // Now run back through the regular code path.
466 fetchPreview( file, callback );
467 };
468 reader.readAsArrayBuffer( file );
469 } else if ( 'URL' in window && 'createObjectURL' in window.URL ) {
470 // Supported in Firefox 4.0 and above <https://developer.mozilla.org/en/DOM/window.URL.createObjectURL>
471 // WebKit has it in a namespace for now but that's ok. ;)
472 //
473 // Lifetime of this URL is until document close, which is fine
474 // for Special:Upload -- if this code gets used on longer-running
475 // pages, add a revokeObjectURL() when it's no longer needed.
476 //
477 // Prefer this over readAsDataURL for Firefox 7 due to bug reading
478 // some SVG files from data URIs <https://bugzilla.mozilla.org/show_bug.cgi?id=694165>
479 callback( window.URL.createObjectURL( file ) );
480 } else {
481 // This ends up decoding the file to base-64 and back again, which
482 // feels horribly inefficient.
483 reader.onload = function () {
484 callback( reader.result );
485 };
486 reader.readAsDataURL( file );
487 }
488 }
489
490 /**
491 * Clear the file upload preview area.
492 */
493 function clearPreview() {
494 $( '#mw-upload-thumbnail' ).remove();
495 }
496
497 /**
498 * Check if the file does not exceed the maximum size
499 */
500 function checkMaxUploadSize( file ) {
501 var maxSize, $error;
502
503 function getMaxUploadSize( type ) {
504 var sizes = mw.config.get( 'wgMaxUploadSize' );
505
506 if ( sizes[ type ] !== undefined ) {
507 return sizes[ type ];
508 }
509 return sizes[ '*' ];
510 }
511
512 $( '.mw-upload-source-error' ).remove();
513
514 maxSize = getMaxUploadSize( 'file' );
515 if ( file.size > maxSize ) {
516 $error = $( '<p class="error mw-upload-source-error" id="wpSourceTypeFile-error">' +
517 mw.message( 'largefileserver', file.size, maxSize ).escaped() + '</p>' );
518
519 $( '#wpUploadFile' ).after( $error );
520
521 return false;
522 }
523
524 return true;
525 }
526
527 /* Initialization */
528 if ( hasFileAPI() ) {
529 // Update thumbnail when the file selection control is updated.
530 $( '#wpUploadFile' ).change( function () {
531 clearPreview();
532 if ( this.files && this.files.length ) {
533 // Note: would need to be updated to handle multiple files.
534 var file = this.files[ 0 ];
535
536 if ( !checkMaxUploadSize( file ) ) {
537 return;
538 }
539
540 if ( fileIsPreviewable( file ) ) {
541 showPreview( file );
542 }
543 }
544 } );
545 }
546 } );
547
548 // Disable all upload source fields except the selected one
549 $( function () {
550 var $rows = $( '.mw-htmlform-field-UploadSourceField' );
551
552 $rows.on( 'change', 'input[type="radio"]', function ( e ) {
553 var currentRow = e.delegateTarget;
554
555 if ( !this.checked ) {
556 return;
557 }
558
559 $( '.mw-upload-source-error' ).remove();
560
561 // Enable selected upload method
562 $( currentRow ).find( 'input' ).prop( 'disabled', false );
563
564 // Disable inputs of other upload methods
565 // (except for the radio button to re-enable it)
566 $rows
567 .not( currentRow )
568 .find( 'input[type!="radio"]' )
569 .prop( 'disabled', true );
570 } );
571
572 // Set initial state
573 if ( !$( '#wpSourceTypeurl' ).prop( 'checked' ) ) {
574 $( '#wpUploadFileURL' ).prop( 'disabled', true );
575 }
576 } );
577
578 $( function () {
579 // Prevent losing work
580 var allowCloseWindow,
581 $uploadForm = $( '#mw-upload-form' );
582
583 if ( !mw.user.options.get( 'useeditwarning' ) ) {
584 // If the user doesn't want edit warnings, don't set things up.
585 return;
586 }
587
588 $uploadForm.data( 'origtext', $uploadForm.serialize() );
589
590 allowCloseWindow = mw.confirmCloseWindow( {
591 test: function () {
592 return $( '#wpUploadFile' ).get( 0 ).files.length !== 0 ||
593 $uploadForm.data( 'origtext' ) !== $uploadForm.serialize();
594 },
595
596 message: mw.msg( 'editwarning-warning' ),
597 namespace: 'uploadwarning'
598 } );
599
600 $uploadForm.submit( function () {
601 allowCloseWindow.release();
602 } );
603 } );
604 }( mediaWiki, jQuery ) );