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 use \core_grades\component_gradeitems
;
31 use core_courseformat\formatactions
;
33 require_once($CFG->dirroot
.'/course/lib.php');
38 * The function does not check user capabilities.
39 * The function creates course module, module instance, add the module to the correct section.
40 * It also trigger common action that need to be done after adding/updating a module.
42 * @param object $moduleinfo the moudle data
43 * @param object $course the course of the module
44 * @param object $mform this is required by an existing hack to deal with files during MODULENAME_add_instance()
45 * @return object the updated module info
47 function add_moduleinfo($moduleinfo, $course, $mform = null) {
50 // Attempt to include module library before we make any changes to DB.
51 include_modulelib($moduleinfo->modulename
);
53 $moduleinfo->course
= $course->id
;
54 $moduleinfo = set_moduleinfo_defaults($moduleinfo);
56 if (!empty($course->groupmodeforce
) or !isset($moduleinfo->groupmode
)) {
57 $moduleinfo->groupmode
= 0; // Do not set groupmode.
60 // First add course_module record because we need the context.
61 $newcm = new stdClass();
62 $newcm->course
= $course->id
;
63 $newcm->module
= $moduleinfo->module
;
64 $newcm->instance
= 0; // Not known yet, will be updated later (this is similar to restore code).
65 $newcm->visible
= $moduleinfo->visible
;
66 $newcm->visibleold
= $moduleinfo->visible
;
67 $newcm->visibleoncoursepage
= $moduleinfo->visibleoncoursepage
;
68 if (isset($moduleinfo->cmidnumber
)) {
69 $newcm->idnumber
= $moduleinfo->cmidnumber
;
71 if (isset($moduleinfo->downloadcontent
)) {
72 $newcm->downloadcontent
= $moduleinfo->downloadcontent
;
74 if (has_capability('moodle/course:setforcedlanguage', context_course
::instance($course->id
))) {
75 $newcm->lang
= $moduleinfo->lang ??
null;
79 $newcm->groupmode
= $moduleinfo->groupmode
;
80 $newcm->groupingid
= $moduleinfo->groupingid
;
81 $completion = new completion_info($course);
82 if ($completion->is_enabled()) {
83 $newcm->completion
= $moduleinfo->completion
;
84 $newcm->completionpassgrade
= $moduleinfo->completionpassgrade ??
0;
85 if ($moduleinfo->completiongradeitemnumber
=== '') {
86 $newcm->completiongradeitemnumber
= null;
88 $newcm->completiongradeitemnumber
= $moduleinfo->completiongradeitemnumber
;
90 $newcm->completionview
= $moduleinfo->completionview
;
91 $newcm->completionexpected
= $moduleinfo->completionexpected
;
93 if(!empty($CFG->enableavailability
)) {
94 // This code is used both when submitting the form, which uses a long
95 // name to avoid clashes, and by unit test code which uses the real
97 $newcm->availability
= null;
98 if (property_exists($moduleinfo, 'availabilityconditionsjson')) {
99 if ($moduleinfo->availabilityconditionsjson
!== '') {
100 $newcm->availability
= $moduleinfo->availabilityconditionsjson
;
102 } else if (property_exists($moduleinfo, 'availability')) {
103 $newcm->availability
= $moduleinfo->availability
;
105 // If there is any availability data, verify it.
106 if ($newcm->availability
) {
107 $tree = new \core_availability\tree
(json_decode($newcm->availability
));
108 // Save time and database space by setting null if the only data
110 if ($tree->is_empty()) {
111 $newcm->availability
= null;
115 if (isset($moduleinfo->showdescription
)) {
116 $newcm->showdescription
= $moduleinfo->showdescription
;
118 $newcm->showdescription
= 0;
120 if (empty($moduleinfo->beforemod
)) {
121 $moduleinfo->beforemod
= null;
124 // From this point we make database changes, so start transaction.
125 $transaction = $DB->start_delegated_transaction();
127 if (!$moduleinfo->coursemodule
= add_course_module($newcm)) {
128 throw new \
moodle_exception('cannotaddcoursemodule');
131 if (plugin_supports('mod', $moduleinfo->modulename
, FEATURE_MOD_INTRO
, true) &&
132 isset($moduleinfo->introeditor
)) {
133 $introeditor = $moduleinfo->introeditor
;
134 unset($moduleinfo->introeditor
);
135 $moduleinfo->intro
= $introeditor['text'];
136 $moduleinfo->introformat
= $introeditor['format'];
139 $addinstancefunction = $moduleinfo->modulename
."_add_instance";
141 $returnfromfunc = $addinstancefunction($moduleinfo, $mform);
142 } catch (moodle_exception
$e) {
143 $returnfromfunc = $e;
145 if (!$returnfromfunc or !is_number($returnfromfunc)) {
146 // Undo everything we can. This is not necessary for databases which
147 // support transactions, but improves consistency for other databases.
148 context_helper
::delete_instance(CONTEXT_MODULE
, $moduleinfo->coursemodule
);
149 $DB->delete_records('course_modules', array('id'=>$moduleinfo->coursemodule
));
151 if ($returnfromfunc instanceof moodle_exception
) {
152 throw $returnfromfunc;
153 } else if (!is_number($returnfromfunc)) {
154 throw new \
moodle_exception('invalidfunction', '', course_get_url($course, $moduleinfo->section
));
156 throw new \
moodle_exception('cannotaddnewmodule', '', course_get_url($course, $moduleinfo->section
),
157 $moduleinfo->modulename
);
161 $moduleinfo->instance
= $returnfromfunc;
163 $DB->set_field('course_modules', 'instance', $returnfromfunc, array('id'=>$moduleinfo->coursemodule
));
165 // Update embedded links and save files.
166 $modcontext = context_module
::instance($moduleinfo->coursemodule
);
167 if (!empty($introeditor)) {
168 // This will respect a module that has set a value for intro in it's modname_add_instance() function.
169 $introeditor['text'] = $moduleinfo->intro
;
171 $moduleinfo->intro
= file_save_draft_area_files($introeditor['itemid'], $modcontext->id
,
172 'mod_'.$moduleinfo->modulename
, 'intro', 0,
173 array('subdirs'=>true), $introeditor['text']);
174 $DB->set_field($moduleinfo->modulename
, 'intro', $moduleinfo->intro
, array('id'=>$moduleinfo->instance
));
178 if (core_tag_tag
::is_enabled('core', 'course_modules') && isset($moduleinfo->tags
)) {
179 core_tag_tag
::set_item_tags('core', 'course_modules', $moduleinfo->coursemodule
, $modcontext, $moduleinfo->tags
);
182 // Course_modules and course_sections each contain a reference to each other.
183 // So we have to update one of them twice.
184 $sectionid = course_add_cm_to_section($course, $moduleinfo->coursemodule
, $moduleinfo->section
, $moduleinfo->beforemod
);
186 // Trigger event based on the action we did.
187 // Api create_from_cm expects modname and id property, and we don't want to modify $moduleinfo since we are returning it.
188 $eventdata = clone $moduleinfo;
189 $eventdata->modname
= $eventdata->modulename
;
190 $eventdata->id
= $eventdata->coursemodule
;
191 $event = \core\event\course_module_created
::create_from_cm($eventdata, $modcontext);
194 $moduleinfo = edit_module_post_actions($moduleinfo, $course);
195 $transaction->allow_commit();
201 * Hook for plugins to take action when a module is created or updated.
203 * @param stdClass $moduleinfo the module info
204 * @param stdClass $course the course of the module
206 * @return stdClass moduleinfo updated by plugins.
208 function plugin_extend_coursemodule_edit_post_actions($moduleinfo, $course) {
209 $callbacks = get_plugins_with_function('coursemodule_edit_post_actions', 'lib.php');
210 foreach ($callbacks as $type => $plugins) {
211 foreach ($plugins as $plugin => $pluginfunction) {
212 $moduleinfo = $pluginfunction($moduleinfo, $course);
219 * Common create/update module module actions that need to be processed as soon as a module is created/updaded.
220 * For example:create grade parent category, add outcomes, rebuild caches, regrade, save plagiarism settings...
221 * Please note this api does not trigger events as of MOODLE 2.6. Please trigger events before calling this api.
223 * @param object $moduleinfo the module info
224 * @param object $course the course of the module
226 * @return object moduleinfo update with grading management info
228 function edit_module_post_actions($moduleinfo, $course) {
230 require_once($CFG->libdir
.'/gradelib.php');
232 $modcontext = context_module
::instance($moduleinfo->coursemodule
);
233 $hasgrades = plugin_supports('mod', $moduleinfo->modulename
, FEATURE_GRADE_HAS_GRADE
, false);
234 $hasoutcomes = plugin_supports('mod', $moduleinfo->modulename
, FEATURE_GRADE_OUTCOMES
, true);
236 $items = grade_item
::fetch_all([
238 'itemmodule' => $moduleinfo->modulename
,
239 'iteminstance' => $moduleinfo->instance
,
240 'courseid' => $course->id
,
243 // Create parent category if requested and move to correct parent category.
244 $component = "mod_{$moduleinfo->modulename}";
246 foreach ($items as $item) {
249 // Sync idnumber with grade_item.
250 // Note: This only happens for itemnumber 0 at this time.
251 if ($item->itemnumber
== 0 && ($item->idnumber
!= $moduleinfo->cmidnumber
)) {
252 $item->idnumber
= $moduleinfo->cmidnumber
;
256 // Determine the grade category.
257 $gradecatfieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $item->itemnumber
, 'gradecat');
258 if (property_exists($moduleinfo, $gradecatfieldname)) {
259 $gradecat = $moduleinfo->$gradecatfieldname;
260 if ($gradecat == -1) {
261 $gradecategory = new grade_category();
262 $gradecategory->courseid
= $course->id
;
263 $gradecategory->fullname
= $moduleinfo->name
;
264 $gradecategory->insert();
266 $parent = $item->get_parent_category();
267 $gradecategory->set_parent($parent->id
);
268 $gradecat = $gradecategory->id
;
272 if ($parent = $item->get_parent_category()) {
273 $oldgradecat = $parent->id
;
275 if ($oldgradecat != $gradecat) {
276 $item->set_parent($gradecat);
281 // Determine the gradepass.
282 $gradepassfieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $item->itemnumber
, 'gradepass');
283 if (isset($moduleinfo->{$gradepassfieldname})) {
284 $gradepass = $moduleinfo->{$gradepassfieldname};
285 if (null !== $gradepass && $gradepass != $item->gradepass
) {
286 $item->gradepass
= $gradepass;
295 if (!empty($moduleinfo->add
)) {
296 $gradecategory = $item->get_parent_category();
297 if ($item->set_aggregation_fields_for_aggregation(0, $gradecategory->aggregation
)) {
304 require_once($CFG->libdir
.'/grade/grade_outcome.php');
305 // Add outcomes if requested.
306 if ($hasoutcomes && $outcomes = grade_outcome
::fetch_all_available($course->id
)) {
307 // Outcome grade_item.itemnumber start at 1000, there is nothing above outcomes.
308 $max_itemnumber = 999;
310 foreach($items as $item) {
311 if ($item->itemnumber
> $max_itemnumber) {
312 $max_itemnumber = $item->itemnumber
;
317 foreach($outcomes as $outcome) {
318 $elname = 'outcome_'.$outcome->id
;
320 if (property_exists($moduleinfo, $elname) and $moduleinfo->$elname) {
321 // Check if this is a new outcome grade item.
322 $outcomeexists = false;
324 foreach($items as $item) {
325 if ($item->outcomeid
== $outcome->id
) {
326 $outcomeexists = true;
330 if ($outcomeexists) {
337 $outcomeitem = new grade_item();
338 $outcomeitem->courseid
= $course->id
;
339 $outcomeitem->itemtype
= 'mod';
340 $outcomeitem->itemmodule
= $moduleinfo->modulename
;
341 $outcomeitem->iteminstance
= $moduleinfo->instance
;
342 $outcomeitem->itemnumber
= $max_itemnumber;
343 $outcomeitem->itemname
= $outcome->fullname
;
344 $outcomeitem->outcomeid
= $outcome->id
;
345 $outcomeitem->gradetype
= GRADE_TYPE_SCALE
;
346 $outcomeitem->scaleid
= $outcome->scaleid
;
347 $outcomeitem->insert();
350 // Move the new outcome into the same category and immediately after the first grade item.
351 $item = reset($items);
352 $outcomeitem->set_parent($item->categoryid
);
353 $outcomeitem->move_after_sortorder($item->sortorder
);
354 } else if (isset($moduleinfo->gradecat
)) {
355 $outcomeitem->set_parent($moduleinfo->gradecat
);
358 if (!$outcomeexists) {
359 $gradecategory = $outcomeitem->get_parent_category();
360 if ($outcomeitem->set_aggregation_fields_for_aggregation(0, $gradecategory->aggregation
)) {
361 $outcomeitem->update();
368 if (plugin_supports('mod', $moduleinfo->modulename
, FEATURE_ADVANCED_GRADING
, false)
369 and has_capability('moodle/grade:managegradingforms', $modcontext)) {
370 require_once($CFG->dirroot
.'/grade/grading/lib.php');
371 $gradingman = get_grading_manager($modcontext, 'mod_'.$moduleinfo->modulename
);
372 $showgradingmanagement = false;
373 foreach ($gradingman->get_available_areas() as $areaname => $aretitle) {
374 $formfield = 'advancedgradingmethod_'.$areaname;
375 if (isset($moduleinfo->{$formfield})) {
376 $gradingman->set_area($areaname);
377 $methodchanged = $gradingman->set_active_method($moduleinfo->{$formfield});
378 if (empty($moduleinfo->{$formfield})) {
379 // Going back to the simple direct grading is not a reason to open the management screen.
380 $methodchanged = false;
382 $showgradingmanagement = $showgradingmanagement ||
$methodchanged;
385 // Update grading management information.
386 $moduleinfo->gradingman
= $gradingman;
387 $moduleinfo->showgradingmanagement
= $showgradingmanagement;
390 \course_modinfo
::purge_course_module_cache($course->id
, $moduleinfo->coursemodule
);
391 rebuild_course_cache($course->id
, true, true);
394 // If regrading will be slow, and this is happening in response to front-end UI...
395 if (!empty($moduleinfo->frontend
) && grade_needs_regrade_progress_bar($course->id
)) {
396 // And if it actually needs regrading...
397 $courseitem = grade_item
::fetch_course_item($course->id
);
398 if ($courseitem->needsupdate
) {
399 // Then don't do it as part of this form save, do it on an extra web request with a
401 $moduleinfo->needsfrontendregrade
= true;
405 grade_regrade_final_grades($course->id
);
409 // Allow plugins to extend the course module form.
410 $moduleinfo = plugin_extend_coursemodule_edit_post_actions($moduleinfo, $course);
412 if (!empty($moduleinfo->coursecontentnotification
)) {
413 // Schedule adhoc-task for delivering the course content updated notification.
414 if ($course->visible
&& $moduleinfo->visible
) {
415 $adhocktask = new \core_course\task\
content_notification_task();
416 $adhocktask->set_custom_data(
417 ['update' => $moduleinfo->update
, 'cmid' => $moduleinfo->coursemodule
,
418 'courseid' => $course->id
, 'userfrom' => $USER->id
]);
419 $adhocktask->set_component('course');
420 \core\task\manager
::queue_adhoc_task($adhocktask, true);
428 * Set module info default values for the unset module attributs.
430 * @param object $moduleinfo the current known data of the module
431 * @return object the completed module info
433 function set_moduleinfo_defaults($moduleinfo) {
435 if (empty($moduleinfo->coursemodule
)) {
438 $moduleinfo->instance
= '';
439 $moduleinfo->coursemodule
= '';
442 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule
, 0, false, MUST_EXIST
);
443 $moduleinfo->instance
= $cm->instance
;
444 $moduleinfo->coursemodule
= $cm->id
;
447 $moduleinfo->modulename
= clean_param($moduleinfo->modulename
, PARAM_PLUGIN
);
449 if (!isset($moduleinfo->groupingid
)) {
450 $moduleinfo->groupingid
= 0;
453 if (!isset($moduleinfo->name
)) { // Label.
454 $moduleinfo->name
= $moduleinfo->modulename
;
457 if (!isset($moduleinfo->completion
)) {
458 $moduleinfo->completion
= COMPLETION_DISABLED
;
460 if (!isset($moduleinfo->completionview
)) {
461 $moduleinfo->completionview
= COMPLETION_VIEW_NOT_REQUIRED
;
463 if (!isset($moduleinfo->completionexpected
)) {
464 $moduleinfo->completionexpected
= 0;
467 // Convert the 'use grade' checkbox into a grade-item number: 0 if checked, null if not.
468 if (isset($moduleinfo->completionusegrade
) &&
469 $moduleinfo->completionusegrade
&&
470 !isset($moduleinfo->completiongradeitemnumber
472 $moduleinfo->completiongradeitemnumber
= 0;
473 } else if (!isset($moduleinfo->completiongradeitemnumber
)) {
474 // If there is no gradeitemnumber set, make sure to disable completionpassgrade.
475 $moduleinfo->completionpassgrade
= 0;
476 $moduleinfo->completiongradeitemnumber
= null;
479 if (!isset($moduleinfo->conditiongradegroup
)) {
480 $moduleinfo->conditiongradegroup
= array();
482 if (!isset($moduleinfo->conditionfieldgroup
)) {
483 $moduleinfo->conditionfieldgroup
= array();
485 if (!isset($moduleinfo->visibleoncoursepage
)) {
486 $moduleinfo->visibleoncoursepage
= 1;
489 if (!isset($moduleinfo->downloadcontent
)) {
490 $moduleinfo->downloadcontent
= DOWNLOAD_COURSE_CONTENT_ENABLED
;
497 * Check that the user can add a module. Also returns some information like the module, context and course section info.
498 * The fucntion create the course section if it doesn't exist.
500 * @param object $course the course of the module
501 * @param string $modulename the module name
502 * @param int $sectionnum the section of the module
503 * @return array list containing module, context, course section.
504 * @throws moodle_exception if user is not allowed to perform the action or module is not allowed in this course
506 function can_add_moduleinfo($course, $modulename, $sectionnum) {
509 $module = $DB->get_record('modules', ['name' => $modulename], '*', MUST_EXIST
);
511 $context = context_course
::instance($course->id
);
512 require_capability('moodle/course:manageactivities', $context);
514 // If the $sectionnum is a delegated section, we cannot execute create_if_missing
515 // because it only works to create regular sections. To prevent that from happening, we
516 // check if the section is already there, no matter if it is delegated or not.
517 $sectioninfo = get_fast_modinfo($course)->get_section_info($sectionnum);
519 formatactions
::section($course)->create_if_missing([$sectionnum]);
520 $sectioninfo = get_fast_modinfo($course)->get_section_info($sectionnum);
523 if (!course_allowed_module($course, $module->name
)) {
524 throw new \
moodle_exception('moduledisable');
527 return [$module, $context, $sectioninfo];
531 * Check if user is allowed to update module info and returns related item/data to the module.
533 * @param object $cm course module
534 * @return array - list of course module, context, module, moduleinfo, and course section.
535 * @throws moodle_exception if user is not allowed to perform the action
537 function can_update_moduleinfo($cm) {
540 // Check the $USER has the right capability.
541 $context = context_module
::instance($cm->id
);
542 require_capability('moodle/course:manageactivities', $context);
544 // Check module exists.
545 $module = $DB->get_record('modules', array('id'=>$cm->module
), '*', MUST_EXIST
);
547 // Check the moduleinfo exists.
548 $data = $DB->get_record($module->name
, array('id'=>$cm->instance
), '*', MUST_EXIST
);
550 // Check the course section exists.
551 $cw = $DB->get_record('course_sections', array('id'=>$cm->section
), '*', MUST_EXIST
);
553 return array($cm, $context, $module, $data, $cw);
558 * Update the module info.
559 * This function doesn't check the user capabilities. It updates the course module and the module instance.
560 * Then execute common action to create/update module process (trigger event, rebuild cache, save plagiarism settings...).
562 * @param object $cm course module
563 * @param object $moduleinfo module info
564 * @param object $course course of the module
565 * @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.
566 * @return array list of course module and module info.
568 function update_moduleinfo($cm, $moduleinfo, $course, $mform = null) {
571 $data = new stdClass();
573 $data = $mform->get_data();
576 // Attempt to include module library before we make any changes to DB.
577 include_modulelib($moduleinfo->modulename
);
579 $moduleinfo->course
= $course->id
;
580 $moduleinfo = set_moduleinfo_defaults($moduleinfo);
582 $modcontext = context_module
::instance($moduleinfo->coursemodule
);
583 if (has_capability('moodle/course:setforcedlanguage', $modcontext)) {
584 $cm->lang
= $moduleinfo->lang ??
null;
589 if (!empty($course->groupmodeforce
) or !isset($moduleinfo->groupmode
)) {
590 $moduleinfo->groupmode
= $cm->groupmode
; // Keep original.
593 // Update course module first.
594 $cm->groupmode
= $moduleinfo->groupmode
;
595 if (isset($moduleinfo->groupingid
)) {
596 $cm->groupingid
= $moduleinfo->groupingid
;
599 $completion = new completion_info($course);
600 if ($completion->is_enabled()) {
601 // Completion settings that would affect users who have already completed
602 // the activity may be locked; if so, these should not be updated.
603 if (!empty($moduleinfo->completionunlocked
)) {
604 $cm->completion
= $moduleinfo->completion
;
605 $cm->completionpassgrade
= $moduleinfo->completionpassgrade ??
0;
606 if ($moduleinfo->completiongradeitemnumber
=== '') {
607 $cm->completiongradeitemnumber
= null;
609 $cm->completiongradeitemnumber
= $moduleinfo->completiongradeitemnumber
;
611 $cm->completionview
= $moduleinfo->completionview
;
613 // The expected date does not affect users who have completed the activity,
614 // so it is safe to update it regardless of the lock status.
615 $cm->completionexpected
= $moduleinfo->completionexpected
;
617 if (!empty($CFG->enableavailability
)) {
618 // This code is used both when submitting the form, which uses a long
619 // name to avoid clashes, and by unit test code which uses the real
620 // name in the table.
621 if (property_exists($moduleinfo, 'availabilityconditionsjson')) {
622 if ($moduleinfo->availabilityconditionsjson
!== '') {
623 $cm->availability
= $moduleinfo->availabilityconditionsjson
;
625 $cm->availability
= null;
627 } else if (property_exists($moduleinfo, 'availability')) {
628 $cm->availability
= $moduleinfo->availability
;
630 // If there is any availability data, verify it.
631 if ($cm->availability
) {
632 $tree = new \core_availability\tree
(json_decode($cm->availability
));
633 // Save time and database space by setting null if the only data
635 if ($tree->is_empty()) {
636 $cm->availability
= null;
640 if (isset($moduleinfo->showdescription
)) {
641 $cm->showdescription
= $moduleinfo->showdescription
;
643 $cm->showdescription
= 0;
646 $DB->update_record('course_modules', $cm);
648 // Update embedded links and save files.
649 if (plugin_supports('mod', $moduleinfo->modulename
, FEATURE_MOD_INTRO
, true)) {
650 $moduleinfo->intro
= file_save_draft_area_files($moduleinfo->introeditor
['itemid'], $modcontext->id
,
651 'mod_'.$moduleinfo->modulename
, 'intro', 0,
652 array('subdirs'=>true), $moduleinfo->introeditor
['text']);
653 $moduleinfo->introformat
= $moduleinfo->introeditor
['format'];
654 unset($moduleinfo->introeditor
);
656 // Get the a copy of the grade_item before it is modified incase we need to scale the grades.
657 $oldgradeitem = null;
658 $newgradeitem = null;
659 if (!empty($data->grade_rescalegrades
) && $data->grade_rescalegrades
== 'yes') {
660 // Fetch the grade item before it is updated.
661 $oldgradeitem = grade_item
::fetch(array('itemtype' => 'mod',
662 'itemmodule' => $moduleinfo->modulename
,
663 'iteminstance' => $moduleinfo->instance
,
665 'courseid' => $moduleinfo->course
));
668 $updateinstancefunction = $moduleinfo->modulename
."_update_instance";
669 if (!$updateinstancefunction($moduleinfo, $mform)) {
670 throw new \
moodle_exception('cannotupdatemod', '', course_get_url($course, $cm->section
), $moduleinfo->modulename
);
673 // This needs to happen AFTER the grademin/grademax have already been updated.
674 if (!empty($data->grade_rescalegrades
) && $data->grade_rescalegrades
== 'yes') {
675 // Get the grade_item after the update call the activity to scale the grades.
676 $newgradeitem = grade_item
::fetch(array('itemtype' => 'mod',
677 'itemmodule' => $moduleinfo->modulename
,
678 'iteminstance' => $moduleinfo->instance
,
680 'courseid' => $moduleinfo->course
));
681 if ($newgradeitem && $oldgradeitem->gradetype
== GRADE_TYPE_VALUE
&& $newgradeitem->gradetype
== GRADE_TYPE_VALUE
) {
685 $oldgradeitem->grademin
,
686 $oldgradeitem->grademax
,
687 $newgradeitem->grademin
,
688 $newgradeitem->grademax
690 if (!component_callback('mod_' . $moduleinfo->modulename
, 'rescale_activity_grades', $params)) {
691 throw new \
moodle_exception('cannotreprocessgrades', '', course_get_url($course, $cm->section
),
692 $moduleinfo->modulename
);
697 // Make sure visibility is set correctly (in particular in calendar).
698 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
699 set_coursemodule_visible($moduleinfo->coursemodule
, $moduleinfo->visible
, $moduleinfo->visibleoncoursepage
);
702 if (isset($moduleinfo->cmidnumber
)) { // Label.
703 // Set cm idnumber - uniqueness is already verified by form validation.
704 set_coursemodule_idnumber($moduleinfo->coursemodule
, $moduleinfo->cmidnumber
);
707 if (isset($moduleinfo->downloadcontent
)) {
708 set_downloadcontent($moduleinfo->coursemodule
, $moduleinfo->downloadcontent
);
711 // Update module tags.
712 if (core_tag_tag
::is_enabled('core', 'course_modules') && isset($moduleinfo->tags
)) {
713 core_tag_tag
::set_item_tags('core', 'course_modules', $moduleinfo->coursemodule
, $modcontext, $moduleinfo->tags
);
715 $moduleinfo = edit_module_post_actions($moduleinfo, $course);
717 // Now that module is fully updated, also update completion data if required.
718 // (this will wipe all user completion data and recalculate it)
719 if ($completion->is_enabled() && !empty($moduleinfo->completionunlocked
)) {
720 // Rebuild course cache before resetting completion states to ensure that the cm_info attributes are up to date.
721 course_modinfo
::build_course_cache($course);
722 // Fetch this course module's info.
723 $cminfo = cm_info
::create($cm);
724 $completion->reset_all_state($cminfo);
727 if ($cm->name
!= $moduleinfo->name
) {
728 $hook = new \core_courseformat\hook\after_cm_name_edited
(
729 get_fast_modinfo($course)->get_cm($cm->id
),
732 \core\hook\manager
::get_instance()->dispatch($hook);
735 $cm->name
= $moduleinfo->name
;
736 \core\event\course_module_updated
::create_from_cm($cm, $modcontext)->trigger();
738 return array($cm, $moduleinfo);
742 * Include once the module lib file.
744 * @param string $modulename module name of the lib to include
745 * @throws moodle_exception if lib.php file for the module does not exist
747 function include_modulelib($modulename) {
749 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
750 if (file_exists($modlib)) {
751 include_once($modlib);
753 throw new moodle_exception('modulemissingcode', '', '', $modlib);
758 * Get module information data required for updating the module.
760 * @param stdClass $cm course module object
761 * @param stdClass $course course object
762 * @return array required data for updating a module
765 function get_moduleinfo_data($cm, $course) {
768 list($cm, $context, $module, $data, $cw) = can_update_moduleinfo($cm);
770 $data->coursemodule
= $cm->id
;
771 $data->section
= $cw->section
; // The section number itself - relative!!! (section column in course_sections)
772 $data->visible
= $cm->visible
; //?? $cw->visible ? $cm->visible : 0; // section hiding overrides
773 $data->visibleoncoursepage
= $cm->visibleoncoursepage
;
774 $data->cmidnumber
= $cm->idnumber
; // The cm IDnumber
775 $data->groupmode
= groups_get_activity_groupmode($cm); // locked later if forced
776 $data->groupingid
= $cm->groupingid
;
777 $data->course
= $course->id
;
778 $data->module
= $module->id
;
779 $data->modulename
= $module->name
;
780 $data->instance
= $cm->instance
;
781 $data->completion
= $cm->completion
;
782 $data->completionview
= $cm->completionview
;
783 $data->completionexpected
= $cm->completionexpected
;
784 $data->completionusegrade
= is_null($cm->completiongradeitemnumber
) ?
0 : 1;
785 $data->completionpassgrade
= $cm->completionpassgrade
;
786 $data->completiongradeitemnumber
= $cm->completiongradeitemnumber
;
787 $data->showdescription
= $cm->showdescription
;
788 $data->downloadcontent
= $cm->downloadcontent
;
789 $data->lang
= $cm->lang
;
790 $data->tags
= core_tag_tag
::get_item_tags_array('core', 'course_modules', $cm->id
);
791 if (!empty($CFG->enableavailability
)) {
792 $data->availabilityconditionsjson
= $cm->availability
;
795 if (plugin_supports('mod', $data->modulename
, FEATURE_MOD_INTRO
, true)) {
796 $draftid_editor = file_get_submitted_draft_itemid('introeditor');
797 $currentintro = file_prepare_draft_area($draftid_editor, $context->id
, 'mod_'.$data->modulename
, 'intro', 0, array('subdirs'=>true), $data->intro
);
798 $data->introeditor
= array('text'=>$currentintro, 'format'=>$data->introformat
, 'itemid'=>$draftid_editor);
801 if (plugin_supports('mod', $data->modulename
, FEATURE_ADVANCED_GRADING
, false)
802 and has_capability('moodle/grade:managegradingforms', $context)) {
803 require_once($CFG->dirroot
.'/grade/grading/lib.php');
804 $gradingman = get_grading_manager($context, 'mod_'.$data->modulename
);
805 $data->_advancedgradingdata
['methods'] = $gradingman->get_available_methods();
806 $areas = $gradingman->get_available_areas();
808 foreach ($areas as $areaname => $areatitle) {
809 $gradingman->set_area($areaname);
810 $method = $gradingman->get_active_method();
811 $data->_advancedgradingdata
['areas'][$areaname] = array(
812 'title' => $areatitle,
815 $formfield = 'advancedgradingmethod_'.$areaname;
816 $data->{$formfield} = $method;
820 $component = "mod_{$data->modulename}";
821 $items = grade_item
::fetch_all([
823 'itemmodule' => $data->modulename
,
824 'iteminstance' => $data->instance
,
825 'courseid' => $course->id
,
829 // Add existing outcomes.
830 foreach ($items as $item) {
831 if (!empty($item->outcomeid
)) {
832 $data->{'outcome_' . $item->outcomeid
} = 1;
833 } else if (isset($item->gradepass
)) {
834 $gradepassfieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $item->itemnumber
, 'gradepass');
835 $data->{$gradepassfieldname} = format_float($item->gradepass
, $item->get_decimals());
840 // set category if present
842 foreach ($items as $item) {
843 if (!isset($gradecat[$item->itemnumber
])) {
844 $gradecat[$item->itemnumber
] = $item->categoryid
;
846 if ($gradecat[$item->itemnumber
] != $item->categoryid
) {
848 $gradecat[$item->itemnumber
] = false;
851 foreach ($gradecat as $itemnumber => $cat) {
852 if ($cat !== false) {
853 $gradecatfieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $itemnumber, 'gradecat');
854 // Do not set if mixed categories present.
855 $data->{$gradecatfieldname} = $cat;
859 return array($cm, $context, $module, $data, $cw);
863 * Prepare the standard module information for a new module instance.
865 * @param stdClass $course course object
866 * @param string $modulename module name
867 * @param int $section section number
868 * @param string $suffix the suffix to add to the name of the completion rules.
869 * @return array module information about other required data
872 function prepare_new_moduleinfo_data($course, $modulename, $section, string $suffix = '') {
875 list($module, $context, $cw) = can_add_moduleinfo($course, $modulename, $section);
879 $data = new stdClass();
880 $data->section
= $section; // The section number itself - relative!!! (section column in course_sections)
881 $data->visible
= $cw->visible
;
882 $data->course
= $course->id
;
883 $data->module
= $module->id
;
884 $data->modulename
= $module->name
;
885 $data->groupmode
= $course->groupmode
;
886 $data->groupingid
= $course->defaultgroupingid
;
888 $data->instance
= '';
889 $data->coursemodule
= '';
890 $data->downloadcontent
= DOWNLOAD_COURSE_CONTENT_ENABLED
;
892 // Apply completion defaults.
893 $defaults = \core_completion\manager
::get_default_completion($course, $module, true, $suffix);
894 foreach ($defaults as $key => $value) {
895 $data->$key = $value;
898 if (plugin_supports('mod', $data->modulename
, FEATURE_MOD_INTRO
, true)) {
899 $draftid_editor = file_get_submitted_draft_itemid('introeditor');
900 file_prepare_draft_area($draftid_editor, null, null, null, null, array('subdirs'=>true));
901 $data->introeditor
= array('text' => '', 'format' => editors_get_preferred_format(), 'itemid' => $draftid_editor);
904 if (plugin_supports('mod', $data->modulename
, FEATURE_ADVANCED_GRADING
, false)
905 and has_capability('moodle/grade:managegradingforms', $context)) {
906 require_once($CFG->dirroot
.'/grade/grading/lib.php');
908 $data->_advancedgradingdata
['methods'] = grading_manager
::available_methods();
909 $areas = grading_manager
::available_areas('mod_'.$module->name
);
911 foreach ($areas as $areaname => $areatitle) {
912 $data->_advancedgradingdata
['areas'][$areaname] = array(
913 'title' => $areatitle,
916 $formfield = 'advancedgradingmethod_'.$areaname;
917 $data->{$formfield} = '';
921 return array($module, $context, $cw, $cm, $data);