2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Library to handle drag and drop course uploads
22 * @copyright 2012 Davo smith
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') ||
die();
28 require_once($CFG->dirroot
.'/repository/lib.php');
29 require_once($CFG->dirroot
.'/repository/upload/lib.php');
30 require_once($CFG->dirroot
.'/course/lib.php');
33 * Add the Javascript to enable drag and drop upload to a course page
35 * @param object $course The currently displayed course
36 * @param array $modnames The list of enabled (visible) modules on this site
39 function dndupload_add_to_course($course, $modnames) {
42 $showstatus = optional_param('notifyeditingon', false, PARAM_BOOL
);
45 $handler = new dndupload_handler($course, $modnames);
46 $jsdata = $handler->get_js_data();
47 if (empty($jsdata->types
) && empty($jsdata->filehandlers
)) {
48 return; // No valid handlers - don't enable drag and drop.
51 // Add the javascript to the page.
53 'name' => 'coursedndupload',
54 'fullpath' => '/course/dndupload.js',
56 array('addfilehere', 'moodle'),
57 array('dndworkingfiletextlink', 'moodle'),
58 array('dndworkingfilelink', 'moodle'),
59 array('dndworkingfiletext', 'moodle'),
60 array('dndworkingfile', 'moodle'),
61 array('dndworkingtextlink', 'moodle'),
62 array('dndworkingtext', 'moodle'),
63 array('dndworkinglink', 'moodle'),
64 array('filetoolarge', 'moodle'),
65 array('actionchoice', 'moodle'),
66 array('servererror', 'moodle'),
67 array('upload', 'moodle'),
68 array('cancel', 'moodle')
70 'requires' => array('node', 'event', 'json', 'anim')
73 array('courseid' => $course->id
,
74 'maxbytes' => get_max_upload_file_size($CFG->maxbytes
, $course->maxbytes
),
75 'handlers' => $handler->get_js_data(),
76 'showstatus' => $showstatus)
79 $PAGE->requires
->js_init_call('M.course_dndupload.init', $vars, true, $jsmodule);
84 * Stores all the information about the available dndupload handlers
87 * @copyright 2012 Davo Smith
88 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
90 class dndupload_handler
{
93 * @var array A list of all registered mime types that can be dropped onto a course
94 * along with the modules that will handle them.
96 protected $types = array();
99 * @var array A list of the different file types (extensions) that different modules
102 protected $filehandlers = array();
105 * Gather a list of dndupload handlers from the different mods
107 * @param object $course The course this is being added to (to check course_allowed_module() )
109 public function __construct($course, $modnames = null) {
112 // Add some default types to handle.
113 // Note: 'Files' type is hard-coded into the Javascript as this needs to be ...
114 // ... treated a little differently.
115 $this->register_type('url', array('url', 'text/uri-list', 'text/x-moz-url'), get_string('addlinkhere', 'moodle'),
116 get_string('nameforlink', 'moodle'), get_string('whatforlink', 'moodle'), 10);
117 $this->register_type('text/html', array('text/html'), get_string('addpagehere', 'moodle'),
118 get_string('nameforpage', 'moodle'), get_string('whatforpage', 'moodle'), 20);
119 $this->register_type('text', array('text', 'text/plain'), get_string('addpagehere', 'moodle'),
120 get_string('nameforpage', 'moodle'), get_string('whatforpage', 'moodle'), 30);
122 // Loop through all modules to find handlers.
123 $mods = get_plugin_list_with_function('mod', 'dndupload_register');
124 foreach ($mods as $component => $funcname) {
125 list($modtype, $modname) = normalize_component($component);
126 if ($modnames && !array_key_exists($modname, $modnames)) {
127 continue; // Module is deactivated (hidden) at the site level.
129 if (!course_allowed_module($course, $modname)) {
130 continue; // User does not have permission to add this module to the course.
136 if (isset($resp['files'])) {
137 foreach ($resp['files'] as $file) {
138 $this->register_file_handler($file['extension'], $modname, $file['message']);
141 if (isset($resp['addtypes'])) {
142 foreach ($resp['addtypes'] as $type) {
143 if (isset($type['priority'])) {
144 $priority = $type['priority'];
148 if (!isset($type['handlermessage'])) {
149 $type['handlermessage'] = '';
151 $this->register_type($type['identifier'], $type['datatransfertypes'],
152 $type['addmessage'], $type['namemessage'], $type['handlermessage'], $priority);
155 if (isset($resp['types'])) {
156 foreach ($resp['types'] as $type) {
157 $noname = !empty($type['noname']);
158 $this->register_type_handler($type['identifier'], $modname, $type['message'], $noname);
161 $PAGE->requires
->string_for_js('pluginname', $modname);
166 * No external code should be directly adding new types - they should be added via a 'addtypes' array, returned
167 * by MODNAME_dndupload_register.
169 * @deprecated deprecated since Moodle 2.5
170 * @param string $identifier
171 * @param array $datatransfertypes
172 * @param string $addmessage
173 * @param string $namemessage
174 * @param int $priority
176 public function add_type($identifier, $datatransfertypes, $addmessage, $namemessage, $priority=100) {
177 debugging('add_type() is deprecated. Plugins should be using the MODNAME_dndupload_register callback.');
178 $this->register_type($identifier, $datatransfertypes, $addmessage, $namemessage, '', $priority);
182 * Used to add a new mime type that can be drag and dropped onto a
183 * course displayed in a browser window
185 * @param string $identifier The name that this type will be known as
186 * @param array $datatransfertypes An array of the different types in the browser
187 * 'dataTransfer.types' object that will map to this type
188 * @param string $addmessage The message to display in the browser when this type is being
189 * dragged onto the page
190 * @param string $namemessage The message to pop up when asking for the name to give the
191 * course module instance when it is created
192 * @param string $handlermessage The message to pop up when asking which module should handle this type
193 * @param int $priority Controls the order in which types are checked by the browser (mainly
194 * needed to check for 'text' last as that is usually given as fallback)
196 protected function register_type($identifier, $datatransfertypes, $addmessage, $namemessage, $handlermessage, $priority=100) {
197 if ($this->is_known_type($identifier)) {
198 throw new coding_exception("Type $identifier is already registered");
202 $add->identifier
= $identifier;
203 $add->datatransfertypes
= $datatransfertypes;
204 $add->addmessage
= $addmessage;
205 $add->namemessage
= $namemessage;
206 $add->handlermessage
= $handlermessage;
207 $add->priority
= $priority;
208 $add->handlers
= array();
210 $this->types
[$identifier] = $add;
214 * No external code should be directly adding new type handlers - they should be added via a 'addtypes' array, returned
215 * by MODNAME_dndupload_register.
217 * @deprecated deprecated since Moodle 2.5
218 * @param string $type The name of the type (as declared in add_type)
219 * @param string $module The name of the module to handle this type
220 * @param string $message The message to show the user if more than one handler is registered
221 * for a type and the user needs to make a choice between them
222 * @param bool $noname If true, the 'name' dialog should be disabled in the pop-up.
223 * @throws coding_exception
225 public function add_type_handler($type, $module, $message, $noname) {
226 debugging('add_type_handler() is deprecated. Plugins should be using the MODNAME_dndupload_register callback.');
227 $this->register_type_handler($type, $module, $message, $noname);
231 * Used to declare that a particular module will handle a particular type
234 * @param string $type The name of the type (as declared in register_type)
235 * @param string $module The name of the module to handle this type
236 * @param string $message The message to show the user if more than one handler is registered
237 * for a type and the user needs to make a choice between them
238 * @param bool $noname If true, the 'name' dialog should be disabled in the pop-up.
239 * @throws coding_exception
241 protected function register_type_handler($type, $module, $message, $noname) {
242 if (!$this->is_known_type($type)) {
243 throw new coding_exception("Trying to add handler for unknown type $type");
248 $add->module
= $module;
249 $add->message
= $message;
250 $add->noname
= $noname ?
1 : 0;
252 $this->types
[$type]->handlers
[] = $add;
256 * No external code should be directly adding new file handlers - they should be added via a 'files' array, returned
257 * by MODNAME_dndupload_register.
259 * @deprecated deprecated since Moodle 2.5
260 * @param string $extension The file extension to handle ('*' for all types)
261 * @param string $module The name of the module to handle this type
262 * @param string $message The message to show the user if more than one handler is registered
263 * for a type and the user needs to make a choice between them
265 public function add_file_handler($extension, $module, $message) {
266 debugging('add_file_handler() is deprecated. Plugins should be using the MODNAME_dndupload_register callback.');
267 $this->register_file_handler($extension, $module, $message);
271 * Used to declare that a particular module will handle a particular type
274 * @param string $extension The file extension to handle ('*' for all types)
275 * @param string $module The name of the module to handle this type
276 * @param string $message The message to show the user if more than one handler is registered
277 * for a type and the user needs to make a choice between them
279 protected function register_file_handler($extension, $module, $message) {
280 $extension = strtolower($extension);
283 $add->extension
= $extension;
284 $add->module
= $module;
285 $add->message
= $message;
287 $this->filehandlers
[] = $add;
291 * Check to see if the type has been registered
293 * @param string $type The identifier of the type you are interested in
294 * @return bool True if the type is registered
296 public function is_known_type($type) {
297 return array_key_exists($type, $this->types
);
301 * Check to see if the module in question has registered to handle the
304 * @param string $module The name of the module
305 * @param string $type The identifier of the type
306 * @return bool True if the module has registered to handle that type
308 public function has_type_handler($module, $type) {
309 if (!$this->is_known_type($type)) {
310 throw new coding_exception("Checking for handler for unknown type $type");
312 foreach ($this->types
[$type]->handlers
as $handler) {
313 if ($handler->module
== $module) {
321 * Check to see if the module in question has registered to handle files
322 * with the given extension (or to handle all file types)
324 * @param string $module The name of the module
325 * @param string $extension The extension of the uploaded file
326 * @return bool True if the module has registered to handle files with
327 * that extension (or to handle all file types)
329 public function has_file_handler($module, $extension) {
330 foreach ($this->filehandlers
as $handler) {
331 if ($handler->module
== $module) {
332 if ($handler->extension
== '*' ||
$handler->extension
== $extension) {
341 * Gets a list of the file types that are handled by a particular module
343 * @param string $module The name of the module to check
344 * @return array of file extensions or string '*'
346 public function get_handled_file_types($module) {
348 foreach ($this->filehandlers
as $handler) {
349 if ($handler->module
== $module) {
350 if ($handler->extension
== '*') {
353 // Prepending '.' as otherwise mimeinfo fails.
354 $types[] = '.'.$handler->extension
;
362 * Returns an object to pass onto the javascript code with data about all the
363 * registered file / type handlers
365 * @return object Data to pass on to Javascript code
367 public function get_js_data() {
372 // Sort the types by priority.
373 uasort($this->types
, array($this, 'type_compare'));
375 $ret->types
= array();
376 if (!empty($CFG->dndallowtextandlinks
)) {
377 foreach ($this->types
as $type) {
378 if (empty($type->handlers
)) {
379 continue; // Skip any types without registered handlers.
381 $ret->types
[] = $type;
385 $ret->filehandlers
= $this->filehandlers
;
386 $uploadrepo = repository
::get_instances(array('type' => 'upload'));
387 if (empty($uploadrepo)) {
388 $ret->filehandlers
= array(); // No upload repo => no file handlers.
395 * Comparison function used when sorting types by priority
396 * @param object $type1 first type to compare
397 * @param object $type2 second type to compare
398 * @return integer -1 for $type1 < $type2; 1 for $type1 > $type2; 0 for equal
400 protected function type_compare($type1, $type2) {
401 if ($type1->priority
< $type2->priority
) {
404 if ($type1->priority
> $type2->priority
) {
413 * Processes the upload, creating the course module and returning the result
416 * @copyright 2012 Davo Smith
417 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
419 class dndupload_ajax_processor
{
421 /** Returned when no error has occurred */
424 /** @var object The course that we are uploading to */
425 protected $course = null;
427 /** @var context_course The course context for capability checking */
428 protected $context = null;
430 /** @var int The section number we are uploading to */
431 protected $section = null;
433 /** @var string The type of upload (e.g. 'Files', 'text/plain') */
434 protected $type = null;
436 /** @var object The details of the module type that will be created */
437 protected $module= null;
439 /** @var object The course module that has been created */
440 protected $cm = null;
442 /** @var dndupload_handler used to check the allowed file types */
443 protected $dnduploadhandler = null;
445 /** @var string The name to give the new activity instance */
446 protected $displayname = null;
449 * Set up some basic information needed to handle the upload
451 * @param int $courseid The ID of the course we are uploading to
452 * @param int $section The section number we are uploading to
453 * @param string $type The type of upload (as reported by the browser)
454 * @param string $modulename The name of the module requested to handle this upload
456 public function __construct($courseid, $section, $type, $modulename) {
459 if (!defined('AJAX_SCRIPT')) {
460 throw new coding_exception('dndupload_ajax_processor should only be used within AJAX requests');
463 $this->course
= $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST
);
465 require_login($this->course
, false);
466 $this->context
= context_course
::instance($this->course
->id
);
468 if (!is_number($section) ||
$section < 0) {
469 throw new coding_exception("Invalid section number $section");
471 $this->section
= $section;
474 if (!$this->module
= $DB->get_record('modules', array('name' => $modulename))) {
475 throw new coding_exception("Module $modulename does not exist");
478 $this->dnduploadhandler
= new dndupload_handler($this->course
);
482 * Check if this upload is a 'file' upload
484 * @return bool true if it is a 'file' upload, false otherwise
486 protected function is_file_upload() {
487 return ($this->type
== 'Files');
491 * Process the upload - creating the module in the course and returning the result to the browser
493 * @param string $displayname optional the name (from the browser) to give the course module instance
494 * @param string $content optional the content of the upload (for non-file uploads)
496 public function process($displayname = null, $content = null) {
497 require_capability('moodle/course:manageactivities', $this->context
);
499 if ($this->is_file_upload()) {
500 require_capability('moodle/course:managefiles', $this->context
);
501 if ($content != null) {
502 throw new moodle_exception('fileuploadwithcontent', 'moodle');
505 if (empty($content)) {
506 throw new moodle_exception('dnduploadwithoutcontent', 'moodle');
512 $this->displayname
= $displayname;
514 if ($this->is_file_upload()) {
515 $this->handle_file_upload();
517 $this->handle_other_upload($content);
522 * Handle uploads containing files - create the course module, ask the upload repository
523 * to process the file, ask the mod to set itself up, then return the result to the browser
525 protected function handle_file_upload() {
528 // Add the file to a draft file area.
529 $draftitemid = file_get_unused_draft_itemid();
530 $maxbytes = get_max_upload_file_size($CFG->maxbytes
, $this->course
->maxbytes
);
531 $types = $this->dnduploadhandler
->get_handled_file_types($this->module
->name
);
532 $repo = repository
::get_instances(array('type' => 'upload'));
534 throw new moodle_exception('errornouploadrepo', 'moodle');
536 $repo = reset($repo); // Get the first (and only) upload repo.
537 $details = $repo->process_upload(null, $maxbytes, $types, '/', $draftitemid);
538 if (empty($this->displayname
)) {
539 $this->displayname
= $this->display_name_from_file($details['file']);
542 // Create a course module to hold the new instance.
543 $this->create_course_module();
545 // Ask the module to set itself up.
546 $moduledata = $this->prepare_module_data($draftitemid);
547 $instanceid = plugin_callback('mod', $this->module
->name
, 'dndupload', 'handle', array($moduledata), 'invalidfunction');
548 if ($instanceid === 'invalidfunction') {
549 throw new coding_exception("{$this->module->name} does not support drag and drop upload (missing {$this->module->name}_dndupload_handle function");
552 // Finish setting up the course module.
553 $this->finish_setup_course_module($instanceid);
557 * Handle uploads not containing file - create the course module, ask the mod to
558 * set itself up, then return the result to the browser
560 * @param string $content the content uploaded to the browser
562 protected function handle_other_upload($content) {
563 // Check this plugin is registered to handle this type of upload
564 if (!$this->dnduploadhandler
->has_type_handler($this->module
->name
, $this->type
)) {
565 $info = (object)array('modname' => $this->module
->name
, 'type' => $this->type
);
566 throw new moodle_exception('moddoesnotsupporttype', 'moodle', $info);
569 // Create a course module to hold the new instance.
570 $this->create_course_module();
572 // Ask the module to set itself up.
573 $moduledata = $this->prepare_module_data(null, $content);
574 $instanceid = plugin_callback('mod', $this->module
->name
, 'dndupload', 'handle', array($moduledata), 'invalidfunction');
575 if ($instanceid === 'invalidfunction') {
576 throw new coding_exception("{$this->module->name} does not support drag and drop upload (missing {$this->module->name}_dndupload_handle function");
579 // Finish setting up the course module.
580 $this->finish_setup_course_module($instanceid);
584 * Generate the name of the mod instance from the name of the file
585 * (remove the extension and convert underscore => space
587 * @param string $filename the filename of the uploaded file
588 * @return string the display name to use
590 protected function display_name_from_file($filename) {
591 $pos = textlib
::strrpos($filename, '.');
592 if ($pos) { // Want to skip if $pos === 0 OR $pos === false.
593 $filename = textlib
::substr($filename, 0, $pos);
595 return str_replace('_', ' ', $filename);
599 * Create the coursemodule to hold the file/content that has been uploaded
601 protected function create_course_module() {
602 if (!course_allowed_module($this->course
, $this->module
->name
)) {
603 throw new coding_exception("The module {$this->module->name} is not allowed to be added to this course");
606 $this->cm
= new stdClass();
607 $this->cm
->course
= $this->course
->id
;
608 $this->cm
->section
= $this->section
;
609 $this->cm
->module
= $this->module
->id
;
610 $this->cm
->modulename
= $this->module
->name
;
611 $this->cm
->instance
= 0; // This will be filled in after we create the instance.
612 $this->cm
->visible
= 1;
613 $this->cm
->groupmode
= $this->course
->groupmode
;
614 $this->cm
->groupingid
= $this->course
->defaultgroupingid
;
616 // Set the correct default for completion tracking.
617 $this->cm
->completion
= COMPLETION_TRACKING_NONE
;
618 $completion = new completion_info($this->course
);
619 if ($completion->is_enabled()) {
620 if (plugin_supports('mod', $this->cm
->modulename
, FEATURE_MODEDIT_DEFAULT_COMPLETION
, true)) {
621 $this->cm
->completion
= COMPLETION_TRACKING_MANUAL
;
625 if (!$this->cm
->id
= add_course_module($this->cm
)) {
626 throw new coding_exception("Unable to create the course module");
628 // The following are used inside some few core functions, so may as well set them here.
629 $this->cm
->coursemodule
= $this->cm
->id
;
630 $groupbuttons = ($this->course
->groupmode
or (!$this->course
->groupmodeforce
));
631 if ($groupbuttons and plugin_supports('mod', $this->module
->name
, FEATURE_GROUPS
, 0)) {
632 $this->cm
->groupmodelink
= (!$this->course
->groupmodeforce
);
634 $this->cm
->groupmodelink
= false;
635 $this->cm
->groupmode
= false;
640 * Gather together all the details to pass on to the mod, so that it can initialise it's
641 * own database tables
643 * @param int $draftitemid optional the id of the draft area containing the file (for file uploads)
644 * @param string $content optional the content dropped onto the course (for non-file uploads)
645 * @return object data to pass on to the mod, containing:
646 * string $type the 'type' as registered with dndupload_handler (or 'Files')
647 * object $course the course the upload was for
648 * int $draftitemid optional the id of the draft area containing the files
649 * int $coursemodule id of the course module that has already been created
650 * string $displayname the name to use for this activity (can be overriden by the mod)
652 protected function prepare_module_data($draftitemid = null, $content = null) {
653 $data = new stdClass();
654 $data->type
= $this->type
;
655 $data->course
= $this->course
;
657 $data->draftitemid
= $draftitemid;
658 } else if ($content) {
659 $data->content
= $content;
661 $data->coursemodule
= $this->cm
->id
;
662 $data->displayname
= $this->displayname
;
667 * Called after the mod has set itself up, to finish off any course module settings
668 * (set instance id, add to correct section, set visibility, etc.) and send the response
670 * @param int $instanceid id returned by the mod when it was created
672 protected function finish_setup_course_module($instanceid) {
676 // Something has gone wrong - undo everything we can.
677 course_delete_module($this->cm
->id
);
678 throw new moodle_exception('errorcreatingactivity', 'moodle', '', $this->module
->name
);
681 // Note the section visibility
682 $visible = get_fast_modinfo($this->course
)->get_section_info($this->section
)->visible
;
684 $DB->set_field('course_modules', 'instance', $instanceid, array('id' => $this->cm
->id
));
685 // Rebuild the course cache after update action
686 rebuild_course_cache($this->course
->id
, true);
687 $this->course
->modinfo
= null; // Otherwise we will just get the old version back again.
689 $sectionid = course_add_cm_to_section($this->course
, $this->cm
->id
, $this->section
);
691 set_coursemodule_visible($this->cm
->id
, $visible);
693 $DB->set_field('course_modules', 'visibleold', 1, array('id' => $this->cm
->id
));
696 // retrieve the final info about this module.
697 $info = get_fast_modinfo($this->course
);
698 if (!isset($info->cms
[$this->cm
->id
])) {
699 // The course module has not been properly created in the course - undo everything.
700 course_delete_module($this->cm
->id
);
701 throw new moodle_exception('errorcreatingactivity', 'moodle', '', $this->module
->name
);
703 $mod = $info->get_cm($this->cm
->id
);
704 $mod->groupmodelink
= $this->cm
->groupmodelink
;
705 $mod->groupmode
= $this->cm
->groupmode
;
707 // Trigger mod_created event with information about this module.
708 $eventdata = new stdClass();
709 $eventdata->modulename
= $mod->modname
;
710 $eventdata->name
= $mod->name
;
711 $eventdata->cmid
= $mod->id
;
712 $eventdata->courseid
= $this->course
->id
;
713 $eventdata->userid
= $USER->id
;
714 events_trigger('mod_created', $eventdata);
716 add_to_log($this->course
->id
, "course", "add mod",
717 "../mod/{$mod->modname}/view.php?id=$mod->id",
718 "{$mod->modname} $instanceid");
719 add_to_log($this->course
->id
, $mod->modname
, "add",
720 "view.php?id=$mod->id",
721 "$instanceid", $mod->id
);
723 $this->send_response($mod);
727 * Send the details of the newly created activity back to the client browser
729 * @param cm_info $mod details of the mod just created
731 protected function send_response($mod) {
732 global $OUTPUT, $PAGE;
733 $courserenderer = $PAGE->get_renderer('core', 'course');
735 $resp = new stdClass();
736 $resp->error
= self
::ERROR_OK
;
737 $resp->icon
= $mod->get_icon_url()->out();
738 $resp->name
= $mod->name
;
739 if ($mod->has_view()) {
740 $resp->link
= $mod->get_url()->out();
744 $resp->content
= $mod->get_content();
745 $resp->elementid
= 'module-'.$mod->id
;
746 $actions = course_get_cm_edit_actions($mod, 0, $mod->sectionnum
);
747 $resp->commands
= ' '. $courserenderer->course_section_cm_edit_actions($actions);
748 $resp->onclick
= $mod->get_on_click();
749 $resp->visible
= $mod->visible
;
751 // if using groupings, then display grouping name
752 if (!empty($mod->groupingid
) && has_capability('moodle/course:managegroups', $this->context
)) {
753 $groupings = groups_get_all_groupings($this->course
->id
);
754 $resp->groupingname
= format_string($groupings[$mod->groupingid
]->name
);
757 echo $OUTPUT->header();
758 echo json_encode($resp);