Merge branch 'MDL-53226-master' of git://github.com/andrewnicols/moodle
[moodle.git] / course / dnduploadlib.php
blob1e1210570d2e166ae360755984adfc26cb78c378
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
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.
8 //
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/>.
17 /**
18 * Library to handle drag and drop course uploads
20 * @package core
21 * @subpackage lib
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');
32 /**
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
37 * @return void
39 function dndupload_add_to_course($course, $modnames) {
40 global $CFG, $PAGE;
42 $showstatus = optional_param('notifyeditingon', false, PARAM_BOOL);
44 // Get all handlers.
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.
52 $jsmodule = array(
53 'name' => 'coursedndupload',
54 'fullpath' => '/course/dndupload.js',
55 'strings' => array(
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('namedfiletoolarge', 'moodle'),
65 array('actionchoice', 'moodle'),
66 array('servererror', 'moodle'),
67 array('filereaderror', 'moodle'),
68 array('upload', 'moodle'),
69 array('cancel', 'moodle')
71 'requires' => array('node', 'event', 'json', 'anim')
73 $vars = array(
74 array('courseid' => $course->id,
75 'maxbytes' => get_max_upload_file_size($CFG->maxbytes, $course->maxbytes),
76 'handlers' => $handler->get_js_data(),
77 'showstatus' => $showstatus)
80 $PAGE->requires->js_init_call('M.course_dndupload.init', $vars, true, $jsmodule);
84 /**
85 * Stores all the information about the available dndupload handlers
87 * @package core
88 * @copyright 2012 Davo Smith
89 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
91 class dndupload_handler {
93 /**
94 * @var array A list of all registered mime types that can be dropped onto a course
95 * along with the modules that will handle them.
97 protected $types = array();
99 /**
100 * @var array A list of the different file types (extensions) that different modules
101 * will handle.
103 protected $filehandlers = array();
106 * @var context_course|null
108 protected $context = null;
111 * Gather a list of dndupload handlers from the different mods
113 * @param object $course The course this is being added to (to check course_allowed_module() )
115 public function __construct($course, $modnames = null) {
116 global $CFG, $PAGE;
118 // Add some default types to handle.
119 // Note: 'Files' type is hard-coded into the Javascript as this needs to be ...
120 // ... treated a little differently.
121 $this->register_type('url', array('url', 'text/uri-list', 'text/x-moz-url'), get_string('addlinkhere', 'moodle'),
122 get_string('nameforlink', 'moodle'), get_string('whatforlink', 'moodle'), 10);
123 $this->register_type('text/html', array('text/html'), get_string('addpagehere', 'moodle'),
124 get_string('nameforpage', 'moodle'), get_string('whatforpage', 'moodle'), 20);
125 $this->register_type('text', array('text', 'text/plain'), get_string('addpagehere', 'moodle'),
126 get_string('nameforpage', 'moodle'), get_string('whatforpage', 'moodle'), 30);
128 $this->context = context_course::instance($course->id);
130 // Loop through all modules to find handlers.
131 $mods = get_plugin_list_with_function('mod', 'dndupload_register');
132 foreach ($mods as $component => $funcname) {
133 list($modtype, $modname) = core_component::normalize_component($component);
134 if ($modnames && !array_key_exists($modname, $modnames)) {
135 continue; // Module is deactivated (hidden) at the site level.
137 if (!course_allowed_module($course, $modname)) {
138 continue; // User does not have permission to add this module to the course.
140 $resp = $funcname();
141 if (!$resp) {
142 continue;
144 if (isset($resp['files'])) {
145 foreach ($resp['files'] as $file) {
146 $this->register_file_handler($file['extension'], $modname, $file['message']);
149 if (isset($resp['addtypes'])) {
150 foreach ($resp['addtypes'] as $type) {
151 if (isset($type['priority'])) {
152 $priority = $type['priority'];
153 } else {
154 $priority = 100;
156 if (!isset($type['handlermessage'])) {
157 $type['handlermessage'] = '';
159 $this->register_type($type['identifier'], $type['datatransfertypes'],
160 $type['addmessage'], $type['namemessage'], $type['handlermessage'], $priority);
163 if (isset($resp['types'])) {
164 foreach ($resp['types'] as $type) {
165 $noname = !empty($type['noname']);
166 $this->register_type_handler($type['identifier'], $modname, $type['message'], $noname);
169 $PAGE->requires->string_for_js('pluginname', $modname);
174 * Used to add a new mime type that can be drag and dropped onto a
175 * course displayed in a browser window
177 * @param string $identifier The name that this type will be known as
178 * @param array $datatransfertypes An array of the different types in the browser
179 * 'dataTransfer.types' object that will map to this type
180 * @param string $addmessage The message to display in the browser when this type is being
181 * dragged onto the page
182 * @param string $namemessage The message to pop up when asking for the name to give the
183 * course module instance when it is created
184 * @param string $handlermessage The message to pop up when asking which module should handle this type
185 * @param int $priority Controls the order in which types are checked by the browser (mainly
186 * needed to check for 'text' last as that is usually given as fallback)
188 protected function register_type($identifier, $datatransfertypes, $addmessage, $namemessage, $handlermessage, $priority=100) {
189 if ($this->is_known_type($identifier)) {
190 throw new coding_exception("Type $identifier is already registered");
193 $add = new stdClass;
194 $add->identifier = $identifier;
195 $add->datatransfertypes = $datatransfertypes;
196 $add->addmessage = $addmessage;
197 $add->namemessage = $namemessage;
198 $add->handlermessage = $handlermessage;
199 $add->priority = $priority;
200 $add->handlers = array();
202 $this->types[$identifier] = $add;
206 * Used to declare that a particular module will handle a particular type
207 * of dropped data
209 * @param string $type The name of the type (as declared in register_type)
210 * @param string $module The name of the module to handle this type
211 * @param string $message The message to show the user if more than one handler is registered
212 * for a type and the user needs to make a choice between them
213 * @param bool $noname If true, the 'name' dialog should be disabled in the pop-up.
214 * @throws coding_exception
216 protected function register_type_handler($type, $module, $message, $noname) {
217 if (!$this->is_known_type($type)) {
218 throw new coding_exception("Trying to add handler for unknown type $type");
221 $add = new stdClass;
222 $add->type = $type;
223 $add->module = $module;
224 $add->message = $message;
225 $add->noname = $noname ? 1 : 0;
227 $this->types[$type]->handlers[] = $add;
231 * Used to declare that a particular module will handle a particular type
232 * of dropped file
234 * @param string $extension The file extension to handle ('*' for all types)
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
239 protected function register_file_handler($extension, $module, $message) {
240 $extension = strtolower($extension);
242 $add = new stdClass;
243 $add->extension = $extension;
244 $add->module = $module;
245 $add->message = $message;
247 $this->filehandlers[] = $add;
251 * Check to see if the type has been registered
253 * @param string $type The identifier of the type you are interested in
254 * @return bool True if the type is registered
256 public function is_known_type($type) {
257 return array_key_exists($type, $this->types);
261 * Check to see if the module in question has registered to handle the
262 * type given
264 * @param string $module The name of the module
265 * @param string $type The identifier of the type
266 * @return bool True if the module has registered to handle that type
268 public function has_type_handler($module, $type) {
269 if (!$this->is_known_type($type)) {
270 throw new coding_exception("Checking for handler for unknown type $type");
272 foreach ($this->types[$type]->handlers as $handler) {
273 if ($handler->module == $module) {
274 return true;
277 return false;
281 * Check to see if the module in question has registered to handle files
282 * with the given extension (or to handle all file types)
284 * @param string $module The name of the module
285 * @param string $extension The extension of the uploaded file
286 * @return bool True if the module has registered to handle files with
287 * that extension (or to handle all file types)
289 public function has_file_handler($module, $extension) {
290 foreach ($this->filehandlers as $handler) {
291 if ($handler->module == $module) {
292 if ($handler->extension == '*' || $handler->extension == $extension) {
293 return true;
297 return false;
301 * Gets a list of the file types that are handled by a particular module
303 * @param string $module The name of the module to check
304 * @return array of file extensions or string '*'
306 public function get_handled_file_types($module) {
307 $types = array();
308 foreach ($this->filehandlers as $handler) {
309 if ($handler->module == $module) {
310 if ($handler->extension == '*') {
311 return '*';
312 } else {
313 // Prepending '.' as otherwise mimeinfo fails.
314 $types[] = '.'.$handler->extension;
318 return $types;
322 * Returns an object to pass onto the javascript code with data about all the
323 * registered file / type handlers
325 * @return object Data to pass on to Javascript code
327 public function get_js_data() {
328 global $CFG;
330 $ret = new stdClass;
332 // Sort the types by priority.
333 uasort($this->types, array($this, 'type_compare'));
335 $ret->types = array();
336 if (!empty($CFG->dndallowtextandlinks)) {
337 foreach ($this->types as $type) {
338 if (empty($type->handlers)) {
339 continue; // Skip any types without registered handlers.
341 $ret->types[] = $type;
345 $ret->filehandlers = $this->filehandlers;
346 $uploadrepo = repository::get_instances(array('type' => 'upload', 'currentcontext' => $this->context));
347 if (empty($uploadrepo)) {
348 $ret->filehandlers = array(); // No upload repo => no file handlers.
351 return $ret;
355 * Comparison function used when sorting types by priority
356 * @param object $type1 first type to compare
357 * @param object $type2 second type to compare
358 * @return integer -1 for $type1 < $type2; 1 for $type1 > $type2; 0 for equal
360 protected function type_compare($type1, $type2) {
361 if ($type1->priority < $type2->priority) {
362 return -1;
364 if ($type1->priority > $type2->priority) {
365 return 1;
367 return 0;
373 * Processes the upload, creating the course module and returning the result
375 * @package core
376 * @copyright 2012 Davo Smith
377 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
379 class dndupload_ajax_processor {
381 /** Returned when no error has occurred */
382 const ERROR_OK = 0;
384 /** @var object The course that we are uploading to */
385 protected $course = null;
387 /** @var context_course The course context for capability checking */
388 protected $context = null;
390 /** @var int The section number we are uploading to */
391 protected $section = null;
393 /** @var string The type of upload (e.g. 'Files', 'text/plain') */
394 protected $type = null;
396 /** @var object The details of the module type that will be created */
397 protected $module= null;
399 /** @var object The course module that has been created */
400 protected $cm = null;
402 /** @var dndupload_handler used to check the allowed file types */
403 protected $dnduploadhandler = null;
405 /** @var string The name to give the new activity instance */
406 protected $displayname = null;
409 * Set up some basic information needed to handle the upload
411 * @param int $courseid The ID of the course we are uploading to
412 * @param int $section The section number we are uploading to
413 * @param string $type The type of upload (as reported by the browser)
414 * @param string $modulename The name of the module requested to handle this upload
416 public function __construct($courseid, $section, $type, $modulename) {
417 global $DB;
419 if (!defined('AJAX_SCRIPT')) {
420 throw new coding_exception('dndupload_ajax_processor should only be used within AJAX requests');
423 $this->course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
425 require_login($this->course, false);
426 $this->context = context_course::instance($this->course->id);
428 if (!is_number($section) || $section < 0) {
429 throw new coding_exception("Invalid section number $section");
431 $this->section = $section;
432 $this->type = $type;
434 if (!$this->module = $DB->get_record('modules', array('name' => $modulename))) {
435 throw new coding_exception("Module $modulename does not exist");
438 $this->dnduploadhandler = new dndupload_handler($this->course);
442 * Check if this upload is a 'file' upload
444 * @return bool true if it is a 'file' upload, false otherwise
446 protected function is_file_upload() {
447 return ($this->type == 'Files');
451 * Process the upload - creating the module in the course and returning the result to the browser
453 * @param string $displayname optional the name (from the browser) to give the course module instance
454 * @param string $content optional the content of the upload (for non-file uploads)
456 public function process($displayname = null, $content = null) {
457 require_capability('moodle/course:manageactivities', $this->context);
459 if ($this->is_file_upload()) {
460 require_capability('moodle/course:managefiles', $this->context);
461 if ($content != null) {
462 throw new moodle_exception('fileuploadwithcontent', 'moodle');
464 } else {
465 if (empty($content)) {
466 throw new moodle_exception('dnduploadwithoutcontent', 'moodle');
470 require_sesskey();
472 $this->displayname = $displayname;
474 if ($this->is_file_upload()) {
475 $this->handle_file_upload();
476 } else {
477 $this->handle_other_upload($content);
482 * Handle uploads containing files - create the course module, ask the upload repository
483 * to process the file, ask the mod to set itself up, then return the result to the browser
485 protected function handle_file_upload() {
486 global $CFG;
488 // Add the file to a draft file area.
489 $draftitemid = file_get_unused_draft_itemid();
490 $maxbytes = get_max_upload_file_size($CFG->maxbytes, $this->course->maxbytes);
491 $types = $this->dnduploadhandler->get_handled_file_types($this->module->name);
492 $repo = repository::get_instances(array('type' => 'upload', 'currentcontext' => $this->context));
493 if (empty($repo)) {
494 throw new moodle_exception('errornouploadrepo', 'moodle');
496 $repo = reset($repo); // Get the first (and only) upload repo.
497 $details = $repo->process_upload(null, $maxbytes, $types, '/', $draftitemid);
498 if (empty($this->displayname)) {
499 $this->displayname = $this->display_name_from_file($details['file']);
502 // Create a course module to hold the new instance.
503 $this->create_course_module();
505 // Ask the module to set itself up.
506 $moduledata = $this->prepare_module_data($draftitemid);
507 $instanceid = plugin_callback('mod', $this->module->name, 'dndupload', 'handle', array($moduledata), 'invalidfunction');
508 if ($instanceid === 'invalidfunction') {
509 throw new coding_exception("{$this->module->name} does not support drag and drop upload (missing {$this->module->name}_dndupload_handle function");
512 // Finish setting up the course module.
513 $this->finish_setup_course_module($instanceid);
517 * Handle uploads not containing file - create the course module, ask the mod to
518 * set itself up, then return the result to the browser
520 * @param string $content the content uploaded to the browser
522 protected function handle_other_upload($content) {
523 // Check this plugin is registered to handle this type of upload
524 if (!$this->dnduploadhandler->has_type_handler($this->module->name, $this->type)) {
525 $info = (object)array('modname' => $this->module->name, 'type' => $this->type);
526 throw new moodle_exception('moddoesnotsupporttype', 'moodle', $info);
529 // Create a course module to hold the new instance.
530 $this->create_course_module();
532 // Ask the module to set itself up.
533 $moduledata = $this->prepare_module_data(null, $content);
534 $instanceid = plugin_callback('mod', $this->module->name, 'dndupload', 'handle', array($moduledata), 'invalidfunction');
535 if ($instanceid === 'invalidfunction') {
536 throw new coding_exception("{$this->module->name} does not support drag and drop upload (missing {$this->module->name}_dndupload_handle function");
539 // Finish setting up the course module.
540 $this->finish_setup_course_module($instanceid);
544 * Generate the name of the mod instance from the name of the file
545 * (remove the extension and convert underscore => space
547 * @param string $filename the filename of the uploaded file
548 * @return string the display name to use
550 protected function display_name_from_file($filename) {
551 $pos = core_text::strrpos($filename, '.');
552 if ($pos) { // Want to skip if $pos === 0 OR $pos === false.
553 $filename = core_text::substr($filename, 0, $pos);
555 return str_replace('_', ' ', $filename);
559 * Create the coursemodule to hold the file/content that has been uploaded
561 protected function create_course_module() {
562 global $CFG;
563 require_once($CFG->dirroot.'/course/modlib.php');
564 list($module, $context, $cw, $cm, $data) = prepare_new_moduleinfo_data($this->course, $this->module->name, $this->section);
566 $data->coursemodule = $data->id = add_course_module($data);
567 $this->cm = $data;
571 * Gather together all the details to pass on to the mod, so that it can initialise it's
572 * own database tables
574 * @param int $draftitemid optional the id of the draft area containing the file (for file uploads)
575 * @param string $content optional the content dropped onto the course (for non-file uploads)
576 * @return object data to pass on to the mod, containing:
577 * string $type the 'type' as registered with dndupload_handler (or 'Files')
578 * object $course the course the upload was for
579 * int $draftitemid optional the id of the draft area containing the files
580 * int $coursemodule id of the course module that has already been created
581 * string $displayname the name to use for this activity (can be overriden by the mod)
583 protected function prepare_module_data($draftitemid = null, $content = null) {
584 $data = new stdClass();
585 $data->type = $this->type;
586 $data->course = $this->course;
587 if ($draftitemid) {
588 $data->draftitemid = $draftitemid;
589 } else if ($content) {
590 $data->content = $content;
592 $data->coursemodule = $this->cm->id;
593 $data->displayname = $this->displayname;
594 return $data;
598 * Called after the mod has set itself up, to finish off any course module settings
599 * (set instance id, add to correct section, set visibility, etc.) and send the response
601 * @param int $instanceid id returned by the mod when it was created
603 protected function finish_setup_course_module($instanceid) {
604 global $DB, $USER;
606 if (!$instanceid) {
607 // Something has gone wrong - undo everything we can.
608 course_delete_module($this->cm->id);
609 throw new moodle_exception('errorcreatingactivity', 'moodle', '', $this->module->name);
612 // Note the section visibility
613 $visible = get_fast_modinfo($this->course)->get_section_info($this->section)->visible;
615 $DB->set_field('course_modules', 'instance', $instanceid, array('id' => $this->cm->id));
616 // Rebuild the course cache after update action
617 rebuild_course_cache($this->course->id, true);
619 $sectionid = course_add_cm_to_section($this->course, $this->cm->id, $this->section);
621 set_coursemodule_visible($this->cm->id, $visible);
622 if (!$visible) {
623 $DB->set_field('course_modules', 'visibleold', 1, array('id' => $this->cm->id));
626 // retrieve the final info about this module.
627 $info = get_fast_modinfo($this->course);
628 if (!isset($info->cms[$this->cm->id])) {
629 // The course module has not been properly created in the course - undo everything.
630 course_delete_module($this->cm->id);
631 throw new moodle_exception('errorcreatingactivity', 'moodle', '', $this->module->name);
633 $mod = $info->get_cm($this->cm->id);
635 // Trigger course module created event.
636 $event = \core\event\course_module_created::create_from_cm($mod);
637 $event->trigger();
639 $this->send_response($mod);
643 * Send the details of the newly created activity back to the client browser
645 * @param cm_info $mod details of the mod just created
647 protected function send_response($mod) {
648 global $OUTPUT, $PAGE;
650 $resp = new stdClass();
651 $resp->error = self::ERROR_OK;
652 $resp->elementid = 'module-' . $mod->id;
654 $courserenderer = $PAGE->get_renderer('core', 'course');
655 $completioninfo = new completion_info($this->course);
656 $info = get_fast_modinfo($this->course);
657 $sr = null;
658 $modulehtml = $courserenderer->course_section_cm($this->course, $completioninfo,
659 $mod, null, array());
660 $resp->fullcontent = $courserenderer->course_section_cm_list_item($this->course, $completioninfo, $mod, $sr);
662 echo $OUTPUT->header();
663 echo json_encode($resp);
664 die();