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