Don't check namespace in SpecialWantedtemplates
[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.charAt( 0 ).toUpperCase().concat( 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 thumb = mw.template.get( 'mediawiki.special.upload', 'thumbnail.html' ).render();
295
296 thumb.find( '.filename' ).text( file.name ).end()
297 .find( '.fileinfo' ).text( prettySize( file.size ) ).end();
298
299 $canvas = $( '<canvas width="' + previewSize + '" height="' + previewSize + '" ></canvas>' );
300 ctx = $canvas[0].getContext( '2d' );
301 $( '#mw-htmlform-source' ).parent().prepend( thumb );
302
303 fetchPreview( file, function ( dataURL ) {
304 var img = new Image(),
305 rotation = 0;
306
307 if ( meta && meta.tiff && meta.tiff.Orientation ) {
308 rotation = ( 360 - ( function () {
309 // See includes/media/Bitmap.php
310 switch ( meta.tiff.Orientation.value ) {
311 case 8:
312 return 90;
313 case 3:
314 return 180;
315 case 6:
316 return 270;
317 default:
318 return 0;
319 }
320 }() ) ) % 360;
321 }
322
323 img.onload = function () {
324 var info, width, height, x, y, dx, dy, logicalWidth, logicalHeight;
325
326 // Fit the image within the previewSizexpreviewSize box
327 if ( img.width > img.height ) {
328 width = previewSize;
329 height = img.height / img.width * previewSize;
330 } else {
331 height = previewSize;
332 width = img.width / img.height * previewSize;
333 }
334 // Determine the offset required to center the image
335 dx = ( 180 - width ) / 2;
336 dy = ( 180 - height ) / 2;
337 switch ( rotation ) {
338 // If a rotation is applied, the direction of the axis
339 // changes as well. You can derive the values below by
340 // drawing on paper an axis system, rotate it and see
341 // where the positive axis direction is
342 case 0:
343 x = dx;
344 y = dy;
345 logicalWidth = img.width;
346 logicalHeight = img.height;
347 break;
348 case 90:
349
350 x = dx;
351 y = dy - previewSize;
352 logicalWidth = img.height;
353 logicalHeight = img.width;
354 break;
355 case 180:
356 x = dx - previewSize;
357 y = dy - previewSize;
358 logicalWidth = img.width;
359 logicalHeight = img.height;
360 break;
361 case 270:
362 x = dx - previewSize;
363 y = dy;
364 logicalWidth = img.height;
365 logicalHeight = img.width;
366 break;
367 }
368
369 ctx.clearRect( 0, 0, 180, 180 );
370 ctx.rotate( rotation / 180 * Math.PI );
371 ctx.drawImage( img, x, y, width, height );
372 thumb.find( '.mw-small-spinner' ).replaceWith( $canvas );
373
374 // Image size
375 info = mw.msg( 'widthheight', logicalWidth, logicalHeight ) +
376 ', ' + prettySize( file.size );
377
378 $( '#mw-upload-thumbnail .fileinfo' ).text( info );
379 };
380 img.src = dataURL;
381 }, mw.config.get( 'wgFileCanRotate' ) ? function ( data ) {
382 try {
383 meta = mw.libs.jpegmeta( data, file.fileName );
384 // jscs:disable requireCamelCaseOrUpperCaseIdentifiers, disallowDanglingUnderscores
385 meta._binary_data = null;
386 // jscs:enable
387 } catch ( e ) {
388 meta = null;
389 }
390 } : null );
391 }
392
393 /**
394 * Start loading a file into memory; when complete, pass it as a
395 * data URL to the callback function. If the callbackBinary is set it will
396 * first be read as binary and afterwards as data URL. Useful if you want
397 * to do preprocessing on the binary data first.
398 *
399 * @param {File} file
400 * @param {Function} callback
401 * @param {Function} callbackBinary
402 */
403 function fetchPreview( file, callback, callbackBinary ) {
404 var reader = new FileReader();
405 if ( callbackBinary && 'readAsBinaryString' in reader ) {
406 // To fetch JPEG metadata we need a binary string; start there.
407 // todo:
408 reader.onload = function () {
409 callbackBinary( reader.result );
410
411 // Now run back through the regular code path.
412 fetchPreview( file, callback );
413 };
414 reader.readAsBinaryString( file );
415 } else if ( callbackBinary && 'readAsArrayBuffer' in reader ) {
416 // readAsArrayBuffer replaces readAsBinaryString
417 // However, our JPEG metadata library wants a string.
418 // So, this is going to be an ugly conversion.
419 reader.onload = function () {
420 var i,
421 buffer = new Uint8Array( reader.result ),
422 string = '';
423 for ( i = 0; i < buffer.byteLength; i++ ) {
424 string += String.fromCharCode( buffer[i] );
425 }
426 callbackBinary( string );
427
428 // Now run back through the regular code path.
429 fetchPreview( file, callback );
430 };
431 reader.readAsArrayBuffer( file );
432 } else if ( 'URL' in window && 'createObjectURL' in window.URL ) {
433 // Supported in Firefox 4.0 and above <https://developer.mozilla.org/en/DOM/window.URL.createObjectURL>
434 // WebKit has it in a namespace for now but that's ok. ;)
435 //
436 // Lifetime of this URL is until document close, which is fine
437 // for Special:Upload -- if this code gets used on longer-running
438 // pages, add a revokeObjectURL() when it's no longer needed.
439 //
440 // Prefer this over readAsDataURL for Firefox 7 due to bug reading
441 // some SVG files from data URIs <https://bugzilla.mozilla.org/show_bug.cgi?id=694165>
442 callback( window.URL.createObjectURL( file ) );
443 } else {
444 // This ends up decoding the file to base-64 and back again, which
445 // feels horribly inefficient.
446 reader.onload = function () {
447 callback( reader.result );
448 };
449 reader.readAsDataURL( file );
450 }
451 }
452
453 /**
454 * Format a file size attractively.
455 *
456 * TODO: Match numeric formatting
457 *
458 * @param {number} s
459 * @return {string}
460 */
461 function prettySize( s ) {
462 var sizeMsgs = ['size-bytes', 'size-kilobytes', 'size-megabytes', 'size-gigabytes'];
463 while ( s >= 1024 && sizeMsgs.length > 1 ) {
464 s /= 1024;
465 sizeMsgs = sizeMsgs.slice( 1 );
466 }
467 return mw.msg( sizeMsgs[0], Math.round( s ) );
468 }
469
470 /**
471 * Clear the file upload preview area.
472 */
473 function clearPreview() {
474 $( '#mw-upload-thumbnail' ).remove();
475 }
476
477 /**
478 * Check if the file does not exceed the maximum size
479 */
480 function checkMaxUploadSize( file ) {
481 var maxSize, $error;
482
483 function getMaxUploadSize( type ) {
484 var sizes = mw.config.get( 'wgMaxUploadSize' );
485
486 if ( sizes[type] !== undefined ) {
487 return sizes[type];
488 }
489 return sizes['*'];
490 }
491
492 $( '.mw-upload-source-error' ).remove();
493
494 maxSize = getMaxUploadSize( 'file' );
495 if ( file.size > maxSize ) {
496 $error = $( '<p class="error mw-upload-source-error" id="wpSourceTypeFile-error">' +
497 mw.message( 'largefileserver', file.size, maxSize ).escaped() + '</p>' );
498
499 $( '#wpUploadFile' ).after( $error );
500
501 return false;
502 }
503
504 return true;
505 }
506
507 /* Initialization */
508 if ( hasFileAPI() ) {
509 // Update thumbnail when the file selection control is updated.
510 $( '#wpUploadFile' ).change( function () {
511 clearPreview();
512 if ( this.files && this.files.length ) {
513 // Note: would need to be updated to handle multiple files.
514 var file = this.files[0];
515
516 if ( !checkMaxUploadSize( file ) ) {
517 return;
518 }
519
520 if ( fileIsPreviewable( file ) ) {
521 showPreview( file );
522 }
523 }
524 } );
525 }
526 } );
527
528 // Disable all upload source fields except the selected one
529 $( function () {
530 var $rows = $( '.mw-htmlform-field-UploadSourceField' );
531
532 $rows.on( 'change', 'input[type="radio"]', function ( e ) {
533 var currentRow = e.delegateTarget;
534
535 if ( !this.checked ) {
536 return;
537 }
538
539 $( '.mw-upload-source-error' ).remove();
540
541 // Enable selected upload method
542 $( currentRow ).find( 'input' ).prop( 'disabled', false );
543
544 // Disable inputs of other upload methods
545 // (except for the radio button to re-enable it)
546 $rows
547 .not( currentRow )
548 .find( 'input[type!="radio"]' )
549 .prop( 'disabled', true );
550 } );
551
552 // Set initial state
553 if ( !$( '#wpSourceTypeurl' ).prop( 'checked' ) ) {
554 $( '#wpUploadFileURL' ).prop( 'disabled', true );
555 }
556 } );
557
558 $( function () {
559 // Prevent losing work
560 var allowCloseWindow,
561 $uploadForm = $( '#mw-upload-form' );
562
563 if ( !mw.user.options.get( 'useeditwarning' ) ) {
564 // If the user doesn't want edit warnings, don't set things up.
565 return;
566 }
567
568 $uploadForm.data( 'origtext', $uploadForm.serialize() );
569
570 allowCloseWindow = mw.confirmCloseWindow( {
571 test: function () {
572 return $( '#wpUploadFile' ).get( 0 ).files.length !== 0 ||
573 $uploadForm.data( 'origtext' ) !== $uploadForm.serialize();
574 },
575
576 message: mw.msg( 'editwarning-warning' ),
577 namespace: 'uploadwarning'
578 } );
579
580 $uploadForm.submit( function () {
581 allowCloseWindow.release();
582 } );
583 } );
584 }( mediaWiki, jQuery ) );