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