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) = core_component
::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 * Used to add a new mime type that can be drag and dropped onto a
167 * course displayed in a browser window
169 * @param string $identifier The name that this type will be known as
170 * @param array $datatransfertypes An array of the different types in the browser
171 * 'dataTransfer.types' object that will map to this type
172 * @param string $addmessage The message to display in the browser when this type is being
173 * dragged onto the page
174 * @param string $namemessage The message to pop up when asking for the name to give the
175 * course module instance when it is created
176 * @param string $handlermessage The message to pop up when asking which module should handle this type
177 * @param int $priority Controls the order in which types are checked by the browser (mainly
178 * needed to check for 'text' last as that is usually given as fallback)
180 protected function register_type($identifier, $datatransfertypes, $addmessage, $namemessage, $handlermessage, $priority=100) {
181 if ($this->is_known_type($identifier)) {
182 throw new coding_exception("Type $identifier is already registered");
186 $add->identifier
= $identifier;
187 $add->datatransfertypes
= $datatransfertypes;
188 $add->addmessage
= $addmessage;
189 $add->namemessage
= $namemessage;
190 $add->handlermessage
= $handlermessage;
191 $add->priority
= $priority;
192 $add->handlers
= array();
194 $this->types
[$identifier] = $add;
198 * Used to declare that a particular module will handle a particular type
201 * @param string $type The name of the type (as declared in register_type)
202 * @param string $module The name of the module to handle this type
203 * @param string $message The message to show the user if more than one handler is registered
204 * for a type and the user needs to make a choice between them
205 * @param bool $noname If true, the 'name' dialog should be disabled in the pop-up.
206 * @throws coding_exception
208 protected function register_type_handler($type, $module, $message, $noname) {
209 if (!$this->is_known_type($type)) {
210 throw new coding_exception("Trying to add handler for unknown type $type");
215 $add->module
= $module;
216 $add->message
= $message;
217 $add->noname
= $noname ?
1 : 0;
219 $this->types
[$type]->handlers
[] = $add;
223 * Used to declare that a particular module will handle a particular type
226 * @param string $extension The file extension to handle ('*' for all types)
227 * @param string $module The name of the module to handle this type
228 * @param string $message The message to show the user if more than one handler is registered
229 * for a type and the user needs to make a choice between them
231 protected function register_file_handler($extension, $module, $message) {
232 $extension = strtolower($extension);
235 $add->extension
= $extension;
236 $add->module
= $module;
237 $add->message
= $message;
239 $this->filehandlers
[] = $add;
243 * Check to see if the type has been registered
245 * @param string $type The identifier of the type you are interested in
246 * @return bool True if the type is registered
248 public function is_known_type($type) {
249 return array_key_exists($type, $this->types
);
253 * Check to see if the module in question has registered to handle the
256 * @param string $module The name of the module
257 * @param string $type The identifier of the type
258 * @return bool True if the module has registered to handle that type
260 public function has_type_handler($module, $type) {
261 if (!$this->is_known_type($type)) {
262 throw new coding_exception("Checking for handler for unknown type $type");
264 foreach ($this->types
[$type]->handlers
as $handler) {
265 if ($handler->module
== $module) {
273 * Check to see if the module in question has registered to handle files
274 * with the given extension (or to handle all file types)
276 * @param string $module The name of the module
277 * @param string $extension The extension of the uploaded file
278 * @return bool True if the module has registered to handle files with
279 * that extension (or to handle all file types)
281 public function has_file_handler($module, $extension) {
282 foreach ($this->filehandlers
as $handler) {
283 if ($handler->module
== $module) {
284 if ($handler->extension
== '*' ||
$handler->extension
== $extension) {
293 * Gets a list of the file types that are handled by a particular module
295 * @param string $module The name of the module to check
296 * @return array of file extensions or string '*'
298 public function get_handled_file_types($module) {
300 foreach ($this->filehandlers
as $handler) {
301 if ($handler->module
== $module) {
302 if ($handler->extension
== '*') {
305 // Prepending '.' as otherwise mimeinfo fails.
306 $types[] = '.'.$handler->extension
;
314 * Returns an object to pass onto the javascript code with data about all the
315 * registered file / type handlers
317 * @return object Data to pass on to Javascript code
319 public function get_js_data() {
324 // Sort the types by priority.
325 uasort($this->types
, array($this, 'type_compare'));
327 $ret->types
= array();
328 if (!empty($CFG->dndallowtextandlinks
)) {
329 foreach ($this->types
as $type) {
330 if (empty($type->handlers
)) {
331 continue; // Skip any types without registered handlers.
333 $ret->types
[] = $type;
337 $ret->filehandlers
= $this->filehandlers
;
338 $uploadrepo = repository
::get_instances(array('type' => 'upload'));
339 if (empty($uploadrepo)) {
340 $ret->filehandlers
= array(); // No upload repo => no file handlers.
347 * Comparison function used when sorting types by priority
348 * @param object $type1 first type to compare
349 * @param object $type2 second type to compare
350 * @return integer -1 for $type1 < $type2; 1 for $type1 > $type2; 0 for equal
352 protected function type_compare($type1, $type2) {
353 if ($type1->priority
< $type2->priority
) {
356 if ($type1->priority
> $type2->priority
) {
365 * Processes the upload, creating the course module and returning the result
368 * @copyright 2012 Davo Smith
369 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
371 class dndupload_ajax_processor
{
373 /** Returned when no error has occurred */
376 /** @var object The course that we are uploading to */
377 protected $course = null;
379 /** @var context_course The course context for capability checking */
380 protected $context = null;
382 /** @var int The section number we are uploading to */
383 protected $section = null;
385 /** @var string The type of upload (e.g. 'Files', 'text/plain') */
386 protected $type = null;
388 /** @var object The details of the module type that will be created */
389 protected $module= null;
391 /** @var object The course module that has been created */
392 protected $cm = null;
394 /** @var dndupload_handler used to check the allowed file types */
395 protected $dnduploadhandler = null;
397 /** @var string The name to give the new activity instance */
398 protected $displayname = null;
401 * Set up some basic information needed to handle the upload
403 * @param int $courseid The ID of the course we are uploading to
404 * @param int $section The section number we are uploading to
405 * @param string $type The type of upload (as reported by the browser)
406 * @param string $modulename The name of the module requested to handle this upload
408 public function __construct($courseid, $section, $type, $modulename) {
411 if (!defined('AJAX_SCRIPT')) {
412 throw new coding_exception('dndupload_ajax_processor should only be used within AJAX requests');
415 $this->course
= $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST
);
417 require_login($this->course
, false);
418 $this->context
= context_course
::instance($this->course
->id
);
420 if (!is_number($section) ||
$section < 0) {
421 throw new coding_exception("Invalid section number $section");
423 $this->section
= $section;
426 if (!$this->module
= $DB->get_record('modules', array('name' => $modulename))) {
427 throw new coding_exception("Module $modulename does not exist");
430 $this->dnduploadhandler
= new dndupload_handler($this->course
);
434 * Check if this upload is a 'file' upload
436 * @return bool true if it is a 'file' upload, false otherwise
438 protected function is_file_upload() {
439 return ($this->type
== 'Files');
443 * Process the upload - creating the module in the course and returning the result to the browser
445 * @param string $displayname optional the name (from the browser) to give the course module instance
446 * @param string $content optional the content of the upload (for non-file uploads)
448 public function process($displayname = null, $content = null) {
449 require_capability('moodle/course:manageactivities', $this->context
);
451 if ($this->is_file_upload()) {
452 require_capability('moodle/course:managefiles', $this->context
);
453 if ($content != null) {
454 throw new moodle_exception('fileuploadwithcontent', 'moodle');
457 if (empty($content)) {
458 throw new moodle_exception('dnduploadwithoutcontent', 'moodle');
464 $this->displayname
= $displayname;
466 if ($this->is_file_upload()) {
467 $this->handle_file_upload();
469 $this->handle_other_upload($content);
474 * Handle uploads containing files - create the course module, ask the upload repository
475 * to process the file, ask the mod to set itself up, then return the result to the browser
477 protected function handle_file_upload() {
480 // Add the file to a draft file area.
481 $draftitemid = file_get_unused_draft_itemid();
482 $maxbytes = get_max_upload_file_size($CFG->maxbytes
, $this->course
->maxbytes
);
483 $types = $this->dnduploadhandler
->get_handled_file_types($this->module
->name
);
484 $repo = repository
::get_instances(array('type' => 'upload'));
486 throw new moodle_exception('errornouploadrepo', 'moodle');
488 $repo = reset($repo); // Get the first (and only) upload repo.
489 $details = $repo->process_upload(null, $maxbytes, $types, '/', $draftitemid);
490 if (empty($this->displayname
)) {
491 $this->displayname
= $this->display_name_from_file($details['file']);
494 // Create a course module to hold the new instance.
495 $this->create_course_module();
497 // Ask the module to set itself up.
498 $moduledata = $this->prepare_module_data($draftitemid);
499 $instanceid = plugin_callback('mod', $this->module
->name
, 'dndupload', 'handle', array($moduledata), 'invalidfunction');
500 if ($instanceid === 'invalidfunction') {
501 throw new coding_exception("{$this->module->name} does not support drag and drop upload (missing {$this->module->name}_dndupload_handle function");
504 // Finish setting up the course module.
505 $this->finish_setup_course_module($instanceid);
509 * Handle uploads not containing file - create the course module, ask the mod to
510 * set itself up, then return the result to the browser
512 * @param string $content the content uploaded to the browser
514 protected function handle_other_upload($content) {
515 // Check this plugin is registered to handle this type of upload
516 if (!$this->dnduploadhandler
->has_type_handler($this->module
->name
, $this->type
)) {
517 $info = (object)array('modname' => $this->module
->name
, 'type' => $this->type
);
518 throw new moodle_exception('moddoesnotsupporttype', 'moodle', $info);
521 // Create a course module to hold the new instance.
522 $this->create_course_module();
524 // Ask the module to set itself up.
525 $moduledata = $this->prepare_module_data(null, $content);
526 $instanceid = plugin_callback('mod', $this->module
->name
, 'dndupload', 'handle', array($moduledata), 'invalidfunction');
527 if ($instanceid === 'invalidfunction') {
528 throw new coding_exception("{$this->module->name} does not support drag and drop upload (missing {$this->module->name}_dndupload_handle function");
531 // Finish setting up the course module.
532 $this->finish_setup_course_module($instanceid);
536 * Generate the name of the mod instance from the name of the file
537 * (remove the extension and convert underscore => space
539 * @param string $filename the filename of the uploaded file
540 * @return string the display name to use
542 protected function display_name_from_file($filename) {
543 $pos = core_text
::strrpos($filename, '.');
544 if ($pos) { // Want to skip if $pos === 0 OR $pos === false.
545 $filename = core_text
::substr($filename, 0, $pos);
547 return str_replace('_', ' ', $filename);
551 * Create the coursemodule to hold the file/content that has been uploaded
553 protected function create_course_module() {
556 if (!course_allowed_module($this->course
, $this->module
->name
)) {
557 throw new coding_exception("The module {$this->module->name} is not allowed to be added to this course");
560 $this->cm
= new stdClass();
561 $this->cm
->course
= $this->course
->id
;
562 $this->cm
->section
= $this->section
;
563 $this->cm
->module
= $this->module
->id
;
564 $this->cm
->modulename
= $this->module
->name
;
565 $this->cm
->instance
= 0; // This will be filled in after we create the instance.
566 $this->cm
->visible
= 1;
567 $this->cm
->groupmode
= $this->course
->groupmode
;
568 $this->cm
->groupingid
= $this->course
->defaultgroupingid
;
570 // Set the correct default for completion tracking.
571 $this->cm
->completion
= COMPLETION_TRACKING_NONE
;
572 $completion = new completion_info($this->course
);
573 if ($completion->is_enabled() && $CFG->completiondefault
) {
574 if (plugin_supports('mod', $this->cm
->modulename
, FEATURE_MODEDIT_DEFAULT_COMPLETION
, true)) {
575 $this->cm
->completion
= COMPLETION_TRACKING_MANUAL
;
579 if (!$this->cm
->id
= add_course_module($this->cm
)) {
580 throw new coding_exception("Unable to create the course module");
582 $this->cm
->coursemodule
= $this->cm
->id
;
586 * Gather together all the details to pass on to the mod, so that it can initialise it's
587 * own database tables
589 * @param int $draftitemid optional the id of the draft area containing the file (for file uploads)
590 * @param string $content optional the content dropped onto the course (for non-file uploads)
591 * @return object data to pass on to the mod, containing:
592 * string $type the 'type' as registered with dndupload_handler (or 'Files')
593 * object $course the course the upload was for
594 * int $draftitemid optional the id of the draft area containing the files
595 * int $coursemodule id of the course module that has already been created
596 * string $displayname the name to use for this activity (can be overriden by the mod)
598 protected function prepare_module_data($draftitemid = null, $content = null) {
599 $data = new stdClass();
600 $data->type
= $this->type
;
601 $data->course
= $this->course
;
603 $data->draftitemid
= $draftitemid;
604 } else if ($content) {
605 $data->content
= $content;
607 $data->coursemodule
= $this->cm
->id
;
608 $data->displayname
= $this->displayname
;
613 * Called after the mod has set itself up, to finish off any course module settings
614 * (set instance id, add to correct section, set visibility, etc.) and send the response
616 * @param int $instanceid id returned by the mod when it was created
618 protected function finish_setup_course_module($instanceid) {
622 // Something has gone wrong - undo everything we can.
623 course_delete_module($this->cm
->id
);
624 throw new moodle_exception('errorcreatingactivity', 'moodle', '', $this->module
->name
);
627 // Note the section visibility
628 $visible = get_fast_modinfo($this->course
)->get_section_info($this->section
)->visible
;
630 $DB->set_field('course_modules', 'instance', $instanceid, array('id' => $this->cm
->id
));
631 // Rebuild the course cache after update action
632 rebuild_course_cache($this->course
->id
, true);
634 $sectionid = course_add_cm_to_section($this->course
, $this->cm
->id
, $this->section
);
636 set_coursemodule_visible($this->cm
->id
, $visible);
638 $DB->set_field('course_modules', 'visibleold', 1, array('id' => $this->cm
->id
));
641 // retrieve the final info about this module.
642 $info = get_fast_modinfo($this->course
);
643 if (!isset($info->cms
[$this->cm
->id
])) {
644 // The course module has not been properly created in the course - undo everything.
645 course_delete_module($this->cm
->id
);
646 throw new moodle_exception('errorcreatingactivity', 'moodle', '', $this->module
->name
);
648 $mod = $info->get_cm($this->cm
->id
);
650 // Trigger course module created event.
651 $event = \core\event\course_module_created
::create(array(
652 'courseid' => $this->course
->id
,
653 'context' => context_module
::instance($mod->id
),
654 'objectid' => $mod->id
,
656 'modulename' => $mod->modname
,
657 'name' => $mod->name
,
658 'instanceid' => $instanceid
663 $this->send_response($mod);
667 * Send the details of the newly created activity back to the client browser
669 * @param cm_info $mod details of the mod just created
671 protected function send_response($mod) {
672 global $OUTPUT, $PAGE;
674 $resp = new stdClass();
675 $resp->error
= self
::ERROR_OK
;
676 $resp->elementid
= 'module-' . $mod->id
;
678 $courserenderer = $PAGE->get_renderer('core', 'course');
679 $completioninfo = new completion_info($this->course
);
680 $info = get_fast_modinfo($this->course
);
682 $modulehtml = $courserenderer->course_section_cm($this->course
, $completioninfo,
683 $mod, null, array());
684 $resp->fullcontent
= $courserenderer->course_section_cm_list_item($this->course
, $completioninfo, $mod, $sr);
686 echo $OUTPUT->header();
687 echo json_encode($resp);