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 $gradecategory = $grade_item->get_parent_category();
213 foreach ($items as $itemid=>$unused) {
214 $items[$itemid]->set_parent($moduleinfo->gradecat
);
215 if ($itemid == $grade_item->id
) {
216 // Use updated grade_item.
217 $grade_item = $items[$itemid];
219 if (!empty($moduleinfo->add
)) {
220 if (grade_category
::aggregation_uses_aggregationcoef($gradecategory->aggregation
)) {
221 if ($gradecategory->aggregation
== GRADE_AGGREGATE_WEIGHTED_MEAN
) {
222 $grade_item->aggregationcoef
= 1;
224 $grade_item->aggregationcoef
= 0;
226 $grade_item->update();
232 require_once($CFG->libdir
.'/grade/grade_outcome.php');
233 // Add outcomes if requested.
234 if ($hasoutcomes && $outcomes = grade_outcome
::fetch_all_available($course->id
)) {
235 $grade_items = array();
237 // Outcome grade_item.itemnumber start at 1000, there is nothing above outcomes.
238 $max_itemnumber = 999;
240 foreach($items as $item) {
241 if ($item->itemnumber
> $max_itemnumber) {
242 $max_itemnumber = $item->itemnumber
;
247 foreach($outcomes as $outcome) {
248 $elname = 'outcome_'.$outcome->id
;
250 if (property_exists($moduleinfo, $elname) and $moduleinfo->$elname) {
251 // So we have a request for new outcome grade item?
253 $outcomeexists = false;
254 foreach($items as $item) {
255 if ($item->outcomeid
== $outcome->id
) {
256 $outcomeexists = true;
260 if ($outcomeexists) {
267 $outcome_item = new grade_item();
268 $outcome_item->courseid
= $course->id
;
269 $outcome_item->itemtype
= 'mod';
270 $outcome_item->itemmodule
= $moduleinfo->modulename
;
271 $outcome_item->iteminstance
= $moduleinfo->instance
;
272 $outcome_item->itemnumber
= $max_itemnumber;
273 $outcome_item->itemname
= $outcome->fullname
;
274 $outcome_item->outcomeid
= $outcome->id
;
275 $outcome_item->gradetype
= GRADE_TYPE_SCALE
;
276 $outcome_item->scaleid
= $outcome->scaleid
;
277 $outcome_item->insert();
279 // Move the new outcome into correct category and fix sortorder if needed.
281 $outcome_item->set_parent($grade_item->categoryid
);
282 $outcome_item->move_after_sortorder($grade_item->sortorder
);
284 } else if (isset($moduleinfo->gradecat
)) {
285 $outcome_item->set_parent($moduleinfo->gradecat
);
287 $gradecategory = $outcome_item->get_parent_category();
288 if ($outcomeexists == false) {
289 if (grade_category
::aggregation_uses_aggregationcoef($gradecategory->aggregation
)) {
290 if ($gradecategory->aggregation
== GRADE_AGGREGATE_WEIGHTED_MEAN
) {
291 $outcome_item->aggregationcoef
= 1;
293 $outcome_item->aggregationcoef
= 0;
295 $outcome_item->update();
302 if (plugin_supports('mod', $moduleinfo->modulename
, FEATURE_ADVANCED_GRADING
, false)
303 and has_capability('moodle/grade:managegradingforms', $modcontext)) {
304 require_once($CFG->dirroot
.'/grade/grading/lib.php');
305 $gradingman = get_grading_manager($modcontext, 'mod_'.$moduleinfo->modulename
);
306 $showgradingmanagement = false;
307 foreach ($gradingman->get_available_areas() as $areaname => $aretitle) {
308 $formfield = 'advancedgradingmethod_'.$areaname;
309 if (isset($moduleinfo->{$formfield})) {
310 $gradingman->set_area($areaname);
311 $methodchanged = $gradingman->set_active_method($moduleinfo->{$formfield});
312 if (empty($moduleinfo->{$formfield})) {
313 // Going back to the simple direct grading is not a reason to open the management screen.
314 $methodchanged = false;
316 $showgradingmanagement = $showgradingmanagement ||
$methodchanged;
319 // Update grading management information.
320 $moduleinfo->gradingman
= $gradingman;
321 $moduleinfo->showgradingmanagement
= $showgradingmanagement;
324 rebuild_course_cache($course->id
, true);
326 grade_regrade_final_grades($course->id
);
328 require_once($CFG->libdir
.'/plagiarismlib.php');
329 plagiarism_save_form_elements($moduleinfo);
336 * Set module info default values for the unset module attributs.
338 * @param object $moduleinfo the current known data of the module
339 * @return object the completed module info
341 function set_moduleinfo_defaults($moduleinfo) {
343 if (empty($moduleinfo->coursemodule
)) {
346 $moduleinfo->instance
= '';
347 $moduleinfo->coursemodule
= '';
350 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule
, 0, false, MUST_EXIST
);
351 $moduleinfo->instance
= $cm->instance
;
352 $moduleinfo->coursemodule
= $cm->id
;
355 $moduleinfo->modulename
= clean_param($moduleinfo->modulename
, PARAM_PLUGIN
);
357 if (!isset($moduleinfo->groupingid
)) {
358 $moduleinfo->groupingid
= 0;
361 if (!isset($moduleinfo->groupmembersonly
)) {
362 $moduleinfo->groupmembersonly
= 0;
365 if (!isset($moduleinfo->name
)) { // Label.
366 $moduleinfo->name
= $moduleinfo->modulename
;
369 if (!isset($moduleinfo->completion
)) {
370 $moduleinfo->completion
= COMPLETION_DISABLED
;
372 if (!isset($moduleinfo->completionview
)) {
373 $moduleinfo->completionview
= COMPLETION_VIEW_NOT_REQUIRED
;
375 if (!isset($moduleinfo->completionexpected
)) {
376 $moduleinfo->completionexpected
= 0;
379 // Convert the 'use grade' checkbox into a grade-item number: 0 if checked, null if not.
380 if (isset($moduleinfo->completionusegrade
) && $moduleinfo->completionusegrade
) {
381 $moduleinfo->completiongradeitemnumber
= 0;
383 $moduleinfo->completiongradeitemnumber
= null;
386 if (!isset($moduleinfo->conditiongradegroup
)) {
387 $moduleinfo->conditiongradegroup
= array();
389 if (!isset($moduleinfo->conditionfieldgroup
)) {
390 $moduleinfo->conditionfieldgroup
= array();
397 * Check that the user can add a module. Also returns some information like the module, context and course section info.
398 * The fucntion create the course section if it doesn't exist.
400 * @param object $course the course of the module
401 * @param object $modulename the module name
402 * @param object $section the section of the module
403 * @return array list containing module, context, course section.
404 * @throws moodle_exception if user is not allowed to perform the action or module is not allowed in this course
406 function can_add_moduleinfo($course, $modulename, $section) {
409 $module = $DB->get_record('modules', array('name'=>$modulename), '*', MUST_EXIST
);
411 $context = context_course
::instance($course->id
);
412 require_capability('moodle/course:manageactivities', $context);
414 course_create_sections_if_missing($course, $section);
415 $cw = get_fast_modinfo($course)->get_section_info($section);
417 if (!course_allowed_module($course, $module->name
)) {
418 print_error('moduledisable');
421 return array($module, $context, $cw);
425 * Check if user is allowed to update module info and returns related item/data to the module.
427 * @param object $cm course module
428 * @return array - list of course module, context, module, moduleinfo, and course section.
429 * @throws moodle_exception if user is not allowed to perform the action
431 function can_update_moduleinfo($cm) {
434 // Check the $USER has the right capability.
435 $context = context_module
::instance($cm->id
);
436 require_capability('moodle/course:manageactivities', $context);
438 // Check module exists.
439 $module = $DB->get_record('modules', array('id'=>$cm->module
), '*', MUST_EXIST
);
441 // Check the moduleinfo exists.
442 $data = $DB->get_record($module->name
, array('id'=>$cm->instance
), '*', MUST_EXIST
);
444 // Check the course section exists.
445 $cw = $DB->get_record('course_sections', array('id'=>$cm->section
), '*', MUST_EXIST
);
447 return array($cm, $context, $module, $data, $cw);
452 * Update the module info.
453 * This function doesn't check the user capabilities. It updates the course module and the module instance.
454 * Then execute common action to create/update module process (trigger event, rebuild cache, save plagiarism settings...).
456 * @param object $cm course module
457 * @param object $moduleinfo module info
458 * @param object $course course of the module
459 * @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.
460 * @return array list of course module and module info.
462 function update_moduleinfo($cm, $moduleinfo, $course, $mform = null) {
465 // Attempt to include module library before we make any changes to DB.
466 include_modulelib($moduleinfo->modulename
);
468 $moduleinfo->course
= $course->id
;
469 $moduleinfo = set_moduleinfo_defaults($moduleinfo);
471 if (!empty($course->groupmodeforce
) or !isset($moduleinfo->groupmode
)) {
472 $moduleinfo->groupmode
= $cm->groupmode
; // Keep original.
475 // Update course module first.
476 $cm->groupmode
= $moduleinfo->groupmode
;
477 if (isset($moduleinfo->groupingid
)) {
478 $cm->groupingid
= $moduleinfo->groupingid
;
480 if (isset($moduleinfo->groupmembersonly
)) {
481 $cm->groupmembersonly
= $moduleinfo->groupmembersonly
;
484 $completion = new completion_info($course);
485 if ($completion->is_enabled() && !empty($moduleinfo->completionunlocked
)) {
486 // Update completion settings.
487 $cm->completion
= $moduleinfo->completion
;
488 $cm->completiongradeitemnumber
= $moduleinfo->completiongradeitemnumber
;
489 $cm->completionview
= $moduleinfo->completionview
;
490 $cm->completionexpected
= $moduleinfo->completionexpected
;
492 if (!empty($CFG->enableavailability
)) {
493 // This code is used both when submitting the form, which uses a long
494 // name to avoid clashes, and by unit test code which uses the real
495 // name in the table.
496 if (property_exists($moduleinfo, 'availabilityconditionsjson')) {
497 if ($moduleinfo->availabilityconditionsjson
!== '') {
498 $cm->availability
= $moduleinfo->availabilityconditionsjson
;
500 $cm->availability
= null;
502 } else if (property_exists($moduleinfo, 'availability')) {
503 $cm->availability
= $moduleinfo->availability
;
506 if (isset($moduleinfo->showdescription
)) {
507 $cm->showdescription
= $moduleinfo->showdescription
;
509 $cm->showdescription
= 0;
512 $DB->update_record('course_modules', $cm);
514 $modcontext = context_module
::instance($moduleinfo->coursemodule
);
516 // Update embedded links and save files.
517 if (plugin_supports('mod', $moduleinfo->modulename
, FEATURE_MOD_INTRO
, true)) {
518 $moduleinfo->intro
= file_save_draft_area_files($moduleinfo->introeditor
['itemid'], $modcontext->id
,
519 'mod_'.$moduleinfo->modulename
, 'intro', 0,
520 array('subdirs'=>true), $moduleinfo->introeditor
['text']);
521 $moduleinfo->introformat
= $moduleinfo->introeditor
['format'];
522 unset($moduleinfo->introeditor
);
524 $updateinstancefunction = $moduleinfo->modulename
."_update_instance";
525 if (!$updateinstancefunction($moduleinfo, $mform)) {
526 print_error('cannotupdatemod', '', course_get_url($course, $cw->section
), $moduleinfo->modulename
);
529 // Make sure visibility is set correctly (in particular in calendar).
530 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
531 set_coursemodule_visible($moduleinfo->coursemodule
, $moduleinfo->visible
);
534 if (isset($moduleinfo->cmidnumber
)) { // Label.
535 // Set cm idnumber - uniqueness is already verified by form validation.
536 set_coursemodule_idnumber($moduleinfo->coursemodule
, $moduleinfo->cmidnumber
);
539 // Now that module is fully updated, also update completion data if required.
540 // (this will wipe all user completion data and recalculate it)
541 if ($completion->is_enabled() && !empty($moduleinfo->completionunlocked
)) {
542 $completion->reset_all_state($cm);
544 $cm->name
= $moduleinfo->name
;
545 \core\event\course_module_updated
::create_from_cm($cm, $modcontext)->trigger();
547 $moduleinfo = edit_module_post_actions($moduleinfo, $course);
549 return array($cm, $moduleinfo);
553 * Include once the module lib file.
555 * @param string $modulename module name of the lib to include
556 * @throws moodle_exception if lib.php file for the module does not exist
558 function include_modulelib($modulename) {
560 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
561 if (file_exists($modlib)) {
562 include_once($modlib);
564 throw new moodle_exception('modulemissingcode', '', '', $modlib);