MDL-45536 atto_html: Update the textarea size when switching to HTML view
[moodle.git] / lib / form / dndupload.js
blobf93f261c0005678f71775d4454cf10788fcff9c3
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
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          *            containerid: htmlid of container
73          *            repositories: array of repository objects passed from filepicker
74          *            filemanager: filemanager element we are working with
75          *            formcallback: callback  to filepicker element to refesh when uploaded
76          *          }
77          */
78         init: function(Y, options) {
79             this.Y = Y;
81             if (!this.browser_supported()) {
82                 Y.one('body').addClass('dndnotsupported');
83                 return; // Browser does not support the required functionality
84             }
85             Y.one('body').addClass('dndsupported');
87             // try and retrieve enabled upload repository
88             this.repositoryid = this.get_upload_repositoryid(options.repositories);
90             if (!this.repositoryid) {
91                 return; // no upload repository is enabled to upload to
92             }
94             this.options = options;
95             this.acceptedtypes = options.acceptedtypes;
96             this.clientid = options.clientid;
97             this.maxbytes = options.maxbytes;
98             this.areamaxbytes = options.areamaxbytes;
99             this.itemid = options.itemid;
100             this.author = options.author;
101             this.container = this.Y.one('#'+options.containerid);
103             if (options.filemanager) {
104                 // Needed to tell the filemanager to redraw when files uploaded
105                 // and to check how many files are already uploaded
106                 this.filemanager = options.filemanager;
107             } else if (options.formcallback) {
109                 // Needed to tell the filepicker to update when a new
110                 // file is uploaded
111                 this.callback = options.formcallback;
112             } else {
113                 if (M.cfg.developerdebug) {
114                     alert('dndupload: Need to define either options.filemanager or options.formcallback');
115                 }
116                 return;
117             }
119             this.init_events();
120             this.init_page_events();
121         },
123         /**
124          * Check the browser has the required functionality
125          * @return true if browser supports drag/drop upload
126          */
127         browser_supported: function() {
129             if (typeof FileReader == 'undefined') {
130                 return false;
131             }
132             if (typeof FormData == 'undefined') {
133                 return false;
134             }
135             return true;
136         },
138         /**
139          * Get upload repoistory from array of enabled repositories
140          *
141          * @param array repositories repository objects passed from filepicker
142          * @param returns int id of upload repository or false if not found
143          */
144         get_upload_repositoryid: function(repositories) {
145             for (var i in repositories) {
146                 if (repositories[i].type == "upload") {
147                     return repositories[i].id;
148                 }
149             }
151             return false;
152         },
154         /**
155          * Initialise drag events on node container, all events need
156          * to be processed for drag and drop to work
157          */
158         init_events: function() {
159             this.Y.on('dragenter', this.drag_enter, this.container, this);
160             this.Y.on('dragleave', this.drag_leave, this.container, this);
161             this.Y.on('dragover',  this.drag_over,  this.container, this);
162             this.Y.on('drop',      this.drop,      this.container, this);
163         },
165         /**
166          * Initialise whole-page events (to show / hide the 'drop files here'
167          * message)
168          */
169         init_page_events: function() {
170             this.Y.on('dragenter', this.drag_enter_page, 'body', this);
171             this.Y.on('dragleave', this.drag_leave_page, 'body', this);
172         },
174         /**
175          * Check if the filemanager / filepicker is disabled
176          * @return bool - true if disabled
177          */
178         is_disabled: function() {
179             return (this.container.ancestor('.fitem.disabled') != null);
180         },
182         /**
183          * Show the 'drop files here' message when file(s) are dragged
184          * onto the page
185          */
186         drag_enter_page: function(e) {
187             if (this.is_disabled()) {
188                 return false;
189             }
190             if (!this.has_files(e)) {
191                 return false;
192             }
194             this.pageentercount++;
195             if (this.pageentercount >= 2) {
196                 this.pageentercount = 2;
197                 return false;
198             }
200             this.show_drop_target();
202             return false;
203         },
205         /**
206          * Hide the 'drop files here' message when file(s) are dragged off
207          * the page again
208          */
209         drag_leave_page: function(e) {
210             this.pageentercount--;
211             if (this.pageentercount == 1) {
212                 return false;
213             }
214             this.pageentercount = 0;
216             this.hide_drop_target();
218             return false;
219         },
221         /**
222          * Check if the drag contents are valid and then call
223          * preventdefault / stoppropagation to let the browser know
224          * we will handle this drag/drop
225          *
226          * @param e event object
227          * @return boolean true if a valid file drag event
228          */
229         check_drag: function(e) {
230             if (this.is_disabled()) {
231                 return false;
232             }
233             if (!this.has_files(e)) {
234                 return false;
235             }
237             e.preventDefault();
238             e.stopPropagation();
240             return true;
241         },
243         /**
244          * Handle a dragenter event, highlight the destination node
245          * when a suitable drag event occurs
246          */
247         drag_enter: function(e) {
248             if (!this.check_drag(e)) {
249                 return true;
250             }
252             this.entercount++;
253             if (this.entercount >= 2) {
254                 this.entercount = 2; // Just moved over a child element - nothing to do
255                 return false;
256             }
258             // These lines are needed if the user has dragged something directly
259             // from application onto the 'fileupload' box, without crossing another
260             // part of the page first
261             this.pageentercount = 2;
262             this.show_drop_target();
264             this.show_upload_ready();
265             return false;
266         },
268         /**
269          * Handle a dragleave event, Remove the highlight if dragged from
270          * node
271          */
272         drag_leave: function(e) {
273             if (!this.check_drag(e)) {
274                 return true;
275             }
277             this.entercount--;
278             if (this.entercount == 1) {
279                 return false; // Just moved over a child element - nothing to do
280             }
282             this.entercount = 0;
283             this.hide_upload_ready();
284             return false;
285         },
287         /**
288          * Handle a dragover event. Required to intercept to prevent the browser from
289          * handling the drag and drop event as normal
290          */
291         drag_over: function(e) {
292             if (!this.check_drag(e)) {
293                 return true;
294             }
296             return false;
297         },
299         /**
300          * Handle a drop event.  Remove the highlight and then upload each
301          * of the files (until we reach the file limit, or run out of files)
302          */
303         drop: function(e) {
304             if (!this.check_drag(e, true)) {
305                 return true;
306             }
308             this.entercount = 0;
309             this.pageentercount = 0;
310             this.hide_upload_ready();
311             this.hide_drop_target();
313             var files = e._event.dataTransfer.files;
314             if (this.filemanager) {
315                 var options = {
316                     files: files,
317                     options: this.options,
318                     repositoryid: this.repositoryid,
319                     currentfilecount: this.filemanager.filecount, // All files uploaded.
320                     currentfiles: this.filemanager.options.list, // Only the current folder.
321                     callback: Y.bind('update_filemanager', this),
322                     callbackprogress: Y.bind('update_progress', this),
323                     callbackcancel:Y.bind('hide_progress', this)
324                 };
325                 this.clear_progress();
326                 this.show_progress();
327                 var uploader = new dnduploader(options);
328                 uploader.start_upload();
329             } else {
330                 if (files.length >= 1) {
331                     options = {
332                         files:[files[0]],
333                         options: this.options,
334                         repositoryid: this.repositoryid,
335                         currentfilecount: 0,
336                         currentfiles: [],
337                         callback: Y.bind('update_filemanager', this),
338                         callbackprogress: Y.bind('update_progress', this),
339                         callbackcancel:Y.bind('hide_progress', this)
340                     };
341                     this.clear_progress();
342                     this.show_progress();
343                     uploader = new dnduploader(options);
344                     uploader.start_upload();
345                 }
346             }
348             return false;
349         },
351         /**
352          * Check to see if the drag event has any files in it
353          *
354          * @param e event object
355          * @return boolean true if event has files
356          */
357         has_files: function(e) {
358             // In some browsers, dataTransfer.types may be null for a
359             // 'dragover' event, so ensure a valid Array is always
360             // inspected.
361             var types = e._event.dataTransfer.types || [];
362             for (var i=0; i<types.length; i++) {
363                 if (types[i] == 'Files') {
364                     return true;
365                 }
366             }
367             return false;
368         },
370         /**
371          * Highlight the area where files could be dropped
372          */
373         show_drop_target: function() {
374             this.container.addClass('dndupload-ready');
375         },
377         hide_drop_target: function() {
378             this.container.removeClass('dndupload-ready');
379         },
381         /**
382          * Highlight the destination node (ready to drop)
383          */
384         show_upload_ready: function() {
385             this.container.addClass('dndupload-over');
386         },
388         /**
389          * Remove highlight on destination node
390          */
391         hide_upload_ready: function() {
392             this.container.removeClass('dndupload-over');
393         },
395         /**
396          * Show the element showing the upload in progress
397          */
398         show_progress: function() {
399             this.container.addClass('dndupload-inprogress');
400         },
402         /**
403          * Hide the element showing upload in progress
404          */
405         hide_progress: function() {
406             this.container.removeClass('dndupload-inprogress');
407         },
409         /**
410          * Tell the attached filemanager element (if any) to refresh on file
411          * upload
412          */
413         update_filemanager: function(params) {
414             this.hide_progress();
415             if (this.filemanager) {
416                 // update the filemanager that we've uploaded the files
417                 this.filemanager.filepicker_callback();
418             } else if (this.callback) {
419                 this.callback(params);
420             }
421         },
423         /**
424          * Clear the current progress bars
425          */
426         clear_progress: function() {
427             var filename;
428             for (filename in this.progressbars) {
429                 if (this.progressbars.hasOwnProperty(filename)) {
430                     this.progressbars[filename].progressouter.remove(true);
431                     delete this.progressbars[filename];
432                 }
433             }
434         },
436         /**
437          * Show the current progress of the uploaded file
438          */
439         update_progress: function(filename, percent) {
440             if (this.progressbars[filename] === undefined) {
441                 var dispfilename = filename;
442                 if (dispfilename.length > 50) {
443                     dispfilename = dispfilename.substr(0, 49)+'&hellip;';
444                 }
445                 var progressouter = this.container.create('<span>'+dispfilename+': <span class="dndupload-progress-outer"><span class="dndupload-progress-inner">&nbsp;</span></span><br /></span>');
446                 var progressinner = progressouter.one('.dndupload-progress-inner');
447                 var progresscontainer = this.container.one('.dndupload-progressbars');
448                 progresscontainer.appendChild(progressouter);
450                 this.progressbars[filename] = {
451                     progressouter: progressouter,
452                     progressinner: progressinner
453                 };
454             }
456             this.progressbars[filename].progressinner.setStyle('width', percent + '%');
457         }
458     };
460     var dnduploader = function(options) {
461         dnduploader.superclass.constructor.apply(this, arguments);
462     };
464     Y.extend(dnduploader, Y.Base, {
465         // The URL to send the upload data to.
466         api: M.cfg.wwwroot+'/repository/repository_ajax.php',
467         // Options passed into the filemanager/filepicker element.
468         options: {},
469         // The function to call when all uploads complete.
470         callback: null,
471         // The function to call as the upload progresses
472         callbackprogress: null,
473         // The function to call if the upload is cancelled
474         callbackcancel: null,
475         // The list of files dropped onto the element.
476         files: null,
477         // The ID of the 'upload' repository.
478         repositoryid: 0,
479         // Array of files already in the current folder (to check for name clashes).
480         currentfiles: null,
481         // Total number of files already uploaded (to check for exceeding limits).
482         currentfilecount: 0,
483         // Total size of the files present in the area.
484         currentareasize: 0,
485         // The list of files to upload.
486         uploadqueue: [],
487         // This list of files with name clashes.
488         renamequeue: [],
489         // Size of the current queue.
490         queuesize: 0,
491         // Set to true if the user has clicked on 'overwrite all'.
492         overwriteall: false,
493         // Set to true if the user has clicked on 'rename all'.
494         renameall: false,
496         /**
497          * Initialise the settings for the dnduploader
498          * @param object params - includes:
499          *                     options (copied from the filepicker / filemanager)
500          *                     repositoryid - ID of the upload repository
501          *                     callback - the function to call when uploads are complete
502          *                     currentfiles - the list of files already in the current folder in the filemanager
503          *                     currentfilecount - the total files already in the filemanager
504          *                     files - the list of files to upload
505          * @return void
506          */
507         initializer: function(params) {
508             this.options = params.options;
509             this.repositoryid = params.repositoryid;
510             this.callback = params.callback;
511             this.callbackprogress = params.callbackprogress;
512             this.callbackcancel = params.callbackcancel;
513             this.currentfiles = params.currentfiles;
514             this.currentfilecount = params.currentfilecount;
515             this.currentareasize = 0;
517             // Retrieve the current size of the area.
518             for (var i = 0; i < this.currentfiles.length; i++) {
519                 this.currentareasize += this.currentfiles[i].size;
520             };
522             if (!this.initialise_queue(params.files)) {
523                 if (this.callbackcancel) {
524                     this.callbackcancel();
525                 }
526             }
527         },
529         /**
530          * Entry point for starting the upload process (starts by processing any
531          * renames needed)
532          */
533         start_upload: function() {
534             this.process_renames(); // Automatically calls 'do_upload' once renames complete.
535         },
537         /**
538          * Display a message in a popup
539          * @param string msg - the message to display
540          * @param string type - 'error' or 'info'
541          */
542         print_msg: function(msg, type) {
543             var header = M.str.moodle.error;
544             if (type != 'error') {
545                 type = 'info'; // one of only two types excepted
546                 header = M.str.moodle.info;
547             }
548             if (!this.msg_dlg) {
549                 this.msg_dlg_node = Y.Node.createWithFilesSkin(M.core_filepicker.templates.message);
550                 this.msg_dlg_node.generateID();
552                 this.msg_dlg = new Y.Panel({
553                     srcNode      : this.msg_dlg_node,
554                     zIndex       : 8000,
555                     centered     : true,
556                     modal        : true,
557                     visible      : false,
558                     render       : true
559                 });
560                 this.msg_dlg.plug(Y.Plugin.Drag,{handles:['#'+this.msg_dlg_node.get('id')+' .yui3-widget-hd']});
561                 this.msg_dlg_node.one('.fp-msg-butok').on('click', function(e) {
562                     e.preventDefault();
563                     this.msg_dlg.hide();
564                 }, this);
565             }
567             this.msg_dlg.set('headerContent', header);
568             this.msg_dlg_node.removeClass('fp-msg-info').removeClass('fp-msg-error').addClass('fp-msg-'+type)
569             this.msg_dlg_node.one('.fp-msg-text').setContent(msg);
570             this.msg_dlg.show();
571         },
573         /**
574          * Check the size of each file and add to either the uploadqueue or, if there
575          * is a name clash, the renamequeue
576          * @param FileList files - the files to upload
577          * @return void
578          */
579         initialise_queue: function(files) {
580             this.uploadqueue = [];
581             this.renamequeue = [];
582             this.queuesize = 0;
584             // Loop through the files and find any name clashes with existing files.
585             var i;
586             for (i=0; i<files.length; i++) {
587                 if (this.options.maxbytes > 0 && files[i].size > this.options.maxbytes) {
588                     // Check filesize before attempting to upload.
589                     this.print_msg(M.util.get_string('maxbytesforfile', 'moodle', files[i].name), 'error');
590                     this.uploadqueue = []; // No uploads if one file is too big.
591                     return;
592                 }
594                 if (this.has_name_clash(files[i].name)) {
595                     this.renamequeue.push(files[i]);
596                 } else {
597                     if (!this.add_to_upload_queue(files[i], files[i].name, false)) {
598                         return false;
599                     }
600                 }
601                 this.queuesize += files[i].size;
602             }
603             return true;
604         },
606         /**
607          * Add a single file to the uploadqueue, whilst checking the maxfiles limit
608          * @param File file - the file to add
609          * @param string filename - the name to give the file on upload
610          * @param bool overwrite - true to overwrite the existing file
611          * @return bool true if added successfully
612          */
613         add_to_upload_queue: function(file, filename, overwrite) {
614             if (!overwrite) {
615                 this.currentfilecount++;
616             }
617             // The value for "unlimited files" is -1, so 0 should mean 0.
618             if (this.options.maxfiles >= 0 && this.currentfilecount > this.options.maxfiles) {
619                 // Too many files - abort entire upload.
620                 this.uploadqueue = [];
621                 this.renamequeue = [];
622                 this.print_msg(M.util.get_string('maxfilesreached', 'moodle', this.options.maxfiles), 'error');
623                 return false;
624             }
625             // The new file will cause the area to reach its limit, we cancel the upload of all files.
626             // -1 is the value defined by FILE_AREA_MAX_BYTES_UNLIMITED.
627             if (this.options.areamaxbytes > -1) {
628                 var sizereached = this.currentareasize + this.queuesize + file.size;
629                 if (sizereached > this.options.areamaxbytes) {
630                     this.uploadqueue = [];
631                     this.renamequeue = [];
632                     this.print_msg(M.util.get_string('maxareabytesreached', 'moodle'), 'error');
633                     return false;
634                 }
635             }
636             this.uploadqueue.push({file:file, filename:filename, overwrite:overwrite});
637             return true;
638         },
640         /**
641          * Take the next file from the renamequeue and ask the user what to do with
642          * it. Called recursively until the queue is empty, then calls do_upload.
643          * @return void
644          */
645         process_renames: function() {
646             if (this.renamequeue.length == 0) {
647                 // All rename processing complete - start the actual upload.
648                 this.do_upload();
649                 return;
650             }
651             var multiplefiles = (this.renamequeue.length > 1);
653             // Get the next file from the rename queue.
654             var file = this.renamequeue.shift();
655             // Generate a non-conflicting name for it.
656             var newname = this.generate_unique_name(file.name);
658             // If the user has clicked on overwrite/rename ALL then process
659             // this file, as appropriate, then process the rest of the queue.
660             if (this.overwriteall) {
661                 this.add_to_upload_queue(file, file.name, true);
662                 this.process_renames();
663                 return;
664             }
665             if (this.renameall) {
666                 this.add_to_upload_queue(file, newname, false);
667                 this.process_renames();
668                 return;
669             }
671             // Ask the user what to do with this file.
672             var self = this;
674             var process_dlg_node;
675             if (multiplefiles) {
676                 process_dlg_node = Y.Node.createWithFilesSkin(M.core_filepicker.templates.processexistingfilemultiple);
677             } else {
678                 process_dlg_node = Y.Node.createWithFilesSkin(M.core_filepicker.templates.processexistingfile);
679             }
680             var node = process_dlg_node;
681             node.generateID();
682             var process_dlg = new Y.Panel({
683                 srcNode      : node,
684                 headerContent: M.str.repository.fileexistsdialogheader,
685                 zIndex       : 8000,
686                 centered     : true,
687                 modal        : true,
688                 visible      : false,
689                 render       : true,
690                 buttons      : {}
691             });
692             process_dlg.plug(Y.Plugin.Drag,{handles:['#'+node.get('id')+' .yui3-widget-hd']});
694             // Overwrite original.
695             node.one('.fp-dlg-butoverwrite').on('click', function(e) {
696                 e.preventDefault();
697                 process_dlg.hide();
698                 self.add_to_upload_queue(file, file.name, true);
699                 self.process_renames();
700             }, this);
702             // Rename uploaded file.
703             node.one('.fp-dlg-butrename').on('click', function(e) {
704                 e.preventDefault();
705                 process_dlg.hide();
706                 self.add_to_upload_queue(file, newname, false);
707                 self.process_renames();
708             }, this);
710             // Cancel all uploads.
711             node.one('.fp-dlg-butcancel').on('click', function(e) {
712                 e.preventDefault();
713                 process_dlg.hide();
714                 if (self.callbackcancel) {
715                     self.callbackcancel();
716                 }
717             }, this);
719             // When we are at the file limit, only allow 'overwrite', not rename.
720             if (this.currentfilecount == this.options.maxfiles) {
721                 node.one('.fp-dlg-butrename').setStyle('display', 'none');
722                 if (multiplefiles) {
723                     node.one('.fp-dlg-butrenameall').setStyle('display', 'none');
724                 }
725             }
727             // If there are more files still to go, offer the 'overwrite/rename all' options.
728             if (multiplefiles) {
729                 // Overwrite all original files.
730                 node.one('.fp-dlg-butoverwriteall').on('click', function(e) {
731                     e.preventDefault();
732                     process_dlg.hide();
733                     this.overwriteall = true;
734                     self.add_to_upload_queue(file, file.name, true);
735                     self.process_renames();
736                 }, this);
738                 // Rename all new files.
739                 node.one('.fp-dlg-butrenameall').on('click', function(e) {
740                     e.preventDefault();
741                     process_dlg.hide();
742                     this.renameall = true;
743                     self.add_to_upload_queue(file, newname, false);
744                     self.process_renames();
745                 }, this);
746             }
747             node.one('.fp-dlg-text').setContent(M.util.get_string('fileexists', 'moodle', file.name));
748             process_dlg_node.one('.fp-dlg-butrename').setContent(M.util.get_string('renameto', 'repository', newname));
750             // Destroy the dialog once it has been hidden.
751             process_dlg.after('visibleChange', function(e) {
752                 if (!process_dlg.get('visible')) {
753                     process_dlg.destroy(true);
754                 }
755             });
757             process_dlg.show();
758         },
760         /**
761          * Checks if there is already a file with the given name in the current folder
762          * or in the list of already uploading files
763          * @param string filename - the name to test
764          * @return bool true if the name already exists
765          */
766         has_name_clash: function(filename) {
767             // Check against the already uploaded files
768             var i;
769             for (i=0; i<this.currentfiles.length; i++) {
770                 if (filename == this.currentfiles[i].filename) {
771                     return true;
772                 }
773             }
774             // Check against the uploading files that have already been processed
775             for (i=0; i<this.uploadqueue.length; i++) {
776                 if (filename == this.uploadqueue[i].filename) {
777                     return true;
778                 }
779             }
780             return false;
781         },
783         /**
784          * Gets a unique file name
785          *
786          * @param string filename
787          * @return string the unique filename generated
788          */
789         generate_unique_name: function(filename) {
790             // Loop through increating numbers until a unique name is found.
791             while (this.has_name_clash(filename)) {
792                 filename = increment_filename(filename);
793             }
794             return filename;
795         },
797         /**
798          * Upload the next file from the uploadqueue - called recursively after each
799          * upload is complete, then handles the callback to the filemanager/filepicker
800          * @param lastresult - the last result from the server
801          */
802         do_upload: function(lastresult) {
803             if (this.uploadqueue.length > 0) {
804                 var filedetails = this.uploadqueue.shift();
805                 this.upload_file(filedetails.file, filedetails.filename, filedetails.overwrite);
806             } else {
807                 this.uploadfinished(lastresult);
808             }
809         },
811         /**
812          * Run the callback to the filemanager/filepicker
813          */
814         uploadfinished: function(lastresult) {
815             this.callback(lastresult);
816         },
818         /**
819          * Upload a single file via an AJAX call to the 'upload' repository. Automatically
820          * calls do_upload as each upload completes.
821          * @param File file - the file to upload
822          * @param string filename - the name to give the file
823          * @param bool overwrite - true if the existing file should be overwritten
824          */
825         upload_file: function(file, filename, overwrite) {
827             // This would be an ideal place to use the Y.io function
828             // however, this does not support data encoded using the
829             // FormData object, which is needed to transfer data from
830             // the DataTransfer object into an XMLHTTPRequest
831             // This can be converted when the YUI issue has been integrated:
832             // http://yuilibrary.com/projects/yui3/ticket/2531274
833             var xhr = new XMLHttpRequest();
834             var self = this;
836             // Update the progress bar
837             xhr.upload.addEventListener('progress', function(e) {
838                 if (e.lengthComputable && self.callbackprogress) {
839                     var percentage = Math.round((e.loaded * 100) / e.total);
840                     self.callbackprogress(filename, percentage);
841                 }
842             }, false);
844             xhr.onreadystatechange = function() { // Process the server response
845                 if (xhr.readyState == 4) {
846                     if (xhr.status == 200) {
847                         var result = JSON.parse(xhr.responseText);
848                         if (result) {
849                             if (result.error) {
850                                 self.print_msg(result.error, 'error'); // TODO add filename?
851                                 self.uploadfinished();
852                             } else {
853                                 // Only update the filepicker if there were no errors
854                                 if (result.event == 'fileexists') {
855                                     // Do not worry about this, as we only care about the last
856                                     // file uploaded, with the filepicker
857                                     result.file = result.newfile.filename;
858                                     result.url = result.newfile.url;
859                                 }
860                                 result.client_id = self.options.clientid;
861                                 if (self.callbackprogress) {
862                                     self.callbackprogress(filename, 100);
863                                 }
864                             }
865                         }
866                         self.do_upload(result); // continue uploading
867                     } else {
868                         self.print_msg(M.util.get_string('serverconnection', 'error'), 'error');
869                         self.uploadfinished();
870                     }
871                 }
872             };
874             // Prepare the data to send
875             var formdata = new FormData();
876             formdata.append('action', 'upload');
877             formdata.append('repo_upload_file', file); // The FormData class allows us to attach a file
878             formdata.append('sesskey', M.cfg.sesskey);
879             formdata.append('repo_id', this.repositoryid);
880             formdata.append('itemid', this.options.itemid);
881             if (this.options.author) {
882                 formdata.append('author', this.options.author);
883             }
884             if (this.options.filemanager) { // Filepickers do not have folders
885                 formdata.append('savepath', this.options.filemanager.currentpath);
886             }
887             formdata.append('title', filename);
888             if (overwrite) {
889                 formdata.append('overwrite', 1);
890             }
892             // Accepted types can be either a string or an array, but an array is
893             // expected in the processing script, so make sure we are sending an array
894             if (this.options.acceptedtypes.constructor == Array) {
895                 for (var i=0; i<this.options.acceptedtypes.length; i++) {
896                     formdata.append('accepted_types[]', this.options.acceptedtypes[i]);
897                 }
898             } else {
899                 formdata.append('accepted_types[]', this.options.acceptedtypes);
900             }
902             // Send the file & required details
903             xhr.open("POST", this.api, true);
904             xhr.send(formdata);
905             return true;
906         }
907     });
909     dnduploadhelper.init(Y, options);