MDL-68890 progressbar: prevent display exist file's progress bar
[moodle.git] / lib / form / dndupload.js
CommitLineData
f08fac7c
DS
1// This file is part of Moodle - http://moodle.org/
2//
3// Moodle is free software: you can redistribute it and/or modify
4// it under the terms of the GNU General Public License as published by
5// the Free Software Foundation, either version 3 of the License, or
6// (at your option) any later version.
7//
8// Moodle is distributed in the hope that it will be useful,
9// but WITHOUT ANY WARRANTY; without even the implied warranty of
10// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11// GNU General Public License for more details.
12//
13// You should have received a copy of the GNU General Public License
14// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
15
16/**
17 * Javascript library for enableing a drag and drop upload interface
18 *
19 * @package moodlecore
20 * @subpackage form
21 * @copyright 2011 Davo Smith
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24
6d9121d3
DS
25M.form_dndupload = {}
26
27M.form_dndupload.init = function(Y, options) {
28 var dnduploadhelper = {
29 // YUI object.
30 Y: null,
31 // URL for upload requests
32 url: M.cfg.wwwroot + '/repository/repository_ajax.php?action=upload',
7b22e2ab 33 // options may include: itemid, acceptedtypes, maxfiles, maxbytes, clientid, repositoryid, author, contextid
52474d74 34 options: {},
6d9121d3
DS
35 // itemid used for repository upload
36 itemid: null,
37 // accepted filetypes accepted by this form passed to repository
38 acceptedtypes: [],
6d9121d3
DS
39 // maximum size of files allowed in this form
40 maxbytes: 0,
68acd115
FM
41 // Maximum combined size of files allowed in this form. {@link FILE_AREA_MAX_BYTES_UNLIMITED}
42 areamaxbytes: -1,
6d9121d3
DS
43 // unqiue id of this form field used for html elements
44 clientid: '',
45 // upload repository id, used for upload
46 repositoryid: 0,
47 // container which holds the node which recieves drag events
48 container: null,
49 // filemanager element we are working with
50 filemanager: null,
51 // callback to filepicker element to refesh when uploaded
52 callback: null,
53 // Nasty hack to distinguish between dragenter(first entry),
54 // dragenter+dragleave(moving between child elements) and dragleave (leaving element)
55 entercount: 0,
7d44996c 56 pageentercount: 0,
ead25632
DS
57 // Holds the progress bar elements for each file.
58 progressbars: {},
6d9121d3
DS
59
60 /**
61 * Initalise the drag and drop upload interface
62 * Note: one and only one of options.filemanager and options.formcallback must be defined
63 *
64 * @param Y the YUI object
65 * @param object options {
66 * itemid: itemid used for repository upload in this form
67 * acceptdtypes: accepted filetypes by this form
68 * maxfiles: maximum number of files this form allows
69 * maxbytes: maximum size of files allowed in this form
21e3ea77 70 * areamaxbytes: maximum combined size of files allowed in this form
6d9121d3 71 * clientid: unqiue id of this form field used for html elements
7b22e2ab 72 * contextid: id of the current cotnext
906e7d89 73 * containerid: htmlid of container
6d9121d3
DS
74 * repositories: array of repository objects passed from filepicker
75 * filemanager: filemanager element we are working with
906e7d89 76 * formcallback: callback to filepicker element to refesh when uploaded
6d9121d3
DS
77 * }
78 */
79 init: function(Y, options) {
80 this.Y = Y;
81
82 if (!this.browser_supported()) {
906e7d89 83 Y.one('body').addClass('dndnotsupported');
6d9121d3 84 return; // Browser does not support the required functionality
6b37c2b0 85 }
f08fac7c 86
6d9121d3
DS
87 // try and retrieve enabled upload repository
88 this.repositoryid = this.get_upload_repositoryid(options.repositories);
f08fac7c 89
6d9121d3 90 if (!this.repositoryid) {
588ff74f 91 Y.one('body').addClass('dndnotsupported');
6d9121d3
DS
92 return; // no upload repository is enabled to upload to
93 }
f08fac7c 94
588ff74f
MG
95 Y.one('body').addClass('dndsupported');
96
52474d74 97 this.options = options;
6d9121d3
DS
98 this.acceptedtypes = options.acceptedtypes;
99 this.clientid = options.clientid;
6d9121d3 100 this.maxbytes = options.maxbytes;
21e3ea77 101 this.areamaxbytes = options.areamaxbytes;
6d9121d3 102 this.itemid = options.itemid;
140669a9 103 this.author = options.author;
906e7d89 104 this.container = this.Y.one('#'+options.containerid);
6d9121d3
DS
105
106 if (options.filemanager) {
107 // Needed to tell the filemanager to redraw when files uploaded
108 // and to check how many files are already uploaded
109 this.filemanager = options.filemanager;
110 } else if (options.formcallback) {
111
112 // Needed to tell the filepicker to update when a new
113 // file is uploaded
114 this.callback = options.formcallback;
115 } else {
116 if (M.cfg.developerdebug) {
906e7d89 117 alert('dndupload: Need to define either options.filemanager or options.formcallback');
6d9121d3
DS
118 }
119 return;
120 }
910e1ecd 121
6d9121d3 122 this.init_events();
7d44996c 123 this.init_page_events();
6d9121d3 124 },
f08fac7c 125
6d9121d3
DS
126 /**
127 * Check the browser has the required functionality
128 * @return true if browser supports drag/drop upload
129 */
130 browser_supported: function() {
f08fac7c 131
6d9121d3
DS
132 if (typeof FileReader == 'undefined') {
133 return false;
134 }
135 if (typeof FormData == 'undefined') {
136 return false;
137 }
f08fac7c 138 return true;
6d9121d3
DS
139 },
140
141 /**
142 * Get upload repoistory from array of enabled repositories
143 *
144 * @param array repositories repository objects passed from filepicker
145 * @param returns int id of upload repository or false if not found
146 */
147 get_upload_repositoryid: function(repositories) {
148 for (var i in repositories) {
149 if (repositories[i].type == "upload") {
150 return repositories[i].id;
151 }
152 }
f08fac7c 153
f08fac7c 154 return false;
6d9121d3
DS
155 },
156
157 /**
158 * Initialise drag events on node container, all events need
159 * to be processed for drag and drop to work
160 */
161 init_events: function() {
162 this.Y.on('dragenter', this.drag_enter, this.container, this);
163 this.Y.on('dragleave', this.drag_leave, this.container, this);
164 this.Y.on('dragover', this.drag_over, this.container, this);
165 this.Y.on('drop', this.drop, this.container, this);
166 },
167
7d44996c
DS
168 /**
169 * Initialise whole-page events (to show / hide the 'drop files here'
170 * message)
171 */
172 init_page_events: function() {
173 this.Y.on('dragenter', this.drag_enter_page, 'body', this);
174 this.Y.on('dragleave', this.drag_leave_page, 'body', this);
175 },
176
b1c669a7
DS
177 /**
178 * Check if the filemanager / filepicker is disabled
179 * @return bool - true if disabled
180 */
181 is_disabled: function() {
c81f3328 182 return (this.container.ancestor('.fitem.disabled') != null);
b1c669a7
DS
183 },
184
7d44996c
DS
185 /**
186 * Show the 'drop files here' message when file(s) are dragged
187 * onto the page
188 */
189 drag_enter_page: function(e) {
b1c669a7
DS
190 if (this.is_disabled()) {
191 return false;
192 }
d0b2d445 193 if (!this.has_files(e)) {
7d44996c
DS
194 return false;
195 }
196
197 this.pageentercount++;
198 if (this.pageentercount >= 2) {
199 this.pageentercount = 2;
200 return false;
201 }
202
203 this.show_drop_target();
204
205 return false;
206 },
207
208 /**
209 * Hide the 'drop files here' message when file(s) are dragged off
210 * the page again
211 */
212 drag_leave_page: function(e) {
213 this.pageentercount--;
214 if (this.pageentercount == 1) {
215 return false;
216 }
217 this.pageentercount = 0;
218
219 this.hide_drop_target();
220
221 return false;
222 },
223
6d9121d3
DS
224 /**
225 * Check if the drag contents are valid and then call
226 * preventdefault / stoppropagation to let the browser know
227 * we will handle this drag/drop
228 *
229 * @param e event object
230 * @return boolean true if a valid file drag event
231 */
d0b2d445 232 check_drag: function(e) {
b1c669a7
DS
233 if (this.is_disabled()) {
234 return false;
235 }
6d9121d3
DS
236 if (!this.has_files(e)) {
237 return false;
238 }
f08fac7c 239
6d9121d3
DS
240 e.preventDefault();
241 e.stopPropagation();
242
f08fac7c 243 return true;
6d9121d3
DS
244 },
245
246 /**
247 * Handle a dragenter event, highlight the destination node
248 * when a suitable drag event occurs
249 */
250 drag_enter: function(e) {
251 if (!this.check_drag(e)) {
252 return true;
253 }
f08fac7c 254
6d9121d3
DS
255 this.entercount++;
256 if (this.entercount >= 2) {
257 this.entercount = 2; // Just moved over a child element - nothing to do
258 return false;
259 }
f08fac7c 260
7d44996c
DS
261 // These lines are needed if the user has dragged something directly
262 // from application onto the 'fileupload' box, without crossing another
263 // part of the page first
264 this.pageentercount = 2;
265 this.show_drop_target();
266
6d9121d3
DS
267 this.show_upload_ready();
268 return false;
269 },
270
271 /**
272 * Handle a dragleave event, Remove the highlight if dragged from
273 * node
274 */
275 drag_leave: function(e) {
276 if (!this.check_drag(e)) {
277 return true;
278 }
f08fac7c 279
6d9121d3
DS
280 this.entercount--;
281 if (this.entercount == 1) {
282 return false; // Just moved over a child element - nothing to do
283 }
f08fac7c 284
6d9121d3
DS
285 this.entercount = 0;
286 this.hide_upload_ready();
287 return false;
288 },
289
290 /**
291 * Handle a dragover event. Required to intercept to prevent the browser from
292 * handling the drag and drop event as normal
293 */
294 drag_over: function(e) {
295 if (!this.check_drag(e)) {
296 return true;
297 }
f08fac7c 298
6d9121d3
DS
299 return false;
300 },
301
302 /**
303 * Handle a drop event. Remove the highlight and then upload each
304 * of the files (until we reach the file limit, or run out of files)
305 */
306 drop: function(e) {
36dc5033 307 if (!this.check_drag(e, true)) {
6d9121d3
DS
308 return true;
309 }
310
311 this.entercount = 0;
7d44996c 312 this.pageentercount = 0;
6d9121d3 313 this.hide_upload_ready();
7d44996c 314 this.hide_drop_target();
f08fac7c 315
6d9121d3
DS
316 var files = e._event.dataTransfer.files;
317 if (this.filemanager) {
52474d74 318 var options = {
d0b2d445 319 files: files,
52474d74
MG
320 options: this.options,
321 repositoryid: this.repositoryid,
d0b2d445
DS
322 currentfilecount: this.filemanager.filecount, // All files uploaded.
323 currentfiles: this.filemanager.options.list, // Only the current folder.
ead25632
DS
324 callback: Y.bind('update_filemanager', this),
325 callbackprogress: Y.bind('update_progress', this),
326 callbackcancel:Y.bind('hide_progress', this)
52474d74 327 };
ead25632
DS
328 this.clear_progress();
329 this.show_progress();
52474d74 330 var uploader = new dnduploader(options);
d0b2d445 331 uploader.start_upload();
6d9121d3
DS
332 } else {
333 if (files.length >= 1) {
52474d74
MG
334 options = {
335 files:[files[0]],
336 options: this.options,
337 repositoryid: this.repositoryid,
d0b2d445
DS
338 currentfilecount: 0,
339 currentfiles: [],
ead25632
DS
340 callback: Y.bind('update_filemanager', this),
341 callbackprogress: Y.bind('update_progress', this),
342 callbackcancel:Y.bind('hide_progress', this)
52474d74 343 };
ead25632
DS
344 this.clear_progress();
345 this.show_progress();
52474d74 346 uploader = new dnduploader(options);
d0b2d445 347 uploader.start_upload();
f08fac7c
DS
348 }
349 }
f08fac7c 350
6d9121d3
DS
351 return false;
352 },
353
354 /**
355 * Check to see if the drag event has any files in it
356 *
357 * @param e event object
358 * @return boolean true if event has files
359 */
360 has_files: function(e) {
6b2b72d6
JF
361 // In some browsers, dataTransfer.types may be null for a
362 // 'dragover' event, so ensure a valid Array is always
363 // inspected.
364 var types = e._event.dataTransfer.types || [];
6d9121d3
DS
365 for (var i=0; i<types.length; i++) {
366 if (types[i] == 'Files') {
367 return true;
368 }
f08fac7c 369 }
6d9121d3
DS
370 return false;
371 },
372
6d9121d3 373 /**
7d44996c
DS
374 * Highlight the area where files could be dropped
375 */
376 show_drop_target: function() {
906e7d89 377 this.container.addClass('dndupload-ready');
7d44996c
DS
378 },
379
380 hide_drop_target: function() {
906e7d89 381 this.container.removeClass('dndupload-ready');
7d44996c
DS
382 },
383
384 /**
385 * Highlight the destination node (ready to drop)
6d9121d3
DS
386 */
387 show_upload_ready: function() {
388 this.container.addClass('dndupload-over');
389 },
390
391 /**
392 * Remove highlight on destination node
393 */
394 hide_upload_ready: function() {
395 this.container.removeClass('dndupload-over');
396 },
397
ead25632
DS
398 /**
399 * Show the element showing the upload in progress
400 */
401 show_progress: function() {
402 this.container.addClass('dndupload-inprogress');
403 },
404
405 /**
406 * Hide the element showing upload in progress
407 */
408 hide_progress: function() {
409 this.container.removeClass('dndupload-inprogress');
410 },
411
6d9121d3
DS
412 /**
413 * Tell the attached filemanager element (if any) to refresh on file
414 * upload
415 */
ead25632
DS
416 update_filemanager: function(params) {
417 this.hide_progress();
6d9121d3
DS
418 if (this.filemanager) {
419 // update the filemanager that we've uploaded the files
420 this.filemanager.filepicker_callback();
ead25632
DS
421 } else if (this.callback) {
422 this.callback(params);
423 }
424 },
425
426 /**
427 * Clear the current progress bars
428 */
429 clear_progress: function() {
430 var filename;
431 for (filename in this.progressbars) {
432 if (this.progressbars.hasOwnProperty(filename)) {
433 this.progressbars[filename].progressouter.remove(true);
434 delete this.progressbars[filename];
435 }
436 }
437 },
438
439 /**
440 * Show the current progress of the uploaded file
441 */
442 update_progress: function(filename, percent) {
443 if (this.progressbars[filename] === undefined) {
444 var dispfilename = filename;
445 if (dispfilename.length > 50) {
446 dispfilename = dispfilename.substr(0, 49)+'&hellip;';
447 }
ccd50411 448 var progressouter = this.container.create('<div>' + dispfilename +
a40cb785
AP
449 '<div class="progress">' +
450 ' <div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">' +
451 ' <span class="sr-only"></span>' +
452 ' </div>' +
ccd50411 453 '</div></div>');
a40cb785
AP
454 var progressinner = progressouter.one('.progress-bar');
455 var progressinnertext = progressinner.one('.sr-only');
ead25632
DS
456 var progresscontainer = this.container.one('.dndupload-progressbars');
457 progresscontainer.appendChild(progressouter);
458
459 this.progressbars[filename] = {
460 progressouter: progressouter,
a40cb785
AP
461 progressinner: progressinner,
462 progressinnertext: progressinnertext
ead25632 463 };
6d9121d3 464 }
ead25632
DS
465
466 this.progressbars[filename].progressinner.setStyle('width', percent + '%');
a40cb785
AP
467 this.progressbars[filename].progressinner.setAttribute('aria-valuenow', percent);
468 this.progressbars[filename].progressinnertext.setContent(percent + '% ' + M.util.get_string('complete', 'moodle'));
52474d74
MG
469 }
470 };
471
472 var dnduploader = function(options) {
473 dnduploader.superclass.constructor.apply(this, arguments);
474 };
475
476 Y.extend(dnduploader, Y.Base, {
d0b2d445 477 // The URL to send the upload data to.
52474d74 478 api: M.cfg.wwwroot+'/repository/repository_ajax.php',
d0b2d445 479 // Options passed into the filemanager/filepicker element.
52474d74 480 options: {},
d0b2d445 481 // The function to call when all uploads complete.
52474d74 482 callback: null,
ead25632
DS
483 // The function to call as the upload progresses
484 callbackprogress: null,
485 // The function to call if the upload is cancelled
486 callbackcancel: null,
d0b2d445 487 // The list of files dropped onto the element.
52474d74 488 files: null,
d0b2d445 489 // The ID of the 'upload' repository.
52474d74 490 repositoryid: 0,
d0b2d445
DS
491 // Array of files already in the current folder (to check for name clashes).
492 currentfiles: null,
493 // Total number of files already uploaded (to check for exceeding limits).
494 currentfilecount: 0,
21e3ea77
FM
495 // Total size of the files present in the area.
496 currentareasize: 0,
d0b2d445
DS
497 // The list of files to upload.
498 uploadqueue: [],
499 // This list of files with name clashes.
500 renamequeue: [],
21e3ea77
FM
501 // Size of the current queue.
502 queuesize: 0,
d0b2d445
DS
503 // Set to true if the user has clicked on 'overwrite all'.
504 overwriteall: false,
505 // Set to true if the user has clicked on 'rename all'.
506 renameall: false,
0b245bf3
HN
507 // Original onbeforeunload event.
508 originalUnloadEvent: null,
52474d74 509
d0b2d445
DS
510 /**
511 * Initialise the settings for the dnduploader
512 * @param object params - includes:
513 * options (copied from the filepicker / filemanager)
514 * repositoryid - ID of the upload repository
515 * callback - the function to call when uploads are complete
516 * currentfiles - the list of files already in the current folder in the filemanager
517 * currentfilecount - the total files already in the filemanager
518 * files - the list of files to upload
519 * @return void
520 */
52474d74
MG
521 initializer: function(params) {
522 this.options = params.options;
523 this.repositoryid = params.repositoryid;
524 this.callback = params.callback;
ead25632
DS
525 this.callbackprogress = params.callbackprogress;
526 this.callbackcancel = params.callbackcancel;
d0b2d445
DS
527 this.currentfiles = params.currentfiles;
528 this.currentfilecount = params.currentfilecount;
21e3ea77
FM
529 this.currentareasize = 0;
530
531 // Retrieve the current size of the area.
532 for (var i = 0; i < this.currentfiles.length; i++) {
533 this.currentareasize += this.currentfiles[i].size;
534 };
d0b2d445 535
ead25632
DS
536 if (!this.initialise_queue(params.files)) {
537 if (this.callbackcancel) {
538 this.callbackcancel();
539 }
540 }
0b245bf3
HN
541 this.originalUnloadEvent = window.onbeforeunload;
542 this.reportUploadDirtyState(true);
52474d74
MG
543 },
544
d0b2d445
DS
545 /**
546 * Entry point for starting the upload process (starts by processing any
547 * renames needed)
548 */
549 start_upload: function() {
550 this.process_renames(); // Automatically calls 'do_upload' once renames complete.
551 },
552
553 /**
554 * Display a message in a popup
555 * @param string msg - the message to display
556 * @param string type - 'error' or 'info'
557 */
558 print_msg: function(msg, type) {
64e7aa4d 559 var header = M.util.get_string('error', 'moodle');
d0b2d445
DS
560 if (type != 'error') {
561 type = 'info'; // one of only two types excepted
64e7aa4d 562 header = M.util.get_string('info', 'moodle');
d0b2d445
DS
563 }
564 if (!this.msg_dlg) {
88af0208 565 this.msg_dlg_node = Y.Node.create(M.core_filepicker.templates.message);
d0b2d445
DS
566 this.msg_dlg_node.generateID();
567
88af0208 568 this.msg_dlg = new M.core.dialogue({
e8272e74
DW
569 bodyContent: this.msg_dlg_node,
570 centered: true,
571 modal: true,
572 visible: false
d0b2d445
DS
573 });
574 this.msg_dlg.plug(Y.Plugin.Drag,{handles:['#'+this.msg_dlg_node.get('id')+' .yui3-widget-hd']});
575 this.msg_dlg_node.one('.fp-msg-butok').on('click', function(e) {
576 e.preventDefault();
577 this.msg_dlg.hide();
578 }, this);
579 }
580
581 this.msg_dlg.set('headerContent', header);
582 this.msg_dlg_node.removeClass('fp-msg-info').removeClass('fp-msg-error').addClass('fp-msg-'+type)
583 this.msg_dlg_node.one('.fp-msg-text').setContent(msg);
584 this.msg_dlg.show();
585 },
586
587 /**
588 * Check the size of each file and add to either the uploadqueue or, if there
589 * is a name clash, the renamequeue
590 * @param FileList files - the files to upload
591 * @return void
592 */
593 initialise_queue: function(files) {
594 this.uploadqueue = [];
595 this.renamequeue = [];
21e3ea77 596 this.queuesize = 0;
d0b2d445 597
21e3ea77 598 // Loop through the files and find any name clashes with existing files.
d0b2d445
DS
599 var i;
600 for (i=0; i<files.length; i++) {
601 if (this.options.maxbytes > 0 && files[i].size > this.options.maxbytes) {
39bb9b1f 602 // Check filesize before attempting to upload.
a2fb838e
BT
603 var maxbytesdisplay = this.display_size(this.options.maxbytes);
604 this.print_msg(M.util.get_string('maxbytesfile', 'error', {
605 file: files[i].name,
606 size: maxbytesdisplay
607 }), 'error');
d0b2d445
DS
608 this.uploadqueue = []; // No uploads if one file is too big.
609 return;
610 }
611
612 if (this.has_name_clash(files[i].name)) {
613 this.renamequeue.push(files[i]);
614 } else {
615 if (!this.add_to_upload_queue(files[i], files[i].name, false)) {
ead25632 616 return false;
d0b2d445
DS
617 }
618 }
21e3ea77 619 this.queuesize += files[i].size;
d0b2d445 620 }
ead25632 621 return true;
d0b2d445
DS
622 },
623
a2fb838e
BT
624 /**
625 * Generate the display for file size
626 * @param int size The size to convert to human readable form
627 * @return string
628 */
629 display_size: function(size) {
630 // This is snippet of code (with some changes) is from the display_size function in moodlelib.
82eb2cf1
AN
631 var gb = M.util.get_string('sizegb', 'moodle'),
632 mb = M.util.get_string('sizemb', 'moodle'),
633 kb = M.util.get_string('sizekb', 'moodle'),
634 b = M.util.get_string('sizeb', 'moodle');
a2fb838e
BT
635
636 if (size >= 1073741824) {
637 size = Math.round(size / 1073741824 * 10) / 10 + gb;
638 } else if (size >= 1048576) {
639 size = Math.round(size / 1048576 * 10) / 10 + mb;
640 } else if (size >= 1024) {
641 size = Math.round(size / 1024 * 10) / 10 + kb;
642 } else {
643 size = parseInt(size, 10) + ' ' + b;
644 }
645
646 return size;
647 },
648
d0b2d445
DS
649 /**
650 * Add a single file to the uploadqueue, whilst checking the maxfiles limit
651 * @param File file - the file to add
652 * @param string filename - the name to give the file on upload
653 * @param bool overwrite - true to overwrite the existing file
654 * @return bool true if added successfully
655 */
656 add_to_upload_queue: function(file, filename, overwrite) {
657 if (!overwrite) {
658 this.currentfilecount++;
659 }
a0dc7da9
PN
660 // The value for "unlimited files" is -1, so 0 should mean 0.
661 if (this.options.maxfiles >= 0 && this.currentfilecount > this.options.maxfiles) {
d0b2d445
DS
662 // Too many files - abort entire upload.
663 this.uploadqueue = [];
664 this.renamequeue = [];
665 this.print_msg(M.util.get_string('maxfilesreached', 'moodle', this.options.maxfiles), 'error');
666 return false;
667 }
21e3ea77 668 // The new file will cause the area to reach its limit, we cancel the upload of all files.
68acd115 669 // -1 is the value defined by FILE_AREA_MAX_BYTES_UNLIMITED.
21e3ea77
FM
670 if (this.options.areamaxbytes > -1) {
671 var sizereached = this.currentareasize + this.queuesize + file.size;
672 if (sizereached > this.options.areamaxbytes) {
673 this.uploadqueue = [];
674 this.renamequeue = [];
39bb9b1f 675 this.print_msg(M.util.get_string('maxareabytesreached', 'moodle'), 'error');
21e3ea77
FM
676 return false;
677 }
678 }
d0b2d445
DS
679 this.uploadqueue.push({file:file, filename:filename, overwrite:overwrite});
680 return true;
681 },
682
683 /**
684 * Take the next file from the renamequeue and ask the user what to do with
685 * it. Called recursively until the queue is empty, then calls do_upload.
686 * @return void
687 */
688 process_renames: function() {
689 if (this.renamequeue.length == 0) {
690 // All rename processing complete - start the actual upload.
691 this.do_upload();
692 return;
693 }
694 var multiplefiles = (this.renamequeue.length > 1);
695
696 // Get the next file from the rename queue.
697 var file = this.renamequeue.shift();
698 // Generate a non-conflicting name for it.
699 var newname = this.generate_unique_name(file.name);
700
701 // If the user has clicked on overwrite/rename ALL then process
702 // this file, as appropriate, then process the rest of the queue.
703 if (this.overwriteall) {
704 this.add_to_upload_queue(file, file.name, true);
705 this.process_renames();
706 return;
707 }
708 if (this.renameall) {
709 this.add_to_upload_queue(file, newname, false);
710 this.process_renames();
711 return;
712 }
713
714 // Ask the user what to do with this file.
715 var self = this;
716
717 var process_dlg_node;
718 if (multiplefiles) {
88af0208 719 process_dlg_node = Y.Node.create(M.core_filepicker.templates.processexistingfilemultiple);
d0b2d445 720 } else {
88af0208 721 process_dlg_node = Y.Node.create(M.core_filepicker.templates.processexistingfile);
d0b2d445
DS
722 }
723 var node = process_dlg_node;
724 node.generateID();
88af0208 725 var process_dlg = new M.core.dialogue({
e8272e74 726 bodyContent: node,
64e7aa4d 727 headerContent: M.util.get_string('fileexistsdialogheader', 'repository'),
e8272e74
DW
728 centered: true,
729 modal: true,
730 visible: false
d0b2d445
DS
731 });
732 process_dlg.plug(Y.Plugin.Drag,{handles:['#'+node.get('id')+' .yui3-widget-hd']});
733
734 // Overwrite original.
735 node.one('.fp-dlg-butoverwrite').on('click', function(e) {
736 e.preventDefault();
737 process_dlg.hide();
738 self.add_to_upload_queue(file, file.name, true);
739 self.process_renames();
740 }, this);
741
742 // Rename uploaded file.
743 node.one('.fp-dlg-butrename').on('click', function(e) {
744 e.preventDefault();
745 process_dlg.hide();
746 self.add_to_upload_queue(file, newname, false);
747 self.process_renames();
748 }, this);
749
750 // Cancel all uploads.
751 node.one('.fp-dlg-butcancel').on('click', function(e) {
752 e.preventDefault();
753 process_dlg.hide();
ead25632
DS
754 if (self.callbackcancel) {
755 self.callbackcancel();
756 }
d0b2d445
DS
757 }, this);
758
759 // When we are at the file limit, only allow 'overwrite', not rename.
760 if (this.currentfilecount == this.options.maxfiles) {
761 node.one('.fp-dlg-butrename').setStyle('display', 'none');
762 if (multiplefiles) {
763 node.one('.fp-dlg-butrenameall').setStyle('display', 'none');
764 }
765 }
766
767 // If there are more files still to go, offer the 'overwrite/rename all' options.
768 if (multiplefiles) {
769 // Overwrite all original files.
770 node.one('.fp-dlg-butoverwriteall').on('click', function(e) {
771 e.preventDefault();
772 process_dlg.hide();
773 this.overwriteall = true;
774 self.add_to_upload_queue(file, file.name, true);
775 self.process_renames();
776 }, this);
777
778 // Rename all new files.
779 node.one('.fp-dlg-butrenameall').on('click', function(e) {
780 e.preventDefault();
781 process_dlg.hide();
782 this.renameall = true;
783 self.add_to_upload_queue(file, newname, false);
784 self.process_renames();
785 }, this);
786 }
787 node.one('.fp-dlg-text').setContent(M.util.get_string('fileexists', 'moodle', file.name));
788 process_dlg_node.one('.fp-dlg-butrename').setContent(M.util.get_string('renameto', 'repository', newname));
789
790 // Destroy the dialog once it has been hidden.
791 process_dlg.after('visibleChange', function(e) {
792 if (!process_dlg.get('visible')) {
793 process_dlg.destroy(true);
794 }
795 });
796
797 process_dlg.show();
798 },
799
800 /**
801 * Checks if there is already a file with the given name in the current folder
802 * or in the list of already uploading files
803 * @param string filename - the name to test
804 * @return bool true if the name already exists
805 */
806 has_name_clash: function(filename) {
807 // Check against the already uploaded files
808 var i;
809 for (i=0; i<this.currentfiles.length; i++) {
810 if (filename == this.currentfiles[i].filename) {
811 return true;
812 }
813 }
814 // Check against the uploading files that have already been processed
815 for (i=0; i<this.uploadqueue.length; i++) {
816 if (filename == this.uploadqueue[i].filename) {
817 return true;
818 }
819 }
820 return false;
821 },
822
823 /**
04cbea2c
FM
824 * Gets a unique file name
825 *
d0b2d445
DS
826 * @param string filename
827 * @return string the unique filename generated
828 */
829 generate_unique_name: function(filename) {
d0b2d445 830 // Loop through increating numbers until a unique name is found.
04cbea2c
FM
831 while (this.has_name_clash(filename)) {
832 filename = increment_filename(filename);
833 }
834 return filename;
d0b2d445
DS
835 },
836
837 /**
838 * Upload the next file from the uploadqueue - called recursively after each
839 * upload is complete, then handles the callback to the filemanager/filepicker
840 * @param lastresult - the last result from the server
841 */
842 do_upload: function(lastresult) {
843 if (this.uploadqueue.length > 0) {
844 var filedetails = this.uploadqueue.shift();
845 this.upload_file(filedetails.file, filedetails.filename, filedetails.overwrite);
52474d74
MG
846 } else {
847 this.uploadfinished(lastresult);
848 }
849 },
850
d0b2d445
DS
851 /**
852 * Run the callback to the filemanager/filepicker
853 */
52474d74 854 uploadfinished: function(lastresult) {
0b245bf3 855 this.reportUploadDirtyState(false);
52474d74
MG
856 this.callback(lastresult);
857 },
858
6d9121d3 859 /**
d0b2d445
DS
860 * Upload a single file via an AJAX call to the 'upload' repository. Automatically
861 * calls do_upload as each upload completes.
862 * @param File file - the file to upload
863 * @param string filename - the name to give the file
864 * @param bool overwrite - true if the existing file should be overwritten
6d9121d3 865 */
d0b2d445 866 upload_file: function(file, filename, overwrite) {
f08fac7c 867
6d9121d3
DS
868 // This would be an ideal place to use the Y.io function
869 // however, this does not support data encoded using the
870 // FormData object, which is needed to transfer data from
871 // the DataTransfer object into an XMLHTTPRequest
872 // This can be converted when the YUI issue has been integrated:
873 // http://yuilibrary.com/projects/yui3/ticket/2531274
874 var xhr = new XMLHttpRequest();
875 var self = this;
ead25632
DS
876
877 // Update the progress bar
878 xhr.upload.addEventListener('progress', function(e) {
879 if (e.lengthComputable && self.callbackprogress) {
880 var percentage = Math.round((e.loaded * 100) / e.total);
881 self.callbackprogress(filename, percentage);
882 }
883 }, false);
884
6d9121d3
DS
885 xhr.onreadystatechange = function() { // Process the server response
886 if (xhr.readyState == 4) {
6d9121d3
DS
887 if (xhr.status == 200) {
888 var result = JSON.parse(xhr.responseText);
889 if (result) {
890 if (result.error) {
78b4da19
DS
891 self.print_msg(result.error, 'error'); // TODO add filename?
892 self.uploadfinished();
52474d74 893 } else {
6d9121d3
DS
894 // Only update the filepicker if there were no errors
895 if (result.event == 'fileexists') {
896 // Do not worry about this, as we only care about the last
897 // file uploaded, with the filepicker
898 result.file = result.newfile.filename;
899 result.url = result.newfile.url;
900 }
52474d74 901 result.client_id = self.options.clientid;
ead25632
DS
902 if (self.callbackprogress) {
903 self.callbackprogress(filename, 100);
904 }
4069ae32 905 }
f08fac7c 906 }
d0b2d445 907 self.do_upload(result); // continue uploading
6d9121d3 908 } else {
78b4da19
DS
909 self.print_msg(M.util.get_string('serverconnection', 'error'), 'error');
910 self.uploadfinished();
f08fac7c
DS
911 }
912 }
6d9121d3
DS
913 };
914
915 // Prepare the data to send
916 var formdata = new FormData();
917 formdata.append('repo_upload_file', file); // The FormData class allows us to attach a file
918 formdata.append('sesskey', M.cfg.sesskey);
919 formdata.append('repo_id', this.repositoryid);
52474d74
MG
920 formdata.append('itemid', this.options.itemid);
921 if (this.options.author) {
922 formdata.append('author', this.options.author);
140669a9 923 }
52474d74
MG
924 if (this.options.filemanager) { // Filepickers do not have folders
925 formdata.append('savepath', this.options.filemanager.currentpath);
f08fac7c 926 }
d0b2d445
DS
927 formdata.append('title', filename);
928 if (overwrite) {
929 formdata.append('overwrite', 1);
930 }
7b22e2ab
MG
931 if (this.options.contextid) {
932 formdata.append('ctx_id', this.options.contextid);
933 }
f08fac7c 934
d0b2d445
DS
935 // Accepted types can be either a string or an array, but an array is
936 // expected in the processing script, so make sure we are sending an array
937 if (this.options.acceptedtypes.constructor == Array) {
52474d74
MG
938 for (var i=0; i<this.options.acceptedtypes.length; i++) {
939 formdata.append('accepted_types[]', this.options.acceptedtypes[i]);
6d9121d3
DS
940 }
941 } else {
52474d74 942 formdata.append('accepted_types[]', this.options.acceptedtypes);
f08fac7c 943 }
6d9121d3 944
658a922f
AN
945 // Send the file & required details.
946 var uploadUrl = this.api;
947 if (uploadUrl.indexOf('?') !== -1) {
948 uploadUrl += '&action=upload';
949 } else {
950 uploadUrl += '?action=upload';
951 }
952 xhr.open("POST", uploadUrl, true);
6d9121d3
DS
953 xhr.send(formdata);
954 return true;
0b245bf3
HN
955 },
956
957 /**
958 * Set the event to prevent user navigate away when upload progress still running.
959 *
960 * @param {bool} enable true if upload progress is running, false otherwise
961 */
962 reportUploadDirtyState: function(enable) {
963 if (!enable) {
964 window.onbeforeunload = this.originalUnloadEvent;
965 } else {
966 window.onbeforeunload = function(e) {
967 var warningMessage = M.util.get_string('changesmadereallygoaway', 'moodle');
968 if (e) {
969 e.returnValue = warningMessage;
970 }
971 return warningMessage;
972 };
973 }
f08fac7c 974 }
52474d74 975 });
f08fac7c 976
6d9121d3 977 dnduploadhelper.init(Y, options);
f08fac7c 978};