Merge branch 'wip_master_mdl-42723' of https://github.com/iarenaza/moodle
[moodle.git] / course / modlib.php
blob42df746f5e559a562210ec564f85e5be11313f62
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 of functions specific to course/modedit.php and course API functions.
19 * The course API function calling them are course/lib.php:create_module() and update_module().
20 * This file has been created has an alternative solution to a full refactor of course/modedit.php
21 * in order to create the course API functions.
23 * @copyright 2013 Jerome Mouneyrac
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 * @package core_course
28 defined('MOODLE_INTERNAL') || die;
30 require_once($CFG->dirroot.'/course/lib.php');
32 /**
33 * Add course module.
35 * The function does not check user capabilities.
36 * The function creates course module, module instance, add the module to the correct section.
37 * It also trigger common action that need to be done after adding/updating a module.
39 * @param object $moduleinfo the moudle data
40 * @param object $course the course of the module
41 * @param object $mform this is required by an existing hack to deal with files during MODULENAME_add_instance()
42 * @return object the updated module info
44 function add_moduleinfo($moduleinfo, $course, $mform = null) {
45 global $DB, $CFG;
47 // Attempt to include module library before we make any changes to DB.
48 include_modulelib($moduleinfo->modulename);
50 $moduleinfo->course = $course->id;
51 $moduleinfo = set_moduleinfo_defaults($moduleinfo);
53 if (!empty($course->groupmodeforce) or !isset($moduleinfo->groupmode)) {
54 $moduleinfo->groupmode = 0; // Do not set groupmode.
57 // First add course_module record because we need the context.
58 $newcm = new stdClass();
59 $newcm->course = $course->id;
60 $newcm->module = $moduleinfo->module;
61 $newcm->instance = 0; // Not known yet, will be updated later (this is similar to restore code).
62 $newcm->visible = $moduleinfo->visible;
63 $newcm->visibleold = $moduleinfo->visible;
64 if (isset($moduleinfo->cmidnumber)) {
65 $newcm->idnumber = $moduleinfo->cmidnumber;
67 $newcm->groupmode = $moduleinfo->groupmode;
68 $newcm->groupingid = $moduleinfo->groupingid;
69 $newcm->groupmembersonly = $moduleinfo->groupmembersonly;
70 $completion = new completion_info($course);
71 if ($completion->is_enabled()) {
72 $newcm->completion = $moduleinfo->completion;
73 $newcm->completiongradeitemnumber = $moduleinfo->completiongradeitemnumber;
74 $newcm->completionview = $moduleinfo->completionview;
75 $newcm->completionexpected = $moduleinfo->completionexpected;
77 if(!empty($CFG->enableavailability)) {
78 $newcm->availablefrom = $moduleinfo->availablefrom;
79 $newcm->availableuntil = $moduleinfo->availableuntil;
80 $newcm->showavailability = $moduleinfo->showavailability;
82 if (isset($moduleinfo->showdescription)) {
83 $newcm->showdescription = $moduleinfo->showdescription;
84 } else {
85 $newcm->showdescription = 0;
88 if (!$moduleinfo->coursemodule = add_course_module($newcm)) {
89 print_error('cannotaddcoursemodule');
92 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true) &&
93 isset($moduleinfo->introeditor)) {
94 $introeditor = $moduleinfo->introeditor;
95 unset($moduleinfo->introeditor);
96 $moduleinfo->intro = $introeditor['text'];
97 $moduleinfo->introformat = $introeditor['format'];
100 $addinstancefunction = $moduleinfo->modulename."_add_instance";
101 $returnfromfunc = $addinstancefunction($moduleinfo, $mform);
102 if (!$returnfromfunc or !is_number($returnfromfunc)) {
103 // Undo everything we can.
104 $modcontext = context_module::instance($moduleinfo->coursemodule);
105 context_helper::delete_instance(CONTEXT_MODULE, $moduleinfo->coursemodule);
106 $DB->delete_records('course_modules', array('id'=>$moduleinfo->coursemodule));
108 if (!is_number($returnfromfunc)) {
109 print_error('invalidfunction', '', course_get_url($course, $moduleinfo->section));
110 } else {
111 print_error('cannotaddnewmodule', '', course_get_url($course, $moduleinfo->section), $moduleinfo->modulename);
115 $moduleinfo->instance = $returnfromfunc;
117 $DB->set_field('course_modules', 'instance', $returnfromfunc, array('id'=>$moduleinfo->coursemodule));
119 // Update embedded links and save files.
120 $modcontext = context_module::instance($moduleinfo->coursemodule);
121 if (!empty($introeditor)) {
122 $moduleinfo->intro = file_save_draft_area_files($introeditor['itemid'], $modcontext->id,
123 'mod_'.$moduleinfo->modulename, 'intro', 0,
124 array('subdirs'=>true), $introeditor['text']);
125 $DB->set_field($moduleinfo->modulename, 'intro', $moduleinfo->intro, array('id'=>$moduleinfo->instance));
128 // Course_modules and course_sections each contain a reference to each other.
129 // So we have to update one of them twice.
130 $sectionid = course_add_cm_to_section($course, $moduleinfo->coursemodule, $moduleinfo->section);
132 // Set up conditions.
133 if ($CFG->enableavailability) {
134 condition_info::update_cm_from_form((object)array('id'=>$moduleinfo->coursemodule), $moduleinfo, false);
137 // Trigger event based on the action we did.
138 $event = \core\event\course_module_created::create(array(
139 'courseid' => $course->id,
140 'context' => $modcontext,
141 'objectid' => $moduleinfo->coursemodule,
142 'other' => array(
143 'modulename' => $moduleinfo->modulename,
144 'name' => $moduleinfo->name,
145 'instanceid' => $moduleinfo->instance
148 $event->trigger();
150 add_to_log($course->id, $moduleinfo->modulename, "add",
151 "view.php?id=$moduleinfo->coursemodule",
152 "$moduleinfo->instance", $moduleinfo->coursemodule);
154 $moduleinfo = edit_module_post_actions($moduleinfo, $course);
156 return $moduleinfo;
161 * Common create/update module module actions that need to be processed as soon as a module is created/updaded.
162 * For example:create grade parent category, add outcomes, rebuild caches, regrade, save plagiarism settings...
163 * Please note this api does not trigger events as of MOODLE 2.6. Please trigger events before calling this api.
165 * @param object $moduleinfo the module info
166 * @param object $course the course of the module
168 * @return object moduleinfo update with grading management info
170 function edit_module_post_actions($moduleinfo, $course) {
171 global $CFG;
173 $modcontext = context_module::instance($moduleinfo->coursemodule);
174 $hasgrades = plugin_supports('mod', $moduleinfo->modulename, FEATURE_GRADE_HAS_GRADE, false);
175 $hasoutcomes = plugin_supports('mod', $moduleinfo->modulename, FEATURE_GRADE_OUTCOMES, true);
177 // Sync idnumber with grade_item.
178 if ($hasgrades && $grade_item = grade_item::fetch(array('itemtype'=>'mod', 'itemmodule'=>$moduleinfo->modulename,
179 'iteminstance'=>$moduleinfo->instance, 'itemnumber'=>0, 'courseid'=>$course->id))) {
180 if ($grade_item->idnumber != $moduleinfo->cmidnumber) {
181 $grade_item->idnumber = $moduleinfo->cmidnumber;
182 $grade_item->update();
186 if ($hasgrades) {
187 $items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$moduleinfo->modulename,
188 'iteminstance'=>$moduleinfo->instance, 'courseid'=>$course->id));
189 } else {
190 $items = array();
193 // Create parent category if requested and move to correct parent category.
194 if ($items and isset($moduleinfo->gradecat)) {
195 if ($moduleinfo->gradecat == -1) {
196 $grade_category = new grade_category();
197 $grade_category->courseid = $course->id;
198 $grade_category->fullname = $moduleinfo->name;
199 $grade_category->insert();
200 if ($grade_item) {
201 $parent = $grade_item->get_parent_category();
202 $grade_category->set_parent($parent->id);
204 $moduleinfo->gradecat = $grade_category->id;
206 foreach ($items as $itemid=>$unused) {
207 $items[$itemid]->set_parent($moduleinfo->gradecat);
208 if ($itemid == $grade_item->id) {
209 // Use updated grade_item.
210 $grade_item = $items[$itemid];
215 // Add outcomes if requested.
216 if ($hasoutcomes && $outcomes = grade_outcome::fetch_all_available($course->id)) {
217 $grade_items = array();
219 // Outcome grade_item.itemnumber start at 1000, there is nothing above outcomes.
220 $max_itemnumber = 999;
221 if ($items) {
222 foreach($items as $item) {
223 if ($item->itemnumber > $max_itemnumber) {
224 $max_itemnumber = $item->itemnumber;
229 foreach($outcomes as $outcome) {
230 $elname = 'outcome_'.$outcome->id;
232 if (property_exists($moduleinfo, $elname) and $moduleinfo->$elname) {
233 // So we have a request for new outcome grade item?
234 if ($items) {
235 $outcomeexists = false;
236 foreach($items as $item) {
237 if ($item->outcomeid == $outcome->id) {
238 $outcomeexists = true;
239 break;
242 if ($outcomeexists) {
243 continue;
247 $max_itemnumber++;
249 $outcome_item = new grade_item();
250 $outcome_item->courseid = $course->id;
251 $outcome_item->itemtype = 'mod';
252 $outcome_item->itemmodule = $moduleinfo->modulename;
253 $outcome_item->iteminstance = $moduleinfo->instance;
254 $outcome_item->itemnumber = $max_itemnumber;
255 $outcome_item->itemname = $outcome->fullname;
256 $outcome_item->outcomeid = $outcome->id;
257 $outcome_item->gradetype = GRADE_TYPE_SCALE;
258 $outcome_item->scaleid = $outcome->scaleid;
259 $outcome_item->insert();
261 // Move the new outcome into correct category and fix sortorder if needed.
262 if ($grade_item) {
263 $outcome_item->set_parent($grade_item->categoryid);
264 $outcome_item->move_after_sortorder($grade_item->sortorder);
266 } else if (isset($moduleinfo->gradecat)) {
267 $outcome_item->set_parent($moduleinfo->gradecat);
273 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_ADVANCED_GRADING, false)
274 and has_capability('moodle/grade:managegradingforms', $modcontext)) {
275 require_once($CFG->dirroot.'/grade/grading/lib.php');
276 $gradingman = get_grading_manager($modcontext, 'mod_'.$moduleinfo->modulename);
277 $showgradingmanagement = false;
278 foreach ($gradingman->get_available_areas() as $areaname => $aretitle) {
279 $formfield = 'advancedgradingmethod_'.$areaname;
280 if (isset($moduleinfo->{$formfield})) {
281 $gradingman->set_area($areaname);
282 $methodchanged = $gradingman->set_active_method($moduleinfo->{$formfield});
283 if (empty($moduleinfo->{$formfield})) {
284 // Going back to the simple direct grading is not a reason to open the management screen.
285 $methodchanged = false;
287 $showgradingmanagement = $showgradingmanagement || $methodchanged;
290 // Update grading management information.
291 $moduleinfo->gradingman = $gradingman;
292 $moduleinfo->showgradingmanagement = $showgradingmanagement;
295 rebuild_course_cache($course->id, true);
296 if ($hasgrades) {
297 grade_regrade_final_grades($course->id);
299 require_once($CFG->libdir.'/plagiarismlib.php');
300 plagiarism_save_form_elements($moduleinfo);
302 return $moduleinfo;
307 * Set module info default values for the unset module attributs.
309 * @param object $moduleinfo the current known data of the module
310 * @return object the completed module info
312 function set_moduleinfo_defaults($moduleinfo) {
314 if (empty($moduleinfo->coursemodule)) {
315 // Add.
316 $cm = null;
317 $moduleinfo->instance = '';
318 $moduleinfo->coursemodule = '';
319 } else {
320 // Update.
321 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule, 0, false, MUST_EXIST);
322 $moduleinfo->instance = $cm->instance;
323 $moduleinfo->coursemodule = $cm->id;
325 // For safety.
326 $moduleinfo->modulename = clean_param($moduleinfo->modulename, PARAM_PLUGIN);
328 if (!isset($moduleinfo->groupingid)) {
329 $moduleinfo->groupingid = 0;
332 if (!isset($moduleinfo->groupmembersonly)) {
333 $moduleinfo->groupmembersonly = 0;
336 if (!isset($moduleinfo->name)) { // Label.
337 $moduleinfo->name = $moduleinfo->modulename;
340 if (!isset($moduleinfo->completion)) {
341 $moduleinfo->completion = COMPLETION_DISABLED;
343 if (!isset($moduleinfo->completionview)) {
344 $moduleinfo->completionview = COMPLETION_VIEW_NOT_REQUIRED;
347 // Convert the 'use grade' checkbox into a grade-item number: 0 if checked, null if not.
348 if (isset($moduleinfo->completionusegrade) && $moduleinfo->completionusegrade) {
349 $moduleinfo->completiongradeitemnumber = 0;
350 } else {
351 $moduleinfo->completiongradeitemnumber = null;
354 return $moduleinfo;
358 * Check that the user can add a module. Also returns some information like the module, context and course section info.
359 * The fucntion create the course section if it doesn't exist.
361 * @param object $course the course of the module
362 * @param object $modulename the module name
363 * @param object $section the section of the module
364 * @return array list containing module, context, course section.
365 * @throws moodle_exception if user is not allowed to perform the action or module is not allowed in this course
367 function can_add_moduleinfo($course, $modulename, $section) {
368 global $DB;
370 $module = $DB->get_record('modules', array('name'=>$modulename), '*', MUST_EXIST);
372 $context = context_course::instance($course->id);
373 require_capability('moodle/course:manageactivities', $context);
375 course_create_sections_if_missing($course, $section);
376 $cw = get_fast_modinfo($course)->get_section_info($section);
378 if (!course_allowed_module($course, $module->name)) {
379 print_error('moduledisable');
382 return array($module, $context, $cw);
386 * Check if user is allowed to update module info and returns related item/data to the module.
388 * @param object $cm course module
389 * @return array - list of course module, context, module, moduleinfo, and course section.
390 * @throws moodle_exception if user is not allowed to perform the action
392 function can_update_moduleinfo($cm) {
393 global $DB;
395 // Check the $USER has the right capability.
396 $context = context_module::instance($cm->id);
397 require_capability('moodle/course:manageactivities', $context);
399 // Check module exists.
400 $module = $DB->get_record('modules', array('id'=>$cm->module), '*', MUST_EXIST);
402 // Check the moduleinfo exists.
403 $data = $DB->get_record($module->name, array('id'=>$cm->instance), '*', MUST_EXIST);
405 // Check the course section exists.
406 $cw = $DB->get_record('course_sections', array('id'=>$cm->section), '*', MUST_EXIST);
408 return array($cm, $context, $module, $data, $cw);
413 * Update the module info.
414 * This function doesn't check the user capabilities. It updates the course module and the module instance.
415 * Then execute common action to create/update module process (trigger event, rebuild cache, save plagiarism settings...).
417 * @param object $cm course module
418 * @param object $moduleinfo module info
419 * @param object $course course of the module
420 * @param object $mform - the mform is required by some specific module in the function MODULE_update_instance(). This is due to a hack in this function.
421 * @return array list of course module and module info.
423 function update_moduleinfo($cm, $moduleinfo, $course, $mform = null) {
424 global $DB, $CFG;
426 // Attempt to include module library before we make any changes to DB.
427 include_modulelib($moduleinfo->modulename);
429 $moduleinfo->course = $course->id;
430 $moduleinfo = set_moduleinfo_defaults($moduleinfo);
432 if (!empty($course->groupmodeforce) or !isset($moduleinfo->groupmode)) {
433 $moduleinfo->groupmode = $cm->groupmode; // Keep original.
436 // Update course module first.
437 $cm->groupmode = $moduleinfo->groupmode;
438 if (isset($moduleinfo->groupingid)) {
439 $cm->groupingid = $moduleinfo->groupingid;
441 if (isset($moduleinfo->groupmembersonly)) {
442 $cm->groupmembersonly = $moduleinfo->groupmembersonly;
445 $completion = new completion_info($course);
446 if ($completion->is_enabled() && !empty($moduleinfo->completionunlocked)) {
447 // Update completion settings.
448 $cm->completion = $moduleinfo->completion;
449 $cm->completiongradeitemnumber = $moduleinfo->completiongradeitemnumber;
450 $cm->completionview = $moduleinfo->completionview;
451 $cm->completionexpected = $moduleinfo->completionexpected;
453 if (!empty($CFG->enableavailability)) {
454 $cm->availablefrom = $moduleinfo->availablefrom;
455 $cm->availableuntil = $moduleinfo->availableuntil;
456 $cm->showavailability = $moduleinfo->showavailability;
457 condition_info::update_cm_from_form($cm,$moduleinfo,true);
459 if (isset($moduleinfo->showdescription)) {
460 $cm->showdescription = $moduleinfo->showdescription;
461 } else {
462 $cm->showdescription = 0;
465 $DB->update_record('course_modules', $cm);
467 $modcontext = context_module::instance($moduleinfo->coursemodule);
469 // Update embedded links and save files.
470 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
471 $moduleinfo->intro = file_save_draft_area_files($moduleinfo->introeditor['itemid'], $modcontext->id,
472 'mod_'.$moduleinfo->modulename, 'intro', 0,
473 array('subdirs'=>true), $moduleinfo->introeditor['text']);
474 $moduleinfo->introformat = $moduleinfo->introeditor['format'];
475 unset($moduleinfo->introeditor);
477 $updateinstancefunction = $moduleinfo->modulename."_update_instance";
478 if (!$updateinstancefunction($moduleinfo, $mform)) {
479 print_error('cannotupdatemod', '', course_get_url($course, $cw->section), $moduleinfo->modulename);
482 // Make sure visibility is set correctly (in particular in calendar).
483 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
484 set_coursemodule_visible($moduleinfo->coursemodule, $moduleinfo->visible);
487 if (isset($moduleinfo->cmidnumber)) { // Label.
488 // Set cm idnumber - uniqueness is already verified by form validation.
489 set_coursemodule_idnumber($moduleinfo->coursemodule, $moduleinfo->cmidnumber);
492 // Now that module is fully updated, also update completion data if required.
493 // (this will wipe all user completion data and recalculate it)
494 if ($completion->is_enabled() && !empty($moduleinfo->completionunlocked)) {
495 $completion->reset_all_state($cm);
498 // Trigger event based on the action we did.
499 $event = \core\event\course_module_updated::create(array(
500 'courseid' => $course->id,
501 'context' => $modcontext,
502 'objectid' => $moduleinfo->coursemodule,
503 'other' => array(
504 'modulename' => $moduleinfo->modulename,
505 'name' => $moduleinfo->name,
506 'instanceid' => $moduleinfo->instance
509 $event->trigger();
511 add_to_log($course->id, $moduleinfo->modulename, "update",
512 "view.php?id=$moduleinfo->coursemodule",
513 "$moduleinfo->instance", $moduleinfo->coursemodule);
515 $moduleinfo = edit_module_post_actions($moduleinfo, $course);
517 return array($cm, $moduleinfo);
521 * Include once the module lib file.
523 * @param string $modulename module name of the lib to include
524 * @throws moodle_exception if lib.php file for the module does not exist
526 function include_modulelib($modulename) {
527 global $CFG;
528 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
529 if (file_exists($modlib)) {
530 include_once($modlib);
531 } else {
532 throw new moodle_exception('modulemissingcode', '', '', $modlib);