Merge "Update docs/hooks.txt for ShowSearchHitTitle"
[mediawiki.git] / resources / src / mediawiki / mediawiki.ForeignStructuredUpload.BookletLayout.js
blobf2b6f5f9c3cb2dcd5cb343a47f7276616b44f34b
1 /* global moment, Uint8Array */
2 ( function ( $, mw ) {
4         /**
5          * mw.ForeignStructuredUpload.BookletLayout encapsulates the process
6          * of uploading a file to MediaWiki using the mw.ForeignStructuredUpload model.
7          *
8          *     var uploadDialog = new mw.Upload.Dialog( {
9          *         bookletClass: mw.ForeignStructuredUpload.BookletLayout,
10          *         booklet: {
11          *             target: 'local'
12          *         }
13          *     } );
14          *     var windowManager = new OO.ui.WindowManager();
15          *     $( 'body' ).append( windowManager.$element );
16          *     windowManager.addWindows( [ uploadDialog ] );
17          *
18          * @class mw.ForeignStructuredUpload.BookletLayout
19          * @uses mw.ForeignStructuredUpload
20          * @extends mw.Upload.BookletLayout
21          *
22          * @constructor
23          * @param {Object} config Configuration options
24          * @cfg {string} [target] Used to choose the target repository.
25          *     If nothing is passed, the {@link mw.ForeignUpload#property-target default} is used.
26          */
27         mw.ForeignStructuredUpload.BookletLayout = function ( config ) {
28                 config = config || {};
29                 // Parent constructor
30                 mw.ForeignStructuredUpload.BookletLayout.parent.call( this, config );
32                 this.target = config.target;
33         };
35         /* Setup */
37         OO.inheritClass( mw.ForeignStructuredUpload.BookletLayout, mw.Upload.BookletLayout );
39         /* Uploading */
41         /**
42          * @inheritdoc
43          */
44         mw.ForeignStructuredUpload.BookletLayout.prototype.initialize = function () {
45                 var booklet = this;
46                 return mw.ForeignStructuredUpload.BookletLayout.parent.prototype.initialize.call( this ).then(
47                         function () {
48                                 return $.when(
49                                         // Point the CategorySelector to the right wiki
50                                         booklet.upload.getApi().then( function ( api ) {
51                                                 // If this is a ForeignApi, it will have a apiUrl, otherwise we don't need to do anything
52                                                 if ( api.apiUrl ) {
53                                                         // Can't reuse the same object, CategorySelector calls #abort on its mw.Api instance
54                                                         booklet.categoriesWidget.api = new mw.ForeignApi( api.apiUrl );
55                                                 }
56                                                 return $.Deferred().resolve();
57                                         } ),
58                                         // Set up booklet fields and license messages to match configuration
59                                         booklet.upload.loadConfig().then( function ( config ) {
60                                                 var
61                                                         msgPromise,
62                                                         isLocal = booklet.upload.target === 'local',
63                                                         fields = config.fields,
64                                                         msgs = config.licensemessages[ isLocal ? 'local' : 'foreign' ];
66                                                 // Hide disabled fields
67                                                 booklet.descriptionField.toggle( !!fields.description );
68                                                 booklet.categoriesField.toggle( !!fields.categories );
69                                                 booklet.dateField.toggle( !!fields.date );
70                                                 // Update form validity
71                                                 booklet.onInfoFormChange();
73                                                 // Load license messages from the remote wiki if we don't have these messages locally
74                                                 // (this means that we only load messages from the foreign wiki for custom config)
75                                                 if ( mw.message( 'upload-form-label-own-work-message-' + msgs ).exists() ) {
76                                                         msgPromise = $.Deferred().resolve();
77                                                 } else {
78                                                         msgPromise = booklet.upload.apiPromise.then( function ( api ) {
79                                                                 return api.loadMessages( [
80                                                                         'upload-form-label-own-work-message-' + msgs,
81                                                                         'upload-form-label-not-own-work-message-' + msgs,
82                                                                         'upload-form-label-not-own-work-local-' + msgs
83                                                                 ] );
84                                                         } );
85                                                 }
87                                                 // Update license messages
88                                                 return msgPromise.then( function () {
89                                                         var $labels;
90                                                         booklet.$ownWorkMessage.msg( 'upload-form-label-own-work-message-' + msgs );
91                                                         booklet.$notOwnWorkMessage.msg( 'upload-form-label-not-own-work-message-' + msgs );
92                                                         booklet.$notOwnWorkLocal.msg( 'upload-form-label-not-own-work-local-' + msgs );
94                                                         $labels = $( [
95                                                                 booklet.$ownWorkMessage[ 0 ],
96                                                                 booklet.$notOwnWorkMessage[ 0 ],
97                                                                 booklet.$notOwnWorkLocal[ 0 ]
98                                                         ] );
100                                                         // Improve the behavior of links inside these labels, which may point to important
101                                                         // things like licensing requirements or terms of use
102                                                         $labels.find( 'a' )
103                                                                 .attr( 'target', '_blank' )
104                                                                 .on( 'click', function ( e ) {
105                                                                         // OO.ui.FieldLayout#onLabelClick is trying to prevent default on all clicks,
106                                                                         // which causes the links to not be openable. Don't let it do that.
107                                                                         e.stopPropagation();
108                                                                 } );
109                                                 } );
110                                         }, function ( errorMsg ) {
111                                                 booklet.getPage( 'upload' ).$element.msg( errorMsg );
112                                                 return $.Deferred().resolve();
113                                         } )
114                                 );
115                         }
116                 ).then(
117                         null,
118                         // Always resolve, never reject
119                         function () { return $.Deferred().resolve(); }
120                 );
121         };
123         /**
124          * Returns a {@link mw.ForeignStructuredUpload mw.ForeignStructuredUpload}
125          * with the {@link #cfg-target target} specified in config.
126          *
127          * @protected
128          * @return {mw.Upload}
129          */
130         mw.ForeignStructuredUpload.BookletLayout.prototype.createUpload = function () {
131                 return new mw.ForeignStructuredUpload( this.target, {
132                         parameters: {
133                                 errorformat: 'html',
134                                 errorlang: mw.config.get( 'wgUserLanguage' ),
135                                 errorsuselocal: 1,
136                                 formatversion: 2
137                         }
138                 } );
139         };
141         /* Form renderers */
143         /**
144          * @inheritdoc
145          */
146         mw.ForeignStructuredUpload.BookletLayout.prototype.renderUploadForm = function () {
147                 var fieldset,
148                         layout = this;
150                 // These elements are filled with text in #initialize
151                 // TODO Refactor this to be in one place
152                 this.$ownWorkMessage = $( '<p>' )
153                         .addClass( 'mw-foreignStructuredUpload-bookletLayout-license' );
154                 this.$notOwnWorkMessage = $( '<p>' );
155                 this.$notOwnWorkLocal = $( '<p>' );
157                 this.selectFileWidget = new OO.ui.SelectFileWidget( {
158                         showDropTarget: true
159                 } );
160                 this.messageLabel = new OO.ui.LabelWidget( {
161                         label: $( '<div>' ).append(
162                                 this.$notOwnWorkMessage,
163                                 this.$notOwnWorkLocal
164                         )
165                 } );
166                 this.ownWorkCheckbox = new OO.ui.CheckboxInputWidget().on( 'change', function ( on ) {
167                         layout.messageLabel.toggle( !on );
168                 } );
170                 fieldset = new OO.ui.FieldsetLayout();
171                 fieldset.addItems( [
172                         new OO.ui.FieldLayout( this.selectFileWidget, {
173                                 align: 'top'
174                         } ),
175                         new OO.ui.FieldLayout( this.ownWorkCheckbox, {
176                                 align: 'inline',
177                                 label: $( '<div>' ).append(
178                                         $( '<p>' ).text( mw.msg( 'upload-form-label-own-work' ) ),
179                                         this.$ownWorkMessage
180                                 )
181                         } ),
182                         new OO.ui.FieldLayout( this.messageLabel, {
183                                 align: 'top'
184                         } )
185                 ] );
186                 this.uploadForm = new OO.ui.FormLayout( { items: [ fieldset ] } );
188                 // Validation
189                 this.selectFileWidget.on( 'change', this.onUploadFormChange.bind( this ) );
190                 this.ownWorkCheckbox.on( 'change', this.onUploadFormChange.bind( this ) );
192                 this.selectFileWidget.on( 'change', function () {
193                         var file = layout.getFile();
195                         // Set the date to lastModified once we have the file
196                         if ( layout.getDateFromLastModified( file ) !== undefined ) {
197                                 layout.dateWidget.setValue( layout.getDateFromLastModified( file ) );
198                         }
200                         // Check if we have EXIF data and set to that where available
201                         layout.getDateFromExif( file ).done( function ( date ) {
202                                 layout.dateWidget.setValue( date );
203                         } );
205                         layout.updateFilePreview();
206                 } );
208                 return this.uploadForm;
209         };
211         /**
212          * @inheritdoc
213          */
214         mw.ForeignStructuredUpload.BookletLayout.prototype.onUploadFormChange = function () {
215                 var file = this.selectFileWidget.getValue(),
216                         ownWork = this.ownWorkCheckbox.isSelected(),
217                         valid = !!file && ownWork;
218                 this.emit( 'uploadValid', valid );
219         };
221         /**
222          * @inheritdoc
223          */
224         mw.ForeignStructuredUpload.BookletLayout.prototype.renderInfoForm = function () {
225                 var fieldset;
227                 this.filePreview = new OO.ui.Widget( {
228                         classes: [ 'mw-upload-bookletLayout-filePreview' ]
229                 } );
230                 this.progressBarWidget = new OO.ui.ProgressBarWidget( {
231                         progress: 0
232                 } );
233                 this.filePreview.$element.append( this.progressBarWidget.$element );
235                 this.filenameWidget = new OO.ui.TextInputWidget( {
236                         required: true,
237                         validate: /.+/
238                 } );
239                 this.descriptionWidget = new OO.ui.TextInputWidget( {
240                         required: true,
241                         validate: /\S+/,
242                         multiline: true,
243                         autosize: true
244                 } );
245                 this.categoriesWidget = new mw.widgets.CategorySelector( {
246                         // Can't be done here because we don't know the target wiki yet... done in #initialize.
247                         // api: new mw.ForeignApi( ... ),
248                         $overlay: this.$overlay
249                 } );
250                 this.dateWidget = new mw.widgets.DateInputWidget( {
251                         $overlay: this.$overlay,
252                         required: true,
253                         mustBeBefore: moment().add( 1, 'day' ).locale( 'en' ).format( 'YYYY-MM-DD' ) // Tomorrow
254                 } );
256                 this.filenameField = new OO.ui.FieldLayout( this.filenameWidget, {
257                         label: mw.msg( 'upload-form-label-infoform-name' ),
258                         align: 'top',
259                         classes: [ 'mw-foreignStructuredUploa-bookletLayout-small-notice' ],
260                         notices: [ mw.msg( 'upload-form-label-infoform-name-tooltip' ) ]
261                 } );
262                 this.descriptionField = new OO.ui.FieldLayout( this.descriptionWidget, {
263                         label: mw.msg( 'upload-form-label-infoform-description' ),
264                         align: 'top',
265                         classes: [ 'mw-foreignStructuredUploa-bookletLayout-small-notice' ],
266                         notices: [ mw.msg( 'upload-form-label-infoform-description-tooltip' ) ]
267                 } );
268                 this.categoriesField = new OO.ui.FieldLayout( this.categoriesWidget, {
269                         label: mw.msg( 'upload-form-label-infoform-categories' ),
270                         align: 'top'
271                 } );
272                 this.dateField = new OO.ui.FieldLayout( this.dateWidget, {
273                         label: mw.msg( 'upload-form-label-infoform-date' ),
274                         align: 'top'
275                 } );
277                 fieldset = new OO.ui.FieldsetLayout( {
278                         label: mw.msg( 'upload-form-label-infoform-title' )
279                 } );
280                 fieldset.addItems( [
281                         this.filenameField,
282                         this.descriptionField,
283                         this.categoriesField,
284                         this.dateField
285                 ] );
286                 this.infoForm = new OO.ui.FormLayout( {
287                         classes: [ 'mw-upload-bookletLayout-infoForm' ],
288                         items: [ this.filePreview, fieldset ]
289                 } );
291                 // Validation
292                 this.filenameWidget.on( 'change', this.onInfoFormChange.bind( this ) );
293                 this.descriptionWidget.on( 'change', this.onInfoFormChange.bind( this ) );
294                 this.dateWidget.on( 'change', this.onInfoFormChange.bind( this ) );
296                 this.on( 'fileUploadProgress', function ( progress ) {
297                         this.progressBarWidget.setProgress( progress * 100 );
298                 }.bind( this ) );
300                 return this.infoForm;
301         };
303         /**
304          * @inheritdoc
305          */
306         mw.ForeignStructuredUpload.BookletLayout.prototype.onInfoFormChange = function () {
307                 var layout = this,
308                         validityPromises = [];
310                 validityPromises.push( this.filenameWidget.getValidity() );
311                 if ( this.descriptionField.isVisible() ) {
312                         validityPromises.push( this.descriptionWidget.getValidity() );
313                 }
314                 if ( this.dateField.isVisible() ) {
315                         validityPromises.push( this.dateWidget.getValidity() );
316                 }
318                 $.when.apply( $, validityPromises ).done( function () {
319                         layout.emit( 'infoValid', true );
320                 } ).fail( function () {
321                         layout.emit( 'infoValid', false );
322                 } );
323         };
325         /**
326          * @param {mw.Title} filename
327          * @return {jQuery.Promise} Resolves (on success) or rejects with OO.ui.Error
328          */
329         mw.ForeignStructuredUpload.BookletLayout.prototype.validateFilename = function ( filename ) {
330                 return ( new mw.Api() ).get( {
331                         action: 'query',
332                         prop: 'info',
333                         titles: filename.getPrefixedDb(),
334                         formatversion: 2
335                 } ).then(
336                         function ( result ) {
337                                 // if the file already exists, reject right away, before
338                                 // ever firing finishStashUpload()
339                                 if ( !result.query.pages[ 0 ].missing ) {
340                                         return $.Deferred().reject( new OO.ui.Error(
341                                                 $( '<p>' ).msg( 'fileexists', filename.getPrefixedDb() ),
342                                                 { recoverable: false }
343                                         ) );
344                                 }
345                         },
346                         function () {
347                                 // API call failed - this could be a connection hiccup...
348                                 // Let's just ignore this validation step and turn this
349                                 // failure into a successful resolve ;)
350                                 return $.Deferred().resolve();
351                         }
352                 );
353         };
355         /**
356          * @inheritdoc
357          */
358         mw.ForeignStructuredUpload.BookletLayout.prototype.saveFile = function () {
359                 var title = mw.Title.newFromText(
360                                 this.getFilename(),
361                                 mw.config.get( 'wgNamespaceIds' ).file
362                         );
364                 return this.uploadPromise
365                         .then( this.validateFilename.bind( this, title ) )
366                         .then( mw.ForeignStructuredUpload.BookletLayout.parent.prototype.saveFile.bind( this ) );
367         };
369         /* Getters */
371         /**
372          * @inheritdoc
373          */
374         mw.ForeignStructuredUpload.BookletLayout.prototype.getText = function () {
375                 var language = mw.config.get( 'wgContentLanguage' );
376                 this.upload.clearDescriptions();
377                 this.upload.addDescription( language, this.descriptionWidget.getValue() );
378                 this.upload.setDate( this.dateWidget.getValue() );
379                 this.upload.clearCategories();
380                 this.upload.addCategories( this.categoriesWidget.getItemsData() );
381                 return this.upload.getText();
382         };
384         /**
385          * Get original date from EXIF data
386          *
387          * @param {Object} file
388          * @return {jQuery.Promise} Promise resolved with the EXIF date
389          */
390         mw.ForeignStructuredUpload.BookletLayout.prototype.getDateFromExif = function ( file ) {
391                 var fileReader,
392                         deferred = $.Deferred();
394                 if ( file && file.type === 'image/jpeg' ) {
395                         fileReader = new FileReader();
396                         fileReader.onload = function () {
397                                 var fileStr, arr, i, metadata;
399                                 if ( typeof fileReader.result === 'string' ) {
400                                         fileStr = fileReader.result;
401                                 } else {
402                                         // Array buffer; convert to binary string for the library.
403                                         arr = new Uint8Array( fileReader.result );
404                                         fileStr = '';
405                                         for ( i = 0; i < arr.byteLength; i++ ) {
406                                                 fileStr += String.fromCharCode( arr[ i ] );
407                                         }
408                                 }
410                                 try {
411                                         metadata = mw.libs.jpegmeta( fileStr, file.name );
412                                 } catch ( e ) {
413                                         metadata = null;
414                                 }
416                                 if ( metadata !== null && metadata.exif !== undefined && metadata.exif.DateTimeOriginal ) {
417                                         deferred.resolve( moment( metadata.exif.DateTimeOriginal, 'YYYY:MM:DD' ).format( 'YYYY-MM-DD' ) );
418                                 } else {
419                                         deferred.reject();
420                                 }
421                         };
423                         if ( 'readAsBinaryString' in fileReader ) {
424                                 fileReader.readAsBinaryString( file );
425                         } else if ( 'readAsArrayBuffer' in fileReader ) {
426                                 fileReader.readAsArrayBuffer( file );
427                         } else {
428                                 // We should never get here
429                                 deferred.reject();
430                                 throw new Error( 'Cannot read thumbnail as binary string or array buffer.' );
431                         }
432                 }
434                 return deferred.promise();
435         };
437         /**
438          * Get last modified date from file
439          *
440          * @param {Object} file
441          * @return {Object} Last modified date from file
442          */
443         mw.ForeignStructuredUpload.BookletLayout.prototype.getDateFromLastModified = function ( file ) {
444                 if ( file && file.lastModified ) {
445                         return moment( file.lastModified ).format( 'YYYY-MM-DD' );
446                 }
447         };
449         /* Setters */
451         /**
452          * @inheritdoc
453          */
454         mw.ForeignStructuredUpload.BookletLayout.prototype.clear = function () {
455                 mw.ForeignStructuredUpload.BookletLayout.parent.prototype.clear.call( this );
457                 this.ownWorkCheckbox.setSelected( false );
458                 this.categoriesWidget.setItemsFromData( [] );
459                 this.dateWidget.setValue( '' ).setValidityFlag( true );
460         };
462 }( jQuery, mediaWiki ) );