Merge branch 'MDL-62945-master' of https://github.com/HuongNV13/moodle
[moodle.git] / lib / form / dndupload.js
blob8b4ed1577f3724b7f93ae964afcd9a426ea6eb6b
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.
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/>.
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  */
25 M.form_dndupload = {}
27 M.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',
33         // options may include: itemid, acceptedtypes, maxfiles, maxbytes, clientid, repositoryid, author, contextid
34         options: {},
35         // itemid used for repository upload
36         itemid: null,
37         // accepted filetypes accepted by this form passed to repository
38         acceptedtypes: [],
39         // maximum size of files allowed in this form
40         maxbytes: 0,
41         // Maximum combined size of files allowed in this form. {@link FILE_AREA_MAX_BYTES_UNLIMITED}
42         areamaxbytes: -1,
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,
56         pageentercount: 0,
57         // Holds the progress bar elements for each file.
58         progressbars: {},
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
70          *            areamaxbytes: maximum combined size of files allowed in this form
71          *            clientid: unqiue id of this form field used for html elements
72          *            contextid: id of the current cotnext
73          *            containerid: htmlid of container
74          *            repositories: array of repository objects passed from filepicker
75          *            filemanager: filemanager element we are working with
76          *            formcallback: callback  to filepicker element to refesh when uploaded
77          *          }
78          */
79         init: function(Y, options) {
80             this.Y = Y;
82             if (!this.browser_supported()) {
83                 Y.one('body').addClass('dndnotsupported');
84                 return; // Browser does not support the required functionality
85             }
87             // try and retrieve enabled upload repository
88             this.repositoryid = this.get_upload_repositoryid(options.repositories);
90             if (!this.repositoryid) {
91                 Y.one('body').addClass('dndnotsupported');
92                 return; // no upload repository is enabled to upload to
93             }
95             Y.one('body').addClass('dndsupported');
97             this.options = options;
98             this.acceptedtypes = options.acceptedtypes;
99             this.clientid = options.clientid;
100             this.maxbytes = options.maxbytes;
101             this.areamaxbytes = options.areamaxbytes;
102             this.itemid = options.itemid;
103             this.author = options.author;
104             this.container = this.Y.one('#'+options.containerid);
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) {
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) {
117                     alert('dndupload: Need to define either options.filemanager or options.formcallback');
118                 }
119                 return;
120             }
122             this.init_events();
123             this.init_page_events();
124         },
126         /**
127          * Check the browser has the required functionality
128          * @return true if browser supports drag/drop upload
129          */
130         browser_supported: function() {
132             if (typeof FileReader == 'undefined') {
133                 return false;
134             }
135             if (typeof FormData == 'undefined') {
136                 return false;
137             }
138             return true;
139         },
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             }
154             return false;
155         },
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         },
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         },
177         /**
178          * Check if the filemanager / filepicker is disabled
179          * @return bool - true if disabled
180          */
181         is_disabled: function() {
182             return (this.container.ancestor('.fitem.disabled') != null);
183         },
185         /**
186          * Show the 'drop files here' message when file(s) are dragged
187          * onto the page
188          */
189         drag_enter_page: function(e) {
190             if (this.is_disabled()) {
191                 return false;
192             }
193             if (!this.has_files(e)) {
194                 return false;
195             }
197             this.pageentercount++;
198             if (this.pageentercount >= 2) {
199                 this.pageentercount = 2;
200                 return false;
201             }
203             this.show_drop_target();
205             return false;
206         },
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;
219             this.hide_drop_target();
221             return false;
222         },
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          */
232         check_drag: function(e) {
233             if (this.is_disabled()) {
234                 return false;
235             }
236             if (!this.has_files(e)) {
237                 return false;
238             }
240             e.preventDefault();
241             e.stopPropagation();
243             return true;
244         },
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             }
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             }
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();
267             this.show_upload_ready();
268             return false;
269         },
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             }
280             this.entercount--;
281             if (this.entercount == 1) {
282                 return false; // Just moved over a child element - nothing to do
283             }
285             this.entercount = 0;
286             this.hide_upload_ready();
287             return false;
288         },
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             }
299             return false;
300         },
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) {
307             if (!this.check_drag(e, true)) {
308                 return true;
309             }
311             this.entercount = 0;
312             this.pageentercount = 0;
313             this.hide_upload_ready();
314             this.hide_drop_target();
316             var files = e._event.dataTransfer.files;
317             if (this.filemanager) {
318                 var options = {
319                     files: files,
320                     options: this.options,
321                     repositoryid: this.repositoryid,
322                     currentfilecount: this.filemanager.filecount, // All files uploaded.
323                     currentfiles: this.filemanager.options.list, // Only the current folder.
324                     callback: Y.bind('update_filemanager', this),
325                     callbackprogress: Y.bind('update_progress', this),
326                     callbackcancel:Y.bind('hide_progress', this)
327                 };
328                 this.clear_progress();
329                 this.show_progress();
330                 var uploader = new dnduploader(options);
331                 uploader.start_upload();
332             } else {
333                 if (files.length >= 1) {
334                     options = {
335                         files:[files[0]],
336                         options: this.options,
337                         repositoryid: this.repositoryid,
338                         currentfilecount: 0,
339                         currentfiles: [],
340                         callback: Y.bind('update_filemanager', this),
341                         callbackprogress: Y.bind('update_progress', this),
342                         callbackcancel:Y.bind('hide_progress', this)
343                     };
344                     this.clear_progress();
345                     this.show_progress();
346                     uploader = new dnduploader(options);
347                     uploader.start_upload();
348                 }
349             }
351             return false;
352         },
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) {
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 || [];
365             for (var i=0; i<types.length; i++) {
366                 if (types[i] == 'Files') {
367                     return true;
368                 }
369             }
370             return false;
371         },
373         /**
374          * Highlight the area where files could be dropped
375          */
376         show_drop_target: function() {
377             this.container.addClass('dndupload-ready');
378         },
380         hide_drop_target: function() {
381             this.container.removeClass('dndupload-ready');
382         },
384         /**
385          * Highlight the destination node (ready to drop)
386          */
387         show_upload_ready: function() {
388             this.container.addClass('dndupload-over');
389         },
391         /**
392          * Remove highlight on destination node
393          */
394         hide_upload_ready: function() {
395             this.container.removeClass('dndupload-over');
396         },
398         /**
399          * Show the element showing the upload in progress
400          */
401         show_progress: function() {
402             this.container.addClass('dndupload-inprogress');
403         },
405         /**
406          * Hide the element showing upload in progress
407          */
408         hide_progress: function() {
409             this.container.removeClass('dndupload-inprogress');
410         },
412         /**
413          * Tell the attached filemanager element (if any) to refresh on file
414          * upload
415          */
416         update_filemanager: function(params) {
417             this.hide_progress();
418             if (this.filemanager) {
419                 // update the filemanager that we've uploaded the files
420                 this.filemanager.filepicker_callback();
421             } else if (this.callback) {
422                 this.callback(params);
423             }
424         },
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         },
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                 }
448                 var progressouter = this.container.create('<span>'+dispfilename+': <span class="dndupload-progress-outer"><span class="dndupload-progress-inner">&nbsp;</span></span><br /></span>');
449                 var progressinner = progressouter.one('.dndupload-progress-inner');
450                 var progresscontainer = this.container.one('.dndupload-progressbars');
451                 progresscontainer.appendChild(progressouter);
453                 this.progressbars[filename] = {
454                     progressouter: progressouter,
455                     progressinner: progressinner
456                 };
457             }
459             this.progressbars[filename].progressinner.setStyle('width', percent + '%');
460         }
461     };
463     var dnduploader = function(options) {
464         dnduploader.superclass.constructor.apply(this, arguments);
465     };
467     Y.extend(dnduploader, Y.Base, {
468         // The URL to send the upload data to.
469         api: M.cfg.wwwroot+'/repository/repository_ajax.php',
470         // Options passed into the filemanager/filepicker element.
471         options: {},
472         // The function to call when all uploads complete.
473         callback: null,
474         // The function to call as the upload progresses
475         callbackprogress: null,
476         // The function to call if the upload is cancelled
477         callbackcancel: null,
478         // The list of files dropped onto the element.
479         files: null,
480         // The ID of the 'upload' repository.
481         repositoryid: 0,
482         // Array of files already in the current folder (to check for name clashes).
483         currentfiles: null,
484         // Total number of files already uploaded (to check for exceeding limits).
485         currentfilecount: 0,
486         // Total size of the files present in the area.
487         currentareasize: 0,
488         // The list of files to upload.
489         uploadqueue: [],
490         // This list of files with name clashes.
491         renamequeue: [],
492         // Size of the current queue.
493         queuesize: 0,
494         // Set to true if the user has clicked on 'overwrite all'.
495         overwriteall: false,
496         // Set to true if the user has clicked on 'rename all'.
497         renameall: false,
498         // Original onbeforeunload event.
499         originalUnloadEvent: null,
501         /**
502          * Initialise the settings for the dnduploader
503          * @param object params - includes:
504          *                     options (copied from the filepicker / filemanager)
505          *                     repositoryid - ID of the upload repository
506          *                     callback - the function to call when uploads are complete
507          *                     currentfiles - the list of files already in the current folder in the filemanager
508          *                     currentfilecount - the total files already in the filemanager
509          *                     files - the list of files to upload
510          * @return void
511          */
512         initializer: function(params) {
513             this.options = params.options;
514             this.repositoryid = params.repositoryid;
515             this.callback = params.callback;
516             this.callbackprogress = params.callbackprogress;
517             this.callbackcancel = params.callbackcancel;
518             this.currentfiles = params.currentfiles;
519             this.currentfilecount = params.currentfilecount;
520             this.currentareasize = 0;
522             // Retrieve the current size of the area.
523             for (var i = 0; i < this.currentfiles.length; i++) {
524                 this.currentareasize += this.currentfiles[i].size;
525             };
527             if (!this.initialise_queue(params.files)) {
528                 if (this.callbackcancel) {
529                     this.callbackcancel();
530                 }
531             }
532             this.originalUnloadEvent = window.onbeforeunload;
533             this.reportUploadDirtyState(true);
534         },
536         /**
537          * Entry point for starting the upload process (starts by processing any
538          * renames needed)
539          */
540         start_upload: function() {
541             this.process_renames(); // Automatically calls 'do_upload' once renames complete.
542         },
544         /**
545          * Display a message in a popup
546          * @param string msg - the message to display
547          * @param string type - 'error' or 'info'
548          */
549         print_msg: function(msg, type) {
550             var header = M.util.get_string('error', 'moodle');
551             if (type != 'error') {
552                 type = 'info'; // one of only two types excepted
553                 header = M.util.get_string('info', 'moodle');
554             }
555             if (!this.msg_dlg) {
556                 this.msg_dlg_node = Y.Node.create(M.core_filepicker.templates.message);
557                 this.msg_dlg_node.generateID();
559                 this.msg_dlg = new M.core.dialogue({
560                     bodyContent: this.msg_dlg_node,
561                     centered: true,
562                     modal: true,
563                     visible: false
564                 });
565                 this.msg_dlg.plug(Y.Plugin.Drag,{handles:['#'+this.msg_dlg_node.get('id')+' .yui3-widget-hd']});
566                 this.msg_dlg_node.one('.fp-msg-butok').on('click', function(e) {
567                     e.preventDefault();
568                     this.msg_dlg.hide();
569                 }, this);
570             }
572             this.msg_dlg.set('headerContent', header);
573             this.msg_dlg_node.removeClass('fp-msg-info').removeClass('fp-msg-error').addClass('fp-msg-'+type)
574             this.msg_dlg_node.one('.fp-msg-text').setContent(msg);
575             this.msg_dlg.show();
576         },
578         /**
579          * Check the size of each file and add to either the uploadqueue or, if there
580          * is a name clash, the renamequeue
581          * @param FileList files - the files to upload
582          * @return void
583          */
584         initialise_queue: function(files) {
585             this.uploadqueue = [];
586             this.renamequeue = [];
587             this.queuesize = 0;
589             // Loop through the files and find any name clashes with existing files.
590             var i;
591             for (i=0; i<files.length; i++) {
592                 if (this.options.maxbytes > 0 && files[i].size > this.options.maxbytes) {
593                     // Check filesize before attempting to upload.
594                     var maxbytesdisplay = this.display_size(this.options.maxbytes);
595                     this.print_msg(M.util.get_string('maxbytesfile', 'error', {
596                             file: files[i].name,
597                             size: maxbytesdisplay
598                         }), 'error');
599                     this.uploadqueue = []; // No uploads if one file is too big.
600                     return;
601                 }
603                 if (this.has_name_clash(files[i].name)) {
604                     this.renamequeue.push(files[i]);
605                 } else {
606                     if (!this.add_to_upload_queue(files[i], files[i].name, false)) {
607                         return false;
608                     }
609                 }
610                 this.queuesize += files[i].size;
611             }
612             return true;
613         },
615         /**
616          * Generate the display for file size
617          * @param int size The size to convert to human readable form
618          * @return string
619          */
620         display_size: function(size) {
621             // This is snippet of code (with some changes) is from the display_size function in moodlelib.
622             var gb = M.util.get_string('sizegb', 'moodle'),
623                 mb = M.util.get_string('sizemb', 'moodle'),
624                 kb = M.util.get_string('sizekb', 'moodle'),
625                 b  = M.util.get_string('sizeb', 'moodle');
627             if (size >= 1073741824) {
628                 size = Math.round(size / 1073741824 * 10) / 10 + gb;
629             } else if (size >= 1048576) {
630                 size = Math.round(size / 1048576 * 10) / 10 + mb;
631             } else if (size >= 1024) {
632                 size = Math.round(size / 1024 * 10) / 10 + kb;
633             } else {
634                 size = parseInt(size, 10) + ' ' + b;
635             }
637             return size;
638         },
640         /**
641          * Add a single file to the uploadqueue, whilst checking the maxfiles limit
642          * @param File file - the file to add
643          * @param string filename - the name to give the file on upload
644          * @param bool overwrite - true to overwrite the existing file
645          * @return bool true if added successfully
646          */
647         add_to_upload_queue: function(file, filename, overwrite) {
648             if (!overwrite) {
649                 this.currentfilecount++;
650             }
651             // The value for "unlimited files" is -1, so 0 should mean 0.
652             if (this.options.maxfiles >= 0 && this.currentfilecount > this.options.maxfiles) {
653                 // Too many files - abort entire upload.
654                 this.uploadqueue = [];
655                 this.renamequeue = [];
656                 this.print_msg(M.util.get_string('maxfilesreached', 'moodle', this.options.maxfiles), 'error');
657                 return false;
658             }
659             // The new file will cause the area to reach its limit, we cancel the upload of all files.
660             // -1 is the value defined by FILE_AREA_MAX_BYTES_UNLIMITED.
661             if (this.options.areamaxbytes > -1) {
662                 var sizereached = this.currentareasize + this.queuesize + file.size;
663                 if (sizereached > this.options.areamaxbytes) {
664                     this.uploadqueue = [];
665                     this.renamequeue = [];
666                     this.print_msg(M.util.get_string('maxareabytesreached', 'moodle'), 'error');
667                     return false;
668                 }
669             }
670             this.uploadqueue.push({file:file, filename:filename, overwrite:overwrite});
671             return true;
672         },
674         /**
675          * Take the next file from the renamequeue and ask the user what to do with
676          * it. Called recursively until the queue is empty, then calls do_upload.
677          * @return void
678          */
679         process_renames: function() {
680             if (this.renamequeue.length == 0) {
681                 // All rename processing complete - start the actual upload.
682                 this.do_upload();
683                 return;
684             }
685             var multiplefiles = (this.renamequeue.length > 1);
687             // Get the next file from the rename queue.
688             var file = this.renamequeue.shift();
689             // Generate a non-conflicting name for it.
690             var newname = this.generate_unique_name(file.name);
692             // If the user has clicked on overwrite/rename ALL then process
693             // this file, as appropriate, then process the rest of the queue.
694             if (this.overwriteall) {
695                 this.add_to_upload_queue(file, file.name, true);
696                 this.process_renames();
697                 return;
698             }
699             if (this.renameall) {
700                 this.add_to_upload_queue(file, newname, false);
701                 this.process_renames();
702                 return;
703             }
705             // Ask the user what to do with this file.
706             var self = this;
708             var process_dlg_node;
709             if (multiplefiles) {
710                 process_dlg_node = Y.Node.create(M.core_filepicker.templates.processexistingfilemultiple);
711             } else {
712                 process_dlg_node = Y.Node.create(M.core_filepicker.templates.processexistingfile);
713             }
714             var node = process_dlg_node;
715             node.generateID();
716             var process_dlg = new M.core.dialogue({
717                 bodyContent: node,
718                 headerContent: M.util.get_string('fileexistsdialogheader', 'repository'),
719                 centered: true,
720                 modal: true,
721                 visible: false
722             });
723             process_dlg.plug(Y.Plugin.Drag,{handles:['#'+node.get('id')+' .yui3-widget-hd']});
725             // Overwrite original.
726             node.one('.fp-dlg-butoverwrite').on('click', function(e) {
727                 e.preventDefault();
728                 process_dlg.hide();
729                 self.add_to_upload_queue(file, file.name, true);
730                 self.process_renames();
731             }, this);
733             // Rename uploaded file.
734             node.one('.fp-dlg-butrename').on('click', function(e) {
735                 e.preventDefault();
736                 process_dlg.hide();
737                 self.add_to_upload_queue(file, newname, false);
738                 self.process_renames();
739             }, this);
741             // Cancel all uploads.
742             node.one('.fp-dlg-butcancel').on('click', function(e) {
743                 e.preventDefault();
744                 process_dlg.hide();
745                 if (self.callbackcancel) {
746                     self.callbackcancel();
747                 }
748             }, this);
750             // When we are at the file limit, only allow 'overwrite', not rename.
751             if (this.currentfilecount == this.options.maxfiles) {
752                 node.one('.fp-dlg-butrename').setStyle('display', 'none');
753                 if (multiplefiles) {
754                     node.one('.fp-dlg-butrenameall').setStyle('display', 'none');
755                 }
756             }
758             // If there are more files still to go, offer the 'overwrite/rename all' options.
759             if (multiplefiles) {
760                 // Overwrite all original files.
761                 node.one('.fp-dlg-butoverwriteall').on('click', function(e) {
762                     e.preventDefault();
763                     process_dlg.hide();
764                     this.overwriteall = true;
765                     self.add_to_upload_queue(file, file.name, true);
766                     self.process_renames();
767                 }, this);
769                 // Rename all new files.
770                 node.one('.fp-dlg-butrenameall').on('click', function(e) {
771                     e.preventDefault();
772                     process_dlg.hide();
773                     this.renameall = true;
774                     self.add_to_upload_queue(file, newname, false);
775                     self.process_renames();
776                 }, this);
777             }
778             node.one('.fp-dlg-text').setContent(M.util.get_string('fileexists', 'moodle', file.name));
779             process_dlg_node.one('.fp-dlg-butrename').setContent(M.util.get_string('renameto', 'repository', newname));
781             // Destroy the dialog once it has been hidden.
782             process_dlg.after('visibleChange', function(e) {
783                 if (!process_dlg.get('visible')) {
784                     process_dlg.destroy(true);
785                 }
786             });
788             process_dlg.show();
789         },
791         /**
792          * Checks if there is already a file with the given name in the current folder
793          * or in the list of already uploading files
794          * @param string filename - the name to test
795          * @return bool true if the name already exists
796          */
797         has_name_clash: function(filename) {
798             // Check against the already uploaded files
799             var i;
800             for (i=0; i<this.currentfiles.length; i++) {
801                 if (filename == this.currentfiles[i].filename) {
802                     return true;
803                 }
804             }
805             // Check against the uploading files that have already been processed
806             for (i=0; i<this.uploadqueue.length; i++) {
807                 if (filename == this.uploadqueue[i].filename) {
808                     return true;
809                 }
810             }
811             return false;
812         },
814         /**
815          * Gets a unique file name
816          *
817          * @param string filename
818          * @return string the unique filename generated
819          */
820         generate_unique_name: function(filename) {
821             // Loop through increating numbers until a unique name is found.
822             while (this.has_name_clash(filename)) {
823                 filename = increment_filename(filename);
824             }
825             return filename;
826         },
828         /**
829          * Upload the next file from the uploadqueue - called recursively after each
830          * upload is complete, then handles the callback to the filemanager/filepicker
831          * @param lastresult - the last result from the server
832          */
833         do_upload: function(lastresult) {
834             if (this.uploadqueue.length > 0) {
835                 var filedetails = this.uploadqueue.shift();
836                 this.upload_file(filedetails.file, filedetails.filename, filedetails.overwrite);
837             } else {
838                 this.uploadfinished(lastresult);
839             }
840         },
842         /**
843          * Run the callback to the filemanager/filepicker
844          */
845         uploadfinished: function(lastresult) {
846             this.reportUploadDirtyState(false);
847             this.callback(lastresult);
848         },
850         /**
851          * Upload a single file via an AJAX call to the 'upload' repository. Automatically
852          * calls do_upload as each upload completes.
853          * @param File file - the file to upload
854          * @param string filename - the name to give the file
855          * @param bool overwrite - true if the existing file should be overwritten
856          */
857         upload_file: function(file, filename, overwrite) {
859             // This would be an ideal place to use the Y.io function
860             // however, this does not support data encoded using the
861             // FormData object, which is needed to transfer data from
862             // the DataTransfer object into an XMLHTTPRequest
863             // This can be converted when the YUI issue has been integrated:
864             // http://yuilibrary.com/projects/yui3/ticket/2531274
865             var xhr = new XMLHttpRequest();
866             var self = this;
868             // Update the progress bar
869             xhr.upload.addEventListener('progress', function(e) {
870                 if (e.lengthComputable && self.callbackprogress) {
871                     var percentage = Math.round((e.loaded * 100) / e.total);
872                     self.callbackprogress(filename, percentage);
873                 }
874             }, false);
876             xhr.onreadystatechange = function() { // Process the server response
877                 if (xhr.readyState == 4) {
878                     if (xhr.status == 200) {
879                         var result = JSON.parse(xhr.responseText);
880                         if (result) {
881                             if (result.error) {
882                                 self.print_msg(result.error, 'error'); // TODO add filename?
883                                 self.uploadfinished();
884                             } else {
885                                 // Only update the filepicker if there were no errors
886                                 if (result.event == 'fileexists') {
887                                     // Do not worry about this, as we only care about the last
888                                     // file uploaded, with the filepicker
889                                     result.file = result.newfile.filename;
890                                     result.url = result.newfile.url;
891                                 }
892                                 result.client_id = self.options.clientid;
893                                 if (self.callbackprogress) {
894                                     self.callbackprogress(filename, 100);
895                                 }
896                             }
897                         }
898                         self.do_upload(result); // continue uploading
899                     } else {
900                         self.print_msg(M.util.get_string('serverconnection', 'error'), 'error');
901                         self.uploadfinished();
902                     }
903                 }
904             };
906             // Prepare the data to send
907             var formdata = new FormData();
908             formdata.append('repo_upload_file', file); // The FormData class allows us to attach a file
909             formdata.append('sesskey', M.cfg.sesskey);
910             formdata.append('repo_id', this.repositoryid);
911             formdata.append('itemid', this.options.itemid);
912             if (this.options.author) {
913                 formdata.append('author', this.options.author);
914             }
915             if (this.options.filemanager) { // Filepickers do not have folders
916                 formdata.append('savepath', this.options.filemanager.currentpath);
917             }
918             formdata.append('title', filename);
919             if (overwrite) {
920                 formdata.append('overwrite', 1);
921             }
922             if (this.options.contextid) {
923                 formdata.append('ctx_id', this.options.contextid);
924             }
926             // Accepted types can be either a string or an array, but an array is
927             // expected in the processing script, so make sure we are sending an array
928             if (this.options.acceptedtypes.constructor == Array) {
929                 for (var i=0; i<this.options.acceptedtypes.length; i++) {
930                     formdata.append('accepted_types[]', this.options.acceptedtypes[i]);
931                 }
932             } else {
933                 formdata.append('accepted_types[]', this.options.acceptedtypes);
934             }
936             // Send the file & required details.
937             var uploadUrl = this.api;
938             if (uploadUrl.indexOf('?') !== -1) {
939                 uploadUrl += '&action=upload';
940             } else {
941                 uploadUrl += '?action=upload';
942             }
943             xhr.open("POST", uploadUrl, true);
944             xhr.send(formdata);
945             return true;
946         },
948         /**
949          * Set the event to prevent user navigate away when upload progress still running.
950          *
951          * @param {bool} enable true if upload progress is running, false otherwise
952          */
953         reportUploadDirtyState: function(enable) {
954             if (!enable) {
955                 window.onbeforeunload = this.originalUnloadEvent;
956             } else {
957                 window.onbeforeunload = function(e) {
958                     var warningMessage = M.util.get_string('changesmadereallygoaway', 'moodle');
959                     if (e) {
960                         e.returnValue = warningMessage;
961                     }
962                     return warningMessage;
963                 };
964             }
965         }
966     });
968     dnduploadhelper.init(Y, options);