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