MDL-73758 availability: fix info::is_available_for_all()
[moodle.git] / course / dndupload.js
blob0f8ff98323bb9b216c39fc3c610acbbc6ca48ad2
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 to courses
18  *
19  * @package    core
20  * @subpackage course
21  * @copyright  2012 Davo Smith
22  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23  */
24 M.course_dndupload = {
25     // YUI object.
26     Y: null,
27     // URL for upload requests
28     url: M.cfg.wwwroot + '/course/dndupload.php',
29     // maximum size of files allowed in this form
30     maxbytes: 0,
31     // ID of the course we are on
32     courseid: null,
33     // Data about the different file/data handlers that are available
34     handlers: null,
35     // Nasty hack to distinguish between dragenter(first entry),
36     // dragenter+dragleave(moving between child elements) and dragleave (leaving element)
37     entercount: 0,
38     // Used to keep track of the section we are dragging across - to make
39     // spotting movement between sections more reliable
40     currentsection: null,
41     // Used to store the pending uploads whilst the user is being asked for further input
42     uploadqueue: null,
43     // True if the there is currently a dialog being shown (asking for a name, or giving a
44     // choice of file handlers)
45     uploaddialog: false,
46     // An array containing the last selected file handler for each file type
47     lastselected: null,
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',
61     /**
62      * Initalise the drag and drop upload interface
63      * Note: one and only one of options.filemanager and options.formcallback must be defined
64      *
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
70      *          }
71      */
72     init: function(Y, options) {
73         this.Y = Y;
75         if (!this.browser_supported()) {
76             return; // Browser does not support the required functionality
77         }
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.
89         }
90         sections.each( function(el) {
91             this.add_preview_element(el);
92             this.init_events(el);
93         }, this);
95         if (options.showstatus) {
96             this.add_status_div();
97         }
99         var self = this;
100         require([
101             'core_courseformat/courseeditor',
102             'core_course/events'
103         ], function(
104             Editor,
105             CourseEvents
106         ) {
107             // Any change to the course must be applied also to the course state via the courseeditor module.
108             self.courseeditor = Editor.getCurrentCourseEditor();
110             // Some formats can add sections without reloading the page.
111             document.querySelector('#' + self.pagecontentid).addEventListener(
112                 CourseEvents.sectionRefreshed,
113                 self.sectionRefreshed.bind(self)
114             );
115         });
116     },
118     /**
119      * Setup Drag and Drop in a section.
120      * @param {CustomEvent} event The custom event
121      */
122     sectionRefreshed: function(event) {
123         if (event.detail.newSectionElement === undefined) {
124             return;
125         }
126         var element = this.Y.one(event.detail.newSectionElement);
127         this.add_preview_element(element);
128         this.init_events(element);
129     },
131     /**
132      * Add a div element to tell the user that drag and drop upload
133      * is available (or to explain why it is not available)
134      */
135     add_status_div: function() {
136         var Y = this.Y,
137             coursecontents = Y.one('#' + this.pagecontentid),
138             div,
139             handlefile = (this.handlers.filehandlers.length > 0),
140             handletext = false,
141             handlelink = false,
142             i = 0,
143             styletop,
144             styletopunit;
146         if (!coursecontents) {
147             return;
148         }
150         div = Y.Node.create('<div id="dndupload-status"></div>').setStyle('opacity', '0.0');
151         coursecontents.insert(div, 0);
153         for (i = 0; i < this.handlers.types.length; i++) {
154             switch (this.handlers.types[i].identifier) {
155                 case 'text':
156                 case 'text/html':
157                     handletext = true;
158                     break;
159                 case 'url':
160                     handlelink = true;
161                     break;
162             }
163         }
164         $msgident = 'dndworking';
165         if (handlefile) {
166             $msgident += 'file';
167         }
168         if (handletext) {
169             $msgident += 'text';
170         }
171         if (handlelink) {
172             $msgident += 'link';
173         }
174         div.setContent(M.util.get_string($msgident, 'moodle'));
176         styletop = div.getStyle('top') || '0px';
177         styletopunit = styletop.replace(/^\d+/, '');
178         styletop = parseInt(styletop.replace(/\D*$/, ''), 10);
180         var fadein = new Y.Anim({
181             node: '#dndupload-status',
182             from: {
183                 opacity: 0.0,
184                 top: (styletop - 30).toString() + styletopunit
185             },
187             to: {
188                 opacity: 1.0,
189                 top: styletop.toString() + styletopunit
190             },
191             duration: 0.5
192         });
194         var fadeout = new Y.Anim({
195             node: '#dndupload-status',
196             from: {
197                 opacity: 1.0,
198                 top: styletop.toString() + styletopunit
199             },
201             to: {
202                 opacity: 0.0,
203                 top: (styletop - 30).toString() + styletopunit
204             },
205             duration: 0.5
206         });
208         fadein.run();
209         fadein.on('end', function(e) {
210             Y.later(3000, this, function() {
211                 fadeout.run();
212             });
213         });
215         fadeout.on('end', function(e) {
216             Y.one('#dndupload-status').remove(true);
217         });
218     },
220     /**
221      * Check the browser has the required functionality
222      * @return true if browser supports drag/drop upload
223      */
224     browser_supported: function() {
225         if (typeof FileReader == 'undefined') {
226             return false;
227         }
228         if (typeof FormData == 'undefined') {
229             return false;
230         }
231         return true;
232     },
234     /**
235      * Initialise drag events on node container, all events need
236      * to be processed for drag and drop to work
237      * @param el the element to add events to
238      */
239     init_events: function(el) {
240         this.Y.on('dragenter', this.drag_enter, el, this);
241         this.Y.on('dragleave', this.drag_leave, el, this);
242         this.Y.on('dragover',  this.drag_over,  el, this);
243         this.Y.on('drop',      this.drop,       el, this);
244     },
246     /**
247      * Work out which course section a given element is in
248      * @param el the child DOM element within the section
249      * @return the DOM element representing the section
250      */
251     get_section: function(el) {
252         var sectionclasses = this.sectionclasses;
253         return el.ancestor( function(test) {
254             var i;
255             for (i=0; i<sectionclasses.length; i++) {
256                 if (!test.hasClass(sectionclasses[i])) {
257                     return false;
258                 }
259                 return true;
260             }
261         }, true);
262     },
264     /**
265      * Work out the number of the section we have been dropped on to, from the section element
266      * @param DOMElement section the selected section
267      * @return int the section number
268      */
269     get_section_number: function(section) {
270         var sectionid = section.get('id').split('-');
271         if (sectionid.length < 2 || sectionid[0] != 'section') {
272             return false;
273         }
274         return parseInt(sectionid[1]);
275     },
277     /**
278      * Check if the event includes data of the given type
279      * @param e the event details
280      * @param type the data type to check for
281      * @return true if the data type is found in the event data
282      */
283     types_includes: function(e, type) {
284         var i;
285         var types = e._event.dataTransfer.types;
286         type = type.toLowerCase();
287         for (i=0; i<types.length; i++) {
288             if (!types.hasOwnProperty(i)) {
289                 continue;
290             }
291             if (types[i].toLowerCase() === type) {
292                 return true;
293             }
294         }
295         return false;
296     },
298     /**
299      * Look through the event data, checking it against the registered data types
300      * (in order of priority) and return details of the first matching data type
301      * @param e the event details
302      * @return object|false - false if not found or an object {
303      *           realtype: the type as given by the browser
304      *           addmessage: the message to show to the user during dragging
305      *           namemessage: the message for requesting a name for the resource from the user
306      *           type: the identifier of the type (may match several 'realtype's)
307      *           }
308      */
309     drag_type: function(e) {
310         // Check there is some data attached.
311         if (e._event.dataTransfer === null) {
312             return false;
313         }
314         if (e._event.dataTransfer.types === null) {
315             return false;
316         }
317         if (e._event.dataTransfer.types.length == 0) {
318             return false;
319         }
321         // Check for files first.
322         if (this.types_includes(e, 'Files')) {
323             if (e.type != 'drop' || e._event.dataTransfer.files.length != 0) {
324                 if (this.handlers.filehandlers.length == 0) {
325                     return false; // No available file handlers - ignore this drag.
326                 }
327                 return {
328                     realtype: 'Files',
329                     addmessage: M.util.get_string('addfilehere', 'moodle'),
330                     namemessage: null, // Should not be asked for anyway
331                     type: 'Files'
332                 };
333             }
334         }
336         // Check each of the registered types.
337         var types = this.handlers.types;
338         for (var i=0; i<types.length; i++) {
339             // Check each of the different identifiers for this type
340             var dttypes = types[i].datatransfertypes;
341             for (var j=0; j<dttypes.length; j++) {
342                 if (this.types_includes(e, dttypes[j])) {
343                     return {
344                         realtype: dttypes[j],
345                         addmessage: types[i].addmessage,
346                         namemessage: types[i].namemessage,
347                         handlermessage: types[i].handlermessage,
348                         type: types[i].identifier,
349                         handlers: types[i].handlers
350                     };
351                 }
352             }
353         }
354         return false; // No types we can handle
355     },
357     /**
358      * Check the content of the drag/drop includes a type we can handle, then, if
359      * it is, notify the browser that we want to handle it
360      * @param event e
361      * @return string type of the event or false
362      */
363     check_drag: function(e) {
364         var type = this.drag_type(e);
365         if (type) {
366             // Notify browser that we will handle this drag/drop
367             e.stopPropagation();
368             e.preventDefault();
369         }
370         return type;
371     },
373     /**
374      * Handle a dragenter event: add a suitable 'add here' message
375      * when a drag event occurs, containing a registered data type
376      * @param e event data
377      * @return false to prevent the event from continuing to be processed
378      */
379     drag_enter: function(e) {
380         if (!(type = this.check_drag(e))) {
381             return false;
382         }
384         var section = this.get_section(e.currentTarget);
385         if (!section) {
386             return false;
387         }
389         if (this.currentsection && this.currentsection != section) {
390             this.currentsection = section;
391             this.entercount = 1;
392         } else {
393             this.entercount++;
394             if (this.entercount > 2) {
395                 this.entercount = 2;
396                 return false;
397             }
398         }
400         this.show_preview_element(section, type);
402         return false;
403     },
405     /**
406      * Handle a dragleave event: remove the 'add here' message (if present)
407      * @param e event data
408      * @return false to prevent the event from continuing to be processed
409      */
410     drag_leave: function(e) {
411         if (!this.check_drag(e)) {
412             return false;
413         }
415         this.entercount--;
416         if (this.entercount == 1) {
417             return false;
418         }
419         this.entercount = 0;
420         this.currentsection = null;
422         this.hide_preview_element();
423         return false;
424     },
426     /**
427      * Handle a dragover event: just prevent the browser default (necessary
428      * to allow drag and drop handling to work)
429      * @param e event data
430      * @return false to prevent the event from continuing to be processed
431      */
432     drag_over: function(e) {
433         this.check_drag(e);
434         return false;
435     },
437     /**
438      * Handle a drop event: hide the 'add here' message, check the attached
439      * data type and start the upload process
440      * @param e event data
441      * @return false to prevent the event from continuing to be processed
442      */
443     drop: function(e) {
444         this.hide_preview_element();
446         if (!(type = this.check_drag(e))) {
447             return false;
448         }
450         // Work out the number of the section we are on (from its id)
451         var section = this.get_section(e.currentTarget);
452         var sectionnumber = this.get_section_number(section);
454         // Process the file or the included data
455         if (type.type == 'Files') {
456             var files = e._event.dataTransfer.files;
457             for (var i=0, f; f=files[i]; i++) {
458                 this.handle_file(f, section, sectionnumber);
459             }
460         } else {
461             var contents = e._event.dataTransfer.getData(type.realtype);
462             if (contents) {
463                 this.handle_item(type, contents, section, sectionnumber);
464             }
465         }
467         return false;
468     },
470     /**
471      * Find or create the 'ul' element that contains all of the module
472      * instances in this section
473      * @param section the DOM element representing the section
474      * @return false to prevent the event from continuing to be processed
475      */
476     get_mods_element: function(section) {
477         // Find the 'ul' containing the list of mods
478         var modsel = section.one(this.modslistselector);
479         if (!modsel) {
480             // Create the above 'ul' if it doesn't exist
481             modsel = document.createElement('ul');
482             modsel.className = 'section img-text';
483             var contentel = section.get('children').pop();
484             var brel = contentel.get('children').pop();
485             contentel.insertBefore(modsel, brel);
486             modsel = this.Y.one(modsel);
487         }
489         return modsel;
490     },
492     /**
493      * Add a new dummy item to the list of mods, to be replaced by a real
494      * item & link once the AJAX upload call has completed
495      * @param name the label to show in the element
496      * @param section the DOM element reperesenting the course section
497      * @return DOM element containing the new item
498      */
499     add_resource_element: function(name, section, module) {
500         var modsel = this.get_mods_element(section);
502         var resel = {
503             parent: modsel,
504             li: document.createElement('li'),
505             div: document.createElement('div'),
506             indentdiv: document.createElement('div'),
507             a: document.createElement('a'),
508             icon: document.createElement('img'),
509             namespan: document.createElement('span'),
510             groupingspan: document.createElement('span'),
511             progressouter: document.createElement('span'),
512             progress: document.createElement('span')
513         };
515         resel.li.className = 'activity ' + module + ' modtype_' + module;
517         resel.indentdiv.className = 'mod-indent';
518         resel.li.appendChild(resel.indentdiv);
520         resel.div.className = 'activityinstance';
521         resel.indentdiv.appendChild(resel.div);
523         resel.a.href = '#';
524         resel.div.appendChild(resel.a);
526         resel.icon.src = M.util.image_url('i/ajaxloader');
527         resel.icon.className = 'activityicon iconlarge';
528         resel.a.appendChild(resel.icon);
530         resel.namespan.className = 'instancename';
531         resel.namespan.innerHTML = name;
532         resel.a.appendChild(resel.namespan);
534         resel.groupingspan.className = 'groupinglabel';
535         resel.div.appendChild(resel.groupingspan);
537         resel.progressouter.className = 'dndupload-progress-outer';
538         resel.progress.className = 'dndupload-progress-inner';
539         resel.progress.innerHTML = '&nbsp;';
540         resel.progressouter.appendChild(resel.progress);
541         resel.div.appendChild(resel.progressouter);
543         modsel.insertBefore(resel.li, modsel.get('children').pop()); // Leave the 'preview element' at the bottom
545         return resel;
546     },
548     /**
549      * Hide any visible dndupload-preview elements on the page
550      */
551     hide_preview_element: function() {
552         this.Y.all('li.dndupload-preview').addClass('dndupload-hidden');
553         this.Y.all('.dndupload-over').removeClass('dndupload-over');
554     },
556     /**
557      * Unhide the preview element for the given section and set it to display
558      * the correct message
559      * @param section the YUI node representing the selected course section
560      * @param type the details of the data type detected in the drag (including the message to display)
561      */
562     show_preview_element: function(section, type) {
563         this.hide_preview_element();
564         var preview = section.one('li.dndupload-preview').removeClass('dndupload-hidden');
565         section.addClass('dndupload-over');
567         // Horrible work-around to allow the 'Add X here' text to be a drop target in Firefox.
568         var node = preview.one('span').getDOMNode();
569         node.firstChild.nodeValue = type.addmessage;
570     },
572     /**
573      * Add the preview element to a course section. Note: this needs to be done before 'addEventListener'
574      * is called, otherwise Firefox will ignore events generated when the mouse is over the preview
575      * element (instead of passing them up to the parent element)
576      * @param section the YUI node representing the selected course section
577      */
578     add_preview_element: function(section) {
579         var modsel = this.get_mods_element(section);
580         var preview = {
581             li: document.createElement('li'),
582             div: document.createElement('div'),
583             icon: document.createElement('img'),
584             namespan: document.createElement('span')
585         };
587         preview.li.className = 'dndupload-preview dndupload-hidden';
589         preview.div.className = 'mod-indent';
590         preview.li.appendChild(preview.div);
592         preview.icon.src = M.util.image_url('t/addfile');
593         preview.icon.className = 'icon';
594         preview.div.appendChild(preview.icon);
596         preview.div.appendChild(document.createTextNode(' '));
598         preview.namespan.className = 'instancename';
599         preview.namespan.innerHTML = M.util.get_string('addfilehere', 'moodle');
600         preview.div.appendChild(preview.namespan);
602         modsel.appendChild(preview.li);
603     },
605     /**
606      * Find the registered handler for the given file type. If there is more than one, ask the
607      * user which one to use. Then upload the file to the server
608      * @param file the details of the file, taken from the FileList in the drop event
609      * @param section the DOM element representing the selected course section
610      * @param sectionnumber the number of the selected course section
611      */
612     handle_file: function(file, section, sectionnumber) {
613         var handlers = new Array();
614         var filehandlers = this.handlers.filehandlers;
615         var extension = '';
616         var dotpos = file.name.lastIndexOf('.');
617         if (dotpos != -1) {
618             extension = file.name.substr(dotpos+1, file.name.length).toLowerCase();
619         }
621         for (var i=0; i<filehandlers.length; i++) {
622             if (filehandlers[i].extension == '*' || filehandlers[i].extension == extension) {
623                 handlers.push(filehandlers[i]);
624             }
625         }
627         if (handlers.length == 0) {
628             // No handlers at all (not even 'resource'?)
629             return;
630         }
632         if (handlers.length == 1) {
633             this.upload_file(file, section, sectionnumber, handlers[0].module);
634             return;
635         }
637         this.file_handler_dialog(handlers, extension, file, section, sectionnumber);
638     },
640     /**
641      * Show a dialog box, allowing the user to choose what to do with the file they are uploading
642      * @param handlers the available handlers to choose between
643      * @param extension the extension of the file being uploaded
644      * @param file the File object being uploaded
645      * @param section the DOM element of the section being uploaded to
646      * @param sectionnumber the number of the selected course section
647      */
648     file_handler_dialog: function(handlers, extension, file, section, sectionnumber) {
649         if (this.uploaddialog) {
650             var details = new Object();
651             details.isfile = true;
652             details.handlers = handlers;
653             details.extension = extension;
654             details.file = file;
655             details.section = section;
656             details.sectionnumber = sectionnumber;
657             this.uploadqueue.push(details);
658             return;
659         }
660         this.uploaddialog = true;
662         var timestamp = new Date().getTime();
663         var uploadid = Math.round(Math.random()*100000)+'-'+timestamp;
664         var content = '';
665         var sel;
666         if (extension in this.lastselected) {
667             sel = this.lastselected[extension];
668         } else {
669             sel = handlers[0].module;
670         }
671         content += '<p>'+M.util.get_string('actionchoice', 'moodle', file.name)+'</p>';
672         content += '<div id="dndupload_handlers'+uploadid+'">';
673         for (var i=0; i<handlers.length; i++) {
674             var id = 'dndupload_handler'+uploadid+handlers[i].module;
675             var checked = (handlers[i].module == sel) ? 'checked="checked" ' : '';
676             content += '<input type="radio" name="handler" value="'+handlers[i].module+'" id="'+id+'" '+checked+'/>';
677             content += ' <label for="'+id+'">';
678             content += handlers[i].message;
679             content += '</label><br/>';
680         }
681         content += '</div>';
683         var Y = this.Y;
684         var self = this;
685         var panel = new M.core.dialogue({
686             bodyContent: content,
687             width: '350px',
688             modal: true,
689             visible: false,
690             render: true,
691             align: {
692                 node: null,
693                 points: [Y.WidgetPositionAlign.CC, Y.WidgetPositionAlign.CC]
694             }
695         });
696         panel.show();
697         // When the panel is hidden - destroy it and then check for other pending uploads
698         panel.after("visibleChange", function(e) {
699             if (!panel.get('visible')) {
700                 panel.destroy(true);
701                 self.check_upload_queue();
702             }
703         });
705         // Add the submit/cancel buttons to the bottom of the dialog.
706         panel.addButton({
707             label: M.util.get_string('upload', 'moodle'),
708             action: function(e) {
709                 e.preventDefault();
710                 // Find out which module was selected
711                 var module = false;
712                 var div = Y.one('#dndupload_handlers'+uploadid);
713                 div.all('input').each(function(input) {
714                     if (input.get('checked')) {
715                         module = input.get('value');
716                     }
717                 });
718                 if (!module) {
719                     return;
720                 }
721                 panel.hide();
722                 // Remember this selection for next time
723                 self.lastselected[extension] = module;
724                 // Do the upload
725                 self.upload_file(file, section, sectionnumber, module);
726             },
727             section: Y.WidgetStdMod.FOOTER
728         });
729         panel.addButton({
730             label: M.util.get_string('cancel', 'moodle'),
731             action: function(e) {
732                 e.preventDefault();
733                 panel.hide();
734             },
735             section: Y.WidgetStdMod.FOOTER
736         });
737     },
739     /**
740      * Check to see if there are any other dialog boxes to show, now that the current one has
741      * been dealt with
742      */
743     check_upload_queue: function() {
744         this.uploaddialog = false;
745         if (this.uploadqueue.length == 0) {
746             return;
747         }
749         var details = this.uploadqueue.shift();
750         if (details.isfile) {
751             this.file_handler_dialog(details.handlers, details.extension, details.file, details.section, details.sectionnumber);
752         } else {
753             this.handle_item(details.type, details.contents, details.section, details.sectionnumber);
754         }
755     },
757     /**
758      * Do the file upload: show the dummy element, use an AJAX call to send the data
759      * to the server, update the progress bar for the file, then replace the dummy
760      * element with the real information once the AJAX call completes
761      * @param file the details of the file, taken from the FileList in the drop event
762      * @param section the DOM element representing the selected course section
763      * @param sectionnumber the number of the selected course section
764      */
765     upload_file: function(file, section, sectionnumber, module) {
767         // This would be an ideal place to use the Y.io function
768         // however, this does not support data encoded using the
769         // FormData object, which is needed to transfer data from
770         // the DataTransfer object into an XMLHTTPRequest
771         // This can be converted when the YUI issue has been integrated:
772         // http://yuilibrary.com/projects/yui3/ticket/2531274
773         var xhr = new XMLHttpRequest();
774         var self = this;
776         if (this.maxbytes > 0 && file.size > this.maxbytes) {
777             new M.core.alert({message: M.util.get_string('namedfiletoolarge', 'moodle', {filename: file.name})});
778             return;
779         }
781         // Add the file to the display
782         var resel = this.add_resource_element(file.name, section, module);
784         // Update the progress bar as the file is uploaded
785         xhr.upload.addEventListener('progress', function(e) {
786             if (e.lengthComputable) {
787                 var percentage = Math.round((e.loaded * 100) / e.total);
788                 resel.progress.style.width = percentage + '%';
789             }
790         }, false);
792         // Wait for the AJAX call to complete, then update the
793         // dummy element with the returned details
794         xhr.onreadystatechange = function() {
795             if (xhr.readyState == 1) {
796                 this.originalUnloadEvent = window.onbeforeunload;
797                 // Trigger form upload start events.
798                 require(['core_form/events'], function(FormEvent) {
799                     FormEvent.notifyUploadStarted(section.get('id'));
800                 });
801             }
802             if (xhr.readyState == 4) {
803                 if (xhr.status == 200) {
804                     var result = JSON.parse(xhr.responseText);
805                     if (result) {
806                         if (result.error == 0) {
807                             // All OK - replace the dummy element.
808                             resel.li.outerHTML = result.fullcontent;
809                             if (self.Y.UA.gecko > 0) {
810                                 // Fix a Firefox bug which makes sites with a '~' in their wwwroot
811                                 // log the user out when clicking on the link (before refreshing the page).
812                                 resel.li.outerHTML = unescape(resel.li.outerHTML);
813                             }
814                             self.add_editing(result.elementid);
815                             // Once done, send any new course module id to the courseeditor to update de course state.
816                             self.courseeditor.dispatch('cmState', [result.cmid]);
817                             // Fire the content updated event.
818                             require(['core/event', 'jquery'], function(event, $) {
819                                 event.notifyFilterContentUpdated($(result.fullcontent));
820                             });
821                         } else {
822                             // Error - remove the dummy element
823                             resel.parent.removeChild(resel.li);
824                             new M.core.alert({message: result.error});
825                         }
826                     }
827                 } else {
828                     new M.core.alert({message: M.util.get_string('servererror', 'moodle')});
829                 }
830                 // Trigger form upload complete events.
831                 require(['core_form/events'], function(FormEvent) {
832                     FormEvent.notifyUploadCompleted(section.get('id'));
833                 });
834             }
835         };
837         // Prepare the data to send
838         var formData = new FormData();
839         try {
840             formData.append('repo_upload_file', file);
841         } catch (e) {
842             // Edge throws an error at this point if we try to upload a folder.
843             resel.parent.removeChild(resel.li);
844             new M.core.alert({message: M.util.get_string('filereaderror', 'moodle', file.name)});
845             return;
846         }
847         formData.append('sesskey', M.cfg.sesskey);
848         formData.append('course', this.courseid);
849         formData.append('section', sectionnumber);
850         formData.append('module', module);
851         formData.append('type', 'Files');
853         // Try reading the file to check it is not a folder, before sending it to the server.
854         var reader = new FileReader();
855         reader.onload = function() {
856             // File was read OK - send it to the server.
857             xhr.open("POST", self.url, true);
858             xhr.send(formData);
859         };
860         reader.onerror = function() {
861             // Unable to read the file (it is probably a folder) - display an error message.
862             resel.parent.removeChild(resel.li);
863             new M.core.alert({message: M.util.get_string('filereaderror', 'moodle', file.name)});
864         };
865         if (file.size > 0) {
866             // If this is a non-empty file, try reading the first few bytes.
867             // This will trigger reader.onerror() for folders and reader.onload() for ordinary, readable files.
868             reader.readAsText(file.slice(0, 5));
869         } else {
870             // If you call slice() on a 0-byte folder, before calling readAsText, then Firefox triggers reader.onload(),
871             // instead of reader.onerror().
872             // So, for 0-byte files, just call readAsText on the whole file (and it will trigger load/error functions as expected).
873             reader.readAsText(file);
874         }
875     },
877     /**
878      * Show a dialog box to gather the name of the resource / activity to be created
879      * from the uploaded content
880      * @param type the details of the type of content
881      * @param contents the contents to be uploaded
882      * @section the DOM element for the section being uploaded to
883      * @sectionnumber the number of the section being uploaded to
884      */
885     handle_item: function(type, contents, section, sectionnumber) {
886         if (type.handlers.length == 0) {
887             // Nothing to handle this - should not have got here
888             return;
889         }
891         if (type.handlers.length == 1 && type.handlers[0].noname) {
892             // Only one handler and it doesn't need a name (i.e. a label).
893             this.upload_item('', type.type, contents, section, sectionnumber, type.handlers[0].module);
894             this.check_upload_queue();
895             return;
896         }
898         if (this.uploaddialog) {
899             var details = new Object();
900             details.isfile = false;
901             details.type = type;
902             details.contents = contents;
903             details.section = section;
904             details.setcionnumber = sectionnumber;
905             this.uploadqueue.push(details);
906             return;
907         }
908         this.uploaddialog = true;
910         var timestamp = new Date().getTime();
911         var uploadid = Math.round(Math.random()*100000)+'-'+timestamp;
912         var nameid = 'dndupload_handler_name'+uploadid;
913         var content = '';
914         if (type.handlers.length > 1) {
915             content += '<p>'+type.handlermessage+'</p>';
916             content += '<div id="dndupload_handlers'+uploadid+'">';
917             var sel = type.handlers[0].module;
918             for (var i=0; i<type.handlers.length; i++) {
919                 var id = 'dndupload_handler'+uploadid+type.handlers[i].module;
920                 var checked = (type.handlers[i].module == sel) ? 'checked="checked" ' : '';
921                 content += '<input type="radio" name="handler" value="'+i+'" id="'+id+'" '+checked+'/>';
922                 content += ' <label for="'+id+'">';
923                 content += type.handlers[i].message;
924                 content += '</label><br/>';
925             }
926             content += '</div>';
927         }
928         var disabled = (type.handlers[0].noname) ? ' disabled = "disabled" ' : '';
929         content += '<label for="'+nameid+'">'+type.namemessage+'</label>';
930         content += ' <input type="text" id="'+nameid+'" value="" '+disabled+' />';
932         var Y = this.Y;
933         var self = this;
934         var panel = new M.core.dialogue({
935             bodyContent: content,
936             width: '350px',
937             modal: true,
938             visible: true,
939             render: true,
940             align: {
941                 node: null,
942                 points: [Y.WidgetPositionAlign.CC, Y.WidgetPositionAlign.CC]
943             }
944         });
946         // When the panel is hidden - destroy it and then check for other pending uploads
947         panel.after("visibleChange", function(e) {
948             if (!panel.get('visible')) {
949                 panel.destroy(true);
950                 self.check_upload_queue();
951             }
952         });
954         var namefield = Y.one('#'+nameid);
955         var submit = function(e) {
956             e.preventDefault();
957             var name = Y.Lang.trim(namefield.get('value'));
958             var module = false;
959             var noname = false;
960             if (type.handlers.length > 1) {
961                 // Find out which module was selected
962                 var div = Y.one('#dndupload_handlers'+uploadid);
963                 div.all('input').each(function(input) {
964                     if (input.get('checked')) {
965                         var idx = input.get('value');
966                         module = type.handlers[idx].module;
967                         noname = type.handlers[idx].noname;
968                     }
969                 });
970                 if (!module) {
971                     return;
972                 }
973             } else {
974                 module = type.handlers[0].module;
975                 noname = type.handlers[0].noname;
976             }
977             if (name == '' && !noname) {
978                 return;
979             }
980             if (noname) {
981                 name = '';
982             }
983             panel.hide();
984             // Do the upload
985             self.upload_item(name, type.type, contents, section, sectionnumber, module);
986         };
988         // Add the submit/cancel buttons to the bottom of the dialog.
989         panel.addButton({
990             label: M.util.get_string('upload', 'moodle'),
991             action: submit,
992             section: Y.WidgetStdMod.FOOTER,
993             name: 'submit'
994         });
995         panel.addButton({
996             label: M.util.get_string('cancel', 'moodle'),
997             action: function(e) {
998                 e.preventDefault();
999                 panel.hide();
1000             },
1001             section: Y.WidgetStdMod.FOOTER
1002         });
1003         var submitbutton = panel.getButton('submit').button;
1004         namefield.on('key', submit, 'enter'); // Submit the form if 'enter' pressed
1005         namefield.after('keyup', function() {
1006             if (Y.Lang.trim(namefield.get('value')) == '') {
1007                 submitbutton.disable();
1008             } else {
1009                 submitbutton.enable();
1010             }
1011         });
1013         // Enable / disable the 'name' box, depending on the handler selected.
1014         for (i=0; i<type.handlers.length; i++) {
1015             if (type.handlers[i].noname) {
1016                 Y.one('#dndupload_handler'+uploadid+type.handlers[i].module).on('click', function (e) {
1017                     namefield.set('disabled', 'disabled');
1018                     submitbutton.enable();
1019                 });
1020             } else {
1021                 Y.one('#dndupload_handler'+uploadid+type.handlers[i].module).on('click', function (e) {
1022                     namefield.removeAttribute('disabled');
1023                     namefield.focus();
1024                     if (Y.Lang.trim(namefield.get('value')) == '') {
1025                         submitbutton.disable();
1026                     }
1027                 });
1028             }
1029         }
1031         // Focus on the 'name' box
1032         Y.one('#'+nameid).focus();
1033     },
1035     /**
1036      * Upload any data types that are not files: display a dummy resource element, send
1037      * the data to the server, update the progress bar for the file, then replace the
1038      * dummy element with the real information once the AJAX call completes
1039      * @param name the display name for the resource / activity to create
1040      * @param type the details of the data type found in the drop event
1041      * @param contents the actual data that was dropped
1042      * @param section the DOM element representing the selected course section
1043      * @param sectionnumber the number of the selected course section
1044      * @param module the module chosen to handle this upload
1045      */
1046     upload_item: function(name, type, contents, section, sectionnumber, module) {
1048         // This would be an ideal place to use the Y.io function
1049         // however, this does not support data encoded using the
1050         // FormData object, which is needed to transfer data from
1051         // the DataTransfer object into an XMLHTTPRequest
1052         // This can be converted when the YUI issue has been integrated:
1053         // http://yuilibrary.com/projects/yui3/ticket/2531274
1054         var xhr = new XMLHttpRequest();
1055         var self = this;
1057         // Add the item to the display
1058         var resel = this.add_resource_element(name, section, module);
1060         // Wait for the AJAX call to complete, then update the
1061         // dummy element with the returned details
1062         xhr.onreadystatechange = function() {
1063             if (xhr.readyState == 1) {
1064                 this.originalUnloadEvent = window.onbeforeunload;
1065                 // Trigger form upload start events.
1066                 require(['core_form/events'], function(FormEvent) {
1067                     FormEvent.notifyUploadStarted(section.get('id'));
1068                 });
1069             }
1070             if (xhr.readyState == 4) {
1071                 if (xhr.status == 200) {
1072                     var result = JSON.parse(xhr.responseText);
1073                     if (result) {
1074                         if (result.error == 0) {
1075                             // All OK - replace the dummy element.
1076                             resel.li.outerHTML = result.fullcontent;
1077                             if (self.Y.UA.gecko > 0) {
1078                                 // Fix a Firefox bug which makes sites with a '~' in their wwwroot
1079                                 // log the user out when clicking on the link (before refreshing the page).
1080                                 resel.li.outerHTML = unescape(resel.li.outerHTML);
1081                             }
1082                             self.add_editing(result.elementid);
1083                             // Once done, send any new course module id to the courseeditor to update de course state.
1084                             self.courseeditor.dispatch('cmState', [result.cmid]);
1085                         } else {
1086                             // Error - remove the dummy element
1087                             resel.parent.removeChild(resel.li);
1088                             // Trigger form upload complete events.
1089                             require(['core_form/events'], function(FormEvent) {
1090                                 FormEvent.notifyUploadCompleted(section.get('id'));
1091                             });
1092                             new M.core.alert({message: result.error});
1093                         }
1094                     }
1095                 } else {
1096                     // Trigger form upload complete events.
1097                     require(['core_form/events'], function(FormEvent) {
1098                         FormEvent.notifyUploadCompleted(section.get('id'));
1099                     });
1100                     new M.core.alert({message: M.util.get_string('servererror', 'moodle')});
1101                 }
1102                 // Trigger form upload complete events.
1103                 require(['core_form/events'], function(FormEvent) {
1104                     FormEvent.notifyUploadCompleted(section.get('id'));
1105                 });
1106             }
1107         };
1109         // Prepare the data to send
1110         var formData = new FormData();
1111         formData.append('contents', contents);
1112         formData.append('displayname', name);
1113         formData.append('sesskey', M.cfg.sesskey);
1114         formData.append('course', this.courseid);
1115         formData.append('section', sectionnumber);
1116         formData.append('type', type);
1117         formData.append('module', module);
1119         // Send the data
1120         xhr.open("POST", this.url, true);
1121         xhr.send(formData);
1122     },
1124     /**
1125      * Call the AJAX course editing initialisation to add the editing tools
1126      * to the newly-created resource link
1127      * @param elementid the id of the DOM element containing the new resource link
1128      * @param sectionnumber the number of the selected course section
1129      */
1130     add_editing: function(elementid) {
1131         var node = Y.one('#' + elementid);
1132         YUI().use('moodle-course-coursebase', function(Y) {
1133             Y.log("Invoking setup_for_resource", 'debug', 'coursedndupload');
1134             M.course.coursebase.invoke_function('setup_for_resource', node);
1135         });
1136         if (M.core.actionmenu && M.core.actionmenu.newDOMNode) {
1137             M.core.actionmenu.newDOMNode(node);
1138         }
1139     }