Merge "Allow to set stub read buffer size for TextPassDumper"
[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 var uploadWarning, uploadLicense,
10 ajaxUploadDestCheck = mw.config.get( 'wgAjaxUploadDestCheck' ),
11 $license = $( '#wpLicense' );
12
13 window.wgUploadWarningObj = uploadWarning = {
14 responseCache: { '': ' ' },
15 nameToCheck: '',
16 typing: false,
17 delay: 500, // ms
18 timeoutID: false,
19
20 keypress: function () {
21 if ( !ajaxUploadDestCheck ) {
22 return;
23 }
24
25 // Find file to upload
26 if ( !$( '#wpDestFile' ).length || !$( '#wpDestFile-warning' ).length ) {
27 return;
28 }
29
30 this.nameToCheck = $( '#wpDestFile' ).val();
31
32 // Clear timer
33 if ( this.timeoutID ) {
34 clearTimeout( this.timeoutID );
35 }
36 // Check response cache
37 if ( this.responseCache.hasOwnProperty( this.nameToCheck ) ) {
38 this.setWarning( this.responseCache[this.nameToCheck] );
39 return;
40 }
41
42 this.timeoutID = setTimeout( function () {
43 uploadWarning.timeout();
44 }, this.delay );
45 },
46
47 checkNow: function ( fname ) {
48 if ( !ajaxUploadDestCheck ) {
49 return;
50 }
51 if ( this.timeoutID ) {
52 clearTimeout( this.timeoutID );
53 }
54 this.nameToCheck = fname;
55 this.timeout();
56 },
57
58 timeout: function () {
59 var $spinnerDestCheck;
60 if ( !ajaxUploadDestCheck || this.nameToCheck === '' ) {
61 return;
62 }
63 $spinnerDestCheck = $.createSpinner().insertAfter( '#wpDestFile' );
64
65 ( new mw.Api() ).get( {
66 action: 'query',
67 titles: ( new mw.Title( this.nameToCheck, mw.config.get( 'wgNamespaceIds' ).file ) ).getPrefixedText(),
68 prop: 'imageinfo',
69 iiprop: 'uploadwarning',
70 indexpageids: ''
71 } ).done( function ( result ) {
72 var resultOut = '';
73 if ( result.query ) {
74 resultOut = result.query.pages[result.query.pageids[0]].imageinfo[0];
75 }
76 $spinnerDestCheck.remove();
77 uploadWarning.processResult( resultOut, uploadWarning.nameToCheck );
78 } );
79 },
80
81 processResult: function ( result, fileName ) {
82 this.setWarning( result.html );
83 this.responseCache[fileName] = result.html;
84 },
85
86 setWarning: function ( warning ) {
87 $( '#wpDestFile-warning' ).html( warning );
88
89 // Set a value in the form indicating that the warning is acknowledged and
90 // doesn't need to be redisplayed post-upload
91 if ( !warning ) {
92 $( '#wpDestFileWarningAck' ).val( '' );
93 } else {
94 $( '#wpDestFileWarningAck' ).val( '1' );
95 }
96
97 }
98 };
99
100 uploadLicense = {
101
102 responseCache: { '': '' },
103
104 fetchPreview: function ( license ) {
105 var $spinnerLicense;
106 if ( !mw.config.get( 'wgAjaxLicensePreview' ) ) {
107 return;
108 }
109 if ( this.responseCache.hasOwnProperty( license ) ) {
110 this.showPreview( this.responseCache[license] );
111 return;
112 }
113
114 $spinnerLicense = $.createSpinner().insertAfter( '#wpLicense' );
115
116 ( new mw.Api() ).get( {
117 action: 'parse',
118 text: '{{' + license + '}}',
119 title: $( '#wpDestFile' ).val() || 'File:Sample.jpg',
120 prop: 'text',
121 pst: ''
122 } ).done( function ( result ) {
123 $spinnerLicense.remove();
124 uploadLicense.processResult( result, license );
125 } );
126 },
127
128 processResult: function ( result, license ) {
129 this.responseCache[license] = result.parse.text['*'];
130 this.showPreview( this.responseCache[license] );
131 },
132
133 showPreview: function ( preview ) {
134 $( '#mw-license-preview' ).html( preview );
135 }
136
137 };
138
139 $( function () {
140 // Disable URL box if the URL copy upload source type is not selected
141 if ( !$( '#wpSourceTypeurl' ).prop( 'checked' ) ) {
142 $( '#wpUploadFileURL' ).prop( 'disabled', true );
143 }
144
145 // AJAX wpDestFile warnings
146 if ( ajaxUploadDestCheck ) {
147 // Insert an event handler that fetches upload warnings when wpDestFile
148 // has been changed
149 $( '#wpDestFile' ).change( function () {
150 uploadWarning.checkNow( $( this ).val() );
151 } );
152 // Insert a row where the warnings will be displayed just below the
153 // wpDestFile row
154 $( '#mw-htmlform-description tbody' ).append(
155 $( '<tr>' ).append(
156 $( '<td>' )
157 .attr( 'id', 'wpDestFile-warning' )
158 .attr( 'colspan', 2 )
159 )
160 );
161 }
162
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() );
168 } );
169
170 // License selector table row
171 $license.closest( 'tr' ).after(
172 $( '<tr>' ).append(
173 $( '<td>' ),
174 $( '<td>' ).attr( 'id', 'mw-license-preview' )
175 )
176 );
177 }
178
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' ) ) {
184 return;
185 }
186 // Remove any previously flagged errors
187 $( '#mw-upload-permitted' ).attr( 'class', '' );
188 $( '#mw-upload-prohibited' ).attr( 'class', '' );
189
190 path = $( this ).val();
191 // Find trailing part
192 slash = path.lastIndexOf( '/' );
193 backslash = path.lastIndexOf( '\\' );
194 if ( slash === -1 && backslash === -1 ) {
195 fname = path;
196 } else if ( slash > backslash ) {
197 fname = path.slice( slash + 1 );
198 } else {
199 fname = path.slice( backslash + 1 );
200 }
201
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
204 // extension check.
205 if (
206 mw.config.get( 'wgCheckFileExtensions' ) &&
207 mw.config.get( 'wgStrictFileExtensions' ) &&
208 mw.config.get( 'wgFileExtensions' ) &&
209 $( this ).attr( 'id' ) !== 'wpUploadFileURL'
210 ) {
211 if (
212 fname.lastIndexOf( '.' ) === -1 ||
213 $.inArray(
214 fname.slice( fname.lastIndexOf( '.' ) + 1 ).toLowerCase(),
215 $.map( mw.config.get( 'wgFileExtensions' ), function ( element ) {
216 return element.toLowerCase();
217 } )
218 ) === -1
219 ) {
220 // Not a valid extension
221 // Clear the upload and set mw-upload-permitted to error
222 $( this ).val( '' );
223 $( '#mw-upload-permitted' ).attr( 'class', 'error' );
224 $( '#mw-upload-prohibited' ).attr( 'class', 'error' );
225 // Clear wpDestFile as well
226 $( '#wpDestFile' ).val( '' );
227
228 return false;
229 }
230 }
231
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 ) );
237 }
238
239 // Output result
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
244 try {
245 $( '#wpDestFile' ).val( decodeURIComponent( fname ) );
246 } catch ( err ) {
247 $( '#wpDestFile' ).val( fname );
248 }
249 uploadWarning.checkNow( fname );
250 }
251 } );
252 } );
253 } );
254
255 // Add a preview to the upload form
256 $( function () {
257 /**
258 * Is the FileAPI available with sufficient functionality?
259 */
260 function hasFileAPI() {
261 return window.FileReader !== undefined;
262 }
263
264 /**
265 * Check if this is a recognizable image type...
266 * Also excludes files over 10M to avoid going insane on memory usage.
267 *
268 * TODO: Is there a way we can ask the browser what's supported in `<img>`s?
269 *
270 * TODO: Put SVG back after working around Firefox 7 bug <https://bugzilla.wikimedia.org/show_bug.cgi?id=31643>
271 *
272 * @param {File} file
273 * @return boolean
274 */
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;
279 }
280
281 /**
282 * Show a thumbnail preview of PNG, JPEG, GIF, and SVG files prior to upload
283 * in browsers supporting HTML5 FileAPI.
284 *
285 * As of this writing, known good:
286 *
287 * - Firefox 3.6+
288 * - Chrome 7.something
289 *
290 * TODO: Check file size limits and warn of likely failures
291 *
292 * @param {File} file
293 */
294 function showPreview( file ) {
295 var $canvas,
296 ctx,
297 meta,
298 previewSize = 180,
299 thumb = mw.template.get( 'mediawiki.special.upload', 'thumbnail.html' ).render();
300
301 thumb.find( '.filename' ).text( file.name ).end()
302 .find( '.fileinfo' ).text( prettySize( file.size ) ).end();
303
304 $canvas = $( '<canvas width="' + previewSize + '" height="' + previewSize + '" ></canvas>' );
305 ctx = $canvas[0].getContext( '2d' );
306 $( '#mw-htmlform-source' ).parent().prepend( thumb );
307
308 fetchPreview( file, function ( dataURL ) {
309 var img = new Image(),
310 rotation = 0;
311
312 if ( meta && meta.tiff && meta.tiff.Orientation ) {
313 rotation = ( 360 - ( function () {
314 // See includes/media/Bitmap.php
315 switch ( meta.tiff.Orientation.value ) {
316 case 8:
317 return 90;
318 case 3:
319 return 180;
320 case 6:
321 return 270;
322 default:
323 return 0;
324 }
325 }() ) ) % 360;
326 }
327
328 img.onload = function () {
329 var info, width, height, x, y, dx, dy, logicalWidth, logicalHeight;
330
331 // Fit the image within the previewSizexpreviewSize box
332 if ( img.width > img.height ) {
333 width = previewSize;
334 height = img.height / img.width * previewSize;
335 } else {
336 height = previewSize;
337 width = img.width / img.height * previewSize;
338 }
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
347 case 0:
348 x = dx;
349 y = dy;
350 logicalWidth = img.width;
351 logicalHeight = img.height;
352 break;
353 case 90:
354
355 x = dx;
356 y = dy - previewSize;
357 logicalWidth = img.height;
358 logicalHeight = img.width;
359 break;
360 case 180:
361 x = dx - previewSize;
362 y = dy - previewSize;
363 logicalWidth = img.width;
364 logicalHeight = img.height;
365 break;
366 case 270:
367 x = dx - previewSize;
368 y = dy;
369 logicalWidth = img.height;
370 logicalHeight = img.width;
371 break;
372 }
373
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 );
378
379 // Image size
380 info = mw.msg( 'widthheight', logicalWidth, logicalHeight ) +
381 ', ' + prettySize( file.size );
382
383 $( '#mw-upload-thumbnail .fileinfo' ).text( info );
384 };
385 img.src = dataURL;
386 }, mw.config.get( 'wgFileCanRotate' ) ? function ( data ) {
387 try {
388 meta = mw.libs.jpegmeta( data, file.fileName );
389 // jscs:disable requireCamelCaseOrUpperCaseIdentifiers, disallowDanglingUnderscores
390 meta._binary_data = null;
391 // jscs:enable
392 } catch ( e ) {
393 meta = null;
394 }
395 } : null );
396 }
397
398 /**
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.
403 *
404 * @param {File} file
405 * @param {Function} callback
406 * @param {Function} callbackBinary
407 */
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.
412 // todo:
413 reader.onload = function () {
414 callbackBinary( reader.result );
415
416 // Now run back through the regular code path.
417 fetchPreview( file, callback );
418 };
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 () {
425 var i,
426 buffer = new Uint8Array( reader.result ),
427 string = '';
428 for ( i = 0; i < buffer.byteLength; i++ ) {
429 string += String.fromCharCode( buffer[i] );
430 }
431 callbackBinary( string );
432
433 // Now run back through the regular code path.
434 fetchPreview( file, callback );
435 };
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. ;)
440 //
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.
444 //
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 ) );
448 } else {
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 );
453 };
454 reader.readAsDataURL( file );
455 }
456 }
457
458 /**
459 * Format a file size attractively.
460 *
461 * TODO: Match numeric formatting
462 *
463 * @param {number} s
464 * @return {string}
465 */
466 function prettySize( s ) {
467 var sizeMsgs = ['size-bytes', 'size-kilobytes', 'size-megabytes', 'size-gigabytes'];
468 while ( s >= 1024 && sizeMsgs.length > 1 ) {
469 s /= 1024;
470 sizeMsgs = sizeMsgs.slice( 1 );
471 }
472 return mw.msg( sizeMsgs[0], Math.round( s ) );
473 }
474
475 /**
476 * Clear the file upload preview area.
477 */
478 function clearPreview() {
479 $( '#mw-upload-thumbnail' ).remove();
480 }
481
482 /**
483 * Check if the file does not exceed the maximum size
484 */
485 function checkMaxUploadSize( file ) {
486 var maxSize, $error;
487
488 function getMaxUploadSize( type ) {
489 var sizes = mw.config.get( 'wgMaxUploadSize' );
490
491 if ( sizes[type] !== undefined ) {
492 return sizes[type];
493 }
494 return sizes['*'];
495 }
496
497 $( '.mw-upload-source-error' ).remove();
498
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>' );
503
504 $( '#wpUploadFile' ).after( $error );
505
506 return false;
507 }
508
509 return true;
510 }
511
512 /* Initialization */
513 if ( hasFileAPI() ) {
514 // Update thumbnail when the file selection control is updated.
515 $( '#wpUploadFile' ).change( function () {
516 clearPreview();
517 if ( this.files && this.files.length ) {
518 // Note: would need to be updated to handle multiple files.
519 var file = this.files[0];
520
521 if ( !checkMaxUploadSize( file ) ) {
522 return;
523 }
524
525 if ( fileIsPreviewable( file ) ) {
526 showPreview( file );
527 }
528 }
529 } );
530 }
531 } );
532
533 // Disable all upload source fields except the selected one
534 $( function () {
535 var i, $row,
536 $rows = $( '.mw-htmlform-field-UploadSourceField' );
537
538 /**
539 * @param {jQuery} $currentRow
540 * @return {Function} Handler
541 * @return {jQuery.Event} return.e
542 */
543 function createHandler( $currentRow ) {
544 return function () {
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 );
551 }
552 };
553 }
554
555 for ( i = $rows.length; i; i-- ) {
556 $row = $rows.eq( i - 1 );
557 $row
558 .find( 'input[name="wpSourceType"]' )
559 .change( createHandler( $row ) );
560 }
561 } );
562
563 $( function () {
564 // Prevent losing work
565 var allowCloseWindow,
566 $uploadForm = $( '#mw-upload-form' );
567
568 if ( !mw.user.options.get( 'useeditwarning' ) ) {
569 // If the user doesn't want edit warnings, don't set things up.
570 return;
571 }
572
573 $uploadForm.data( 'origtext', $uploadForm.serialize() );
574
575 allowCloseWindow = mw.confirmCloseWindow( {
576 test: function () {
577 return $( '#wpUploadFile' ).get( 0 ).files.length !== 0 ||
578 $uploadForm.data( 'origtext' ) !== $uploadForm.serialize();
579 },
580
581 message: mw.msg( 'editwarning-warning' ),
582 namespace: 'uploadwarning'
583 } );
584
585 $uploadForm.submit( function () {
586 allowCloseWindow();
587 } );
588 } );
589 }( mediaWiki, jQuery ) );