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);
726 $cm->name
= $moduleinfo->name
;
727 \core\event\course_module_updated
::create_from_cm($cm, $modcontext)->trigger();
729 return array($cm, $moduleinfo);
733 * Include once the module lib file.
735 * @param string $modulename module name of the lib to include
736 * @throws moodle_exception if lib.php file for the module does not exist
738 function include_modulelib($modulename) {
740 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
741 if (file_exists($modlib)) {
742 include_once($modlib);
744 throw new moodle_exception('modulemissingcode', '', '', $modlib);
749 * Get module information data required for updating the module.
751 * @param stdClass $cm course module object
752 * @param stdClass $course course object
753 * @return array required data for updating a module
756 function get_moduleinfo_data($cm, $course) {
759 list($cm, $context, $module, $data, $cw) = can_update_moduleinfo($cm);
761 $data->coursemodule
= $cm->id
;
762 $data->section
= $cw->section
; // The section number itself - relative!!! (section column in course_sections)
763 $data->visible
= $cm->visible
; //?? $cw->visible ? $cm->visible : 0; // section hiding overrides
764 $data->visibleoncoursepage
= $cm->visibleoncoursepage
;
765 $data->cmidnumber
= $cm->idnumber
; // The cm IDnumber
766 $data->groupmode
= groups_get_activity_groupmode($cm); // locked later if forced
767 $data->groupingid
= $cm->groupingid
;
768 $data->course
= $course->id
;
769 $data->module
= $module->id
;
770 $data->modulename
= $module->name
;
771 $data->instance
= $cm->instance
;
772 $data->completion
= $cm->completion
;
773 $data->completionview
= $cm->completionview
;
774 $data->completionexpected
= $cm->completionexpected
;
775 $data->completionusegrade
= is_null($cm->completiongradeitemnumber
) ?
0 : 1;
776 $data->completionpassgrade
= $cm->completionpassgrade
;
777 $data->completiongradeitemnumber
= $cm->completiongradeitemnumber
;
778 $data->showdescription
= $cm->showdescription
;
779 $data->downloadcontent
= $cm->downloadcontent
;
780 $data->lang
= $cm->lang
;
781 $data->tags
= core_tag_tag
::get_item_tags_array('core', 'course_modules', $cm->id
);
782 if (!empty($CFG->enableavailability
)) {
783 $data->availabilityconditionsjson
= $cm->availability
;
786 if (plugin_supports('mod', $data->modulename
, FEATURE_MOD_INTRO
, true)) {
787 $draftid_editor = file_get_submitted_draft_itemid('introeditor');
788 $currentintro = file_prepare_draft_area($draftid_editor, $context->id
, 'mod_'.$data->modulename
, 'intro', 0, array('subdirs'=>true), $data->intro
);
789 $data->introeditor
= array('text'=>$currentintro, 'format'=>$data->introformat
, 'itemid'=>$draftid_editor);
792 if (plugin_supports('mod', $data->modulename
, FEATURE_ADVANCED_GRADING
, false)
793 and has_capability('moodle/grade:managegradingforms', $context)) {
794 require_once($CFG->dirroot
.'/grade/grading/lib.php');
795 $gradingman = get_grading_manager($context, 'mod_'.$data->modulename
);
796 $data->_advancedgradingdata
['methods'] = $gradingman->get_available_methods();
797 $areas = $gradingman->get_available_areas();
799 foreach ($areas as $areaname => $areatitle) {
800 $gradingman->set_area($areaname);
801 $method = $gradingman->get_active_method();
802 $data->_advancedgradingdata
['areas'][$areaname] = array(
803 'title' => $areatitle,
806 $formfield = 'advancedgradingmethod_'.$areaname;
807 $data->{$formfield} = $method;
811 $component = "mod_{$data->modulename}";
812 $items = grade_item
::fetch_all([
814 'itemmodule' => $data->modulename
,
815 'iteminstance' => $data->instance
,
816 'courseid' => $course->id
,
820 // Add existing outcomes.
821 foreach ($items as $item) {
822 if (!empty($item->outcomeid
)) {
823 $data->{'outcome_' . $item->outcomeid
} = 1;
824 } else if (isset($item->gradepass
)) {
825 $gradepassfieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $item->itemnumber
, 'gradepass');
826 $data->{$gradepassfieldname} = format_float($item->gradepass
, $item->get_decimals());
831 // set category if present
833 foreach ($items as $item) {
834 if (!isset($gradecat[$item->itemnumber
])) {
835 $gradecat[$item->itemnumber
] = $item->categoryid
;
837 if ($gradecat[$item->itemnumber
] != $item->categoryid
) {
839 $gradecat[$item->itemnumber
] = false;
842 foreach ($gradecat as $itemnumber => $cat) {
843 if ($cat !== false) {
844 $gradecatfieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $itemnumber, 'gradecat');
845 // Do not set if mixed categories present.
846 $data->{$gradecatfieldname} = $cat;
850 return array($cm, $context, $module, $data, $cw);
854 * Prepare the standard module information for a new module instance.
856 * @param stdClass $course course object
857 * @param string $modulename module name
858 * @param int $section section number
859 * @param string $suffix the suffix to add to the name of the completion rules.
860 * @return array module information about other required data
863 function prepare_new_moduleinfo_data($course, $modulename, $section, string $suffix = '') {
866 list($module, $context, $cw) = can_add_moduleinfo($course, $modulename, $section);
870 $data = new stdClass();
871 $data->section
= $section; // The section number itself - relative!!! (section column in course_sections)
872 $data->visible
= $cw->visible
;
873 $data->course
= $course->id
;
874 $data->module
= $module->id
;
875 $data->modulename
= $module->name
;
876 $data->groupmode
= $course->groupmode
;
877 $data->groupingid
= $course->defaultgroupingid
;
879 $data->instance
= '';
880 $data->coursemodule
= '';
881 $data->downloadcontent
= DOWNLOAD_COURSE_CONTENT_ENABLED
;
883 // Apply completion defaults.
884 $defaults = \core_completion\manager
::get_default_completion($course, $module, true, $suffix);
885 foreach ($defaults as $key => $value) {
886 $data->$key = $value;
889 if (plugin_supports('mod', $data->modulename
, FEATURE_MOD_INTRO
, true)) {
890 $draftid_editor = file_get_submitted_draft_itemid('introeditor');
891 file_prepare_draft_area($draftid_editor, null, null, null, null, array('subdirs'=>true));
892 $data->introeditor
= array('text' => '', 'format' => editors_get_preferred_format(), 'itemid' => $draftid_editor);
895 if (plugin_supports('mod', $data->modulename
, FEATURE_ADVANCED_GRADING
, false)
896 and has_capability('moodle/grade:managegradingforms', $context)) {
897 require_once($CFG->dirroot
.'/grade/grading/lib.php');
899 $data->_advancedgradingdata
['methods'] = grading_manager
::available_methods();
900 $areas = grading_manager
::available_areas('mod_'.$module->name
);
902 foreach ($areas as $areaname => $areatitle) {
903 $data->_advancedgradingdata
['areas'][$areaname] = array(
904 'title' => $areatitle,
907 $formfield = 'advancedgradingmethod_'.$areaname;
908 $data->{$formfield} = '';
912 return array($module, $context, $cw, $cm, $data);