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