on-demand release 2.3dev
[moodle.git] / course / dndupload.js
CommitLineData
32528f94
DS
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.
12//
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/>.
15
16/**
17 * Javascript library for enableing a drag and drop upload to courses
18 *
a0a06d05 19 * @package core
32528f94
DS
20 * @subpackage course
21 * @copyright 2012 Davo Smith
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24M.course_dndupload = {
25 // YUI object.
26 Y: null,
27 // URL for upload requests
33b24bdd 28 url: M.cfg.wwwroot + '/course/dndupload.php',
32528f94
DS
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,
48
49 // The following are used to identify specific parts of the course page
50
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-content',
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',
60
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;
74
75 if (!this.browser_supported()) {
76 return; // Browser does not support the required functionality
77 }
78
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();
84
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);
94
b64300fc 95 this.add_status_div();
32528f94
DS
96 },
97
98 /**
99 * Add a div element to tell the user that drag and drop upload
100 * is available (or to explain why it is not available)
32528f94
DS
101 */
102 add_status_div: function() {
103 var div = document.createElement('div');
104 div.id = 'dndupload-status';
105 var coursecontents = document.getElementById(this.pagecontentid);
106 if (coursecontents) {
107 coursecontents.insertBefore(div, coursecontents.firstChild);
108 }
b64300fc
DS
109 div = this.Y.one(div);
110
111 var handlefile = (this.handlers.filehandlers.length > 0);
112 var handletext = false;
113 var handlelink = false;
114 var i;
115 for (i=0; i<this.handlers.types.length; i++) {
116 switch (this.handlers.types[i].identifier) {
117 case 'text':
118 case 'text/html':
119 handletext = true;
120 break;
121 case 'url':
122 handlelink = true;
123 break;
124 }
125 }
126 $msgident = 'dndworking';
127 if (handlefile) {
128 $msgident += 'file';
129 }
130 if (handletext) {
131 $msgident += 'text';
132 }
133 if (handlelink) {
134 $msgident += 'link';
135 }
136 div.setContent(M.util.get_string($msgident, 'moodle'));
32528f94
DS
137 },
138
139 /**
140 * Check the browser has the required functionality
141 * @return true if browser supports drag/drop upload
142 */
143 browser_supported: function() {
32528f94
DS
144 if (typeof FileReader == 'undefined') {
145 return false;
146 }
147 if (typeof FormData == 'undefined') {
148 return false;
149 }
150 return true;
151 },
152
153 /**
154 * Initialise drag events on node container, all events need
155 * to be processed for drag and drop to work
156 * @param el the element to add events to
157 */
158 init_events: function(el) {
159 this.Y.on('dragenter', this.drag_enter, el, this);
160 this.Y.on('dragleave', this.drag_leave, el, this);
161 this.Y.on('dragover', this.drag_over, el, this);
162 this.Y.on('drop', this.drop, el, this);
163 },
164
165 /**
166 * Work out which course section a given element is in
167 * @param el the child DOM element within the section
168 * @return the DOM element representing the section
169 */
170 get_section: function(el) {
171 var sectionclasses = this.sectionclasses;
172 return el.ancestor( function(test) {
173 var i;
174 for (i=0; i<sectionclasses.length; i++) {
175 if (!test.hasClass(sectionclasses[i])) {
176 return false;
177 }
178 return true;
179 }
180 }, true);
181 },
182
183 /**
184 * Work out the number of the section we have been dropped on to, from the section element
185 * @param DOMElement section the selected section
186 * @return int the section number
187 */
188 get_section_number: function(section) {
189 var sectionid = section.get('id').split('-');
190 if (sectionid.length < 2 || sectionid[0] != 'section') {
191 return false;
192 }
193 return parseInt(sectionid[1]);
194 },
195
196 /**
197 * Check if the event includes data of the given type
198 * @param e the event details
199 * @param type the data type to check for
200 * @return true if the data type is found in the event data
201 */
202 types_includes: function(e, type) {
203 var i;
204 var types = e._event.dataTransfer.types;
205 for (i=0; i<types.length; i++) {
206 if (types[i] == type) {
207 return true;
208 }
209 }
210 return false;
211 },
212
213 /**
214 * Look through the event data, checking it against the registered data types
215 * (in order of priority) and return details of the first matching data type
216 * @param e the event details
217 * @return mixed false if not found or an object {
218 * realtype: the type as given by the browser
219 * addmessage: the message to show to the user during dragging
220 * namemessage: the message for requesting a name for the resource from the user
221 * type: the identifier of the type (may match several 'realtype's)
222 * }
223 */
224 drag_type: function(e) {
b64300fc
DS
225 // Check there is some data attached.
226 if (e._event.dataTransfer === null) {
227 return false;
228 }
229 if (e._event.dataTransfer.types === null) {
230 return false;
231 }
232 if (e._event.dataTransfer.types.length == 0) {
233 return false;
234 }
235
236 // Check for files first.
32528f94 237 if (this.types_includes(e, 'Files')) {
5a4decbc
DS
238 if (e.type != 'drop' || e._event.dataTransfer.files.length != 0) {
239 if (this.handlers.filehandlers.length == 0) {
240 return false; // No available file handlers - ignore this drag.
241 }
242 return {
243 realtype: 'Files',
244 addmessage: M.util.get_string('addfilehere', 'moodle'),
245 namemessage: null, // Should not be asked for anyway
246 type: 'Files'
247 };
5103b5e6 248 }
32528f94
DS
249 }
250
b64300fc 251 // Check each of the registered types.
32528f94
DS
252 var types = this.handlers.types;
253 for (var i=0; i<types.length; i++) {
254 // Check each of the different identifiers for this type
255 var dttypes = types[i].datatransfertypes;
256 for (var j=0; j<dttypes.length; j++) {
257 if (this.types_includes(e, dttypes[j])) {
258 return {
259 realtype: dttypes[j],
260 addmessage: types[i].addmessage,
261 namemessage: types[i].namemessage,
262 type: types[i].identifier,
263 handlers: types[i].handlers
264 };
265 }
266 }
267 }
268 return false; // No types we can handle
269 },
270
271 /**
272 * Check the content of the drag/drop includes a type we can handle, then, if
273 * it is, notify the browser that we want to handle it
274 * @param event e
275 * @return string type of the event or false
276 */
277 check_drag: function(e) {
278 var type = this.drag_type(e);
279 if (type) {
280 // Notify browser that we will handle this drag/drop
281 e.stopPropagation();
282 e.preventDefault();
283 }
284 return type;
285 },
286
287 /**
288 * Handle a dragenter event: add a suitable 'add here' message
289 * when a drag event occurs, containing a registered data type
290 * @param e event data
291 * @return false to prevent the event from continuing to be processed
292 */
293 drag_enter: function(e) {
294 if (!(type = this.check_drag(e))) {
295 return false;
296 }
297
298 var section = this.get_section(e.currentTarget);
299 if (!section) {
300 return false;
301 }
302
303 if (this.currentsection && this.currentsection != section) {
304 this.currentsection = section;
305 this.entercount = 1;
306 } else {
307 this.entercount++;
308 if (this.entercount > 2) {
309 this.entercount = 2;
310 return false;
311 }
312 }
313
314 this.show_preview_element(section, type);
315
316 return false;
317 },
318
319 /**
320 * Handle a dragleave event: remove the 'add here' message (if present)
321 * @param e event data
322 * @return false to prevent the event from continuing to be processed
323 */
324 drag_leave: function(e) {
325 if (!this.check_drag(e)) {
326 return false;
327 }
328
329 this.entercount--;
330 if (this.entercount == 1) {
331 return false;
332 }
333 this.entercount = 0;
334 this.currentsection = null;
335
336 this.hide_preview_element();
337 return false;
338 },
339
340 /**
341 * Handle a dragover event: just prevent the browser default (necessary
342 * to allow drag and drop handling to work)
343 * @param e event data
344 * @return false to prevent the event from continuing to be processed
345 */
346 drag_over: function(e) {
347 this.check_drag(e);
348 return false;
349 },
350
351 /**
352 * Handle a drop event: hide the 'add here' message, check the attached
353 * data type and start the upload process
354 * @param e event data
355 * @return false to prevent the event from continuing to be processed
356 */
357 drop: function(e) {
358 if (!(type = this.check_drag(e))) {
359 return false;
360 }
361
362 this.hide_preview_element();
363
364 // Work out the number of the section we are on (from its id)
365 var section = this.get_section(e.currentTarget);
366 var sectionnumber = this.get_section_number(section);
367
368 // Process the file or the included data
369 if (type.type == 'Files') {
370 var files = e._event.dataTransfer.files;
371 for (var i=0, f; f=files[i]; i++) {
372 this.handle_file(f, section, sectionnumber);
373 }
374 } else {
375 var contents = e._event.dataTransfer.getData(type.realtype);
376 if (contents) {
377 this.handle_item(type, contents, section, sectionnumber);
378 }
379 }
380
381 return false;
382 },
383
384 /**
385 * Find or create the 'ul' element that contains all of the module
386 * instances in this section
387 * @param section the DOM element representing the section
388 * @return false to prevent the event from continuing to be processed
389 */
390 get_mods_element: function(section) {
391 // Find the 'ul' containing the list of mods
392 var modsel = section.one(this.modslistselector);
393 if (!modsel) {
394 // Create the above 'ul' if it doesn't exist
395 var modsel = document.createElement('ul');
396 modsel.className = 'section img-text';
397 var contentel = section.get('children').pop();
398 var brel = contentel.get('children').pop();
399 contentel.insertBefore(modsel, brel);
400 modsel = this.Y.one(modsel);
401 }
402
403 return modsel;
404 },
405
406 /**
407 * Add a new dummy item to the list of mods, to be replaced by a real
408 * item & link once the AJAX upload call has completed
409 * @param name the label to show in the element
410 * @param section the DOM element reperesenting the course section
411 * @return DOM element containing the new item
412 */
413 add_resource_element: function(name, section) {
414 var modsel = this.get_mods_element(section);
415
416 var resel = {
417 parent: modsel,
418 li: document.createElement('li'),
419 div: document.createElement('div'),
420 a: document.createElement('a'),
421 icon: document.createElement('img'),
422 namespan: document.createElement('span'),
423 progressouter: document.createElement('span'),
424 progress: document.createElement('span')
425 };
426
427 resel.li.className = 'activity resource modtype_resource';
428
429 resel.div.className = 'mod-indent';
430 resel.li.appendChild(resel.div);
431
432 resel.a.href = '#';
433 resel.div.appendChild(resel.a);
434
435 resel.icon.src = M.util.image_url('i/ajaxloader');
b64300fc 436 resel.icon.className = 'activityicon';
32528f94
DS
437 resel.a.appendChild(resel.icon);
438
439 resel.a.appendChild(document.createTextNode(' '));
440
441 resel.namespan.className = 'instancename';
442 resel.namespan.innerHTML = name;
443 resel.a.appendChild(resel.namespan);
444
445 resel.div.appendChild(document.createTextNode(' '));
446
447 resel.progressouter.className = 'dndupload-progress-outer';
448 resel.progress.className = 'dndupload-progress-inner';
449 resel.progress.innerHTML = '&nbsp;';
450 resel.progressouter.appendChild(resel.progress);
451 resel.div.appendChild(resel.progressouter);
452
453 modsel.insertBefore(resel.li, modsel.get('children').pop()); // Leave the 'preview element' at the bottom
454
455 return resel;
456 },
457
458 /**
459 * Hide any visible dndupload-preview elements on the page
460 */
461 hide_preview_element: function() {
462 this.Y.all('li.dndupload-preview').addClass('dndupload-hidden');
463 },
464
465 /**
466 * Unhide the preview element for the given section and set it to display
467 * the correct message
468 * @param section the YUI node representing the selected course section
469 * @param type the details of the data type detected in the drag (including the message to display)
470 */
471 show_preview_element: function(section, type) {
472 this.hide_preview_element();
473 var preview = section.one('li.dndupload-preview').removeClass('dndupload-hidden');
474 preview.one('span').setContent(type.addmessage);
475 },
476
477 /**
478 * Add the preview element to a course section. Note: this needs to be done before 'addEventListener'
479 * is called, otherwise Firefox will ignore events generated when the mouse is over the preview
480 * element (instead of passing them up to the parent element)
481 * @param section the YUI node representing the selected course section
482 */
483 add_preview_element: function(section) {
484 var modsel = this.get_mods_element(section);
485 var preview = {
486 li: document.createElement('li'),
487 div: document.createElement('div'),
488 icon: document.createElement('img'),
489 namespan: document.createElement('span')
490 };
491
492 preview.li.className = 'dndupload-preview activity resource modtype_resource dndupload-hidden';
493
494 preview.div.className = 'mod-indent';
495 preview.li.appendChild(preview.div);
496
497 preview.icon.src = M.util.image_url('t/addfile');
498 preview.div.appendChild(preview.icon);
499
500 preview.div.appendChild(document.createTextNode(' '));
501
502 preview.namespan.className = 'instancename';
33b24bdd 503 preview.namespan.innerHTML = M.util.get_string('addfilehere', 'moodle');
32528f94
DS
504 preview.div.appendChild(preview.namespan);
505
506 modsel.appendChild(preview.li);
507 },
508
509 /**
510 * Find the registered handler for the given file type. If there is more than one, ask the
511 * user which one to use. Then upload the file to the server
512 * @param file the details of the file, taken from the FileList in the drop event
513 * @param section the DOM element representing the selected course section
514 * @param sectionnumber the number of the selected course section
515 */
516 handle_file: function(file, section, sectionnumber) {
517 var handlers = new Array();
518 var filehandlers = this.handlers.filehandlers;
519 var extension = '';
520 var dotpos = file.name.lastIndexOf('.');
521 if (dotpos != -1) {
522 extension = file.name.substr(dotpos+1, file.name.length);
523 }
524
525 for (var i=0; i<filehandlers.length; i++) {
526 if (filehandlers[i].extension == '*' || filehandlers[i].extension == extension) {
527 handlers.push(filehandlers[i]);
528 }
529 }
530
531 if (handlers.length == 0) {
532 // No handlers at all (not even 'resource'?)
533 return;
534 }
535
536 if (handlers.length == 1) {
537 this.upload_file(file, section, sectionnumber, handlers[0].module);
538 return;
539 }
540
541 this.file_handler_dialog(handlers, extension, file, section, sectionnumber);
542 },
543
544 /**
545 * Show a dialog box, allowing the user to choose what to do with the file they are uploading
546 * @param handlers the available handlers to choose between
547 * @param extension the extension of the file being uploaded
548 * @param file the File object being uploaded
549 * @param section the DOM element of the section being uploaded to
550 * @param sectionnumber the number of the selected course section
551 */
552 file_handler_dialog: function(handlers, extension, file, section, sectionnumber) {
553 if (this.uploaddialog) {
554 var details = new Object();
555 details.isfile = true;
556 details.handlers = handlers;
557 details.extension = extension;
558 details.file = file;
559 details.section = section;
560 details.sectionnumber = sectionnumber;
561 this.uploadqueue.push(details);
562 return;
563 }
564 this.uploaddialog = true;
565
566 var timestamp = new Date().getTime();
567 var uploadid = Math.round(Math.random()*100000)+'-'+timestamp;
568 var content = '';
569 var sel;
570 if (extension in this.lastselected) {
571 sel = this.lastselected[extension];
572 } else {
573 sel = handlers[0].module;
574 }
33b24bdd 575 content += '<p>'+M.util.get_string('actionchoice', 'moodle', file.name)+'</p>';
32528f94
DS
576 content += '<div id="dndupload_handlers'+uploadid+'">';
577 for (var i=0; i<handlers.length; i++) {
578 var id = 'dndupload_handler'+uploadid+handlers[i].module;
579 var checked = (handlers[i].module == sel) ? 'checked="checked" ' : '';
580 content += '<input type="radio" name="handler" value="'+handlers[i].module+'" id="'+id+'" '+checked+'/>';
581 content += ' <label for="'+id+'">';
582 content += handlers[i].message;
583 content += '</label><br/>';
584 }
585 content += '</div>';
586
587 var Y = this.Y;
588 var self = this;
589 var panel = new Y.Panel({
590 bodyContent: content,
591 width: 350,
592 zIndex: 5,
593 centered: true,
594 modal: true,
595 visible: true,
596 render: true,
597 buttons: [{
a0a06d05 598 value: M.util.get_string('upload', 'moodle'),
32528f94
DS
599 action: function(e) {
600 e.preventDefault();
601 // Find out which module was selected
602 var module = false;
603 var div = Y.one('#dndupload_handlers'+uploadid);
604 div.all('input').each(function(input) {
605 if (input.get('checked')) {
606 module = input.get('value');
607 }
608 });
609 if (!module) {
610 return;
611 }
612 panel.hide();
613 // Remember this selection for next time
614 self.lastselected[extension] = module;
615 // Do the upload
616 self.upload_file(file, section, sectionnumber, module);
617 },
618 section: Y.WidgetStdMod.FOOTER
619 },{
a0a06d05 620 value: M.util.get_string('cancel', 'moodle'),
32528f94
DS
621 action: function(e) {
622 e.preventDefault();
623 panel.hide();
624 },
625 section: Y.WidgetStdMod.FOOTER
626 }]
627 });
628 // When the panel is hidden - destroy it and then check for other pending uploads
629 panel.after("visibleChange", function(e) {
630 if (!panel.get('visible')) {
631 panel.destroy(true);
632 self.check_upload_queue();
633 }
634 });
635 },
636
637 /**
638 * Check to see if there are any other dialog boxes to show, now that the current one has
639 * been dealt with
640 */
641 check_upload_queue: function() {
642 this.uploaddialog = false;
643 if (this.uploadqueue.length == 0) {
644 return;
645 }
646
647 var details = this.uploadqueue.shift();
648 if (details.isfile) {
649 this.file_handler_dialog(details.handlers, details.extension, details.file, details.section, details.sectionnumber);
650 } else {
651 this.handle_item(details.type, details.contents, details.section, details.sectionnumber);
652 }
653 },
654
655 /**
656 * Do the file upload: show the dummy element, use an AJAX call to send the data
657 * to the server, update the progress bar for the file, then replace the dummy
658 * element with the real information once the AJAX call completes
659 * @param file the details of the file, taken from the FileList in the drop event
660 * @param section the DOM element representing the selected course section
661 * @param sectionnumber the number of the selected course section
662 */
663 upload_file: function(file, section, sectionnumber, module) {
664
665 // This would be an ideal place to use the Y.io function
666 // however, this does not support data encoded using the
667 // FormData object, which is needed to transfer data from
668 // the DataTransfer object into an XMLHTTPRequest
669 // This can be converted when the YUI issue has been integrated:
670 // http://yuilibrary.com/projects/yui3/ticket/2531274
671 var xhr = new XMLHttpRequest();
672 var self = this;
673
674 if (file.size > this.maxbytes) {
33b24bdd 675 alert("'"+file.name+"' "+M.util.get_string('filetoolarge', 'moodle'));
32528f94
DS
676 return;
677 }
678
679 // Add the file to the display
680 var resel = this.add_resource_element(file.name, section);
681
682 // Update the progress bar as the file is uploaded
683 xhr.upload.addEventListener('progress', function(e) {
684 if (e.lengthComputable) {
685 var percentage = Math.round((e.loaded * 100) / e.total);
686 resel.progress.style.width = percentage + '%';
687 }
688 }, false);
689
690 // Wait for the AJAX call to complete, then update the
691 // dummy element with the returned details
692 xhr.onreadystatechange = function() {
693 if (xhr.readyState == 4) {
694 if (xhr.status == 200) {
695 var result = JSON.parse(xhr.responseText);
696 if (result) {
697 if (result.error == 0) {
698 // All OK - update the dummy element
699 resel.icon.src = result.icon;
700 resel.a.href = result.link;
701 resel.namespan.innerHTML = result.name;
702 resel.div.removeChild(resel.progressouter);
703 resel.li.id = result.elementid;
704 resel.div.innerHTML += result.commands;
705 if (result.onclick) {
706 resel.a.onclick = result.onclick;
707 }
5a4decbc
DS
708 if (self.Y.UA.gecko > 0) {
709 // Fix a Firefox bug which makes sites with a '~' in their wwwroot
710 // log the user out when clicking on the link (before refreshing the page).
711 resel.div.innerHTML = unescape(resel.div.innerHTML);
712 }
32528f94
DS
713 self.add_editing(result.elementid);
714 } else {
715 // Error - remove the dummy element
716 resel.parent.removeChild(resel.li);
717 alert(result.error);
718 }
719 }
720 } else {
33b24bdd 721 alert(M.util.get_string('servererror', 'moodle'));
32528f94
DS
722 }
723 }
724 };
725
726 // Prepare the data to send
727 var formData = new FormData();
728 formData.append('repo_upload_file', file);
729 formData.append('sesskey', M.cfg.sesskey);
730 formData.append('course', this.courseid);
731 formData.append('section', sectionnumber);
732 formData.append('module', module);
733 formData.append('type', 'Files');
734
735 // Send the AJAX call
736 xhr.open("POST", this.url, true);
737 xhr.send(formData);
738 },
739
740 /**
741 * Show a dialog box to gather the name of the resource / activity to be created
742 * from the uploaded content
743 * @param type the details of the type of content
744 * @param contents the contents to be uploaded
745 * @section the DOM element for the section being uploaded to
746 * @sectionnumber the number of the section being uploaded to
747 */
748 handle_item: function(type, contents, section, sectionnumber) {
749 if (type.handlers.length == 0) {
750 // Nothing to handle this - should not have got here
751 return;
752 }
753
754 if (this.uploaddialog) {
755 var details = new Object();
756 details.isfile = false;
757 details.type = type;
758 details.contents = contents;
759 details.section = section;
760 details.setcionnumber = sectionnumber;
761 this.uploadqueue.push(details);
762 return;
763 }
764 this.uploaddialog = true;
765
766 var timestamp = new Date().getTime();
767 var uploadid = Math.round(Math.random()*100000)+'-'+timestamp;
768 var nameid = 'dndupload_handler_name'+uploadid;
769 var content = '';
770 content += '<label for="'+nameid+'">'+type.namemessage+'</label>';
771 content += ' <input type="text" id="'+nameid+'" value="" />';
772 if (type.handlers.length > 1) {
773 content += '<div id="dndupload_handlers'+uploadid+'">';
774 var sel = type.handlers[0].module;
775 for (var i=0; i<type.handlers.length; i++) {
776 var id = 'dndupload_handler'+uploadid;
777 var checked = (type.handlers[i].module == sel) ? 'checked="checked" ' : '';
778 content += '<input type="radio" name="handler" value="'+type.handlers[i].module+'" id="'+id+'" '+checked+'/>';
779 content += ' <label for="'+id+'">';
780 content += type.handlers[i].message;
781 content += '</label><br/>';
782 }
783 content += '</div>';
784 }
785
786 var Y = this.Y;
787 var self = this;
788 var panel = new Y.Panel({
789 bodyContent: content,
790 width: 350,
791 zIndex: 5,
792 centered: true,
793 modal: true,
794 visible: true,
795 render: true,
796 buttons: [{
a0a06d05 797 value: M.util.get_string('upload', 'moodle'),
32528f94
DS
798 action: function(e) {
799 e.preventDefault();
800 var name = Y.one('#dndupload_handler_name'+uploadid).get('value');
801 name = name.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); // Trim
802 if (name == '') {
803 return;
804 }
805 var module = false;
806 if (type.handlers.length > 1) {
807 // Find out which module was selected
808 var div = Y.one('#dndupload_handlers'+uploadid);
809 div.all('input').each(function(input) {
810 if (input.get('checked')) {
811 module = input.get('value');
812 }
813 });
814 if (!module) {
815 return;
816 }
817 } else {
818 module = type.handlers[0].module;
819 }
820 panel.hide();
821 // Do the upload
822 self.upload_item(name, type.type, contents, section, sectionnumber, module);
823 },
824 section: Y.WidgetStdMod.FOOTER
825 },{
a0a06d05 826 value: M.util.get_string('cancel', 'moodle'),
32528f94
DS
827 action: function(e) {
828 e.preventDefault();
829 panel.hide();
830 },
831 section: Y.WidgetStdMod.FOOTER
832 }]
833 });
834 // When the panel is hidden - destroy it and then check for other pending uploads
835 panel.after("visibleChange", function(e) {
836 if (!panel.get('visible')) {
837 panel.destroy(true);
838 self.check_upload_queue();
839 }
840 });
841 // Focus on the 'name' box
842 Y.one('#'+nameid).focus();
843 },
844
845 /**
846 * Upload any data types that are not files: display a dummy resource element, send
847 * the data to the server, update the progress bar for the file, then replace the
848 * dummy element with the real information once the AJAX call completes
849 * @param name the display name for the resource / activity to create
850 * @param type the details of the data type found in the drop event
851 * @param contents the actual data that was dropped
852 * @param section the DOM element representing the selected course section
853 * @param sectionnumber the number of the selected course section
5a4decbc 854 * @param module the module chosen to handle this upload
32528f94
DS
855 */
856 upload_item: function(name, type, contents, section, sectionnumber, module) {
857
858 // This would be an ideal place to use the Y.io function
859 // however, this does not support data encoded using the
860 // FormData object, which is needed to transfer data from
861 // the DataTransfer object into an XMLHTTPRequest
862 // This can be converted when the YUI issue has been integrated:
863 // http://yuilibrary.com/projects/yui3/ticket/2531274
864 var xhr = new XMLHttpRequest();
865 var self = this;
866
867 // Add the item to the display
868 var resel = this.add_resource_element(name, section);
869
870 // Wait for the AJAX call to complete, then update the
871 // dummy element with the returned details
872 xhr.onreadystatechange = function() {
873 if (xhr.readyState == 4) {
874 if (xhr.status == 200) {
875 var result = JSON.parse(xhr.responseText);
876 if (result) {
877 if (result.error == 0) {
878 // All OK - update the dummy element
879 resel.icon.src = result.icon;
880 resel.a.href = result.link;
881 resel.namespan.innerHTML = result.name;
882 resel.div.removeChild(resel.progressouter);
883 resel.li.id = result.elementid;
884 resel.div.innerHTML += result.commands;
885 if (result.onclick) {
886 resel.a.onclick = result.onclick;
887 }
5a4decbc
DS
888 if (self.Y.UA.gecko > 0) {
889 // Fix a Firefox bug which makes sites with a '~' in their wwwroot
890 // log the user out when clicking on the link (before refreshing the page).
891 resel.div.innerHTML = unescape(resel.div.innerHTML);
892 }
32528f94
DS
893 self.add_editing(result.elementid, sectionnumber);
894 } else {
895 // Error - remove the dummy element
896 resel.parent.removeChild(resel.li);
897 alert(result.error);
898 }
899 }
900 } else {
33b24bdd 901 alert(M.util.get_string('servererror', 'moodle'));
32528f94
DS
902 }
903 }
904 };
905
906 // Prepare the data to send
907 var formData = new FormData();
908 formData.append('contents', contents);
909 formData.append('displayname', name);
910 formData.append('sesskey', M.cfg.sesskey);
911 formData.append('course', this.courseid);
912 formData.append('section', sectionnumber);
913 formData.append('type', type);
914 formData.append('module', module);
915
916 // Send the data
917 xhr.open("POST", this.url, true);
918 xhr.send(formData);
919 },
920
921 /**
922 * Call the AJAX course editing initialisation to add the editing tools
923 * to the newly-created resource link
924 * @param elementid the id of the DOM element containing the new resource link
925 * @param sectionnumber the number of the selected course section
926 */
927 add_editing: function(elementid) {
928 YUI().use('moodle-course-coursebase', function(Y) {
929 M.course.coursebase.invoke_function('setup_for_resource', '#' + elementid);
930 });
931 }
932};