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