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