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