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