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