1 // This file is part of Moodle - http://moodle.org/
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.
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/>.
17 * Javascript library for enableing a drag and drop upload interface
21 * @copyright 2011 Davo Smith
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 M.form_dndupload.init = function(Y, options) {
28 var dnduploadhelper = {
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
35 // itemid used for repository upload
37 // accepted filetypes accepted by this form passed to repository
39 // maximum size of files allowed in this form
41 // Maximum combined size of files allowed in this form. {@link FILE_AREA_MAX_BYTES_UNLIMITED}
43 // unqiue id of this form field used for html elements
45 // upload repository id, used for upload
47 // container which holds the node which recieves drag events
49 // filemanager element we are working with
51 // callback to filepicker element to refesh when uploaded
53 // Nasty hack to distinguish between dragenter(first entry),
54 // dragenter+dragleave(moving between child elements) and dragleave (leaving element)
57 // Holds the progress bar elements for each file.
61 * Initalise the drag and drop upload interface
62 * Note: one and only one of options.filemanager and options.formcallback must be defined
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
78 init: function(Y, options) {
81 if (!this.browser_supported()) {
82 Y.one('body').addClass('dndnotsupported');
83 return; // Browser does not support the required functionality
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
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
111 this.callback = options.formcallback;
113 if (M.cfg.developerdebug) {
114 alert('dndupload: Need to define either options.filemanager or options.formcallback');
120 this.init_page_events();
124 * Check the browser has the required functionality
125 * @return true if browser supports drag/drop upload
127 browser_supported: function() {
129 if (typeof FileReader == 'undefined') {
132 if (typeof FormData == 'undefined') {
139 * Get upload repoistory from array of enabled repositories
141 * @param array repositories repository objects passed from filepicker
142 * @param returns int id of upload repository or false if not found
144 get_upload_repositoryid: function(repositories) {
145 for (var i in repositories) {
146 if (repositories[i].type == "upload") {
147 return repositories[i].id;
155 * Initialise drag events on node container, all events need
156 * to be processed for drag and drop to work
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);
166 * Initialise whole-page events (to show / hide the 'drop files here'
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);
175 * Check if the filemanager / filepicker is disabled
176 * @return bool - true if disabled
178 is_disabled: function() {
179 return (this.container.ancestor('.fitem.disabled') != null);
183 * Show the 'drop files here' message when file(s) are dragged
186 drag_enter_page: function(e) {
187 if (this.is_disabled()) {
190 if (!this.has_files(e)) {
194 this.pageentercount++;
195 if (this.pageentercount >= 2) {
196 this.pageentercount = 2;
200 this.show_drop_target();
206 * Hide the 'drop files here' message when file(s) are dragged off
209 drag_leave_page: function(e) {
210 this.pageentercount--;
211 if (this.pageentercount == 1) {
214 this.pageentercount = 0;
216 this.hide_drop_target();
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
226 * @param e event object
227 * @return boolean true if a valid file drag event
229 check_drag: function(e) {
230 if (this.is_disabled()) {
233 if (!this.has_files(e)) {
244 * Handle a dragenter event, highlight the destination node
245 * when a suitable drag event occurs
247 drag_enter: function(e) {
248 if (!this.check_drag(e)) {
253 if (this.entercount >= 2) {
254 this.entercount = 2; // Just moved over a child element - nothing to do
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();
269 * Handle a dragleave event, Remove the highlight if dragged from
272 drag_leave: function(e) {
273 if (!this.check_drag(e)) {
278 if (this.entercount == 1) {
279 return false; // Just moved over a child element - nothing to do
283 this.hide_upload_ready();
288 * Handle a dragover event. Required to intercept to prevent the browser from
289 * handling the drag and drop event as normal
291 drag_over: function(e) {
292 if (!this.check_drag(e)) {
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)
304 if (!this.check_drag(e, true)) {
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) {
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)
325 this.clear_progress();
326 this.show_progress();
327 var uploader = new dnduploader(options);
328 uploader.start_upload();
330 if (files.length >= 1) {
333 options: this.options,
334 repositoryid: this.repositoryid,
337 callback: Y.bind('update_filemanager', this),
338 callbackprogress: Y.bind('update_progress', this),
339 callbackcancel:Y.bind('hide_progress', this)
341 this.clear_progress();
342 this.show_progress();
343 uploader = new dnduploader(options);
344 uploader.start_upload();
352 * Check to see if the drag event has any files in it
354 * @param e event object
355 * @return boolean true if event has files
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
361 var types = e._event.dataTransfer.types || [];
362 for (var i=0; i<types.length; i++) {
363 if (types[i] == 'Files') {
371 * Highlight the area where files could be dropped
373 show_drop_target: function() {
374 this.container.addClass('dndupload-ready');
377 hide_drop_target: function() {
378 this.container.removeClass('dndupload-ready');
382 * Highlight the destination node (ready to drop)
384 show_upload_ready: function() {
385 this.container.addClass('dndupload-over');
389 * Remove highlight on destination node
391 hide_upload_ready: function() {
392 this.container.removeClass('dndupload-over');
396 * Show the element showing the upload in progress
398 show_progress: function() {
399 this.container.addClass('dndupload-inprogress');
403 * Hide the element showing upload in progress
405 hide_progress: function() {
406 this.container.removeClass('dndupload-inprogress');
410 * Tell the attached filemanager element (if any) to refresh on file
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);
424 * Clear the current progress bars
426 clear_progress: function() {
428 for (filename in this.progressbars) {
429 if (this.progressbars.hasOwnProperty(filename)) {
430 this.progressbars[filename].progressouter.remove(true);
431 delete this.progressbars[filename];
437 * Show the current progress of the uploaded file
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)+'…';
445 var progressouter = this.container.create('<span>'+dispfilename+': <span class="dndupload-progress-outer"><span class="dndupload-progress-inner"> </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
456 this.progressbars[filename].progressinner.setStyle('width', percent + '%');
460 var dnduploader = function(options) {
461 dnduploader.superclass.constructor.apply(this, arguments);
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.
469 // The function to call when all uploads complete.
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.
477 // The ID of the 'upload' repository.
479 // Array of files already in the current folder (to check for name clashes).
481 // Total number of files already uploaded (to check for exceeding limits).
483 // Total size of the files present in the area.
485 // The list of files to upload.
487 // This list of files with name clashes.
489 // Size of the current queue.
491 // Set to true if the user has clicked on 'overwrite all'.
493 // Set to true if the user has clicked on 'rename all'.
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
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;
522 if (!this.initialise_queue(params.files)) {
523 if (this.callbackcancel) {
524 this.callbackcancel();
530 * Entry point for starting the upload process (starts by processing any
533 start_upload: function() {
534 this.process_renames(); // Automatically calls 'do_upload' once renames complete.
538 * Display a message in a popup
539 * @param string msg - the message to display
540 * @param string type - 'error' or 'info'
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;
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,
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) {
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);
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
579 initialise_queue: function(files) {
580 this.uploadqueue = [];
581 this.renamequeue = [];
584 // Loop through the files and find any name clashes with existing files.
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.
594 if (this.has_name_clash(files[i].name)) {
595 this.renamequeue.push(files[i]);
597 if (!this.add_to_upload_queue(files[i], files[i].name, false)) {
601 this.queuesize += files[i].size;
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
613 add_to_upload_queue: function(file, filename, overwrite) {
615 this.currentfilecount++;
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');
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');
636 this.uploadqueue.push({file:file, filename:filename, overwrite:overwrite});
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.
645 process_renames: function() {
646 if (this.renamequeue.length == 0) {
647 // All rename processing complete - start the actual upload.
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();
665 if (this.renameall) {
666 this.add_to_upload_queue(file, newname, false);
667 this.process_renames();
671 // Ask the user what to do with this file.
674 var process_dlg_node;
676 process_dlg_node = Y.Node.createWithFilesSkin(M.core_filepicker.templates.processexistingfilemultiple);
678 process_dlg_node = Y.Node.createWithFilesSkin(M.core_filepicker.templates.processexistingfile);
680 var node = process_dlg_node;
682 var process_dlg = new Y.Panel({
684 headerContent: M.str.repository.fileexistsdialogheader,
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) {
698 self.add_to_upload_queue(file, file.name, true);
699 self.process_renames();
702 // Rename uploaded file.
703 node.one('.fp-dlg-butrename').on('click', function(e) {
706 self.add_to_upload_queue(file, newname, false);
707 self.process_renames();
710 // Cancel all uploads.
711 node.one('.fp-dlg-butcancel').on('click', function(e) {
714 if (self.callbackcancel) {
715 self.callbackcancel();
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');
723 node.one('.fp-dlg-butrenameall').setStyle('display', 'none');
727 // If there are more files still to go, offer the 'overwrite/rename all' options.
729 // Overwrite all original files.
730 node.one('.fp-dlg-butoverwriteall').on('click', function(e) {
733 this.overwriteall = true;
734 self.add_to_upload_queue(file, file.name, true);
735 self.process_renames();
738 // Rename all new files.
739 node.one('.fp-dlg-butrenameall').on('click', function(e) {
742 this.renameall = true;
743 self.add_to_upload_queue(file, newname, false);
744 self.process_renames();
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);
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
766 has_name_clash: function(filename) {
767 // Check against the already uploaded files
769 for (i=0; i<this.currentfiles.length; i++) {
770 if (filename == this.currentfiles[i].filename) {
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) {
784 * Gets a unique file name
786 * @param string filename
787 * @return string the unique filename generated
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);
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
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);
807 this.uploadfinished(lastresult);
812 * Run the callback to the filemanager/filepicker
814 uploadfinished: function(lastresult) {
815 this.callback(lastresult);
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
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();
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);
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);
850 self.print_msg(result.error, 'error'); // TODO add filename?
851 self.uploadfinished();
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;
860 result.client_id = self.options.clientid;
861 if (self.callbackprogress) {
862 self.callbackprogress(filename, 100);
866 self.do_upload(result); // continue uploading
868 self.print_msg(M.util.get_string('serverconnection', 'error'), 'error');
869 self.uploadfinished();
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);
884 if (this.options.filemanager) { // Filepickers do not have folders
885 formdata.append('savepath', this.options.filemanager.currentpath);
887 formdata.append('title', filename);
889 formdata.append('overwrite', 1);
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]);
899 formdata.append('accepted_types[]', this.options.acceptedtypes);
902 // Send the file & required details
903 xhr.open("POST", this.api, true);
909 dnduploadhelper.init(Y, options);