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