Merge "SpecialMovepage: Convert form to use OOUI controls"
[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;
61 if ( !ajaxUploadDestCheck || this.nameToCheck === '' ) {
62 return;
63 }
64 $spinnerDestCheck = $.createSpinner().insertAfter( '#wpDestFile' );
65
66 ( new mw.Api() ).get( {
67 action: 'query',
68 titles: ( new mw.Title( this.nameToCheck, mw.config.get( 'wgNamespaceIds' ).file ) ).getPrefixedText(),
69 prop: 'imageinfo',
70 iiprop: 'uploadwarning',
71 indexpageids: ''
72 } ).done( function ( result ) {
73 var resultOut = '';
74 if ( result.query ) {
75 resultOut = result.query.pages[ result.query.pageids[ 0 ] ].imageinfo[ 0 ];
76 }
77 $spinnerDestCheck.remove();
78 uploadWarning.processResult( resultOut, uploadWarning.nameToCheck );
79 } );
80 },
81
82 processResult: function ( result, fileName ) {
83 this.setWarning( result.html );
84 this.responseCache[ fileName ] = result.html;
85 },
86
87 setWarning: function ( warning ) {
88 $( '#wpDestFile-warning' ).html( warning );
89
90 // Set a value in the form indicating that the warning is acknowledged and
91 // doesn't need to be redisplayed post-upload
92 if ( !warning ) {
93 $( '#wpDestFileWarningAck' ).val( '' );
94 } else {
95 $( '#wpDestFileWarningAck' ).val( '1' );
96 }
97
98 }
99 };
100
101 uploadLicense = {
102
103 responseCache: { '': '' },
104
105 fetchPreview: function ( license ) {
106 var $spinnerLicense;
107 if ( !mw.config.get( 'wgAjaxLicensePreview' ) ) {
108 return;
109 }
110 if ( this.responseCache.hasOwnProperty( license ) ) {
111 this.showPreview( this.responseCache[ license ] );
112 return;
113 }
114
115 $spinnerLicense = $.createSpinner().insertAfter( '#wpLicense' );
116
117 ( new mw.Api() ).get( {
118 action: 'parse',
119 text: '{{' + license + '}}',
120 title: $( '#wpDestFile' ).val() || 'File:Sample.jpg',
121 prop: 'text',
122 pst: ''
123 } ).done( function ( result ) {
124 $spinnerLicense.remove();
125 uploadLicense.processResult( result, license );
126 } );
127 },
128
129 processResult: function ( result, license ) {
130 this.responseCache[ license ] = result.parse.text[ '*' ];
131 this.showPreview( this.responseCache[ license ] );
132 },
133
134 showPreview: function ( preview ) {
135 $( '#mw-license-preview' ).html( preview );
136 }
137
138 };
139
140 $( function () {
141 // AJAX wpDestFile warnings
142 if ( ajaxUploadDestCheck ) {
143 // Insert an event handler that fetches upload warnings when wpDestFile
144 // has been changed
145 $( '#wpDestFile' ).change( function () {
146 uploadWarning.checkNow( $( this ).val() );
147 } );
148 // Insert a row where the warnings will be displayed just below the
149 // wpDestFile row
150 $( '#mw-htmlform-description tbody' ).append(
151 $( '<tr>' ).append(
152 $( '<td>' )
153 .attr( 'id', 'wpDestFile-warning' )
154 .attr( 'colspan', 2 )
155 )
156 );
157 }
158
159 if ( mw.config.get( 'wgAjaxLicensePreview' ) && $license.length ) {
160 // License selector check
161 $license.change( function () {
162 // We might show a preview
163 uploadLicense.fetchPreview( $license.val() );
164 } );
165
166 // License selector table row
167 $license.closest( 'tr' ).after(
168 $( '<tr>' ).append(
169 $( '<td>' ),
170 $( '<td>' ).attr( 'id', 'mw-license-preview' )
171 )
172 );
173 }
174
175 // fillDestFile setup
176 $.each( mw.config.get( 'wgUploadSourceIds' ), function ( index, sourceId ) {
177 $( '#' + sourceId ).change( function () {
178 var path, slash, backslash, fname;
179 if ( !mw.config.get( 'wgUploadAutoFill' ) ) {
180 return;
181 }
182 // Remove any previously flagged errors
183 $( '#mw-upload-permitted' ).attr( 'class', '' );
184 $( '#mw-upload-prohibited' ).attr( 'class', '' );
185
186 path = $( this ).val();
187 // Find trailing part
188 slash = path.lastIndexOf( '/' );
189 backslash = path.lastIndexOf( '\\' );
190 if ( slash === -1 && backslash === -1 ) {
191 fname = path;
192 } else if ( slash > backslash ) {
193 fname = path.slice( slash + 1 );
194 } else {
195 fname = path.slice( backslash + 1 );
196 }
197
198 // Clear the filename if it does not have a valid extension.
199 // URLs are less likely to have a useful extension, so don't include them in the
200 // extension check.
201 if (
202 mw.config.get( 'wgCheckFileExtensions' ) &&
203 mw.config.get( 'wgStrictFileExtensions' ) &&
204 mw.config.get( 'wgFileExtensions' ) &&
205 $( this ).attr( 'id' ) !== 'wpUploadFileURL'
206 ) {
207 if (
208 fname.lastIndexOf( '.' ) === -1 ||
209 $.inArray(
210 fname.slice( fname.lastIndexOf( '.' ) + 1 ).toLowerCase(),
211 $.map( mw.config.get( 'wgFileExtensions' ), function ( element ) {
212 return element.toLowerCase();
213 } )
214 ) === -1
215 ) {
216 // Not a valid extension
217 // Clear the upload and set mw-upload-permitted to error
218 $( this ).val( '' );
219 $( '#mw-upload-permitted' ).attr( 'class', 'error' );
220 $( '#mw-upload-prohibited' ).attr( 'class', 'error' );
221 // Clear wpDestFile as well
222 $( '#wpDestFile' ).val( '' );
223
224 return false;
225 }
226 }
227
228 // Replace spaces by underscores
229 fname = fname.replace( / /g, '_' );
230 // Capitalise first letter if needed
231 if ( mw.config.get( 'wgCapitalizeUploads' ) ) {
232 fname = fname[ 0 ].toUpperCase() + fname.slice( 1 );
233 }
234
235 // Output result
236 if ( $( '#wpDestFile' ).length ) {
237 // Call decodeURIComponent function to remove possible URL-encoded characters
238 // from the file name (bug 30390). Especially likely with upload-form-url.
239 // decodeURIComponent can throw an exception if input is invalid utf-8
240 try {
241 $( '#wpDestFile' ).val( decodeURIComponent( fname ) );
242 } catch ( err ) {
243 $( '#wpDestFile' ).val( fname );
244 }
245 uploadWarning.checkNow( fname );
246 }
247 } );
248 } );
249 } );
250
251 // Add a preview to the upload form
252 $( function () {
253 /**
254 * Is the FileAPI available with sufficient functionality?
255 */
256 function hasFileAPI() {
257 return window.FileReader !== undefined;
258 }
259
260 /**
261 * Check if this is a recognizable image type...
262 * Also excludes files over 10M to avoid going insane on memory usage.
263 *
264 * TODO: Is there a way we can ask the browser what's supported in `<img>`s?
265 *
266 * TODO: Put SVG back after working around Firefox 7 bug <https://bugzilla.wikimedia.org/show_bug.cgi?id=31643>
267 *
268 * @param {File} file
269 * @return {boolean}
270 */
271 function fileIsPreviewable( file ) {
272 var known = [ 'image/png', 'image/gif', 'image/jpeg', 'image/svg+xml' ],
273 tooHuge = 10 * 1024 * 1024;
274 return ( $.inArray( file.type, known ) !== -1 ) && file.size > 0 && file.size < tooHuge;
275 }
276
277 /**
278 * Format a file size attractively.
279 *
280 * TODO: Match numeric formatting
281 *
282 * @param {number} s
283 * @return {string}
284 */
285 function prettySize( s ) {
286 var sizeMsgs = [ 'size-bytes', 'size-kilobytes', 'size-megabytes', 'size-gigabytes' ];
287 while ( s >= 1024 && sizeMsgs.length > 1 ) {
288 s /= 1024;
289 sizeMsgs = sizeMsgs.slice( 1 );
290 }
291 return mw.msg( sizeMsgs[ 0 ], Math.round( s ) );
292 }
293
294 /**
295 * Show a thumbnail preview of PNG, JPEG, GIF, and SVG files prior to upload
296 * in browsers supporting HTML5 FileAPI.
297 *
298 * As of this writing, known good:
299 *
300 * - Firefox 3.6+
301 * - Chrome 7.something
302 *
303 * TODO: Check file size limits and warn of likely failures
304 *
305 * @param {File} file
306 */
307 function showPreview( file ) {
308 var $canvas,
309 ctx,
310 meta,
311 previewSize = 180,
312 $spinner = $.createSpinner( { size: 'small', type: 'block' } )
313 .css( { width: previewSize, height: previewSize } ),
314 thumb = mw.template.get( 'mediawiki.special.upload', 'thumbnail.html' ).render();
315
316 thumb
317 .find( '.filename' ).text( file.name ).end()
318 .find( '.fileinfo' ).text( prettySize( file.size ) ).end()
319 .find( '.thumbinner' ).prepend( $spinner ).end();
320
321 $canvas = $( '<canvas>' ).attr( { width: previewSize, height: previewSize } );
322 ctx = $canvas[ 0 ].getContext( '2d' );
323 $( '#mw-htmlform-source' ).parent().prepend( thumb );
324
325 fetchPreview( file, function ( dataURL ) {
326 var img = new Image(),
327 rotation = 0;
328
329 if ( meta && meta.tiff && meta.tiff.Orientation ) {
330 rotation = ( 360 - ( function () {
331 // See includes/media/Bitmap.php
332 switch ( meta.tiff.Orientation.value ) {
333 case 8:
334 return 90;
335 case 3:
336 return 180;
337 case 6:
338 return 270;
339 default:
340 return 0;
341 }
342 }() ) ) % 360;
343 }
344
345 img.onload = function () {
346 var info, width, height, x, y, dx, dy, logicalWidth, logicalHeight;
347
348 // Fit the image within the previewSizexpreviewSize box
349 if ( img.width > img.height ) {
350 width = previewSize;
351 height = img.height / img.width * previewSize;
352 } else {
353 height = previewSize;
354 width = img.width / img.height * previewSize;
355 }
356 // Determine the offset required to center the image
357 dx = ( 180 - width ) / 2;
358 dy = ( 180 - height ) / 2;
359 switch ( rotation ) {
360 // If a rotation is applied, the direction of the axis
361 // changes as well. You can derive the values below by
362 // drawing on paper an axis system, rotate it and see
363 // where the positive axis direction is
364 case 0:
365 x = dx;
366 y = dy;
367 logicalWidth = img.width;
368 logicalHeight = img.height;
369 break;
370 case 90:
371
372 x = dx;
373 y = dy - previewSize;
374 logicalWidth = img.height;
375 logicalHeight = img.width;
376 break;
377 case 180:
378 x = dx - previewSize;
379 y = dy - previewSize;
380 logicalWidth = img.width;
381 logicalHeight = img.height;
382 break;
383 case 270:
384 x = dx - previewSize;
385 y = dy;
386 logicalWidth = img.height;
387 logicalHeight = img.width;
388 break;
389 }
390
391 ctx.clearRect( 0, 0, 180, 180 );
392 ctx.rotate( rotation / 180 * Math.PI );
393 ctx.drawImage( img, x, y, width, height );
394 $spinner.replaceWith( $canvas );
395
396 // Image size
397 info = mw.msg( 'widthheight', logicalWidth, logicalHeight ) +
398 ', ' + prettySize( file.size );
399
400 $( '#mw-upload-thumbnail .fileinfo' ).text( info );
401 };
402 img.src = dataURL;
403 }, mw.config.get( 'wgFileCanRotate' ) ? function ( data ) {
404 try {
405 meta = mw.libs.jpegmeta( data, file.fileName );
406 // jscs:disable requireCamelCaseOrUpperCaseIdentifiers, disallowDanglingUnderscores
407 meta._binary_data = null;
408 // jscs:enable
409 } catch ( e ) {
410 meta = null;
411 }
412 } : null );
413 }
414
415 /**
416 * Start loading a file into memory; when complete, pass it as a
417 * data URL to the callback function. If the callbackBinary is set it will
418 * first be read as binary and afterwards as data URL. Useful if you want
419 * to do preprocessing on the binary data first.
420 *
421 * @param {File} file
422 * @param {Function} callback
423 * @param {Function} callbackBinary
424 */
425 function fetchPreview( file, callback, callbackBinary ) {
426 var reader = new FileReader();
427 if ( callbackBinary && 'readAsBinaryString' in reader ) {
428 // To fetch JPEG metadata we need a binary string; start there.
429 // todo:
430 reader.onload = function () {
431 callbackBinary( reader.result );
432
433 // Now run back through the regular code path.
434 fetchPreview( file, callback );
435 };
436 reader.readAsBinaryString( file );
437 } else if ( callbackBinary && 'readAsArrayBuffer' in reader ) {
438 // readAsArrayBuffer replaces readAsBinaryString
439 // However, our JPEG metadata library wants a string.
440 // So, this is going to be an ugly conversion.
441 reader.onload = function () {
442 var i,
443 buffer = new Uint8Array( reader.result ),
444 string = '';
445 for ( i = 0; i < buffer.byteLength; i++ ) {
446 string += String.fromCharCode( buffer[ i ] );
447 }
448 callbackBinary( string );
449
450 // Now run back through the regular code path.
451 fetchPreview( file, callback );
452 };
453 reader.readAsArrayBuffer( file );
454 } else if ( 'URL' in window && 'createObjectURL' in window.URL ) {
455 // Supported in Firefox 4.0 and above <https://developer.mozilla.org/en/DOM/window.URL.createObjectURL>
456 // WebKit has it in a namespace for now but that's ok. ;)
457 //
458 // Lifetime of this URL is until document close, which is fine
459 // for Special:Upload -- if this code gets used on longer-running
460 // pages, add a revokeObjectURL() when it's no longer needed.
461 //
462 // Prefer this over readAsDataURL for Firefox 7 due to bug reading
463 // some SVG files from data URIs <https://bugzilla.mozilla.org/show_bug.cgi?id=694165>
464 callback( window.URL.createObjectURL( file ) );
465 } else {
466 // This ends up decoding the file to base-64 and back again, which
467 // feels horribly inefficient.
468 reader.onload = function () {
469 callback( reader.result );
470 };
471 reader.readAsDataURL( file );
472 }
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 $rows = $( '.mw-htmlform-field-UploadSourceField' );
536
537 $rows.on( 'change', 'input[type="radio"]', function ( e ) {
538 var currentRow = e.delegateTarget;
539
540 if ( !this.checked ) {
541 return;
542 }
543
544 $( '.mw-upload-source-error' ).remove();
545
546 // Enable selected upload method
547 $( currentRow ).find( 'input' ).prop( 'disabled', false );
548
549 // Disable inputs of other upload methods
550 // (except for the radio button to re-enable it)
551 $rows
552 .not( currentRow )
553 .find( 'input[type!="radio"]' )
554 .prop( 'disabled', true );
555 } );
556
557 // Set initial state
558 if ( !$( '#wpSourceTypeurl' ).prop( 'checked' ) ) {
559 $( '#wpUploadFileURL' ).prop( 'disabled', true );
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.release();
587 } );
588 } );
589 }( mediaWiki, jQuery ) );