Merge "Replace Linker::link() with LinkRenderer in some special pages"
[lhc/web/wiklou.git] / resources / src / mediawiki / mediawiki.ForeignStructuredUpload.BookletLayout.js
1 /* global moment, Uint8Array */
2 ( function ( $, mw ) {
3
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 );
31
32 this.target = config.target;
33 };
34
35 /* Setup */
36
37 OO.inheritClass( mw.ForeignStructuredUpload.BookletLayout, mw.Upload.BookletLayout );
38
39 /* Uploading */
40
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' ];
65
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();
72
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 }
86
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 );
93
94 $labels = $( [
95 booklet.$ownWorkMessage[ 0 ],
96 booklet.$notOwnWorkMessage[ 0 ],
97 booklet.$notOwnWorkLocal[ 0 ]
98 ] );
99
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 } )
111 );
112 }
113 ).then(
114 null,
115 // Always resolve, never reject
116 function () { return $.Deferred().resolve(); }
117 );
118 };
119
120 /**
121 * Returns a {@link mw.ForeignStructuredUpload mw.ForeignStructuredUpload}
122 * with the {@link #cfg-target target} specified in config.
123 *
124 * @protected
125 * @return {mw.Upload}
126 */
127 mw.ForeignStructuredUpload.BookletLayout.prototype.createUpload = function () {
128 return new mw.ForeignStructuredUpload( this.target );
129 };
130
131 /* Form renderers */
132
133 /**
134 * @inheritdoc
135 */
136 mw.ForeignStructuredUpload.BookletLayout.prototype.renderUploadForm = function () {
137 var fieldset,
138 layout = this;
139
140 // These elements are filled with text in #initialize
141 // TODO Refactor this to be in one place
142 this.$ownWorkMessage = $( '<p>' )
143 .addClass( 'mw-foreignStructuredUpload-bookletLayout-license' );
144 this.$notOwnWorkMessage = $( '<p>' );
145 this.$notOwnWorkLocal = $( '<p>' );
146
147 this.selectFileWidget = new OO.ui.SelectFileWidget( {
148 showDropTarget: true
149 } );
150 this.messageLabel = new OO.ui.LabelWidget( {
151 label: $( '<div>' ).append(
152 this.$notOwnWorkMessage,
153 this.$notOwnWorkLocal
154 )
155 } );
156 this.ownWorkCheckbox = new OO.ui.CheckboxInputWidget().on( 'change', function ( on ) {
157 layout.messageLabel.toggle( !on );
158 } );
159
160 fieldset = new OO.ui.FieldsetLayout();
161 fieldset.addItems( [
162 new OO.ui.FieldLayout( this.selectFileWidget, {
163 align: 'top'
164 } ),
165 new OO.ui.FieldLayout( this.ownWorkCheckbox, {
166 align: 'inline',
167 label: $( '<div>' ).append(
168 $( '<p>' ).text( mw.msg( 'upload-form-label-own-work' ) ),
169 this.$ownWorkMessage
170 )
171 } ),
172 new OO.ui.FieldLayout( this.messageLabel, {
173 align: 'top'
174 } )
175 ] );
176 this.uploadForm = new OO.ui.FormLayout( { items: [ fieldset ] } );
177
178 // Validation
179 this.selectFileWidget.on( 'change', this.onUploadFormChange.bind( this ) );
180 this.ownWorkCheckbox.on( 'change', this.onUploadFormChange.bind( this ) );
181
182 this.selectFileWidget.on( 'change', function () {
183 var file = layout.getFile();
184
185 // Set the date to lastModified once we have the file
186 if ( layout.getDateFromLastModified( file ) !== undefined ) {
187 layout.dateWidget.setValue( layout.getDateFromLastModified( file ) );
188 }
189
190 // Check if we have EXIF data and set to that where available
191 layout.getDateFromExif( file ).done( function ( date ) {
192 layout.dateWidget.setValue( date );
193 } );
194
195 layout.updateFilePreview();
196 } );
197
198 return this.uploadForm;
199 };
200
201 /**
202 * @inheritdoc
203 */
204 mw.ForeignStructuredUpload.BookletLayout.prototype.onUploadFormChange = function () {
205 var file = this.selectFileWidget.getValue(),
206 ownWork = this.ownWorkCheckbox.isSelected(),
207 valid = !!file && ownWork;
208 this.emit( 'uploadValid', valid );
209 };
210
211 /**
212 * @inheritdoc
213 */
214 mw.ForeignStructuredUpload.BookletLayout.prototype.renderInfoForm = function () {
215 var fieldset;
216
217 this.filePreview = new OO.ui.Widget( {
218 classes: [ 'mw-upload-bookletLayout-filePreview' ]
219 } );
220 this.progressBarWidget = new OO.ui.ProgressBarWidget( {
221 progress: 0
222 } );
223 this.filePreview.$element.append( this.progressBarWidget.$element );
224
225 this.filenameWidget = new OO.ui.TextInputWidget( {
226 required: true,
227 validate: /.+/
228 } );
229 this.descriptionWidget = new OO.ui.TextInputWidget( {
230 required: true,
231 validate: /\S+/,
232 multiline: true,
233 autosize: true
234 } );
235 this.categoriesWidget = new mw.widgets.CategorySelector( {
236 // Can't be done here because we don't know the target wiki yet... done in #initialize.
237 // api: new mw.ForeignApi( ... ),
238 $overlay: this.$overlay
239 } );
240 this.dateWidget = new mw.widgets.DateInputWidget( {
241 $overlay: this.$overlay,
242 required: true,
243 mustBeBefore: moment().add( 1, 'day' ).locale( 'en' ).format( 'YYYY-MM-DD' ) // Tomorrow
244 } );
245
246 this.filenameField = new OO.ui.FieldLayout( this.filenameWidget, {
247 label: mw.msg( 'upload-form-label-infoform-name' ),
248 align: 'top',
249 classes: [ 'mw-foreignStructuredUploa-bookletLayout-small-notice' ],
250 notices: [ mw.msg( 'upload-form-label-infoform-name-tooltip' ) ]
251 } );
252 this.descriptionField = new OO.ui.FieldLayout( this.descriptionWidget, {
253 label: mw.msg( 'upload-form-label-infoform-description' ),
254 align: 'top',
255 classes: [ 'mw-foreignStructuredUploa-bookletLayout-small-notice' ],
256 notices: [ mw.msg( 'upload-form-label-infoform-description-tooltip' ) ]
257 } );
258 this.categoriesField = new OO.ui.FieldLayout( this.categoriesWidget, {
259 label: mw.msg( 'upload-form-label-infoform-categories' ),
260 align: 'top'
261 } );
262 this.dateField = new OO.ui.FieldLayout( this.dateWidget, {
263 label: mw.msg( 'upload-form-label-infoform-date' ),
264 align: 'top'
265 } );
266
267 fieldset = new OO.ui.FieldsetLayout( {
268 label: mw.msg( 'upload-form-label-infoform-title' )
269 } );
270 fieldset.addItems( [
271 this.filenameField,
272 this.descriptionField,
273 this.categoriesField,
274 this.dateField
275 ] );
276 this.infoForm = new OO.ui.FormLayout( {
277 classes: [ 'mw-upload-bookletLayout-infoForm' ],
278 items: [ this.filePreview, fieldset ]
279 } );
280
281 // Validation
282 this.filenameWidget.on( 'change', this.onInfoFormChange.bind( this ) );
283 this.descriptionWidget.on( 'change', this.onInfoFormChange.bind( this ) );
284 this.dateWidget.on( 'change', this.onInfoFormChange.bind( this ) );
285
286 this.on( 'fileUploadProgress', function ( progress ) {
287 this.progressBarWidget.setProgress( progress * 100 );
288 }.bind( this ) );
289
290 return this.infoForm;
291 };
292
293 /**
294 * @inheritdoc
295 */
296 mw.ForeignStructuredUpload.BookletLayout.prototype.onInfoFormChange = function () {
297 var layout = this,
298 validityPromises = [];
299
300 validityPromises.push( this.filenameWidget.getValidity() );
301 if ( this.descriptionField.isVisible() ) {
302 validityPromises.push( this.descriptionWidget.getValidity() );
303 }
304 if ( this.dateField.isVisible() ) {
305 validityPromises.push( this.dateWidget.getValidity() );
306 }
307
308 $.when.apply( $, validityPromises ).done( function () {
309 layout.emit( 'infoValid', true );
310 } ).fail( function () {
311 layout.emit( 'infoValid', false );
312 } );
313 };
314
315 /**
316 * @param {mw.Title} filename
317 * @return {jQuery.Promise} Resolves (on success) or rejects with OO.ui.Error
318 */
319 mw.ForeignStructuredUpload.BookletLayout.prototype.validateFilename = function ( filename ) {
320 return ( new mw.Api() ).get( {
321 action: 'query',
322 prop: 'info',
323 titles: filename.getPrefixedDb(),
324 formatversion: 2
325 } ).then(
326 function ( result ) {
327 // if the file already exists, reject right away, before
328 // ever firing finishStashUpload()
329 if ( !result.query.pages[ 0 ].missing ) {
330 return $.Deferred().reject( new OO.ui.Error(
331 $( '<p>' ).msg( 'fileexists', filename.getPrefixedDb() ),
332 { recoverable: false }
333 ) );
334 }
335 },
336 function () {
337 // API call failed - this could be a connection hiccup...
338 // Let's just ignore this validation step and turn this
339 // failure into a successful resolve ;)
340 return $.Deferred().resolve();
341 }
342 );
343 };
344
345 /**
346 * @inheritdoc
347 */
348 mw.ForeignStructuredUpload.BookletLayout.prototype.saveFile = function () {
349 var title = mw.Title.newFromText(
350 this.getFilename(),
351 mw.config.get( 'wgNamespaceIds' ).file
352 );
353
354 return this.uploadPromise
355 .then( this.validateFilename.bind( this, title ) )
356 .then( mw.ForeignStructuredUpload.BookletLayout.parent.prototype.saveFile.bind( this ) );
357 };
358
359 /* Getters */
360
361 /**
362 * @inheritdoc
363 */
364 mw.ForeignStructuredUpload.BookletLayout.prototype.getText = function () {
365 var language = mw.config.get( 'wgContentLanguage' );
366 this.upload.clearDescriptions();
367 this.upload.addDescription( language, this.descriptionWidget.getValue() );
368 this.upload.setDate( this.dateWidget.getValue() );
369 this.upload.clearCategories();
370 this.upload.addCategories( this.categoriesWidget.getItemsData() );
371 return this.upload.getText();
372 };
373
374 /**
375 * Get original date from EXIF data
376 *
377 * @param {Object} file
378 * @return {jQuery.Promise} Promise resolved with the EXIF date
379 */
380 mw.ForeignStructuredUpload.BookletLayout.prototype.getDateFromExif = function ( file ) {
381 var fileReader,
382 deferred = $.Deferred();
383
384 if ( file && file.type === 'image/jpeg' ) {
385 fileReader = new FileReader();
386 fileReader.onload = function () {
387 var fileStr, arr, i, metadata;
388
389 if ( typeof fileReader.result === 'string' ) {
390 fileStr = fileReader.result;
391 } else {
392 // Array buffer; convert to binary string for the library.
393 arr = new Uint8Array( fileReader.result );
394 fileStr = '';
395 for ( i = 0; i < arr.byteLength; i++ ) {
396 fileStr += String.fromCharCode( arr[ i ] );
397 }
398 }
399
400 try {
401 metadata = mw.libs.jpegmeta( fileStr, file.name );
402 } catch ( e ) {
403 metadata = null;
404 }
405
406 if ( metadata !== null && metadata.exif !== undefined && metadata.exif.DateTimeOriginal ) {
407 deferred.resolve( moment( metadata.exif.DateTimeOriginal, 'YYYY:MM:DD' ).format( 'YYYY-MM-DD' ) );
408 } else {
409 deferred.reject();
410 }
411 };
412
413 if ( 'readAsBinaryString' in fileReader ) {
414 fileReader.readAsBinaryString( file );
415 } else if ( 'readAsArrayBuffer' in fileReader ) {
416 fileReader.readAsArrayBuffer( file );
417 } else {
418 // We should never get here
419 deferred.reject();
420 throw new Error( 'Cannot read thumbnail as binary string or array buffer.' );
421 }
422 }
423
424 return deferred.promise();
425 };
426
427 /**
428 * Get last modified date from file
429 *
430 * @param {Object} file
431 * @return {Object} Last modified date from file
432 */
433 mw.ForeignStructuredUpload.BookletLayout.prototype.getDateFromLastModified = function ( file ) {
434 if ( file && file.lastModified ) {
435 return moment( file.lastModified ).format( 'YYYY-MM-DD' );
436 }
437 };
438
439 /* Setters */
440
441 /**
442 * @inheritdoc
443 */
444 mw.ForeignStructuredUpload.BookletLayout.prototype.clear = function () {
445 mw.ForeignStructuredUpload.BookletLayout.parent.prototype.clear.call( this );
446
447 this.ownWorkCheckbox.setSelected( false );
448 this.categoriesWidget.setItemsFromData( [] );
449 this.dateWidget.setValue( '' ).setValidityFlag( true );
450 };
451
452 }( jQuery, mediaWiki ) );