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