Merge "Add possibility to filter for log_action in all core logs"
[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 */
65 mw.Upload.BookletLayout = function ( config ) {
66 // Parent constructor
67 mw.Upload.BookletLayout.parent.call( this, config );
68
69 this.$overlay = config.$overlay;
70
71 this.renderUploadForm();
72 this.renderInfoForm();
73 this.renderInsertForm();
74
75 this.addPages( [
76 new OO.ui.PageLayout( 'upload', {
77 scrollable: true,
78 padded: true,
79 content: [ this.uploadForm ]
80 } ),
81 new OO.ui.PageLayout( 'info', {
82 scrollable: true,
83 padded: true,
84 content: [ this.infoForm ]
85 } ),
86 new OO.ui.PageLayout( 'insert', {
87 scrollable: true,
88 padded: true,
89 content: [ this.insertForm ]
90 } )
91 ] );
92 };
93
94 /* Setup */
95
96 OO.inheritClass( mw.Upload.BookletLayout, OO.ui.BookletLayout );
97
98 /* Events */
99
100 /**
101 * Progress events for the uploaded file
102 *
103 * @event fileUploadProgress
104 * @param {number} progress In percentage
105 * @param {Object} duration Duration object from `moment.duration()`
106 */
107
108 /**
109 * The file has finished uploading
110 *
111 * @event fileUploaded
112 */
113
114 /**
115 * The file has been saved to the database
116 *
117 * @event fileSaved
118 * @param {Object} imageInfo See mw.Upload#getImageInfo
119 */
120
121 /**
122 * The upload form has changed
123 *
124 * @event uploadValid
125 * @param {boolean} isValid The form is valid
126 */
127
128 /**
129 * The info form has changed
130 *
131 * @event infoValid
132 * @param {boolean} isValid The form is valid
133 */
134
135 /* Properties */
136
137 /**
138 * @property {OO.ui.FormLayout} uploadForm
139 * The form rendered in the first step to get the file object.
140 * Rendered in {@link #renderUploadForm renderUploadForm}.
141 */
142
143 /**
144 * @property {OO.ui.FormLayout} infoForm
145 * The form rendered in the second step to get metadata.
146 * Rendered in {@link #renderInfoForm renderInfoForm}
147 */
148
149 /**
150 * @property {OO.ui.FormLayout} insertForm
151 * The form rendered in the third step to show usage
152 * Rendered in {@link #renderInsertForm renderInsertForm}
153 */
154
155 /* Methods */
156
157 /**
158 * Initialize for a new upload
159 *
160 * @return {jQuery.Promise} Promise resolved when everything is initialized
161 */
162 mw.Upload.BookletLayout.prototype.initialize = function () {
163 var booklet = this;
164
165 this.clear();
166 this.upload = this.createUpload();
167 this.setPage( 'upload' );
168
169 return this.upload.getApi().then(
170 function ( api ) {
171 // If the user can't upload anything, don't give them the option to.
172 return api.getUserInfo().then(
173 function ( userInfo ) {
174 if ( userInfo.rights.indexOf( 'upload' ) === -1 ) {
175 // TODO Use a better error message when not all logged-in users can upload
176 booklet.getPage( 'upload' ).$element.msg( 'api-error-mustbeloggedin' );
177 }
178 return $.Deferred().resolve();
179 },
180 function () {
181 return $.Deferred().resolve();
182 }
183 );
184 },
185 function ( errorMsg ) {
186 booklet.getPage( 'upload' ).$element.msg( errorMsg );
187 return $.Deferred().resolve();
188 }
189 );
190 };
191
192 /**
193 * Create a new upload model
194 *
195 * @protected
196 * @return {mw.Upload} Upload model
197 */
198 mw.Upload.BookletLayout.prototype.createUpload = function () {
199 return new mw.Upload();
200 };
201
202 /* Uploading */
203
204 /**
205 * Uploads the file that was added in the upload form. Uses
206 * {@link #getFile getFile} to get the HTML5
207 * file object.
208 *
209 * @protected
210 * @fires fileUploadProgress
211 * @fires fileUploaded
212 * @return {jQuery.Promise}
213 */
214 mw.Upload.BookletLayout.prototype.uploadFile = function () {
215 var deferred = $.Deferred(),
216 startTime = new Date(),
217 layout = this,
218 file = this.getFile();
219
220 this.setFilename( file.name );
221
222 this.setPage( 'info' );
223
224 this.upload.setFile( file );
225 // The original file name might contain invalid characters, so use our sanitized one
226 this.upload.setFilename( this.getFilename() );
227
228 this.uploadPromise = this.upload.uploadToStash();
229 this.uploadPromise.then( function () {
230 deferred.resolve();
231 layout.emit( 'fileUploaded' );
232 }, function () {
233 // These errors will be thrown while the user is on the info page.
234 // Pretty sure it's impossible to get a warning other than 'stashfailed' here, which should
235 // really be an error...
236 var errorMessage = layout.getErrorMessageForStateDetails();
237 deferred.reject( errorMessage );
238 }, function ( progress ) {
239 var elapsedTime = new Date() - startTime,
240 estimatedTotalTime = ( 1 / progress ) * elapsedTime,
241 estimatedRemainingTime = moment.duration( estimatedTotalTime - elapsedTime );
242 layout.emit( 'fileUploadProgress', progress, estimatedRemainingTime );
243 } );
244
245 // If there is an error in uploading, come back to the upload page
246 deferred.fail( function () {
247 layout.setPage( 'upload' );
248 } );
249
250 return deferred;
251 };
252
253 /**
254 * Saves the stash finalizes upload. Uses
255 * {@link #getFilename getFilename}, and
256 * {@link #getText getText} to get details from
257 * the form.
258 *
259 * @protected
260 * @fires fileSaved
261 * @return {jQuery.Promise} Rejects the promise with an
262 * {@link OO.ui.Error error}, or resolves if the upload was successful.
263 */
264 mw.Upload.BookletLayout.prototype.saveFile = function () {
265 var layout = this,
266 deferred = $.Deferred();
267
268 this.upload.setFilename( this.getFilename() );
269 this.upload.setText( this.getText() );
270
271 this.uploadPromise.then( function () {
272 layout.upload.finishStashUpload().then( function () {
273 var name;
274
275 // Normalize page name and localise the 'File:' prefix
276 name = new mw.Title( 'File:' + layout.upload.getFilename() ).toString();
277 layout.filenameUsageWidget.setValue( '[[' + name + ']]' );
278 layout.setPage( 'insert' );
279
280 deferred.resolve();
281 layout.emit( 'fileSaved', layout.upload.getImageInfo() );
282 }, function () {
283 var errorMessage = layout.getErrorMessageForStateDetails();
284 deferred.reject( errorMessage );
285 } );
286 } );
287
288 return deferred.promise();
289 };
290
291 /**
292 * Get an error message (as OO.ui.Error object) that should be displayed to the user for current
293 * state and state details.
294 *
295 * @protected
296 * @return {OO.ui.Error} Error to display for given state and details.
297 */
298 mw.Upload.BookletLayout.prototype.getErrorMessageForStateDetails = function () {
299 var message,
300 state = this.upload.getState(),
301 stateDetails = this.upload.getStateDetails(),
302 error = stateDetails.error,
303 warnings = stateDetails.upload && stateDetails.upload.warnings;
304
305 if ( state === mw.Upload.State.ERROR ) {
306 if ( !error ) {
307 // If there's an 'exception' key, this might be a timeout, or other connection problem
308 return new OO.ui.Error(
309 $( '<p>' ).msg( 'api-error-unknownerror', JSON.stringify( stateDetails ) ),
310 { recoverable: false }
311 );
312 }
313
314 // HACK We should either have a hook here to allow TitleBlacklist to handle this, or just have
315 // TitleBlacklist produce sane error messages that can be displayed without arcane knowledge
316 if ( error.info === 'TitleBlacklist prevents this title from being created' ) {
317 // HACK Apparently the only reliable way to determine whether TitleBlacklist was involved
318 return new OO.ui.Error(
319 // HACK TitleBlacklist doesn't have a sensible message, this one is from UploadWizard
320 $( '<p>' ).msg( 'api-error-blacklisted' ),
321 { recoverable: false }
322 );
323 }
324
325 if ( error.code === 'protectedpage' ) {
326 message = mw.message( 'protectedpagetext' );
327 } else {
328 message = mw.message( 'api-error-' + error.code );
329 if ( !message.exists() ) {
330 message = mw.message( 'api-error-unknownerror', JSON.stringify( stateDetails ) );
331 }
332 }
333 return new OO.ui.Error(
334 $( '<p>' ).append( message.parseDom() ),
335 { recoverable: false }
336 );
337 }
338
339 if ( state === mw.Upload.State.WARNING ) {
340 // We could get more than one of these errors, these are in order
341 // of importance. For example fixing the thumbnail like file name
342 // won't help the fact that the file already exists.
343 if ( warnings.stashfailed !== undefined ) {
344 return new OO.ui.Error(
345 $( '<p>' ).msg( 'api-error-stashfailed' ),
346 { recoverable: false }
347 );
348 } else if ( warnings.exists !== undefined ) {
349 return new OO.ui.Error(
350 $( '<p>' ).msg( 'fileexists', 'File:' + warnings.exists ),
351 { recoverable: false }
352 );
353 } else if ( warnings[ 'exists-normalized' ] !== undefined ) {
354 return new OO.ui.Error(
355 $( '<p>' ).msg( 'fileexists', 'File:' + warnings[ 'exists-normalized' ] ),
356 { recoverable: false }
357 );
358 } else if ( warnings[ 'page-exists' ] !== undefined ) {
359 return new OO.ui.Error(
360 $( '<p>' ).msg( 'filepageexists', 'File:' + warnings[ 'page-exists' ] ),
361 { recoverable: false }
362 );
363 } else if ( warnings.duplicate !== undefined ) {
364 return new OO.ui.Error(
365 $( '<p>' ).msg( 'api-error-duplicate', warnings.duplicate.length ),
366 { recoverable: false }
367 );
368 } else if ( warnings[ 'thumb-name' ] !== undefined ) {
369 return new OO.ui.Error(
370 $( '<p>' ).msg( 'filename-thumb-name' ),
371 { recoverable: false }
372 );
373 } else if ( warnings[ 'bad-prefix' ] !== undefined ) {
374 return new OO.ui.Error(
375 $( '<p>' ).msg( 'filename-bad-prefix', warnings[ 'bad-prefix' ] ),
376 { recoverable: false }
377 );
378 } else if ( warnings[ 'duplicate-archive' ] !== undefined ) {
379 return new OO.ui.Error(
380 $( '<p>' ).msg( 'api-error-duplicate-archive', 1 ),
381 { recoverable: false }
382 );
383 } else if ( warnings[ 'was-deleted' ] !== undefined ) {
384 return new OO.ui.Error(
385 $( '<p>' ).msg( 'api-error-was-deleted' ),
386 { recoverable: false }
387 );
388 } else if ( warnings.badfilename !== undefined ) {
389 // Change the name if the current name isn't acceptable
390 // TODO This might not really be the best place to do this
391 this.setFilename( warnings.badfilename );
392 return new OO.ui.Error(
393 $( '<p>' ).msg( 'badfilename', warnings.badfilename )
394 );
395 } else {
396 return new OO.ui.Error(
397 // Let's get all the help we can if we can't pin point the error
398 $( '<p>' ).msg( 'api-error-unknown-warning', JSON.stringify( stateDetails ) ),
399 { recoverable: false }
400 );
401 }
402 }
403 };
404
405 /* Form renderers */
406
407 /**
408 * Renders and returns the upload form and sets the
409 * {@link #uploadForm uploadForm} property.
410 *
411 * @protected
412 * @fires selectFile
413 * @return {OO.ui.FormLayout}
414 */
415 mw.Upload.BookletLayout.prototype.renderUploadForm = function () {
416 var fieldset,
417 layout = this;
418
419 this.selectFileWidget = new OO.ui.SelectFileWidget( {
420 showDropTarget: true
421 } );
422 fieldset = new OO.ui.FieldsetLayout();
423 fieldset.addItems( [ this.selectFileWidget ] );
424 this.uploadForm = new OO.ui.FormLayout( { items: [ fieldset ] } );
425
426 // Validation
427 this.selectFileWidget.on( 'change', this.onUploadFormChange.bind( this ) );
428
429 this.selectFileWidget.on( 'change', function () {
430 layout.updateFilePreview();
431 } );
432
433 return this.uploadForm;
434 };
435
436 /**
437 * Updates the file preview on the info form when a file is added.
438 *
439 * @protected
440 */
441 mw.Upload.BookletLayout.prototype.updateFilePreview = function () {
442 this.selectFileWidget.loadAndGetImageUrl().done( function ( url ) {
443 this.filePreview.$element.find( 'p' ).remove();
444 this.filePreview.$element.css( 'background-image', 'url(' + url + ')' );
445 this.infoForm.$element.addClass( 'mw-upload-bookletLayout-hasThumbnail' );
446 }.bind( this ) ).fail( function () {
447 this.filePreview.$element.find( 'p' ).remove();
448 if ( this.selectFileWidget.getValue() ) {
449 this.filePreview.$element.append(
450 $( '<p>' ).text( this.selectFileWidget.getValue().name )
451 );
452 }
453 this.filePreview.$element.css( 'background-image', '' );
454 this.infoForm.$element.removeClass( 'mw-upload-bookletLayout-hasThumbnail' );
455 }.bind( this ) );
456 };
457
458 /**
459 * Handle change events to the upload form
460 *
461 * @protected
462 * @fires uploadValid
463 */
464 mw.Upload.BookletLayout.prototype.onUploadFormChange = function () {
465 this.emit( 'uploadValid', !!this.selectFileWidget.getValue() );
466 };
467
468 /**
469 * Renders and returns the information form for collecting
470 * metadata and sets the {@link #infoForm infoForm}
471 * property.
472 *
473 * @protected
474 * @return {OO.ui.FormLayout}
475 */
476 mw.Upload.BookletLayout.prototype.renderInfoForm = function () {
477 var fieldset;
478
479 this.filePreview = new OO.ui.Widget( {
480 classes: [ 'mw-upload-bookletLayout-filePreview' ]
481 } );
482 this.progressBarWidget = new OO.ui.ProgressBarWidget( {
483 progress: 0
484 } );
485 this.filePreview.$element.append( this.progressBarWidget.$element );
486
487 this.filenameWidget = new OO.ui.TextInputWidget( {
488 indicator: 'required',
489 required: true,
490 validate: /.+/
491 } );
492 this.descriptionWidget = new OO.ui.TextInputWidget( {
493 indicator: 'required',
494 required: true,
495 validate: /\S+/,
496 multiline: true,
497 autosize: true
498 } );
499
500 fieldset = new OO.ui.FieldsetLayout( {
501 label: mw.msg( 'upload-form-label-infoform-title' )
502 } );
503 fieldset.addItems( [
504 new OO.ui.FieldLayout( this.filenameWidget, {
505 label: mw.msg( 'upload-form-label-infoform-name' ),
506 align: 'top',
507 help: mw.msg( 'upload-form-label-infoform-name-tooltip' )
508 } ),
509 new OO.ui.FieldLayout( this.descriptionWidget, {
510 label: mw.msg( 'upload-form-label-infoform-description' ),
511 align: 'top',
512 help: mw.msg( 'upload-form-label-infoform-description-tooltip' )
513 } )
514 ] );
515 this.infoForm = new OO.ui.FormLayout( {
516 classes: [ 'mw-upload-bookletLayout-infoForm' ],
517 items: [ this.filePreview, fieldset ]
518 } );
519
520 this.on( 'fileUploadProgress', function ( progress ) {
521 this.progressBarWidget.setProgress( progress * 100 );
522 }.bind( this ) );
523
524 this.filenameWidget.on( 'change', this.onInfoFormChange.bind( this ) );
525 this.descriptionWidget.on( 'change', this.onInfoFormChange.bind( this ) );
526
527 return this.infoForm;
528 };
529
530 /**
531 * Handle change events to the info form
532 *
533 * @protected
534 * @fires infoValid
535 */
536 mw.Upload.BookletLayout.prototype.onInfoFormChange = function () {
537 var layout = this;
538 $.when(
539 this.filenameWidget.getValidity(),
540 this.descriptionWidget.getValidity()
541 ).done( function () {
542 layout.emit( 'infoValid', true );
543 } ).fail( function () {
544 layout.emit( 'infoValid', false );
545 } );
546 };
547
548 /**
549 * Renders and returns the insert form to show file usage and
550 * sets the {@link #insertForm insertForm} property.
551 *
552 * @protected
553 * @return {OO.ui.FormLayout}
554 */
555 mw.Upload.BookletLayout.prototype.renderInsertForm = function () {
556 var fieldset;
557
558 this.filenameUsageWidget = new OO.ui.TextInputWidget();
559 fieldset = new OO.ui.FieldsetLayout( {
560 label: mw.msg( 'upload-form-label-usage-title' )
561 } );
562 fieldset.addItems( [
563 new OO.ui.FieldLayout( this.filenameUsageWidget, {
564 label: mw.msg( 'upload-form-label-usage-filename' ),
565 align: 'top'
566 } )
567 ] );
568 this.insertForm = new OO.ui.FormLayout( { items: [ fieldset ] } );
569
570 return this.insertForm;
571 };
572
573 /* Getters */
574
575 /**
576 * Gets the file object from the
577 * {@link #uploadForm upload form}.
578 *
579 * @protected
580 * @return {File|null}
581 */
582 mw.Upload.BookletLayout.prototype.getFile = function () {
583 return this.selectFileWidget.getValue();
584 };
585
586 /**
587 * Gets the file name from the
588 * {@link #infoForm information form}.
589 *
590 * @protected
591 * @return {string}
592 */
593 mw.Upload.BookletLayout.prototype.getFilename = function () {
594 var filename = this.filenameWidget.getValue();
595 if ( this.filenameExtension ) {
596 filename += '.' + this.filenameExtension;
597 }
598 return filename;
599 };
600
601 /**
602 * Prefills the {@link #infoForm information form} with the given filename.
603 *
604 * @protected
605 * @param {string} filename
606 */
607 mw.Upload.BookletLayout.prototype.setFilename = function ( filename ) {
608 var title = mw.Title.newFromFileName( filename );
609
610 if ( title ) {
611 this.filenameWidget.setValue( title.getNameText() );
612 this.filenameExtension = mw.Title.normalizeExtension( title.getExtension() );
613 } else {
614 // Seems to happen for files with no extension, which should fail some checks anyway...
615 this.filenameWidget.setValue( filename );
616 this.filenameExtension = null;
617 }
618 };
619
620 /**
621 * Gets the page text from the
622 * {@link #infoForm information form}.
623 *
624 * @protected
625 * @return {string}
626 */
627 mw.Upload.BookletLayout.prototype.getText = function () {
628 return this.descriptionWidget.getValue();
629 };
630
631 /* Setters */
632
633 /**
634 * Sets the file object
635 *
636 * @protected
637 * @param {File|null} file File to select
638 */
639 mw.Upload.BookletLayout.prototype.setFile = function ( file ) {
640 this.selectFileWidget.setValue( file );
641 };
642
643 /**
644 * Clear the values of all fields
645 *
646 * @protected
647 */
648 mw.Upload.BookletLayout.prototype.clear = function () {
649 this.selectFileWidget.setValue( null );
650 this.progressBarWidget.setProgress( 0 );
651 this.filenameWidget.setValue( null ).setValidityFlag( true );
652 this.descriptionWidget.setValue( null ).setValidityFlag( true );
653 this.filenameUsageWidget.setValue( null );
654 };
655
656 }( jQuery, mediaWiki, moment ) );