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 to courses
21 * @copyright 2012 Davo Smith
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 M.course_dndupload = {
27 // URL for upload requests
28 url: M.cfg.wwwroot + '/course/dndupload.php',
29 // maximum size of files allowed in this form
31 // ID of the course we are on
33 // Data about the different file/data handlers that are available
35 // Nasty hack to distinguish between dragenter(first entry),
36 // dragenter+dragleave(moving between child elements) and dragleave (leaving element)
38 // Used to keep track of the section we are dragging across - to make
39 // spotting movement between sections more reliable
41 // Used to store the pending uploads whilst the user is being asked for further input
43 // True if the there is currently a dialog being shown (asking for a name, or giving a
44 // choice of file handlers)
46 // An array containing the last selected file handler for each file type
49 // The following are used to identify specific parts of the course page
51 // The type of HTML element that is a course section
52 sectiontypename: 'li',
53 // The classes that an element must have to be identified as a course section
54 sectionclasses: ['section', 'main'],
55 // The ID of the main content area of the page (for adding the 'status' div)
56 pagecontentid: 'page',
57 // The selector identifying the list of modules within a section (note changing this may require
58 // changes to the get_mods_element function)
59 modslistselector: 'ul.section',
62 * Initalise the drag and drop upload interface
63 * Note: one and only one of options.filemanager and options.formcallback must be defined
65 * @param Y the YUI object
66 * @param object options {
67 * courseid: ID of the course we are on
68 * maxbytes: maximum size of files allowed in this form
69 * handlers: Data about the different file/data handlers that are available
72 init: function(Y, options) {
75 if (!this.browser_supported()) {
76 return; // Browser does not support the required functionality
79 this.maxbytes = options.maxbytes;
80 this.courseid = options.courseid;
81 this.handlers = options.handlers;
82 this.uploadqueue = new Array();
83 this.lastselected = new Array();
85 var sectionselector = this.sectiontypename + '.' + this.sectionclasses.join('.');
86 var sections = this.Y.all(sectionselector);
87 if (sections.isEmpty()) {
88 return; // No sections - incompatible course format or front page.
90 sections.each( function(el) {
91 this.add_preview_element(el);
95 if (options.showstatus) {
96 this.add_status_div();
101 * Add a div element to tell the user that drag and drop upload
102 * is available (or to explain why it is not available)
104 add_status_div: function() {
106 coursecontents = Y.one('#' + this.pagecontentid),
108 handlefile = (this.handlers.filehandlers.length > 0),
115 if (!coursecontents) {
119 div = Y.Node.create('<div id="dndupload-status"></div>').setStyle('opacity', '0.0');
120 coursecontents.insert(div, 0);
122 for (i = 0; i < this.handlers.types.length; i++) {
123 switch (this.handlers.types[i].identifier) {
133 $msgident = 'dndworking';
143 div.setContent(M.util.get_string($msgident, 'moodle'));
145 styletop = div.getStyle('top') || '0px';
146 styletopunit = styletop.replace(/^\d+/, '');
147 styletop = parseInt(styletop.replace(/\D*$/, ''), 10);
149 var fadein = new Y.Anim({
150 node: '#dndupload-status',
153 top: (styletop - 30).toString() + styletopunit
158 top: styletop.toString() + styletopunit
163 var fadeout = new Y.Anim({
164 node: '#dndupload-status',
167 top: styletop.toString() + styletopunit
172 top: (styletop - 30).toString() + styletopunit
178 fadein.on('end', function(e) {
179 Y.later(3000, this, function() {
184 fadeout.on('end', function(e) {
185 Y.one('#dndupload-status').remove(true);
190 * Check the browser has the required functionality
191 * @return true if browser supports drag/drop upload
193 browser_supported: function() {
194 if (typeof FileReader == 'undefined') {
197 if (typeof FormData == 'undefined') {
204 * Initialise drag events on node container, all events need
205 * to be processed for drag and drop to work
206 * @param el the element to add events to
208 init_events: function(el) {
209 this.Y.on('dragenter', this.drag_enter, el, this);
210 this.Y.on('dragleave', this.drag_leave, el, this);
211 this.Y.on('dragover', this.drag_over, el, this);
212 this.Y.on('drop', this.drop, el, this);
216 * Work out which course section a given element is in
217 * @param el the child DOM element within the section
218 * @return the DOM element representing the section
220 get_section: function(el) {
221 var sectionclasses = this.sectionclasses;
222 return el.ancestor( function(test) {
224 for (i=0; i<sectionclasses.length; i++) {
225 if (!test.hasClass(sectionclasses[i])) {
234 * Work out the number of the section we have been dropped on to, from the section element
235 * @param DOMElement section the selected section
236 * @return int the section number
238 get_section_number: function(section) {
239 var sectionid = section.get('id').split('-');
240 if (sectionid.length < 2 || sectionid[0] != 'section') {
243 return parseInt(sectionid[1]);
247 * Check if the event includes data of the given type
248 * @param e the event details
249 * @param type the data type to check for
250 * @return true if the data type is found in the event data
252 types_includes: function(e, type) {
254 var types = e._event.dataTransfer.types;
255 type = type.toLowerCase();
256 for (i=0; i<types.length; i++) {
257 if (!types.hasOwnProperty(i)) {
260 if (types[i].toLowerCase() === type) {
268 * Look through the event data, checking it against the registered data types
269 * (in order of priority) and return details of the first matching data type
270 * @param e the event details
271 * @return object|false - false if not found or an object {
272 * realtype: the type as given by the browser
273 * addmessage: the message to show to the user during dragging
274 * namemessage: the message for requesting a name for the resource from the user
275 * type: the identifier of the type (may match several 'realtype's)
278 drag_type: function(e) {
279 // Check there is some data attached.
280 if (e._event.dataTransfer === null) {
283 if (e._event.dataTransfer.types === null) {
286 if (e._event.dataTransfer.types.length == 0) {
290 // Check for files first.
291 if (this.types_includes(e, 'Files')) {
292 if (e.type != 'drop' || e._event.dataTransfer.files.length != 0) {
293 if (this.handlers.filehandlers.length == 0) {
294 return false; // No available file handlers - ignore this drag.
298 addmessage: M.util.get_string('addfilehere', 'moodle'),
299 namemessage: null, // Should not be asked for anyway
305 // Check each of the registered types.
306 var types = this.handlers.types;
307 for (var i=0; i<types.length; i++) {
308 // Check each of the different identifiers for this type
309 var dttypes = types[i].datatransfertypes;
310 for (var j=0; j<dttypes.length; j++) {
311 if (this.types_includes(e, dttypes[j])) {
313 realtype: dttypes[j],
314 addmessage: types[i].addmessage,
315 namemessage: types[i].namemessage,
316 handlermessage: types[i].handlermessage,
317 type: types[i].identifier,
318 handlers: types[i].handlers
323 return false; // No types we can handle
327 * Check the content of the drag/drop includes a type we can handle, then, if
328 * it is, notify the browser that we want to handle it
330 * @return string type of the event or false
332 check_drag: function(e) {
333 var type = this.drag_type(e);
335 // Notify browser that we will handle this drag/drop
343 * Handle a dragenter event: add a suitable 'add here' message
344 * when a drag event occurs, containing a registered data type
345 * @param e event data
346 * @return false to prevent the event from continuing to be processed
348 drag_enter: function(e) {
349 if (!(type = this.check_drag(e))) {
353 var section = this.get_section(e.currentTarget);
358 if (this.currentsection && this.currentsection != section) {
359 this.currentsection = section;
363 if (this.entercount > 2) {
369 this.show_preview_element(section, type);
375 * Handle a dragleave event: remove the 'add here' message (if present)
376 * @param e event data
377 * @return false to prevent the event from continuing to be processed
379 drag_leave: function(e) {
380 if (!this.check_drag(e)) {
385 if (this.entercount == 1) {
389 this.currentsection = null;
391 this.hide_preview_element();
396 * Handle a dragover event: just prevent the browser default (necessary
397 * to allow drag and drop handling to work)
398 * @param e event data
399 * @return false to prevent the event from continuing to be processed
401 drag_over: function(e) {
407 * Handle a drop event: hide the 'add here' message, check the attached
408 * data type and start the upload process
409 * @param e event data
410 * @return false to prevent the event from continuing to be processed
413 this.hide_preview_element();
415 if (!(type = this.check_drag(e))) {
419 // Work out the number of the section we are on (from its id)
420 var section = this.get_section(e.currentTarget);
421 var sectionnumber = this.get_section_number(section);
423 // Process the file or the included data
424 if (type.type == 'Files') {
425 var files = e._event.dataTransfer.files;
426 for (var i=0, f; f=files[i]; i++) {
427 this.handle_file(f, section, sectionnumber);
430 var contents = e._event.dataTransfer.getData(type.realtype);
432 this.handle_item(type, contents, section, sectionnumber);
440 * Find or create the 'ul' element that contains all of the module
441 * instances in this section
442 * @param section the DOM element representing the section
443 * @return false to prevent the event from continuing to be processed
445 get_mods_element: function(section) {
446 // Find the 'ul' containing the list of mods
447 var modsel = section.one(this.modslistselector);
449 // Create the above 'ul' if it doesn't exist
450 modsel = document.createElement('ul');
451 modsel.className = 'section img-text';
452 var contentel = section.get('children').pop();
453 var brel = contentel.get('children').pop();
454 contentel.insertBefore(modsel, brel);
455 modsel = this.Y.one(modsel);
462 * Add a new dummy item to the list of mods, to be replaced by a real
463 * item & link once the AJAX upload call has completed
464 * @param name the label to show in the element
465 * @param section the DOM element reperesenting the course section
466 * @return DOM element containing the new item
468 add_resource_element: function(name, section, module) {
469 var modsel = this.get_mods_element(section);
473 li: document.createElement('li'),
474 div: document.createElement('div'),
475 indentdiv: document.createElement('div'),
476 a: document.createElement('a'),
477 icon: document.createElement('img'),
478 namespan: document.createElement('span'),
479 groupingspan: document.createElement('span'),
480 progressouter: document.createElement('span'),
481 progress: document.createElement('span')
484 resel.li.className = 'activity ' + module + ' modtype_' + module;
486 resel.indentdiv.className = 'mod-indent';
487 resel.li.appendChild(resel.indentdiv);
489 resel.div.className = 'activityinstance';
490 resel.indentdiv.appendChild(resel.div);
493 resel.div.appendChild(resel.a);
495 resel.icon.src = M.util.image_url('i/ajaxloader');
496 resel.icon.className = 'activityicon iconlarge';
497 resel.a.appendChild(resel.icon);
499 resel.namespan.className = 'instancename';
500 resel.namespan.innerHTML = name;
501 resel.a.appendChild(resel.namespan);
503 resel.groupingspan.className = 'groupinglabel';
504 resel.div.appendChild(resel.groupingspan);
506 resel.progressouter.className = 'dndupload-progress-outer';
507 resel.progress.className = 'dndupload-progress-inner';
508 resel.progress.innerHTML = ' ';
509 resel.progressouter.appendChild(resel.progress);
510 resel.div.appendChild(resel.progressouter);
512 modsel.insertBefore(resel.li, modsel.get('children').pop()); // Leave the 'preview element' at the bottom
518 * Hide any visible dndupload-preview elements on the page
520 hide_preview_element: function() {
521 this.Y.all('li.dndupload-preview').addClass('dndupload-hidden');
522 this.Y.all('.dndupload-over').removeClass('dndupload-over');
526 * Unhide the preview element for the given section and set it to display
527 * the correct message
528 * @param section the YUI node representing the selected course section
529 * @param type the details of the data type detected in the drag (including the message to display)
531 show_preview_element: function(section, type) {
532 this.hide_preview_element();
533 var preview = section.one('li.dndupload-preview').removeClass('dndupload-hidden');
534 section.addClass('dndupload-over');
536 // Horrible work-around to allow the 'Add X here' text to be a drop target in Firefox.
537 var node = preview.one('span').getDOMNode();
538 node.firstChild.nodeValue = type.addmessage;
542 * Add the preview element to a course section. Note: this needs to be done before 'addEventListener'
543 * is called, otherwise Firefox will ignore events generated when the mouse is over the preview
544 * element (instead of passing them up to the parent element)
545 * @param section the YUI node representing the selected course section
547 add_preview_element: function(section) {
548 var modsel = this.get_mods_element(section);
550 li: document.createElement('li'),
551 div: document.createElement('div'),
552 icon: document.createElement('img'),
553 namespan: document.createElement('span')
556 preview.li.className = 'dndupload-preview dndupload-hidden';
558 preview.div.className = 'mod-indent';
559 preview.li.appendChild(preview.div);
561 preview.icon.src = M.util.image_url('t/addfile');
562 preview.icon.className = 'icon';
563 preview.div.appendChild(preview.icon);
565 preview.div.appendChild(document.createTextNode(' '));
567 preview.namespan.className = 'instancename';
568 preview.namespan.innerHTML = M.util.get_string('addfilehere', 'moodle');
569 preview.div.appendChild(preview.namespan);
571 modsel.appendChild(preview.li);
575 * Find the registered handler for the given file type. If there is more than one, ask the
576 * user which one to use. Then upload the file to the server
577 * @param file the details of the file, taken from the FileList in the drop event
578 * @param section the DOM element representing the selected course section
579 * @param sectionnumber the number of the selected course section
581 handle_file: function(file, section, sectionnumber) {
582 var handlers = new Array();
583 var filehandlers = this.handlers.filehandlers;
585 var dotpos = file.name.lastIndexOf('.');
587 extension = file.name.substr(dotpos+1, file.name.length).toLowerCase();
590 for (var i=0; i<filehandlers.length; i++) {
591 if (filehandlers[i].extension == '*' || filehandlers[i].extension == extension) {
592 handlers.push(filehandlers[i]);
596 if (handlers.length == 0) {
597 // No handlers at all (not even 'resource'?)
601 if (handlers.length == 1) {
602 this.upload_file(file, section, sectionnumber, handlers[0].module);
606 this.file_handler_dialog(handlers, extension, file, section, sectionnumber);
610 * Show a dialog box, allowing the user to choose what to do with the file they are uploading
611 * @param handlers the available handlers to choose between
612 * @param extension the extension of the file being uploaded
613 * @param file the File object being uploaded
614 * @param section the DOM element of the section being uploaded to
615 * @param sectionnumber the number of the selected course section
617 file_handler_dialog: function(handlers, extension, file, section, sectionnumber) {
618 if (this.uploaddialog) {
619 var details = new Object();
620 details.isfile = true;
621 details.handlers = handlers;
622 details.extension = extension;
624 details.section = section;
625 details.sectionnumber = sectionnumber;
626 this.uploadqueue.push(details);
629 this.uploaddialog = true;
631 var timestamp = new Date().getTime();
632 var uploadid = Math.round(Math.random()*100000)+'-'+timestamp;
635 if (extension in this.lastselected) {
636 sel = this.lastselected[extension];
638 sel = handlers[0].module;
640 content += '<p>'+M.util.get_string('actionchoice', 'moodle', file.name)+'</p>';
641 content += '<div id="dndupload_handlers'+uploadid+'">';
642 for (var i=0; i<handlers.length; i++) {
643 var id = 'dndupload_handler'+uploadid+handlers[i].module;
644 var checked = (handlers[i].module == sel) ? 'checked="checked" ' : '';
645 content += '<input type="radio" name="handler" value="'+handlers[i].module+'" id="'+id+'" '+checked+'/>';
646 content += ' <label for="'+id+'">';
647 content += handlers[i].message;
648 content += '</label><br/>';
654 var panel = new M.core.dialogue({
655 bodyContent: content,
662 points: [Y.WidgetPositionAlign.CC, Y.WidgetPositionAlign.CC]
666 // When the panel is hidden - destroy it and then check for other pending uploads
667 panel.after("visibleChange", function(e) {
668 if (!panel.get('visible')) {
670 self.check_upload_queue();
674 // Add the submit/cancel buttons to the bottom of the dialog.
676 label: M.util.get_string('upload', 'moodle'),
677 action: function(e) {
679 // Find out which module was selected
681 var div = Y.one('#dndupload_handlers'+uploadid);
682 div.all('input').each(function(input) {
683 if (input.get('checked')) {
684 module = input.get('value');
691 // Remember this selection for next time
692 self.lastselected[extension] = module;
694 self.upload_file(file, section, sectionnumber, module);
696 section: Y.WidgetStdMod.FOOTER
699 label: M.util.get_string('cancel', 'moodle'),
700 action: function(e) {
704 section: Y.WidgetStdMod.FOOTER
709 * Check to see if there are any other dialog boxes to show, now that the current one has
712 check_upload_queue: function() {
713 this.uploaddialog = false;
714 if (this.uploadqueue.length == 0) {
718 var details = this.uploadqueue.shift();
719 if (details.isfile) {
720 this.file_handler_dialog(details.handlers, details.extension, details.file, details.section, details.sectionnumber);
722 this.handle_item(details.type, details.contents, details.section, details.sectionnumber);
727 * Do the file upload: show the dummy element, use an AJAX call to send the data
728 * to the server, update the progress bar for the file, then replace the dummy
729 * element with the real information once the AJAX call completes
730 * @param file the details of the file, taken from the FileList in the drop event
731 * @param section the DOM element representing the selected course section
732 * @param sectionnumber the number of the selected course section
734 upload_file: function(file, section, sectionnumber, module) {
736 // This would be an ideal place to use the Y.io function
737 // however, this does not support data encoded using the
738 // FormData object, which is needed to transfer data from
739 // the DataTransfer object into an XMLHTTPRequest
740 // This can be converted when the YUI issue has been integrated:
741 // http://yuilibrary.com/projects/yui3/ticket/2531274
742 var xhr = new XMLHttpRequest();
745 if (file.size > this.maxbytes) {
746 new M.core.alert({message: M.util.get_string('namedfiletoolarge', 'moodle', {filename: file.name})});
750 // Add the file to the display
751 var resel = this.add_resource_element(file.name, section, module);
753 // Update the progress bar as the file is uploaded
754 xhr.upload.addEventListener('progress', function(e) {
755 if (e.lengthComputable) {
756 var percentage = Math.round((e.loaded * 100) / e.total);
757 resel.progress.style.width = percentage + '%';
761 // Wait for the AJAX call to complete, then update the
762 // dummy element with the returned details
763 xhr.onreadystatechange = function() {
764 if (xhr.readyState == 4) {
765 if (xhr.status == 200) {
766 var result = JSON.parse(xhr.responseText);
768 if (result.error == 0) {
769 // All OK - replace the dummy element.
770 resel.li.outerHTML = result.fullcontent;
771 if (self.Y.UA.gecko > 0) {
772 // Fix a Firefox bug which makes sites with a '~' in their wwwroot
773 // log the user out when clicking on the link (before refreshing the page).
774 resel.li.outerHTML = unescape(resel.li.outerHTML);
776 self.add_editing(result.elementid);
777 // Fire the content updated event.
778 require(['core/event', 'jquery'], function(event, $) {
779 event.notifyFilterContentUpdated($(result.fullcontent));
782 // Error - remove the dummy element
783 resel.parent.removeChild(resel.li);
784 new M.core.alert({message: result.error});
788 new M.core.alert({message: M.util.get_string('servererror', 'moodle')});
793 // Prepare the data to send
794 var formData = new FormData();
796 formData.append('repo_upload_file', file);
798 // Edge throws an error at this point if we try to upload a folder.
799 resel.parent.removeChild(resel.li);
800 new M.core.alert({message: M.util.get_string('filereaderror', 'moodle', file.name)});
803 formData.append('sesskey', M.cfg.sesskey);
804 formData.append('course', this.courseid);
805 formData.append('section', sectionnumber);
806 formData.append('module', module);
807 formData.append('type', 'Files');
809 // Try reading the file to check it is not a folder, before sending it to the server.
810 var reader = new FileReader();
811 reader.onload = function() {
812 // File was read OK - send it to the server.
813 xhr.open("POST", self.url, true);
816 reader.onerror = function() {
817 // Unable to read the file (it is probably a folder) - display an error message.
818 resel.parent.removeChild(resel.li);
819 new M.core.alert({message: M.util.get_string('filereaderror', 'moodle', file.name)});
822 // If this is a non-empty file, try reading the first few bytes.
823 // This will trigger reader.onerror() for folders and reader.onload() for ordinary, readable files.
824 reader.readAsText(file.slice(0, 5));
826 // If you call slice() on a 0-byte folder, before calling readAsText, then Firefox triggers reader.onload(),
827 // instead of reader.onerror().
828 // So, for 0-byte files, just call readAsText on the whole file (and it will trigger load/error functions as expected).
829 reader.readAsText(file);
834 * Show a dialog box to gather the name of the resource / activity to be created
835 * from the uploaded content
836 * @param type the details of the type of content
837 * @param contents the contents to be uploaded
838 * @section the DOM element for the section being uploaded to
839 * @sectionnumber the number of the section being uploaded to
841 handle_item: function(type, contents, section, sectionnumber) {
842 if (type.handlers.length == 0) {
843 // Nothing to handle this - should not have got here
847 if (type.handlers.length == 1 && type.handlers[0].noname) {
848 // Only one handler and it doesn't need a name (i.e. a label).
849 this.upload_item('', type.type, contents, section, sectionnumber, type.handlers[0].module);
850 this.check_upload_queue();
854 if (this.uploaddialog) {
855 var details = new Object();
856 details.isfile = false;
858 details.contents = contents;
859 details.section = section;
860 details.setcionnumber = sectionnumber;
861 this.uploadqueue.push(details);
864 this.uploaddialog = true;
866 var timestamp = new Date().getTime();
867 var uploadid = Math.round(Math.random()*100000)+'-'+timestamp;
868 var nameid = 'dndupload_handler_name'+uploadid;
870 if (type.handlers.length > 1) {
871 content += '<p>'+type.handlermessage+'</p>';
872 content += '<div id="dndupload_handlers'+uploadid+'">';
873 var sel = type.handlers[0].module;
874 for (var i=0; i<type.handlers.length; i++) {
875 var id = 'dndupload_handler'+uploadid+type.handlers[i].module;
876 var checked = (type.handlers[i].module == sel) ? 'checked="checked" ' : '';
877 content += '<input type="radio" name="handler" value="'+i+'" id="'+id+'" '+checked+'/>';
878 content += ' <label for="'+id+'">';
879 content += type.handlers[i].message;
880 content += '</label><br/>';
884 var disabled = (type.handlers[0].noname) ? ' disabled = "disabled" ' : '';
885 content += '<label for="'+nameid+'">'+type.namemessage+'</label>';
886 content += ' <input type="text" id="'+nameid+'" value="" '+disabled+' />';
890 var panel = new M.core.dialogue({
891 bodyContent: content,
898 points: [Y.WidgetPositionAlign.CC, Y.WidgetPositionAlign.CC]
902 // When the panel is hidden - destroy it and then check for other pending uploads
903 panel.after("visibleChange", function(e) {
904 if (!panel.get('visible')) {
906 self.check_upload_queue();
910 var namefield = Y.one('#'+nameid);
911 var submit = function(e) {
913 var name = Y.Lang.trim(namefield.get('value'));
916 if (type.handlers.length > 1) {
917 // Find out which module was selected
918 var div = Y.one('#dndupload_handlers'+uploadid);
919 div.all('input').each(function(input) {
920 if (input.get('checked')) {
921 var idx = input.get('value');
922 module = type.handlers[idx].module;
923 noname = type.handlers[idx].noname;
930 module = type.handlers[0].module;
931 noname = type.handlers[0].noname;
933 if (name == '' && !noname) {
941 self.upload_item(name, type.type, contents, section, sectionnumber, module);
944 // Add the submit/cancel buttons to the bottom of the dialog.
946 label: M.util.get_string('upload', 'moodle'),
948 section: Y.WidgetStdMod.FOOTER,
952 label: M.util.get_string('cancel', 'moodle'),
953 action: function(e) {
957 section: Y.WidgetStdMod.FOOTER
959 var submitbutton = panel.getButton('submit').button;
960 namefield.on('key', submit, 'enter'); // Submit the form if 'enter' pressed
961 namefield.after('keyup', function() {
962 if (Y.Lang.trim(namefield.get('value')) == '') {
963 submitbutton.disable();
965 submitbutton.enable();
969 // Enable / disable the 'name' box, depending on the handler selected.
970 for (i=0; i<type.handlers.length; i++) {
971 if (type.handlers[i].noname) {
972 Y.one('#dndupload_handler'+uploadid+type.handlers[i].module).on('click', function (e) {
973 namefield.set('disabled', 'disabled');
974 submitbutton.enable();
977 Y.one('#dndupload_handler'+uploadid+type.handlers[i].module).on('click', function (e) {
978 namefield.removeAttribute('disabled');
980 if (Y.Lang.trim(namefield.get('value')) == '') {
981 submitbutton.disable();
987 // Focus on the 'name' box
988 Y.one('#'+nameid).focus();
992 * Upload any data types that are not files: display a dummy resource element, send
993 * the data to the server, update the progress bar for the file, then replace the
994 * dummy element with the real information once the AJAX call completes
995 * @param name the display name for the resource / activity to create
996 * @param type the details of the data type found in the drop event
997 * @param contents the actual data that was dropped
998 * @param section the DOM element representing the selected course section
999 * @param sectionnumber the number of the selected course section
1000 * @param module the module chosen to handle this upload
1002 upload_item: function(name, type, contents, section, sectionnumber, module) {
1004 // This would be an ideal place to use the Y.io function
1005 // however, this does not support data encoded using the
1006 // FormData object, which is needed to transfer data from
1007 // the DataTransfer object into an XMLHTTPRequest
1008 // This can be converted when the YUI issue has been integrated:
1009 // http://yuilibrary.com/projects/yui3/ticket/2531274
1010 var xhr = new XMLHttpRequest();
1013 // Add the item to the display
1014 var resel = this.add_resource_element(name, section, module);
1016 // Wait for the AJAX call to complete, then update the
1017 // dummy element with the returned details
1018 xhr.onreadystatechange = function() {
1019 if (xhr.readyState == 4) {
1020 if (xhr.status == 200) {
1021 var result = JSON.parse(xhr.responseText);
1023 if (result.error == 0) {
1024 // All OK - replace the dummy element.
1025 resel.li.outerHTML = result.fullcontent;
1026 if (self.Y.UA.gecko > 0) {
1027 // Fix a Firefox bug which makes sites with a '~' in their wwwroot
1028 // log the user out when clicking on the link (before refreshing the page).
1029 resel.li.outerHTML = unescape(resel.li.outerHTML);
1031 self.add_editing(result.elementid);
1033 // Error - remove the dummy element
1034 resel.parent.removeChild(resel.li);
1035 new M.core.alert({message: result.error});
1039 new M.core.alert({message: M.util.get_string('servererror', 'moodle')});
1044 // Prepare the data to send
1045 var formData = new FormData();
1046 formData.append('contents', contents);
1047 formData.append('displayname', name);
1048 formData.append('sesskey', M.cfg.sesskey);
1049 formData.append('course', this.courseid);
1050 formData.append('section', sectionnumber);
1051 formData.append('type', type);
1052 formData.append('module', module);
1055 xhr.open("POST", this.url, true);
1060 * Call the AJAX course editing initialisation to add the editing tools
1061 * to the newly-created resource link
1062 * @param elementid the id of the DOM element containing the new resource link
1063 * @param sectionnumber the number of the selected course section
1065 add_editing: function(elementid) {
1066 var node = Y.one('#' + elementid);
1067 YUI().use('moodle-course-coursebase', function(Y) {
1068 Y.log("Invoking setup_for_resource", 'debug', 'coursedndupload');
1069 M.course.coursebase.invoke_function('setup_for_resource', node);
1071 if (M.core.actionmenu && M.core.actionmenu.newDOMNode) {
1072 M.core.actionmenu.newDOMNode(node);