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