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