2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
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');
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) {
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 // This code is used both when submitting the form, which uses a long
79 // name to avoid clashes, and by unit test code which uses the real
81 $newcm->availability = null;
82 if (property_exists($moduleinfo, 'availabilityconditionsjson')) {
83 if ($moduleinfo->availabilityconditionsjson !== '') {
84 $newcm->availability = $moduleinfo->availabilityconditionsjson;
86 } else if (property_exists($moduleinfo, 'availability')) {
87 $newcm->availability = $moduleinfo->availability;
90 if (isset($moduleinfo->showdescription)) {
91 $newcm->showdescription = $moduleinfo->showdescription;
93 $newcm->showdescription = 0;
96 // From this point we make database changes, so start transaction.
97 $transaction = $DB->start_delegated_transaction();
99 if (!$moduleinfo->coursemodule = add_course_module($newcm)) {
100 print_error('cannotaddcoursemodule');
103 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true) &&
104 isset($moduleinfo->introeditor)) {
105 $introeditor = $moduleinfo->introeditor;
106 unset($moduleinfo->introeditor);
107 $moduleinfo->intro = $introeditor['text'];
108 $moduleinfo->introformat = $introeditor['format'];
111 $addinstancefunction = $moduleinfo->modulename."_add_instance";
113 $returnfromfunc = $addinstancefunction($moduleinfo, $mform);
114 } catch (moodle_exception $e) {
115 $returnfromfunc = $e;
117 if (!$returnfromfunc or !is_number($returnfromfunc)) {
118 // Undo everything we can. This is not necessary for databases which
119 // support transactions, but improves consistency for other databases.
120 $modcontext = context_module::instance($moduleinfo->coursemodule);
121 context_helper::delete_instance(CONTEXT_MODULE, $moduleinfo->coursemodule);
122 $DB->delete_records('course_modules', array('id'=>$moduleinfo->coursemodule));
124 if ($e instanceof moodle_exception) {
126 } else if (!is_number($returnfromfunc)) {
127 print_error('invalidfunction', '', course_get_url($course, $moduleinfo->section));
129 print_error('cannotaddnewmodule', '', course_get_url($course, $moduleinfo->section), $moduleinfo->modulename);
133 $moduleinfo->instance = $returnfromfunc;
135 $DB->set_field('course_modules', 'instance', $returnfromfunc, array('id'=>$moduleinfo->coursemodule));
137 // Update embedded links and save files.
138 $modcontext = context_module::instance($moduleinfo->coursemodule);
139 if (!empty($introeditor)) {
140 $moduleinfo->intro = file_save_draft_area_files($introeditor['itemid'], $modcontext->id,
141 'mod_'.$moduleinfo->modulename, 'intro', 0,
142 array('subdirs'=>true), $introeditor['text']);
143 $DB->set_field($moduleinfo->modulename, 'intro', $moduleinfo->intro, array('id'=>$moduleinfo->instance));
146 // Course_modules and course_sections each contain a reference to each other.
147 // So we have to update one of them twice.
148 $sectionid = course_add_cm_to_section($course, $moduleinfo->coursemodule, $moduleinfo->section);
150 // Trigger event based on the action we did.
151 // Api create_from_cm expects modname and id property, and we don't want to modify $moduleinfo since we are returning it.
152 $eventdata = clone $moduleinfo;
153 $eventdata->modname = $eventdata->modulename;
154 $eventdata->id = $eventdata->coursemodule;
155 $event = \core\event\course_module_created::create_from_cm($eventdata, $modcontext);
158 $moduleinfo = edit_module_post_actions($moduleinfo, $course);
159 $transaction->allow_commit();
166 * Common create/update module module actions that need to be processed as soon as a module is created/updaded.
167 * For example:create grade parent category, add outcomes, rebuild caches, regrade, save plagiarism settings...
168 * Please note this api does not trigger events as of MOODLE 2.6. Please trigger events before calling this api.
170 * @param object $moduleinfo the module info
171 * @param object $course the course of the module
173 * @return object moduleinfo update with grading management info
175 function edit_module_post_actions($moduleinfo, $course) {
177 require_once($CFG->libdir.'/gradelib.php');
179 $modcontext = context_module::instance($moduleinfo->coursemodule);
180 $hasgrades = plugin_supports('mod', $moduleinfo->modulename, FEATURE_GRADE_HAS_GRADE, false);
181 $hasoutcomes = plugin_supports('mod', $moduleinfo->modulename, FEATURE_GRADE_OUTCOMES, true);
183 // Sync idnumber with grade_item.
184 if ($hasgrades && $grade_item = grade_item::fetch(array('itemtype'=>'mod', 'itemmodule'=>$moduleinfo->modulename,
185 'iteminstance'=>$moduleinfo->instance, 'itemnumber'=>0, 'courseid'=>$course->id))) {
186 if ($grade_item->idnumber != $moduleinfo->cmidnumber) {
187 $grade_item->idnumber = $moduleinfo->cmidnumber;
188 $grade_item->update();
193 $items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$moduleinfo->modulename,
194 'iteminstance'=>$moduleinfo->instance, 'courseid'=>$course->id));
199 // Create parent category if requested and move to correct parent category.
200 if ($items and isset($moduleinfo->gradecat)) {
201 if ($moduleinfo->gradecat == -1) {
202 $grade_category = new grade_category();
203 $grade_category->courseid = $course->id;
204 $grade_category->fullname = $moduleinfo->name;
205 $grade_category->insert();
207 $parent = $grade_item->get_parent_category();
208 $grade_category->set_parent($parent->id);
210 $moduleinfo->gradecat = $grade_category->id;
212 foreach ($items as $itemid=>$unused) {
213 $items[$itemid]->set_parent($moduleinfo->gradecat);
214 if ($itemid == $grade_item->id) {
215 // Use updated grade_item.
216 $grade_item = $items[$itemid];
221 require_once($CFG->libdir.'/grade/grade_outcome.php');
222 // Add outcomes if requested.
223 if ($hasoutcomes && $outcomes = grade_outcome::fetch_all_available($course->id)) {
224 $grade_items = array();
226 // Outcome grade_item.itemnumber start at 1000, there is nothing above outcomes.
227 $max_itemnumber = 999;
229 foreach($items as $item) {
230 if ($item->itemnumber > $max_itemnumber) {
231 $max_itemnumber = $item->itemnumber;
236 foreach($outcomes as $outcome) {
237 $elname = 'outcome_'.$outcome->id;
239 if (property_exists($moduleinfo, $elname) and $moduleinfo->$elname) {
240 // So we have a request for new outcome grade item?
242 $outcomeexists = false;
243 foreach($items as $item) {
244 if ($item->outcomeid == $outcome->id) {
245 $outcomeexists = true;
249 if ($outcomeexists) {
256 $outcome_item = new grade_item();
257 $outcome_item->courseid = $course->id;
258 $outcome_item->itemtype = 'mod';
259 $outcome_item->itemmodule = $moduleinfo->modulename;
260 $outcome_item->iteminstance = $moduleinfo->instance;
261 $outcome_item->itemnumber = $max_itemnumber;
262 $outcome_item->itemname = $outcome->fullname;
263 $outcome_item->outcomeid = $outcome->id;
264 $outcome_item->gradetype = GRADE_TYPE_SCALE;
265 $outcome_item->scaleid = $outcome->scaleid;
266 $outcome_item->insert();
268 // Move the new outcome into correct category and fix sortorder if needed.
270 $outcome_item->set_parent($grade_item->categoryid);
271 $outcome_item->move_after_sortorder($grade_item->sortorder);
273 } else if (isset($moduleinfo->gradecat)) {
274 $outcome_item->set_parent($moduleinfo->gradecat);
280 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_ADVANCED_GRADING, false)
281 and has_capability('moodle/grade:managegradingforms', $modcontext)) {
282 require_once($CFG->dirroot.'/grade/grading/lib.php');
283 $gradingman = get_grading_manager($modcontext, 'mod_'.$moduleinfo->modulename);
284 $showgradingmanagement = false;
285 foreach ($gradingman->get_available_areas() as $areaname => $aretitle) {
286 $formfield = 'advancedgradingmethod_'.$areaname;
287 if (isset($moduleinfo->{$formfield})) {
288 $gradingman->set_area($areaname);
289 $methodchanged = $gradingman->set_active_method($moduleinfo->{$formfield});
290 if (empty($moduleinfo->{$formfield})) {
291 // Going back to the simple direct grading is not a reason to open the management screen.
292 $methodchanged = false;
294 $showgradingmanagement = $showgradingmanagement || $methodchanged;
297 // Update grading management information.
298 $moduleinfo->gradingman = $gradingman;
299 $moduleinfo->showgradingmanagement = $showgradingmanagement;
302 rebuild_course_cache($course->id, true);
304 grade_regrade_final_grades($course->id);
306 require_once($CFG->libdir.'/plagiarismlib.php');
307 plagiarism_save_form_elements($moduleinfo);
314 * Set module info default values for the unset module attributs.
316 * @param object $moduleinfo the current known data of the module
317 * @return object the completed module info
319 function set_moduleinfo_defaults($moduleinfo) {
321 if (empty($moduleinfo->coursemodule)) {
324 $moduleinfo->instance = '';
325 $moduleinfo->coursemodule = '';
328 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule, 0, false, MUST_EXIST);
329 $moduleinfo->instance = $cm->instance;
330 $moduleinfo->coursemodule = $cm->id;
333 $moduleinfo->modulename = clean_param($moduleinfo->modulename, PARAM_PLUGIN);
335 if (!isset($moduleinfo->groupingid)) {
336 $moduleinfo->groupingid = 0;
339 if (!isset($moduleinfo->groupmembersonly)) {
340 $moduleinfo->groupmembersonly = 0;
343 if (!isset($moduleinfo->name)) { // Label.
344 $moduleinfo->name = $moduleinfo->modulename;
347 if (!isset($moduleinfo->completion)) {
348 $moduleinfo->completion = COMPLETION_DISABLED;
350 if (!isset($moduleinfo->completionview)) {
351 $moduleinfo->completionview = COMPLETION_VIEW_NOT_REQUIRED;
353 if (!isset($moduleinfo->completionexpected)) {
354 $moduleinfo->completionexpected = 0;
357 // Convert the 'use grade' checkbox into a grade-item number: 0 if checked, null if not.
358 if (isset($moduleinfo->completionusegrade) && $moduleinfo->completionusegrade) {
359 $moduleinfo->completiongradeitemnumber = 0;
361 $moduleinfo->completiongradeitemnumber = null;
364 if (!isset($moduleinfo->conditiongradegroup)) {
365 $moduleinfo->conditiongradegroup = array();
367 if (!isset($moduleinfo->conditionfieldgroup)) {
368 $moduleinfo->conditionfieldgroup = array();
375 * Check that the user can add a module. Also returns some information like the module, context and course section info.
376 * The fucntion create the course section if it doesn't exist.
378 * @param object $course the course of the module
379 * @param object $modulename the module name
380 * @param object $section the section of the module
381 * @return array list containing module, context, course section.
382 * @throws moodle_exception if user is not allowed to perform the action or module is not allowed in this course
384 function can_add_moduleinfo($course, $modulename, $section) {
387 $module = $DB->get_record('modules', array('name'=>$modulename), '*', MUST_EXIST);
389 $context = context_course::instance($course->id);
390 require_capability('moodle/course:manageactivities', $context);
392 course_create_sections_if_missing($course, $section);
393 $cw = get_fast_modinfo($course)->get_section_info($section);
395 if (!course_allowed_module($course, $module->name)) {
396 print_error('moduledisable');
399 return array($module, $context, $cw);
403 * Check if user is allowed to update module info and returns related item/data to the module.
405 * @param object $cm course module
406 * @return array - list of course module, context, module, moduleinfo, and course section.
407 * @throws moodle_exception if user is not allowed to perform the action
409 function can_update_moduleinfo($cm) {
412 // Check the $USER has the right capability.
413 $context = context_module::instance($cm->id);
414 require_capability('moodle/course:manageactivities', $context);
416 // Check module exists.
417 $module = $DB->get_record('modules', array('id'=>$cm->module), '*', MUST_EXIST);
419 // Check the moduleinfo exists.
420 $data = $DB->get_record($module->name, array('id'=>$cm->instance), '*', MUST_EXIST);
422 // Check the course section exists.
423 $cw = $DB->get_record('course_sections', array('id'=>$cm->section), '*', MUST_EXIST);
425 return array($cm, $context, $module, $data, $cw);
430 * Update the module info.
431 * This function doesn't check the user capabilities. It updates the course module and the module instance.
432 * Then execute common action to create/update module process (trigger event, rebuild cache, save plagiarism settings...).
434 * @param object $cm course module
435 * @param object $moduleinfo module info
436 * @param object $course course of the module
437 * @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.
438 * @return array list of course module and module info.
440 function update_moduleinfo($cm, $moduleinfo, $course, $mform = null) {
443 // Attempt to include module library before we make any changes to DB.
444 include_modulelib($moduleinfo->modulename);
446 $moduleinfo->course = $course->id;
447 $moduleinfo = set_moduleinfo_defaults($moduleinfo);
449 if (!empty($course->groupmodeforce) or !isset($moduleinfo->groupmode)) {
450 $moduleinfo->groupmode = $cm->groupmode; // Keep original.
453 // Update course module first.
454 $cm->groupmode = $moduleinfo->groupmode;
455 if (isset($moduleinfo->groupingid)) {
456 $cm->groupingid = $moduleinfo->groupingid;
458 if (isset($moduleinfo->groupmembersonly)) {
459 $cm->groupmembersonly = $moduleinfo->groupmembersonly;
462 $completion = new completion_info($course);
463 if ($completion->is_enabled() && !empty($moduleinfo->completionunlocked)) {
464 // Update completion settings.
465 $cm->completion = $moduleinfo->completion;
466 $cm->completiongradeitemnumber = $moduleinfo->completiongradeitemnumber;
467 $cm->completionview = $moduleinfo->completionview;
468 $cm->completionexpected = $moduleinfo->completionexpected;
470 if (!empty($CFG->enableavailability)) {
471 // This code is used both when submitting the form, which uses a long
472 // name to avoid clashes, and by unit test code which uses the real
473 // name in the table.
474 if (property_exists($moduleinfo, 'availabilityconditionsjson')) {
475 if ($moduleinfo->availabilityconditionsjson !== '') {
476 $cm->availability = $moduleinfo->availabilityconditionsjson;
478 $cm->availability = null;
480 } else if (property_exists($moduleinfo, 'availability')) {
481 $cm->availability = $moduleinfo->availability;
484 if (isset($moduleinfo->showdescription)) {
485 $cm->showdescription = $moduleinfo->showdescription;
487 $cm->showdescription = 0;
490 $DB->update_record('course_modules', $cm);
492 $modcontext = context_module::instance($moduleinfo->coursemodule);
494 // Update embedded links and save files.
495 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
496 $moduleinfo->intro = file_save_draft_area_files($moduleinfo->introeditor['itemid'], $modcontext->id,
497 'mod_'.$moduleinfo->modulename, 'intro', 0,
498 array('subdirs'=>true), $moduleinfo->introeditor['text']);
499 $moduleinfo->introformat = $moduleinfo->introeditor['format'];
500 unset($moduleinfo->introeditor);
502 $updateinstancefunction = $moduleinfo->modulename."_update_instance";
503 if (!$updateinstancefunction($moduleinfo, $mform)) {
504 print_error('cannotupdatemod', '', course_get_url($course, $cw->section), $moduleinfo->modulename);
507 // Make sure visibility is set correctly (in particular in calendar).
508 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
509 set_coursemodule_visible($moduleinfo->coursemodule, $moduleinfo->visible);
512 if (isset($moduleinfo->cmidnumber)) { // Label.
513 // Set cm idnumber - uniqueness is already verified by form validation.
514 set_coursemodule_idnumber($moduleinfo->coursemodule, $moduleinfo->cmidnumber);
517 // Now that module is fully updated, also update completion data if required.
518 // (this will wipe all user completion data and recalculate it)
519 if ($completion->is_enabled() && !empty($moduleinfo->completionunlocked)) {
520 $completion->reset_all_state($cm);
522 $cm->name = $moduleinfo->name;
523 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
525 $moduleinfo = edit_module_post_actions($moduleinfo, $course);
527 return array($cm, $moduleinfo);
531 * Include once the module lib file.
533 * @param string $modulename module name of the lib to include
534 * @throws moodle_exception if lib.php file for the module does not exist
536 function include_modulelib($modulename) {
538 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
539 if (file_exists($modlib)) {
540 include_once($modlib);
542 throw new moodle_exception('modulemissingcode', '', '', $modlib);