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