Merge "Add parameter to API modules to apply change tags to log entries"
[lhc/web/wiklou.git] / resources / src / mediawiki / mediawiki.Upload.BookletLayout.js
1 /* global moment*/
2 ( function ( $, mw, moment ) {
3
4 /**
5 * mw.Upload.BookletLayout encapsulates the process of uploading a file
6 * to MediaWiki using the {@link mw.Upload upload model}.
7 * The booklet emits events that can be used to get the stashed
8 * upload and the final file. It can be extended to accept
9 * additional fields from the user for specific scenarios like
10 * for Commons, or campaigns.
11 *
12 * ## Structure
13 *
14 * The {@link OO.ui.BookletLayout booklet layout} has three steps:
15 *
16 * - **Upload**: Has a {@link OO.ui.SelectFileWidget field} to get the file object.
17 *
18 * - **Information**: Has a {@link OO.ui.FormLayout form} to collect metadata. This can be
19 * extended.
20 *
21 * - **Insert**: Has details on how to use the file that was uploaded.
22 *
23 * Each step has a form associated with it defined in
24 * {@link #renderUploadForm renderUploadForm},
25 * {@link #renderInfoForm renderInfoForm}, and
26 * {@link #renderInsertForm renderInfoForm}. The
27 * {@link #getFile getFile},
28 * {@link #getFilename getFilename}, and
29 * {@link #getText getText} methods are used to get
30 * the information filled in these forms, required to call
31 * {@link mw.Upload mw.Upload}.
32 *
33 * ## Usage
34 *
35 * See the {@link mw.Upload.Dialog upload dialog}.
36 *
37 * The {@link #event-fileUploaded fileUploaded},
38 * and {@link #event-fileSaved fileSaved} events can
39 * be used to get details of the upload.
40 *
41 * ## Extending
42 *
43 * To extend using {@link mw.Upload mw.Upload}, override
44 * {@link #renderInfoForm renderInfoForm} to render
45 * the form required for the specific use-case. Update the
46 * {@link #getFilename getFilename}, and
47 * {@link #getText getText} methods to return data
48 * from your newly created form. If you added new fields you'll also have
49 * to update the {@link #clear} method.
50 *
51 * If you plan to use a different upload model, apart from what is mentioned
52 * above, you'll also have to override the
53 * {@link #createUpload createUpload} method to
54 * return the new model. The {@link #saveFile saveFile}, and
55 * the {@link #uploadFile uploadFile} methods need to be
56 * overridden to use the new model and data returned from the forms.
57 *
58 * @class
59 * @extends OO.ui.BookletLayout
60 *
61 * @constructor
62 * @param {Object} config Configuration options
63 * @cfg {jQuery} [$overlay] Overlay to use for widgets in the booklet
64 * @cfg {string} [filekey] Sets the stashed file to finish uploading. Overrides most of the file selection process, and fetches a thumbnail from the server.
65 */
66 mw.Upload.BookletLayout = function ( config ) {
67 // Parent constructor
68 mw.Upload.BookletLayout.parent.call( this, config );
69
70 this.$overlay = config.$overlay;
71
72 this.filekey = config.filekey;
73
74 this.renderUploadForm();
75 this.renderInfoForm();
76 this.renderInsertForm();
77
78 this.addPages( [
79 new OO.ui.PageLayout( 'upload', {
80 scrollable: true,
81 padded: true,
82 content: [ this.uploadForm ]
83 } ),
84 new OO.ui.PageLayout( 'info', {
85 scrollable: true,
86 padded: true,
87 content: [ this.infoForm ]
88 } ),
89 new OO.ui.PageLayout( 'insert', {
90 scrollable: true,
91 padded: true,
92 content: [ this.insertForm ]
93 } )
94 ] );
95 };
96
97 /* Setup */
98
99 OO.inheritClass( mw.Upload.BookletLayout, OO.ui.BookletLayout );
100
101 /* Events */
102
103 /**
104 * Progress events for the uploaded file
105 *
106 * @event fileUploadProgress
107 * @param {number} progress In percentage
108 * @param {Object} duration Duration object from `moment.duration()`
109 */
110
111 /**
112 * The file has finished uploading
113 *
114 * @event fileUploaded
115 */
116
117 /**
118 * The file has been saved to the database
119 *
120 * @event fileSaved
121 * @param {Object} imageInfo See mw.Upload#getImageInfo
122 */
123
124 /**
125 * The upload form has changed
126 *
127 * @event uploadValid
128 * @param {boolean} isValid The form is valid
129 */
130
131 /**
132 * The info form has changed
133 *
134 * @event infoValid
135 * @param {boolean} isValid The form is valid
136 */
137
138 /* Properties */
139
140 /**
141 * @property {OO.ui.FormLayout} uploadForm
142 * The form rendered in the first step to get the file object.
143 * Rendered in {@link #renderUploadForm renderUploadForm}.
144 */
145
146 /**
147 * @property {OO.ui.FormLayout} infoForm
148 * The form rendered in the second step to get metadata.
149 * Rendered in {@link #renderInfoForm renderInfoForm}
150 */
151
152 /**
153 * @property {OO.ui.FormLayout} insertForm
154 * The form rendered in the third step to show usage
155 * Rendered in {@link #renderInsertForm renderInsertForm}
156 */
157
158 /* Methods */
159
160 /**
161 * Initialize for a new upload
162 *
163 * @return {jQuery.Promise} Promise resolved when everything is initialized
164 */
165 mw.Upload.BookletLayout.prototype.initialize = function () {
166 var booklet = this;
167
168 this.clear();
169 this.upload = this.createUpload();
170
171 this.setPage( 'upload' );
172
173 if ( this.filekey ) {
174 this.setFilekey( this.filekey );
175 }
176
177 return this.upload.getApi().then(
178 function ( api ) {
179 // If the user can't upload anything, don't give them the option to.
180 return api.getUserInfo().then(
181 function ( userInfo ) {
182 if ( userInfo.rights.indexOf( 'upload' ) === -1 ) {
183 if ( mw.user.isAnon() ) {
184 booklet.getPage( 'upload' ).$element.msg( 'api-error-mustbeloggedin' );
185 } else {
186 booklet.getPage( 'upload' ).$element.msg( 'api-error-badaccess-groups' );
187 }
188 }
189 return $.Deferred().resolve();
190 },
191 // Always resolve, never reject
192 function () { return $.Deferred().resolve(); }
193 );
194 },
195 function ( errorMsg ) {
196 booklet.getPage( 'upload' ).$element.msg( errorMsg );
197 return $.Deferred().resolve();
198 }
199 );
200 };
201
202 /**
203 * Create a new upload model
204 *
205 * @protected
206 * @return {mw.Upload} Upload model
207 */
208 mw.Upload.BookletLayout.prototype.createUpload = function () {
209 return new mw.Upload();
210 };
211
212 /* Uploading */
213
214 /**
215 * Uploads the file that was added in the upload form. Uses
216 * {@link #getFile getFile} to get the HTML5
217 * file object.
218 *
219 * @protected
220 * @fires fileUploadProgress
221 * @fires fileUploaded
222 * @return {jQuery.Promise}
223 */
224 mw.Upload.BookletLayout.prototype.uploadFile = function () {
225 var deferred = $.Deferred(),
226 startTime = new Date(),
227 layout = this,
228 file = this.getFile();
229
230 this.setPage( 'info' );
231
232 if ( this.filekey ) {
233 if ( file === null ) {
234 // Someone gonna get-a hurt real bad
235 throw new Error( 'filekey not passed into file select widget, which is impossible. Quitting while we\'re behind.' );
236 }
237
238 // Stashed file already uploaded.
239 deferred.resolve();
240 this.uploadPromise = deferred;
241 this.emit( 'fileUploaded' );
242 return deferred;
243 }
244
245 this.setFilename( file.name );
246
247 this.upload.setFile( file );
248 // The original file name might contain invalid characters, so use our sanitized one
249 this.upload.setFilename( this.getFilename() );
250
251 this.uploadPromise = this.upload.uploadToStash();
252 this.uploadPromise.then( function () {
253 deferred.resolve();
254 layout.emit( 'fileUploaded' );
255 }, function () {
256 // These errors will be thrown while the user is on the info page.
257 layout.getErrorMessageForStateDetails().then( function ( errorMessage ) {
258 deferred.reject( errorMessage );
259 } );
260 }, function ( progress ) {
261 var elapsedTime = new Date() - startTime,
262 estimatedTotalTime = ( 1 / progress ) * elapsedTime,
263 estimatedRemainingTime = moment.duration( estimatedTotalTime - elapsedTime );
264 layout.emit( 'fileUploadProgress', progress, estimatedRemainingTime );
265 } );
266
267 // If there is an error in uploading, come back to the upload page
268 deferred.fail( function () {
269 layout.setPage( 'upload' );
270 } );
271
272 return deferred;
273 };
274
275 /**
276 * Saves the stash finalizes upload. Uses
277 * {@link #getFilename getFilename}, and
278 * {@link #getText getText} to get details from
279 * the form.
280 *
281 * @protected
282 * @fires fileSaved
283 * @return {jQuery.Promise} Rejects the promise with an
284 * {@link OO.ui.Error error}, or resolves if the upload was successful.
285 */
286 mw.Upload.BookletLayout.prototype.saveFile = function () {
287 var layout = this,
288 deferred = $.Deferred();
289
290 this.upload.setFilename( this.getFilename() );
291 this.upload.setText( this.getText() );
292
293 this.uploadPromise.then( function () {
294 layout.upload.finishStashUpload().then( function () {
295 var name;
296
297 // Normalize page name and localise the 'File:' prefix
298 name = new mw.Title( 'File:' + layout.upload.getFilename() ).toString();
299 layout.filenameUsageWidget.setValue( '[[' + name + ']]' );
300 layout.setPage( 'insert' );
301
302 deferred.resolve();
303 layout.emit( 'fileSaved', layout.upload.getImageInfo() );
304 }, function () {
305 layout.getErrorMessageForStateDetails().then( function ( errorMessage ) {
306 deferred.reject( errorMessage );
307 } );
308 } );
309 } );
310
311 return deferred.promise();
312 };
313
314 /**
315 * Get an error message (as OO.ui.Error object) that should be displayed to the user for current
316 * state and state details.
317 *
318 * @protected
319 * @return {jQuery.Promise} A Promise that will be resolved with an OO.ui.Error.
320 */
321 mw.Upload.BookletLayout.prototype.getErrorMessageForStateDetails = function () {
322 var message,
323 state = this.upload.getState(),
324 stateDetails = this.upload.getStateDetails(),
325 error = stateDetails.error,
326 warnings = stateDetails.upload && stateDetails.upload.warnings;
327
328 if ( state === mw.Upload.State.ERROR ) {
329 if ( !error ) {
330 // If there's an 'exception' key, this might be a timeout, or other connection problem
331 return $.Deferred().resolve( new OO.ui.Error(
332 $( '<p>' ).msg( 'api-error-unknownerror', JSON.stringify( stateDetails ) ),
333 { recoverable: false }
334 ) );
335 }
336
337 // Errors in this format are produced by TitleBlacklist and AbuseFilter. Perhaps other
338 // extensions will follow this format in the future.
339 if ( error.message ) {
340 return this.upload.getApi()
341 .then( function ( api ) {
342 // 'amenableparser' will expand templates and parser functions server-side.
343 // We still do the rest of wikitext parsing here (through jqueryMsg).
344 return api.loadMessagesIfMissing( [ error.message.key ], { amenableparser: true } )
345 .then( function () {
346 if ( !mw.message( error.message.key ).exists() ) {
347 return $.Deferred().reject();
348 }
349 return new OO.ui.Error(
350 $( '<p>' ).msg( error.message.key, error.message.params || [] ),
351 { recoverable: false }
352 );
353 } );
354 } )
355 .then( null, function () {
356 // We failed when loading the error message, or it doesn't actually exist, fall back
357 return $.Deferred().resolve( new OO.ui.Error(
358 $( '<p>' ).msg( 'api-error-unknownerror', JSON.stringify( stateDetails ) ),
359 { recoverable: false }
360 ) );
361 } );
362 }
363
364 if ( error.code === 'protectedpage' ) {
365 message = mw.message( 'protectedpagetext' );
366 } else {
367 message = mw.message( 'api-error-' + error.code );
368 if ( !message.exists() ) {
369 message = mw.message( 'api-error-unknownerror', JSON.stringify( stateDetails ) );
370 }
371 }
372 return $.Deferred().resolve( new OO.ui.Error(
373 $( '<p>' ).append( message.parseDom() ),
374 { recoverable: false }
375 ) );
376 }
377
378 if ( state === mw.Upload.State.WARNING ) {
379 // We could get more than one of these errors, these are in order
380 // of importance. For example fixing the thumbnail like file name
381 // won't help the fact that the file already exists.
382 if ( warnings.stashfailed !== undefined ) {
383 return $.Deferred().resolve( new OO.ui.Error(
384 $( '<p>' ).msg( 'api-error-stashfailed' ),
385 { recoverable: false }
386 ) );
387 } else if ( warnings.exists !== undefined ) {
388 return $.Deferred().resolve( new OO.ui.Error(
389 $( '<p>' ).msg( 'fileexists', 'File:' + warnings.exists ),
390 { recoverable: false }
391 ) );
392 } else if ( warnings[ 'exists-normalized' ] !== undefined ) {
393 return $.Deferred().resolve( new OO.ui.Error(
394 $( '<p>' ).msg( 'fileexists', 'File:' + warnings[ 'exists-normalized' ] ),
395 { recoverable: false }
396 ) );
397 } else if ( warnings[ 'page-exists' ] !== undefined ) {
398 return $.Deferred().resolve( new OO.ui.Error(
399 $( '<p>' ).msg( 'filepageexists', 'File:' + warnings[ 'page-exists' ] ),
400 { recoverable: false }
401 ) );
402 } else if ( warnings.duplicate !== undefined ) {
403 return $.Deferred().resolve( new OO.ui.Error(
404 $( '<p>' ).msg( 'api-error-duplicate', warnings.duplicate.length ),
405 { recoverable: false }
406 ) );
407 } else if ( warnings[ 'thumb-name' ] !== undefined ) {
408 return $.Deferred().resolve( new OO.ui.Error(
409 $( '<p>' ).msg( 'filename-thumb-name' ),
410 { recoverable: false }
411 ) );
412 } else if ( warnings[ 'bad-prefix' ] !== undefined ) {
413 return $.Deferred().resolve( new OO.ui.Error(
414 $( '<p>' ).msg( 'filename-bad-prefix', warnings[ 'bad-prefix' ] ),
415 { recoverable: false }
416 ) );
417 } else if ( warnings[ 'duplicate-archive' ] !== undefined ) {
418 return $.Deferred().resolve( new OO.ui.Error(
419 $( '<p>' ).msg( 'api-error-duplicate-archive', 1 ),
420 { recoverable: false }
421 ) );
422 } else if ( warnings[ 'was-deleted' ] !== undefined ) {
423 return $.Deferred().resolve( new OO.ui.Error(
424 $( '<p>' ).msg( 'api-error-was-deleted' ),
425 { recoverable: false }
426 ) );
427 } else if ( warnings.badfilename !== undefined ) {
428 // Change the name if the current name isn't acceptable
429 // TODO This might not really be the best place to do this
430 this.setFilename( warnings.badfilename );
431 return $.Deferred().resolve( new OO.ui.Error(
432 $( '<p>' ).msg( 'badfilename', warnings.badfilename )
433 ) );
434 } else {
435 return $.Deferred().resolve( new OO.ui.Error(
436 // Let's get all the help we can if we can't pin point the error
437 $( '<p>' ).msg( 'api-error-unknown-warning', JSON.stringify( stateDetails ) ),
438 { recoverable: false }
439 ) );
440 }
441 }
442 };
443
444 /* Form renderers */
445
446 /**
447 * Renders and returns the upload form and sets the
448 * {@link #uploadForm uploadForm} property.
449 *
450 * @protected
451 * @fires selectFile
452 * @return {OO.ui.FormLayout}
453 */
454 mw.Upload.BookletLayout.prototype.renderUploadForm = function () {
455 var fieldset,
456 layout = this;
457
458 this.selectFileWidget = this.getFileWidget();
459 fieldset = new OO.ui.FieldsetLayout();
460 fieldset.addItems( [ this.selectFileWidget ] );
461 this.uploadForm = new OO.ui.FormLayout( { items: [ fieldset ] } );
462
463 // Validation (if the SFW is for a stashed file, this never fires)
464 this.selectFileWidget.on( 'change', this.onUploadFormChange.bind( this ) );
465
466 this.selectFileWidget.on( 'change', function () {
467 layout.updateFilePreview();
468 } );
469
470 return this.uploadForm;
471 };
472
473 /**
474 * Gets the widget for displaying or inputting the file to upload.
475 *
476 * @return {OO.ui.SelectFileWidget|mw.widgets.StashedFileWidget}
477 */
478 mw.Upload.BookletLayout.prototype.getFileWidget = function () {
479 if ( this.filekey ) {
480 return new mw.widgets.StashedFileWidget( {
481 filekey: this.filekey
482 } );
483 }
484
485 return new OO.ui.SelectFileWidget( {
486 showDropTarget: true
487 } );
488 };
489
490 /**
491 * Updates the file preview on the info form when a file is added.
492 *
493 * @protected
494 */
495 mw.Upload.BookletLayout.prototype.updateFilePreview = function () {
496 this.selectFileWidget.loadAndGetImageUrl().done( function ( url ) {
497 this.filePreview.$element.find( 'p' ).remove();
498 this.filePreview.$element.css( 'background-image', 'url(' + url + ')' );
499 this.infoForm.$element.addClass( 'mw-upload-bookletLayout-hasThumbnail' );
500 }.bind( this ) ).fail( function () {
501 this.filePreview.$element.find( 'p' ).remove();
502 if ( this.selectFileWidget.getValue() ) {
503 this.filePreview.$element.append(
504 $( '<p>' ).text( this.selectFileWidget.getValue().name )
505 );
506 }
507 this.filePreview.$element.css( 'background-image', '' );
508 this.infoForm.$element.removeClass( 'mw-upload-bookletLayout-hasThumbnail' );
509 }.bind( this ) );
510 };
511
512 /**
513 * Handle change events to the upload form
514 *
515 * @protected
516 * @fires uploadValid
517 */
518 mw.Upload.BookletLayout.prototype.onUploadFormChange = function () {
519 this.emit( 'uploadValid', !!this.selectFileWidget.getValue() );
520 };
521
522 /**
523 * Renders and returns the information form for collecting
524 * metadata and sets the {@link #infoForm infoForm}
525 * property.
526 *
527 * @protected
528 * @return {OO.ui.FormLayout}
529 */
530 mw.Upload.BookletLayout.prototype.renderInfoForm = function () {
531 var fieldset;
532
533 this.filePreview = new OO.ui.Widget( {
534 classes: [ 'mw-upload-bookletLayout-filePreview' ]
535 } );
536 this.progressBarWidget = new OO.ui.ProgressBarWidget( {
537 progress: 0
538 } );
539 this.filePreview.$element.append( this.progressBarWidget.$element );
540
541 this.filenameWidget = new OO.ui.TextInputWidget( {
542 indicator: 'required',
543 required: true,
544 validate: /.+/
545 } );
546 this.descriptionWidget = new OO.ui.TextInputWidget( {
547 indicator: 'required',
548 required: true,
549 validate: /\S+/,
550 multiline: true,
551 autosize: true
552 } );
553
554 fieldset = new OO.ui.FieldsetLayout( {
555 label: mw.msg( 'upload-form-label-infoform-title' )
556 } );
557 fieldset.addItems( [
558 new OO.ui.FieldLayout( this.filenameWidget, {
559 label: mw.msg( 'upload-form-label-infoform-name' ),
560 align: 'top',
561 help: mw.msg( 'upload-form-label-infoform-name-tooltip' )
562 } ),
563 new OO.ui.FieldLayout( this.descriptionWidget, {
564 label: mw.msg( 'upload-form-label-infoform-description' ),
565 align: 'top',
566 help: mw.msg( 'upload-form-label-infoform-description-tooltip' )
567 } )
568 ] );
569 this.infoForm = new OO.ui.FormLayout( {
570 classes: [ 'mw-upload-bookletLayout-infoForm' ],
571 items: [ this.filePreview, fieldset ]
572 } );
573
574 this.on( 'fileUploadProgress', function ( progress ) {
575 this.progressBarWidget.setProgress( progress * 100 );
576 }.bind( this ) );
577
578 this.filenameWidget.on( 'change', this.onInfoFormChange.bind( this ) );
579 this.descriptionWidget.on( 'change', this.onInfoFormChange.bind( this ) );
580
581 return this.infoForm;
582 };
583
584 /**
585 * Handle change events to the info form
586 *
587 * @protected
588 * @fires infoValid
589 */
590 mw.Upload.BookletLayout.prototype.onInfoFormChange = function () {
591 var layout = this;
592 $.when(
593 this.filenameWidget.getValidity(),
594 this.descriptionWidget.getValidity()
595 ).done( function () {
596 layout.emit( 'infoValid', true );
597 } ).fail( function () {
598 layout.emit( 'infoValid', false );
599 } );
600 };
601
602 /**
603 * Renders and returns the insert form to show file usage and
604 * sets the {@link #insertForm insertForm} property.
605 *
606 * @protected
607 * @return {OO.ui.FormLayout}
608 */
609 mw.Upload.BookletLayout.prototype.renderInsertForm = function () {
610 var fieldset;
611
612 this.filenameUsageWidget = new OO.ui.TextInputWidget();
613 fieldset = new OO.ui.FieldsetLayout( {
614 label: mw.msg( 'upload-form-label-usage-title' )
615 } );
616 fieldset.addItems( [
617 new OO.ui.FieldLayout( this.filenameUsageWidget, {
618 label: mw.msg( 'upload-form-label-usage-filename' ),
619 align: 'top'
620 } )
621 ] );
622 this.insertForm = new OO.ui.FormLayout( { items: [ fieldset ] } );
623
624 return this.insertForm;
625 };
626
627 /* Getters */
628
629 /**
630 * Gets the file object from the
631 * {@link #uploadForm upload form}.
632 *
633 * @protected
634 * @return {File|null}
635 */
636 mw.Upload.BookletLayout.prototype.getFile = function () {
637 return this.selectFileWidget.getValue();
638 };
639
640 /**
641 * Gets the file name from the
642 * {@link #infoForm information form}.
643 *
644 * @protected
645 * @return {string}
646 */
647 mw.Upload.BookletLayout.prototype.getFilename = function () {
648 var filename = this.filenameWidget.getValue();
649 if ( this.filenameExtension ) {
650 filename += '.' + this.filenameExtension;
651 }
652 return filename;
653 };
654
655 /**
656 * Prefills the {@link #infoForm information form} with the given filename.
657 *
658 * @protected
659 * @param {string} filename
660 */
661 mw.Upload.BookletLayout.prototype.setFilename = function ( filename ) {
662 var title = mw.Title.newFromFileName( filename );
663
664 if ( title ) {
665 this.filenameWidget.setValue( title.getNameText() );
666 this.filenameExtension = mw.Title.normalizeExtension( title.getExtension() );
667 } else {
668 // Seems to happen for files with no extension, which should fail some checks anyway...
669 this.filenameWidget.setValue( filename );
670 this.filenameExtension = null;
671 }
672 };
673
674 /**
675 * Gets the page text from the
676 * {@link #infoForm information form}.
677 *
678 * @protected
679 * @return {string}
680 */
681 mw.Upload.BookletLayout.prototype.getText = function () {
682 return this.descriptionWidget.getValue();
683 };
684
685 /* Setters */
686
687 /**
688 * Sets the file object
689 *
690 * @protected
691 * @param {File|null} file File to select
692 */
693 mw.Upload.BookletLayout.prototype.setFile = function ( file ) {
694 this.selectFileWidget.setValue( file );
695 };
696
697 /**
698 * Sets the filekey of a file already stashed on the server
699 * as the target of this upload operation.
700 *
701 * @protected
702 * @param {string} filekey
703 */
704 mw.Upload.BookletLayout.prototype.setFilekey = function ( filekey ) {
705 this.upload.setFilekey( this.filekey );
706 this.selectFileWidget.setValue( filekey );
707
708 this.onUploadFormChange();
709 };
710
711 /**
712 * Clear the values of all fields
713 *
714 * @protected
715 */
716 mw.Upload.BookletLayout.prototype.clear = function () {
717 this.selectFileWidget.setValue( null );
718 this.progressBarWidget.setProgress( 0 );
719 this.filenameWidget.setValue( null ).setValidityFlag( true );
720 this.descriptionWidget.setValue( null ).setValidityFlag( true );
721 this.filenameUsageWidget.setValue( null );
722 };
723
724 }( jQuery, mediaWiki, moment ) );