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