Merge "Fix sessionfailure i18n message during authentication"
[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( 'apierror-mustbeloggedin', mw.msg( 'action-upload' ) );
185 } else {
186 booklet.getPage( 'upload' ).$element.msg( 'apierror-permissiondenied', mw.msg( 'action-upload' ) );
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 parameters: {
211 errorformat: 'html',
212 errorlang: mw.config.get( 'wgUserLanguage' ),
213 errorsuselocal: 1,
214 formatversion: 2
215 }
216 } );
217 };
218
219 /* Uploading */
220
221 /**
222 * Uploads the file that was added in the upload form. Uses
223 * {@link #getFile getFile} to get the HTML5
224 * file object.
225 *
226 * @protected
227 * @fires fileUploadProgress
228 * @fires fileUploaded
229 * @return {jQuery.Promise}
230 */
231 mw.Upload.BookletLayout.prototype.uploadFile = function () {
232 var deferred = $.Deferred(),
233 startTime = mw.now(),
234 layout = this,
235 file = this.getFile();
236
237 this.setPage( 'info' );
238
239 if ( this.filekey ) {
240 if ( file === null ) {
241 // Someone gonna get-a hurt real bad
242 throw new Error( 'filekey not passed into file select widget, which is impossible. Quitting while we\'re behind.' );
243 }
244
245 // Stashed file already uploaded.
246 deferred.resolve();
247 this.uploadPromise = deferred;
248 this.emit( 'fileUploaded' );
249 return deferred;
250 }
251
252 this.setFilename( file.name );
253
254 this.upload.setFile( file );
255 // The original file name might contain invalid characters, so use our sanitized one
256 this.upload.setFilename( this.getFilename() );
257
258 this.uploadPromise = this.upload.uploadToStash();
259 this.uploadPromise.then( function () {
260 deferred.resolve();
261 layout.emit( 'fileUploaded' );
262 }, function () {
263 // These errors will be thrown while the user is on the info page.
264 layout.getErrorMessageForStateDetails().then( function ( errorMessage ) {
265 deferred.reject( errorMessage );
266 } );
267 }, function ( progress ) {
268 var elapsedTime = mw.now() - startTime,
269 estimatedTotalTime = ( 1 / progress ) * elapsedTime,
270 estimatedRemainingTime = moment.duration( estimatedTotalTime - elapsedTime );
271 layout.emit( 'fileUploadProgress', progress, estimatedRemainingTime );
272 } );
273
274 // If there is an error in uploading, come back to the upload page
275 deferred.fail( function () {
276 layout.setPage( 'upload' );
277 } );
278
279 return deferred;
280 };
281
282 /**
283 * Saves the stash finalizes upload. Uses
284 * {@link #getFilename getFilename}, and
285 * {@link #getText getText} to get details from
286 * the form.
287 *
288 * @protected
289 * @fires fileSaved
290 * @return {jQuery.Promise} Rejects the promise with an
291 * {@link OO.ui.Error error}, or resolves if the upload was successful.
292 */
293 mw.Upload.BookletLayout.prototype.saveFile = function () {
294 var layout = this,
295 deferred = $.Deferred();
296
297 this.upload.setFilename( this.getFilename() );
298 this.upload.setText( this.getText() );
299
300 this.uploadPromise.then( function () {
301 layout.upload.finishStashUpload().then( function () {
302 var name;
303
304 // Normalize page name and localise the 'File:' prefix
305 name = new mw.Title( 'File:' + layout.upload.getFilename() ).toString();
306 layout.filenameUsageWidget.setValue( '[[' + name + ']]' );
307 layout.setPage( 'insert' );
308
309 deferred.resolve();
310 layout.emit( 'fileSaved', layout.upload.getImageInfo() );
311 }, function () {
312 layout.getErrorMessageForStateDetails().then( function ( errorMessage ) {
313 deferred.reject( errorMessage );
314 } );
315 } );
316 } );
317
318 return deferred.promise();
319 };
320
321 /**
322 * Get an error message (as OO.ui.Error object) that should be displayed to the user for current
323 * state and state details.
324 *
325 * @protected
326 * @return {jQuery.Promise} A Promise that will be resolved with an OO.ui.Error.
327 */
328 mw.Upload.BookletLayout.prototype.getErrorMessageForStateDetails = function () {
329 var state = this.upload.getState(),
330 stateDetails = this.upload.getStateDetails(),
331 error = stateDetails.errors ? stateDetails.errors[ 0 ] : false,
332 warnings = stateDetails.upload && stateDetails.upload.warnings,
333 $ul = $( '<ul>' ),
334 errorText;
335
336 if ( state === mw.Upload.State.ERROR ) {
337 if ( !error ) {
338 if ( stateDetails.textStatus === 'timeout' ) {
339 // in case of $.ajax.fail(), there is no response json
340 errorText = mw.message( 'apierror-timeout' ).parse();
341 } else if ( stateDetails.xhr && stateDetails.xhr.status === 0 ) {
342 // failed to even connect to server
343 errorText = mw.message( 'apierror-offline' ).parse();
344 } else if ( stateDetails.textStatus ) {
345 errorText = stateDetails.textStatus;
346 } else {
347 errorText = mw.message( 'apierror-unknownerror', JSON.stringify( stateDetails ) ).parse();
348 }
349
350 // If there's an 'exception' key, this might be a timeout, or other connection problem
351 return $.Deferred().resolve( new OO.ui.Error(
352 $( '<p>' ).html( errorText ),
353 { recoverable: false }
354 ) );
355 }
356
357 return $.Deferred().resolve( new OO.ui.Error(
358 $( '<p>' ).html( error.html ),
359 { recoverable: false }
360 ) );
361 }
362
363 if ( state === mw.Upload.State.WARNING ) {
364 // We could get more than one of these errors, these are in order
365 // of importance. For example fixing the thumbnail like file name
366 // won't help the fact that the file already exists.
367 if ( warnings.exists !== undefined ) {
368 return $.Deferred().resolve( new OO.ui.Error(
369 $( '<p>' ).msg( 'fileexists', 'File:' + warnings.exists ),
370 { recoverable: false }
371 ) );
372 } else if ( warnings[ 'exists-normalized' ] !== undefined ) {
373 return $.Deferred().resolve( new OO.ui.Error(
374 $( '<p>' ).msg( 'fileexists', 'File:' + warnings[ 'exists-normalized' ] ),
375 { recoverable: false }
376 ) );
377 } else if ( warnings[ 'page-exists' ] !== undefined ) {
378 return $.Deferred().resolve( new OO.ui.Error(
379 $( '<p>' ).msg( 'filepageexists', 'File:' + warnings[ 'page-exists' ] ),
380 { recoverable: false }
381 ) );
382 } else if ( Array.isArray( warnings.duplicate ) ) {
383 warnings.duplicate.forEach( function ( filename ) {
384 var $a = $( '<a>' ).text( filename ),
385 href = mw.Title.makeTitle( mw.config.get( 'wgNamespaceIds' ).file, filename ).getUrl( {} );
386
387 $a.attr( { href: href, target: '_blank' } );
388 $ul.append( $( '<li>' ).append( $a ) );
389 } );
390
391 return $.Deferred().resolve( new OO.ui.Error(
392 $( '<p>' ).msg( 'file-exists-duplicate', warnings.duplicate.length ).append( $ul ),
393 { recoverable: false }
394 ) );
395 } else if ( warnings[ 'thumb-name' ] !== undefined ) {
396 return $.Deferred().resolve( new OO.ui.Error(
397 $( '<p>' ).msg( 'filename-thumb-name' ),
398 { recoverable: false }
399 ) );
400 } else if ( warnings[ 'bad-prefix' ] !== undefined ) {
401 return $.Deferred().resolve( new OO.ui.Error(
402 $( '<p>' ).msg( 'filename-bad-prefix', warnings[ 'bad-prefix' ] ),
403 { recoverable: false }
404 ) );
405 } else if ( warnings[ 'duplicate-archive' ] !== undefined ) {
406 return $.Deferred().resolve( new OO.ui.Error(
407 $( '<p>' ).msg( 'file-deleted-duplicate', 'File:' + warnings[ 'duplicate-archive' ] ),
408 { recoverable: false }
409 ) );
410 } else if ( warnings[ 'was-deleted' ] !== undefined ) {
411 return $.Deferred().resolve( new OO.ui.Error(
412 $( '<p>' ).msg( 'filewasdeleted', 'File:' + warnings[ 'was-deleted' ] ),
413 { recoverable: false }
414 ) );
415 } else if ( warnings.badfilename !== undefined ) {
416 // Change the name if the current name isn't acceptable
417 // TODO This might not really be the best place to do this
418 this.setFilename( warnings.badfilename );
419 return $.Deferred().resolve( new OO.ui.Error(
420 $( '<p>' ).msg( 'badfilename', warnings.badfilename )
421 ) );
422 } else {
423 return $.Deferred().resolve( new OO.ui.Error(
424 // Let's get all the help we can if we can't pin point the error
425 $( '<p>' ).msg( 'api-error-unknown-warning', JSON.stringify( stateDetails ) ),
426 { recoverable: false }
427 ) );
428 }
429 }
430 };
431
432 /* Form renderers */
433
434 /**
435 * Renders and returns the upload form and sets the
436 * {@link #uploadForm uploadForm} property.
437 *
438 * @protected
439 * @fires selectFile
440 * @return {OO.ui.FormLayout}
441 */
442 mw.Upload.BookletLayout.prototype.renderUploadForm = function () {
443 var fieldset,
444 layout = this;
445
446 this.selectFileWidget = this.getFileWidget();
447 fieldset = new OO.ui.FieldsetLayout();
448 fieldset.addItems( [ this.selectFileWidget ] );
449 this.uploadForm = new OO.ui.FormLayout( { items: [ fieldset ] } );
450
451 // Validation (if the SFW is for a stashed file, this never fires)
452 this.selectFileWidget.on( 'change', this.onUploadFormChange.bind( this ) );
453
454 this.selectFileWidget.on( 'change', function () {
455 layout.updateFilePreview();
456 } );
457
458 return this.uploadForm;
459 };
460
461 /**
462 * Gets the widget for displaying or inputting the file to upload.
463 *
464 * @return {OO.ui.SelectFileWidget|mw.widgets.StashedFileWidget}
465 */
466 mw.Upload.BookletLayout.prototype.getFileWidget = function () {
467 if ( this.filekey ) {
468 return new mw.widgets.StashedFileWidget( {
469 filekey: this.filekey
470 } );
471 }
472
473 return new OO.ui.SelectFileWidget( {
474 showDropTarget: true
475 } );
476 };
477
478 /**
479 * Updates the file preview on the info form when a file is added.
480 *
481 * @protected
482 */
483 mw.Upload.BookletLayout.prototype.updateFilePreview = function () {
484 this.selectFileWidget.loadAndGetImageUrl().done( function ( url ) {
485 this.filePreview.$element.find( 'p' ).remove();
486 this.filePreview.$element.css( 'background-image', 'url(' + url + ')' );
487 this.infoForm.$element.addClass( 'mw-upload-bookletLayout-hasThumbnail' );
488 }.bind( this ) ).fail( function () {
489 this.filePreview.$element.find( 'p' ).remove();
490 if ( this.selectFileWidget.getValue() ) {
491 this.filePreview.$element.append(
492 $( '<p>' ).text( this.selectFileWidget.getValue().name )
493 );
494 }
495 this.filePreview.$element.css( 'background-image', '' );
496 this.infoForm.$element.removeClass( 'mw-upload-bookletLayout-hasThumbnail' );
497 }.bind( this ) );
498 };
499
500 /**
501 * Handle change events to the upload form
502 *
503 * @protected
504 * @fires uploadValid
505 */
506 mw.Upload.BookletLayout.prototype.onUploadFormChange = function () {
507 this.emit( 'uploadValid', !!this.selectFileWidget.getValue() );
508 };
509
510 /**
511 * Renders and returns the information form for collecting
512 * metadata and sets the {@link #infoForm infoForm}
513 * property.
514 *
515 * @protected
516 * @return {OO.ui.FormLayout}
517 */
518 mw.Upload.BookletLayout.prototype.renderInfoForm = function () {
519 var fieldset;
520
521 this.filePreview = new OO.ui.Widget( {
522 classes: [ 'mw-upload-bookletLayout-filePreview' ]
523 } );
524 this.progressBarWidget = new OO.ui.ProgressBarWidget( {
525 progress: 0
526 } );
527 this.filePreview.$element.append( this.progressBarWidget.$element );
528
529 this.filenameWidget = new OO.ui.TextInputWidget( {
530 indicator: 'required',
531 required: true,
532 validate: /.+/
533 } );
534 this.descriptionWidget = new OO.ui.MultilineTextInputWidget( {
535 indicator: 'required',
536 required: true,
537 validate: /\S+/,
538 autosize: true
539 } );
540
541 fieldset = new OO.ui.FieldsetLayout( {
542 label: mw.msg( 'upload-form-label-infoform-title' )
543 } );
544 fieldset.addItems( [
545 new OO.ui.FieldLayout( this.filenameWidget, {
546 label: mw.msg( 'upload-form-label-infoform-name' ),
547 align: 'top',
548 help: mw.msg( 'upload-form-label-infoform-name-tooltip' )
549 } ),
550 new OO.ui.FieldLayout( this.descriptionWidget, {
551 label: mw.msg( 'upload-form-label-infoform-description' ),
552 align: 'top',
553 help: mw.msg( 'upload-form-label-infoform-description-tooltip' )
554 } )
555 ] );
556 this.infoForm = new OO.ui.FormLayout( {
557 classes: [ 'mw-upload-bookletLayout-infoForm' ],
558 items: [ this.filePreview, fieldset ]
559 } );
560
561 this.on( 'fileUploadProgress', function ( progress ) {
562 this.progressBarWidget.setProgress( progress * 100 );
563 }.bind( this ) );
564
565 this.filenameWidget.on( 'change', this.onInfoFormChange.bind( this ) );
566 this.descriptionWidget.on( 'change', this.onInfoFormChange.bind( this ) );
567
568 return this.infoForm;
569 };
570
571 /**
572 * Handle change events to the info form
573 *
574 * @protected
575 * @fires infoValid
576 */
577 mw.Upload.BookletLayout.prototype.onInfoFormChange = function () {
578 var layout = this;
579 $.when(
580 this.filenameWidget.getValidity(),
581 this.descriptionWidget.getValidity()
582 ).done( function () {
583 layout.emit( 'infoValid', true );
584 } ).fail( function () {
585 layout.emit( 'infoValid', false );
586 } );
587 };
588
589 /**
590 * Renders and returns the insert form to show file usage and
591 * sets the {@link #insertForm insertForm} property.
592 *
593 * @protected
594 * @return {OO.ui.FormLayout}
595 */
596 mw.Upload.BookletLayout.prototype.renderInsertForm = function () {
597 var fieldset;
598
599 this.filenameUsageWidget = new OO.ui.TextInputWidget();
600 fieldset = new OO.ui.FieldsetLayout( {
601 label: mw.msg( 'upload-form-label-usage-title' )
602 } );
603 fieldset.addItems( [
604 new OO.ui.FieldLayout( this.filenameUsageWidget, {
605 label: mw.msg( 'upload-form-label-usage-filename' ),
606 align: 'top'
607 } )
608 ] );
609 this.insertForm = new OO.ui.FormLayout( { items: [ fieldset ] } );
610
611 return this.insertForm;
612 };
613
614 /* Getters */
615
616 /**
617 * Gets the file object from the
618 * {@link #uploadForm upload form}.
619 *
620 * @protected
621 * @return {File|null}
622 */
623 mw.Upload.BookletLayout.prototype.getFile = function () {
624 return this.selectFileWidget.getValue();
625 };
626
627 /**
628 * Gets the file name from the
629 * {@link #infoForm information form}.
630 *
631 * @protected
632 * @return {string}
633 */
634 mw.Upload.BookletLayout.prototype.getFilename = function () {
635 var filename = this.filenameWidget.getValue();
636 if ( this.filenameExtension ) {
637 filename += '.' + this.filenameExtension;
638 }
639 return filename;
640 };
641
642 /**
643 * Prefills the {@link #infoForm information form} with the given filename.
644 *
645 * @protected
646 * @param {string} filename
647 */
648 mw.Upload.BookletLayout.prototype.setFilename = function ( filename ) {
649 var title = mw.Title.newFromFileName( filename );
650
651 if ( title ) {
652 this.filenameWidget.setValue( title.getNameText() );
653 this.filenameExtension = mw.Title.normalizeExtension( title.getExtension() );
654 } else {
655 // Seems to happen for files with no extension, which should fail some checks anyway...
656 this.filenameWidget.setValue( filename );
657 this.filenameExtension = null;
658 }
659 };
660
661 /**
662 * Gets the page text from the
663 * {@link #infoForm information form}.
664 *
665 * @protected
666 * @return {string}
667 */
668 mw.Upload.BookletLayout.prototype.getText = function () {
669 return this.descriptionWidget.getValue();
670 };
671
672 /* Setters */
673
674 /**
675 * Sets the file object
676 *
677 * @protected
678 * @param {File|null} file File to select
679 */
680 mw.Upload.BookletLayout.prototype.setFile = function ( file ) {
681 this.selectFileWidget.setValue( file );
682 };
683
684 /**
685 * Sets the filekey of a file already stashed on the server
686 * as the target of this upload operation.
687 *
688 * @protected
689 * @param {string} filekey
690 */
691 mw.Upload.BookletLayout.prototype.setFilekey = function ( filekey ) {
692 this.upload.setFilekey( this.filekey );
693 this.selectFileWidget.setValue( filekey );
694
695 this.onUploadFormChange();
696 };
697
698 /**
699 * Clear the values of all fields
700 *
701 * @protected
702 */
703 mw.Upload.BookletLayout.prototype.clear = function () {
704 this.selectFileWidget.setValue( null );
705 this.progressBarWidget.setProgress( 0 );
706 this.filenameWidget.setValue( null ).setValidityFlag( true );
707 this.descriptionWidget.setValue( null ).setValidityFlag( true );
708 this.filenameUsageWidget.setValue( null );
709 };
710
711 }( jQuery, mediaWiki, moment ) );