MDL-22504 Course drag and drop upload - now correctly ignores disabled modules and...
[moodle.git] / lib / dnduploadlib.php
CommitLineData
32528f94
DS
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.
13//
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/>.
16
17/**
18 * Library to handle drag and drop course uploads
19 *
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
24 */
25
26defined('MOODLE_INTERNAL') || die();
27
28require_once($CFG->dirroot.'/repository/lib.php');
29require_once($CFG->dirroot.'/repository/upload/lib.php');
30require_once($CFG->dirroot.'/course/lib.php');
31
32/**
33 * Add the Javascript to enable drag and drop upload to a course page
34 *
35 * @param object $course The currently displayed course
5103b5e6
DS
36 * @param array $modnames The list of enabled (visible) modules on this site
37 * @return void
32528f94 38 */
5103b5e6 39function dndupload_add_to_course($course, $modnames) {
32528f94
DS
40 global $CFG, $PAGE;
41
42 // Get all handlers.
5103b5e6
DS
43 $handler = new dndupload_handler($course, $modnames);
44 $jsdata = $handler->get_js_data();
45 if (empty($jsdata->types) && empty($jsdata->filehandlers)) {
46 return; // No valid handlers - don't enable drag and drop.
47 }
32528f94
DS
48
49 // Add the javascript to the page.
50 $jsmodule = array(
51 'name' => 'dndupload',
52 'fullpath' => new moodle_url('/lib/ajax/dndupload.js'),
53 'strings' => array(
54 array('addfilehere', 'core_dndupload'),
55 array('dndworking', 'core_dndupload'),
56 array('filetoolarge', 'core_dndupload'),
57 array('nofilereader', 'core_dndupload'),
58 array('noajax', 'core_dndupload'),
59 array('actionchoice', 'core_dndupload'),
60 array('servererror', 'core_dndupload'),
61 array('upload', 'core'),
62 array('cancel', 'core')
63 ),
64 'requires' => array('node', 'event', 'panel', 'json')
65 );
66 $vars = array(
67 array('courseid' => $course->id,
68 'maxbytes' => get_max_upload_file_size($CFG->maxbytes, $course->maxbytes),
69 'handlers' => $handler->get_js_data())
70 );
71
72 $PAGE->requires->js_init_call('M.course_dndupload.init', $vars, true, $jsmodule);
73}
74
75
76/**
77 * Stores all the information about the available dndupload handlers
78 *
79 * @package core
80 * @copyright 2012 Davo Smith
81 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
82 */
83class dndupload_handler {
84
85 /**
86 * @var array A list of all registered mime types that can be dropped onto a course
87 * along with the modules that will handle them.
88 */
89 protected $types = array();
90
91 /**
92 * @var array A list of the different file types (extensions) that different modules
93 * will handle.
94 */
95 protected $filehandlers = array();
96
97 /**
98 * Gather a list of dndupload handlers from the different mods
99 *
100 * @param object $course The course this is being added to (to check course_allowed_module() )
101 */
5103b5e6 102 public function __construct($course, $modnames = null) {
32528f94
DS
103 global $CFG;
104
105 // Add some default types to handle.
106 // Note: 'Files' type is hard-coded into the Javascript as this needs to be ...
107 // ... treated a little differently.
108 $this->add_type('url', array('url', 'text/uri-list'), get_string('addlinkhere', 'core_dndupload'),
109 get_string('nameforlink', 'core_dndupload'), 10);
110 $this->add_type('text/html', array('text/html'), get_string('addpagehere', 'core_dndupload'),
111 get_string('nameforpage', 'core_dndupload'), 20);
112 $this->add_type('text', array('text', 'text/plain'), get_string('addpagehere', 'core_dndupload'),
113 get_string('nameforpage', 'core_dndupload'), 30);
114
115 // Loop through all modules to find handlers.
abed5d65
DS
116 $mods = get_plugin_list_with_function('mod', 'dndupload_register');
117 foreach ($mods as $component => $funcname) {
118 list($modtype, $modname) = normalize_component($component);
5103b5e6
DS
119 if ($modnames && !array_key_exists($modname, $modnames)) {
120 continue; // Module is deactivated (hidden) at the site level.
121 }
32528f94 122 if (!course_allowed_module($course, $modname)) {
5103b5e6 123 continue; // User does not have permission to add this module to the course.
32528f94 124 }
abed5d65 125 $resp = $funcname();
32528f94
DS
126 if (!$resp) {
127 continue;
128 }
129 if (isset($resp['files'])) {
130 foreach ($resp['files'] as $file) {
131 $this->add_file_handler($file['extension'], $modname, $file['message']);
132 }
133 }
134 if (isset($resp['addtypes'])) {
135 foreach ($resp['addtypes'] as $type) {
136 if (isset($type['priority'])) {
137 $priority = $type['priority'];
138 } else {
139 $priority = 100;
140 }
141 $this->add_type($type['identifier'], $type['datatransfertypes'],
142 $type['addmessage'], $type['namemessage'], $priority);
143 }
144 }
145 if (isset($resp['types'])) {
146 foreach ($resp['types'] as $type) {
147 $this->add_type_handler($type['identifier'], $modname, $type['message']);
148 }
149 }
150 }
151 }
152
153 /**
154 * Used to add a new mime type that can be drag and dropped onto a
155 * course displayed in a browser window
156 *
157 * @param string $identifier The name that this type will be known as
158 * @param array $datatransfertypes An array of the different types in the browser
159 * 'dataTransfer.types' object that will map to this type
160 * @param string $addmessage The message to display in the browser when this type is being
161 * dragged onto the page
162 * @param string $namemessage The message to pop up when asking for the name to give the
163 * course module instance when it is created
164 * @param int $priority Controls the order in which types are checked by the browser (mainly
165 * needed to check for 'text' last as that is usually given as fallback)
166 */
167 public function add_type($identifier, $datatransfertypes, $addmessage, $namemessage, $priority=100) {
168 if ($this->is_known_type($identifier)) {
169 throw new coding_exception("Type $identifier is already registered");
170 }
171
172 $add = new stdClass;
173 $add->identifier = $identifier;
174 $add->datatransfertypes = $datatransfertypes;
175 $add->addmessage = $addmessage;
176 $add->namemessage = $namemessage;
177 $add->priority = $priority;
178 $add->handlers = array();
179
abed5d65 180 $this->types[$identifier] = $add;
32528f94
DS
181 }
182
183 /**
184 * Used to declare that a particular module will handle a particular type
185 * of dropped data
186 *
187 * @param string $type The name of the type (as declared in add_type)
188 * @param string $module The name of the module to handle this type
189 * @param string $message The message to show the user if more than one handler is registered
190 * for a type and the user needs to make a choice between them
191 */
192 public function add_type_handler($type, $module, $message) {
abed5d65
DS
193 if (!$this->is_known_type($type)) {
194 throw new coding_exception("Trying to add handler for unknown type $type");
32528f94
DS
195 }
196
abed5d65
DS
197 $add = new stdClass;
198 $add->type = $type;
199 $add->module = $module;
200 $add->message = $message;
201
202 $this->types[$type]->handlers[] = $add;
32528f94
DS
203 }
204
205 /**
206 * Used to declare that a particular module will handle a particular type
207 * of dropped file
208 *
209 * @param string $extension The file extension to handle ('*' for all types)
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 */
214 public function add_file_handler($extension, $module, $message) {
abed5d65
DS
215 $extension = strtolower($extension);
216
32528f94
DS
217 $add = new stdClass;
218 $add->extension = $extension;
219 $add->module = $module;
220 $add->message = $message;
221
222 $this->filehandlers[] = $add;
223 }
224
225 /**
226 * Check to see if the type has been registered
227 *
228 * @param string $type The identifier of the type you are interested in
229 * @return bool True if the type is registered
230 */
231 public function is_known_type($type) {
abed5d65 232 return array_key_exists($type, $this->types);
32528f94
DS
233 }
234
235 /**
236 * Check to see if the module in question has registered to handle the
237 * type given
238 *
239 * @param string $module The name of the module
240 * @param string $type The identifier of the type
241 * @return bool True if the module has registered to handle that type
242 */
243 public function has_type_handler($module, $type) {
abed5d65
DS
244 if (!$this->is_known_type($type)) {
245 throw new coding_exception("Checking for handler for unknown type $type");
246 }
247 foreach ($this->types[$type]->handlers as $handler) {
248 if ($handler->module == $module) {
249 return true;
32528f94
DS
250 }
251 }
252 return false;
253 }
254
255 /**
256 * Check to see if the module in question has registered to handle files
257 * with the given extension (or to handle all file types)
258 *
259 * @param string $module The name of the module
260 * @param string $extension The extension of the uploaded file
261 * @return bool True if the module has registered to handle files with
262 * that extension (or to handle all file types)
263 */
264 public function has_file_handler($module, $extension) {
265 foreach ($this->filehandlers as $handler) {
266 if ($handler->module == $module) {
267 if ($handler->extension == '*' || $handler->extension == $extension) {
268 return true;
269 }
270 }
271 }
272 return false;
273 }
274
275 /**
276 * Gets a list of the file types that are handled by a particular module
277 *
278 * @param string $module The name of the module to check
279 * @return array of file extensions or string '*'
280 */
281 public function get_handled_file_types($module) {
282 $types = array();
283 foreach ($this->filehandlers as $handler) {
284 if ($handler->module == $module) {
285 if ($handler->extension == '*') {
286 return '*';
287 } else {
288 // Prepending '.' as otherwise mimeinfo fails.
289 $types[] = '.'.$handler->extension;
290 }
291 }
292 }
293 return $types;
294 }
295
296 /**
297 * Returns an object to pass onto the javascript code with data about all the
298 * registered file / type handlers
299 *
300 * @return object Data to pass on to Javascript code
301 */
302 public function get_js_data() {
303 $ret = new stdClass;
304
305 // Sort the types by priority.
306 uasort($this->types, array($this, 'type_compare'));
307
308 $ret->types = array();
309 foreach ($this->types as $type) {
310 if (empty($type->handlers)) {
311 continue; // Skip any types without registered handlers.
312 }
313 $ret->types[] = $type;
314 }
315
316 $ret->filehandlers = $this->filehandlers;
317 $uploadrepo = repository::get_instances(array('type' => 'upload'));
318 if (empty($uploadrepo)) {
319 $ret->filehandlers = array(); // No upload repo => no file handlers.
320 }
321
322 return $ret;
323 }
324
325 /**
326 * Comparison function used when sorting types by priority
327 * @param object $type1 first type to compare
328 * @param object $type2 second type to compare
329 * @return integer -1 for $type1 < $type2; 1 for $type1 > $type2; 0 for equal
330 */
331 protected function type_compare($type1, $type2) {
332 if ($type1->priority < $type2->priority) {
333 return -1;
334 }
335 if ($type1->priority > $type2->priority) {
336 return 1;
337 }
338 return 0;
339 }
340
341}
342
343/**
344 * Processes the upload, creating the course module and returning the result
345 *
346 * @package core
347 * @copyright 2012 Davo Smith
348 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
349 */
abed5d65 350class dndupload_ajax_processor {
32528f94
DS
351
352 /** Returned when no error has occurred */
353 const ERROR_OK = 0;
354
355 /** @var object The course that we are uploading to */
356 protected $course = null;
357
358 /** @var context_course The course context for capability checking */
359 protected $context = null;
360
361 /** @var int The section number we are uploading to */
362 protected $section = null;
363
364 /** @var string The type of upload (e.g. 'Files', 'text/plain') */
365 protected $type = null;
366
367 /** @var object The details of the module type that will be created */
368 protected $module= null;
369
370 /** @var object The course module that has been created */
371 protected $cm = null;
372
373 /** @var dndupload_handler used to check the allowed file types */
374 protected $dnduploadhandler = null;
375
376 /** @var string The name to give the new activity instance */
377 protected $displayname = null;
378
379 /**
380 * Set up some basic information needed to handle the upload
381 *
382 * @param int $courseid The ID of the course we are uploading to
383 * @param int $section The section number we are uploading to
384 * @param string $type The type of upload (as reported by the browser)
385 * @param string $modulename The name of the module requested to handle this upload
386 */
387 public function __construct($courseid, $section, $type, $modulename) {
388 global $DB;
389
abed5d65
DS
390 if (!defined('AJAX_SCRIPT')) {
391 throw new coding_exception('dndupload_ajax_processor should only be used within AJAX requests');
392 }
393
32528f94
DS
394 $this->course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
395
396 require_login($this->course, false);
397 $this->context = context_course::instance($this->course->id);
398
5103b5e6 399 if (!is_number($section) || $section < 0) {
32528f94
DS
400 throw new coding_exception("Invalid section number $section");
401 }
402 $this->section = $section;
403 $this->type = $type;
404
405 if (!$this->module = $DB->get_record('modules', array('name' => $modulename))) {
406 throw new coding_exception("Module $modulename does not exist");
407 }
408
409 $this->dnduploadhandler = new dndupload_handler($this->course);
410 }
411
412 /**
413 * Check if this upload is a 'file' upload
414 *
415 * @return bool true if it is a 'file' upload, false otherwise
416 */
417 protected function is_file_upload() {
418 return ($this->type == 'Files');
419 }
420
421 /**
422 * Process the upload - creating the module in the course and returning the result to the browser
423 *
424 * @param string $displayname optional the name (from the browser) to give the course module instance
425 * @param string $content optional the content of the upload (for non-file uploads)
426 */
427 public function process($displayname = null, $content = null) {
428 require_capability('moodle/course:manageactivities', $this->context);
429
430 if ($this->is_file_upload()) {
431 require_capability('moodle/course:managefiles', $this->context);
abed5d65
DS
432 if ($content != null) {
433 throw new moodle_exception('fileuploadwithcontent', 'core_dndupload');
434 }
32528f94
DS
435 }
436
437 require_sesskey();
438
439 $this->displayname = $displayname;
440
441 if ($this->is_file_upload()) {
442 $this->handle_file_upload();
443 } else {
444 $this->handle_other_upload($content);
445 }
446 }
447
448 /**
449 * Handle uploads containing files - create the course module, ask the upload repository
450 * to process the file, ask the mod to set itself up, then return the result to the browser
451 */
452 protected function handle_file_upload() {
453 global $CFG;
454
455 // Add the file to a draft file area.
456 $draftitemid = file_get_unused_draft_itemid();
457 $maxbytes = get_max_upload_file_size($CFG->maxbytes, $this->course->maxbytes);
458 $types = $this->dnduploadhandler->get_handled_file_types($this->module->name);
459 $repo = repository::get_instances(array('type' => 'upload'));
460 if (empty($repo)) {
461 throw new moodle_exception('errornouploadrepo', 'core_dndupload');
462 }
463 $repo = reset($repo); // Get the first (and only) upload repo.
464 $details = $repo->process_upload(null, $maxbytes, $types, '/', $draftitemid);
465 if (empty($this->displayname)) {
466 $this->displayname = $this->display_name_from_file($details['file']);
467 }
468
469 // Create a course module to hold the new instance.
470 $this->create_course_module();
471
472 // Ask the module to set itself up.
473 $moduledata = $this->prepare_module_data($draftitemid);
474 $instanceid = plugin_callback('mod', $this->module->name, 'dndupload', 'handle', array($moduledata), 'invalidfunction');
475 if ($instanceid === 'invalidfunction') {
476 throw new coding_exception("{$this->module->name} does not support drag and drop upload (missing {$this->module->name}_dndupload_handle function");
477 }
478
479 // Finish setting up the course module.
480 $this->finish_setup_course_module($instanceid);
481 }
482
483 /**
484 * Handle uploads not containing file - create the course module, ask the mod to
485 * set itself up, then return the result to the browser
486 *
487 * @param string $content the content uploaded to the browser
488 */
489 protected function handle_other_upload($content) {
abed5d65
DS
490 // Check this plugin is registered to handle this type of upload
491 if (!$this->dnduploadhandler->has_type_handler($this->module->name, $this->type)) {
492 $info = (object)array('modname' => $this->module->name, 'type' => $this->type);
493 throw new moodle_exception('moddoesnotsupporttype', 'core_dndupload', $info);
494 }
495
32528f94
DS
496 // Create a course module to hold the new instance.
497 $this->create_course_module();
498
499 // Ask the module to set itself up.
500 $moduledata = $this->prepare_module_data(null, $content);
501 $instanceid = plugin_callback('mod', $this->module->name, 'dndupload', 'handle', array($moduledata), 'invalidfunction');
502 if ($instanceid === 'invalidfunction') {
503 throw new coding_exception("{$this->module->name} does not support drag and drop upload (missing {$this->module->name}_dndupload_handle function");
504 }
505
506 // Finish setting up the course module.
507 $this->finish_setup_course_module($instanceid);
508 }
509
510 /**
511 * Generate the name of the mod instance from the name of the file
512 * (remove the extension and convert underscore => space
513 *
514 * @param string $filename the filename of the uploaded file
515 * @return string the display name to use
516 */
517 protected function display_name_from_file($filename) {
518 $pos = textlib::strrpos($filename, '.');
519 if ($pos) { // Want to skip if $pos === 0 OR $pos === false.
520 $filename = textlib::substr($filename, 0, $pos);
521 }
522 return str_replace('_', ' ', $filename);
523 }
524
525 /**
526 * Create the coursemodule to hold the file/content that has been uploaded
527 */
528 protected function create_course_module() {
529 if (!course_allowed_module($this->course, $this->module->name)) {
530 throw new coding_exception("The module {$this->module->name} is not allowed to be added to this course");
531 }
532
533 $this->cm = new stdClass();
534 $this->cm->course = $this->course->id;
535 $this->cm->section = $this->section;
536 $this->cm->module = $this->module->id;
537 $this->cm->modulename = $this->module->name;
538 $this->cm->instance = 0; // This will be filled in after we create the instance.
539 $this->cm->visible = 1;
540 $this->cm->groupmode = $this->course->groupmode;
541 $this->cm->groupingid = $this->course->defaultgroupingid;
542
543 if (!$this->cm->id = add_course_module($this->cm)) {
544 throw new coding_exception("Unable to create the course module");
545 }
546 // The following are used inside some few core functions, so may as well set them here.
547 $this->cm->coursemodule = $this->cm->id;
548 $this->cm->groupmodelink = (!$this->course->groupmodeforce);
549 }
550
551 /**
552 * Gather together all the details to pass on to the mod, so that it can initialise it's
553 * own database tables
554 *
555 * @param int $draftitemid optional the id of the draft area containing the file (for file uploads)
556 * @param string $content optional the content dropped onto the course (for non-file uploads)
557 * @return object data to pass on to the mod, containing:
558 * string $type the 'type' as registered with dndupload_handler (or 'Files')
559 * object $course the course the upload was for
560 * int $draftitemid optional the id of the draft area containing the files
561 * int $coursemodule id of the course module that has already been created
562 * string $displayname the name to use for this activity (can be overriden by the mod)
563 */
564 protected function prepare_module_data($draftitemid = null, $content = null) {
565 $data = new stdClass();
566 $data->type = $this->type;
567 $data->course = $this->course;
568 if ($draftitemid) {
569 $data->draftitemid = $draftitemid;
570 } else if ($content) {
571 $data->content = $content;
572 }
573 $data->coursemodule = $this->cm->id;
574 $data->displayname = $this->displayname;
575 return $data;
576 }
577
578 /**
579 * Called after the mod has set itself up, to finish off any course module settings
580 * (set instance id, add to correct section, set visibility, etc.) and send the response
581 *
582 * @param int $instanceid id returned by the mod when it was created
583 */
584 protected function finish_setup_course_module($instanceid) {
585 global $DB, $USER;
586
587 if (!$instanceid) {
588 // Something has gone wrong - undo everything we can.
abed5d65
DS
589 delete_course_module($this->cm->id);
590 throw new moodle_exception('errorcreatingactivity', 'core_dndupload', '', $this->module->name);
32528f94
DS
591 }
592
593 $DB->set_field('course_modules', 'instance', $instanceid, array('id' => $this->cm->id));
594
595 $sectionid = add_mod_to_section($this->cm);
596 $DB->set_field('course_modules', 'section', $sectionid, array('id' => $this->cm->id));
597
598 set_coursemodule_visible($this->cm->id, true);
599
600 // Rebuild the course cache and retrieve the final info about this module.
601 rebuild_course_cache($this->course->id, true);
602 $this->course->modinfo = null; // Otherwise we will just get the old version back again.
603 $info = get_fast_modinfo($this->course);
5103b5e6
DS
604 if (!isset($info->cms[$this->cm->id])) {
605 // The course module has not been properly created in the course - undo everything.
606 delete_course_module($this->cm->id);
607 throw new moodle_exception('errorcreatingactivity', 'core_dndupload', '', $this->module->name);
608 }
32528f94
DS
609 $mod = $info->cms[$this->cm->id];
610
611 // Trigger mod_created event with information about this module.
612 $eventdata = new stdClass();
613 $eventdata->modulename = $mod->modname;
614 $eventdata->name = $mod->name;
615 $eventdata->cmid = $mod->id;
616 $eventdata->courseid = $this->course->id;
617 $eventdata->userid = $USER->id;
618 events_trigger('mod_created', $eventdata);
619
620 add_to_log($this->course->id, "course", "add mod",
621 "../mod/{$mod->modname}/view.php?id=$mod->id",
622 "{$mod->modname} $instanceid");
623 add_to_log($this->course->id, $mod->modname, "add",
624 "view.php?id=$mod->id",
625 "$instanceid", $mod->id);
626
627 if ($this->cm->groupmodelink && plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
628 $mod->groupmodelink = $this->cm->groupmodelink;
629 } else {
630 $mod->groupmodelink = false;
631 }
632
633 $this->send_response($mod);
634 }
635
636 /**
637 * Send the details of the newly created activity back to the client browser
638 *
639 * @param cm_info $mod details of the mod just created
640 */
641 protected function send_response($mod) {
abed5d65
DS
642 global $OUTPUT;
643
32528f94
DS
644 $resp = new stdClass();
645 $resp->error = self::ERROR_OK;
abed5d65 646 $resp->icon = $mod->get_icon_url()->out();
32528f94 647 $resp->name = $mod->name;
abed5d65 648 $resp->link = $mod->get_url()->out();
32528f94
DS
649 $resp->elementid = 'module-'.$mod->id;
650 $resp->commands = make_editing_buttons($mod, true, true, 0, $mod->sectionnum);
651 $resp->onclick = $mod->get_on_click();
652
abed5d65 653 echo $OUTPUT->header();
32528f94
DS
654 echo json_encode($resp);
655 die();
656 }
657}