Merge branch 'MDL-73784-master' of https://github.com/HuongNV13/moodle
[moodle.git] / course / modlib.php
blobc2b3bd8c8ebda40eeffca833579ec7d611a601f0
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Library of functions specific to course/modedit.php and course API functions.
19 * The course API function calling them are course/lib.php:create_module() and update_module().
20 * This file has been created has an alternative solution to a full refactor of course/modedit.php
21 * in order to create the course API functions.
23 * @copyright 2013 Jerome Mouneyrac
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 * @package core_course
28 defined('MOODLE_INTERNAL') || die;
30 use \core_grades\component_gradeitems;
32 require_once($CFG->dirroot.'/course/lib.php');
34 /**
35 * Add course module.
37 * The function does not check user capabilities.
38 * The function creates course module, module instance, add the module to the correct section.
39 * It also trigger common action that need to be done after adding/updating a module.
41 * @param object $moduleinfo the moudle data
42 * @param object $course the course of the module
43 * @param object $mform this is required by an existing hack to deal with files during MODULENAME_add_instance()
44 * @return object the updated module info
46 function add_moduleinfo($moduleinfo, $course, $mform = null) {
47 global $DB, $CFG;
49 // Attempt to include module library before we make any changes to DB.
50 include_modulelib($moduleinfo->modulename);
52 $moduleinfo->course = $course->id;
53 $moduleinfo = set_moduleinfo_defaults($moduleinfo);
55 if (!empty($course->groupmodeforce) or !isset($moduleinfo->groupmode)) {
56 $moduleinfo->groupmode = 0; // Do not set groupmode.
59 // First add course_module record because we need the context.
60 $newcm = new stdClass();
61 $newcm->course = $course->id;
62 $newcm->module = $moduleinfo->module;
63 $newcm->instance = 0; // Not known yet, will be updated later (this is similar to restore code).
64 $newcm->visible = $moduleinfo->visible;
65 $newcm->visibleold = $moduleinfo->visible;
66 $newcm->visibleoncoursepage = $moduleinfo->visibleoncoursepage;
67 if (isset($moduleinfo->cmidnumber)) {
68 $newcm->idnumber = $moduleinfo->cmidnumber;
70 if (isset($moduleinfo->downloadcontent)) {
71 $newcm->downloadcontent = $moduleinfo->downloadcontent;
73 $newcm->groupmode = $moduleinfo->groupmode;
74 $newcm->groupingid = $moduleinfo->groupingid;
75 $completion = new completion_info($course);
76 if ($completion->is_enabled()) {
77 $newcm->completion = $moduleinfo->completion;
78 $newcm->completionpassgrade = $moduleinfo->completionpassgrade ?? 0;
79 if ($moduleinfo->completiongradeitemnumber === '') {
80 $newcm->completiongradeitemnumber = null;
81 } else {
82 $newcm->completiongradeitemnumber = $moduleinfo->completiongradeitemnumber;
84 $newcm->completionview = $moduleinfo->completionview;
85 $newcm->completionexpected = $moduleinfo->completionexpected;
87 if(!empty($CFG->enableavailability)) {
88 // This code is used both when submitting the form, which uses a long
89 // name to avoid clashes, and by unit test code which uses the real
90 // name in the table.
91 $newcm->availability = null;
92 if (property_exists($moduleinfo, 'availabilityconditionsjson')) {
93 if ($moduleinfo->availabilityconditionsjson !== '') {
94 $newcm->availability = $moduleinfo->availabilityconditionsjson;
96 } else if (property_exists($moduleinfo, 'availability')) {
97 $newcm->availability = $moduleinfo->availability;
99 // If there is any availability data, verify it.
100 if ($newcm->availability) {
101 $tree = new \core_availability\tree(json_decode($newcm->availability));
102 // Save time and database space by setting null if the only data
103 // is an empty tree.
104 if ($tree->is_empty()) {
105 $newcm->availability = null;
109 if (isset($moduleinfo->showdescription)) {
110 $newcm->showdescription = $moduleinfo->showdescription;
111 } else {
112 $newcm->showdescription = 0;
115 // From this point we make database changes, so start transaction.
116 $transaction = $DB->start_delegated_transaction();
118 if (!$moduleinfo->coursemodule = add_course_module($newcm)) {
119 print_error('cannotaddcoursemodule');
122 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true) &&
123 isset($moduleinfo->introeditor)) {
124 $introeditor = $moduleinfo->introeditor;
125 unset($moduleinfo->introeditor);
126 $moduleinfo->intro = $introeditor['text'];
127 $moduleinfo->introformat = $introeditor['format'];
130 $addinstancefunction = $moduleinfo->modulename."_add_instance";
131 try {
132 $returnfromfunc = $addinstancefunction($moduleinfo, $mform);
133 } catch (moodle_exception $e) {
134 $returnfromfunc = $e;
136 if (!$returnfromfunc or !is_number($returnfromfunc)) {
137 // Undo everything we can. This is not necessary for databases which
138 // support transactions, but improves consistency for other databases.
139 context_helper::delete_instance(CONTEXT_MODULE, $moduleinfo->coursemodule);
140 $DB->delete_records('course_modules', array('id'=>$moduleinfo->coursemodule));
142 if ($returnfromfunc instanceof moodle_exception) {
143 throw $returnfromfunc;
144 } else if (!is_number($returnfromfunc)) {
145 print_error('invalidfunction', '', course_get_url($course, $moduleinfo->section));
146 } else {
147 print_error('cannotaddnewmodule', '', course_get_url($course, $moduleinfo->section), $moduleinfo->modulename);
151 $moduleinfo->instance = $returnfromfunc;
153 $DB->set_field('course_modules', 'instance', $returnfromfunc, array('id'=>$moduleinfo->coursemodule));
155 // Update embedded links and save files.
156 $modcontext = context_module::instance($moduleinfo->coursemodule);
157 if (!empty($introeditor)) {
158 // This will respect a module that has set a value for intro in it's modname_add_instance() function.
159 $introeditor['text'] = $moduleinfo->intro;
161 $moduleinfo->intro = file_save_draft_area_files($introeditor['itemid'], $modcontext->id,
162 'mod_'.$moduleinfo->modulename, 'intro', 0,
163 array('subdirs'=>true), $introeditor['text']);
164 $DB->set_field($moduleinfo->modulename, 'intro', $moduleinfo->intro, array('id'=>$moduleinfo->instance));
167 // Add module tags.
168 if (core_tag_tag::is_enabled('core', 'course_modules') && isset($moduleinfo->tags)) {
169 core_tag_tag::set_item_tags('core', 'course_modules', $moduleinfo->coursemodule, $modcontext, $moduleinfo->tags);
172 // Course_modules and course_sections each contain a reference to each other.
173 // So we have to update one of them twice.
174 $sectionid = course_add_cm_to_section($course, $moduleinfo->coursemodule, $moduleinfo->section);
176 // Trigger event based on the action we did.
177 // Api create_from_cm expects modname and id property, and we don't want to modify $moduleinfo since we are returning it.
178 $eventdata = clone $moduleinfo;
179 $eventdata->modname = $eventdata->modulename;
180 $eventdata->id = $eventdata->coursemodule;
181 $event = \core\event\course_module_created::create_from_cm($eventdata, $modcontext);
182 $event->trigger();
184 $moduleinfo = edit_module_post_actions($moduleinfo, $course);
185 $transaction->allow_commit();
187 return $moduleinfo;
191 * Hook for plugins to take action when a module is created or updated.
193 * @param stdClass $moduleinfo the module info
194 * @param stdClass $course the course of the module
196 * @return stdClass moduleinfo updated by plugins.
198 function plugin_extend_coursemodule_edit_post_actions($moduleinfo, $course) {
199 $callbacks = get_plugins_with_function('coursemodule_edit_post_actions', 'lib.php');
200 foreach ($callbacks as $type => $plugins) {
201 foreach ($plugins as $plugin => $pluginfunction) {
202 $moduleinfo = $pluginfunction($moduleinfo, $course);
205 return $moduleinfo;
209 * Common create/update module module actions that need to be processed as soon as a module is created/updaded.
210 * For example:create grade parent category, add outcomes, rebuild caches, regrade, save plagiarism settings...
211 * Please note this api does not trigger events as of MOODLE 2.6. Please trigger events before calling this api.
213 * @param object $moduleinfo the module info
214 * @param object $course the course of the module
216 * @return object moduleinfo update with grading management info
218 function edit_module_post_actions($moduleinfo, $course) {
219 global $CFG, $USER;
220 require_once($CFG->libdir.'/gradelib.php');
222 $modcontext = context_module::instance($moduleinfo->coursemodule);
223 $hasgrades = plugin_supports('mod', $moduleinfo->modulename, FEATURE_GRADE_HAS_GRADE, false);
224 $hasoutcomes = plugin_supports('mod', $moduleinfo->modulename, FEATURE_GRADE_OUTCOMES, true);
226 $items = grade_item::fetch_all([
227 'itemtype' => 'mod',
228 'itemmodule' => $moduleinfo->modulename,
229 'iteminstance' => $moduleinfo->instance,
230 'courseid' => $course->id,
233 // Create parent category if requested and move to correct parent category.
234 $component = "mod_{$moduleinfo->modulename}";
235 if ($items) {
236 foreach ($items as $item) {
237 $update = false;
239 // Sync idnumber with grade_item.
240 // Note: This only happens for itemnumber 0 at this time.
241 if ($item->itemnumber == 0 && ($item->idnumber != $moduleinfo->cmidnumber)) {
242 $item->idnumber = $moduleinfo->cmidnumber;
243 $update = true;
246 // Determine the grade category.
247 $gradecatfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $item->itemnumber, 'gradecat');
248 if (property_exists($moduleinfo, $gradecatfieldname)) {
249 $gradecat = $moduleinfo->$gradecatfieldname;
250 if ($gradecat == -1) {
251 $gradecategory = new grade_category();
252 $gradecategory->courseid = $course->id;
253 $gradecategory->fullname = $moduleinfo->name;
254 $gradecategory->insert();
256 $parent = $item->get_parent_category();
257 $gradecategory->set_parent($parent->id);
258 $gradecat = $gradecategory->id;
261 $oldgradecat = null;
262 if ($parent = $item->get_parent_category()) {
263 $oldgradecat = $parent->id;
265 if ($oldgradecat != $gradecat) {
266 $item->set_parent($gradecat);
267 $update = true;
271 // Determine the gradepass.
272 $gradepassfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $item->itemnumber, 'gradepass');
273 if (isset($moduleinfo->{$gradepassfieldname})) {
274 $gradepass = $moduleinfo->{$gradepassfieldname};
275 if (null !== $gradepass && $gradepass != $item->gradepass) {
276 $item->gradepass = $gradepass;
277 $update = true;
281 if ($update) {
282 $item->update();
285 if (!empty($moduleinfo->add)) {
286 $gradecategory = $item->get_parent_category();
287 if ($item->set_aggregation_fields_for_aggregation(0, $gradecategory->aggregation)) {
288 $item->update();
294 require_once($CFG->libdir.'/grade/grade_outcome.php');
295 // Add outcomes if requested.
296 if ($hasoutcomes && $outcomes = grade_outcome::fetch_all_available($course->id)) {
297 // Outcome grade_item.itemnumber start at 1000, there is nothing above outcomes.
298 $max_itemnumber = 999;
299 if ($items) {
300 foreach($items as $item) {
301 if ($item->itemnumber > $max_itemnumber) {
302 $max_itemnumber = $item->itemnumber;
307 foreach($outcomes as $outcome) {
308 $elname = 'outcome_'.$outcome->id;
310 if (property_exists($moduleinfo, $elname) and $moduleinfo->$elname) {
311 // Check if this is a new outcome grade item.
312 $outcomeexists = false;
313 if ($items) {
314 foreach($items as $item) {
315 if ($item->outcomeid == $outcome->id) {
316 $outcomeexists = true;
317 break;
320 if ($outcomeexists) {
321 continue;
325 $max_itemnumber++;
327 $outcomeitem = new grade_item();
328 $outcomeitem->courseid = $course->id;
329 $outcomeitem->itemtype = 'mod';
330 $outcomeitem->itemmodule = $moduleinfo->modulename;
331 $outcomeitem->iteminstance = $moduleinfo->instance;
332 $outcomeitem->itemnumber = $max_itemnumber;
333 $outcomeitem->itemname = $outcome->fullname;
334 $outcomeitem->outcomeid = $outcome->id;
335 $outcomeitem->gradetype = GRADE_TYPE_SCALE;
336 $outcomeitem->scaleid = $outcome->scaleid;
337 $outcomeitem->insert();
339 if ($items) {
340 // Move the new outcome into the same category and immediately after the first grade item.
341 $item = reset($items);
342 $outcomeitem->set_parent($item->categoryid);
343 $outcomeitem->move_after_sortorder($item->sortorder);
344 } else if (isset($moduleinfo->gradecat)) {
345 $outcomeitem->set_parent($moduleinfo->gradecat);
348 if (!$outcomeexists) {
349 $gradecategory = $outcomeitem->get_parent_category();
350 if ($outcomeitem->set_aggregation_fields_for_aggregation(0, $gradecategory->aggregation)) {
351 $outcomeitem->update();
358 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_ADVANCED_GRADING, false)
359 and has_capability('moodle/grade:managegradingforms', $modcontext)) {
360 require_once($CFG->dirroot.'/grade/grading/lib.php');
361 $gradingman = get_grading_manager($modcontext, 'mod_'.$moduleinfo->modulename);
362 $showgradingmanagement = false;
363 foreach ($gradingman->get_available_areas() as $areaname => $aretitle) {
364 $formfield = 'advancedgradingmethod_'.$areaname;
365 if (isset($moduleinfo->{$formfield})) {
366 $gradingman->set_area($areaname);
367 $methodchanged = $gradingman->set_active_method($moduleinfo->{$formfield});
368 if (empty($moduleinfo->{$formfield})) {
369 // Going back to the simple direct grading is not a reason to open the management screen.
370 $methodchanged = false;
372 $showgradingmanagement = $showgradingmanagement || $methodchanged;
375 // Update grading management information.
376 $moduleinfo->gradingman = $gradingman;
377 $moduleinfo->showgradingmanagement = $showgradingmanagement;
380 rebuild_course_cache($course->id, true);
381 if ($hasgrades) {
382 grade_regrade_final_grades($course->id);
385 // To be removed (deprecated) with MDL-67526 (both lines).
386 require_once($CFG->libdir.'/plagiarismlib.php');
387 plagiarism_save_form_elements($moduleinfo);
389 // Allow plugins to extend the course module form.
390 $moduleinfo = plugin_extend_coursemodule_edit_post_actions($moduleinfo, $course);
392 if (!empty($moduleinfo->coursecontentnotification)) {
393 // Schedule adhoc-task for delivering the course content updated notification.
394 if ($course->visible && $moduleinfo->visible) {
395 $adhocktask = new \core_course\task\content_notification_task();
396 $adhocktask->set_custom_data(
397 ['update' => $moduleinfo->update, 'cmid' => $moduleinfo->coursemodule,
398 'courseid' => $course->id, 'userfrom' => $USER->id]);
399 $adhocktask->set_component('course');
400 \core\task\manager::queue_adhoc_task($adhocktask, true);
404 return $moduleinfo;
408 * Set module info default values for the unset module attributs.
410 * @param object $moduleinfo the current known data of the module
411 * @return object the completed module info
413 function set_moduleinfo_defaults($moduleinfo) {
415 if (empty($moduleinfo->coursemodule)) {
416 // Add.
417 $cm = null;
418 $moduleinfo->instance = '';
419 $moduleinfo->coursemodule = '';
420 } else {
421 // Update.
422 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule, 0, false, MUST_EXIST);
423 $moduleinfo->instance = $cm->instance;
424 $moduleinfo->coursemodule = $cm->id;
426 // For safety.
427 $moduleinfo->modulename = clean_param($moduleinfo->modulename, PARAM_PLUGIN);
429 if (!isset($moduleinfo->groupingid)) {
430 $moduleinfo->groupingid = 0;
433 if (!isset($moduleinfo->name)) { // Label.
434 $moduleinfo->name = $moduleinfo->modulename;
437 if (!isset($moduleinfo->completion)) {
438 $moduleinfo->completion = COMPLETION_DISABLED;
440 if (!isset($moduleinfo->completionview)) {
441 $moduleinfo->completionview = COMPLETION_VIEW_NOT_REQUIRED;
443 if (!isset($moduleinfo->completionexpected)) {
444 $moduleinfo->completionexpected = 0;
447 // Convert the 'use grade' checkbox into a grade-item number: 0 if checked, null if not.
448 if (isset($moduleinfo->completionusegrade) && $moduleinfo->completionusegrade) {
449 $moduleinfo->completiongradeitemnumber = 0;
450 } else if (!isset($moduleinfo->completiongradeitemnumber)) {
451 // If there is no gradeitemnumber set, make sure to disable completionpassgrade.
452 $moduleinfo->completionpassgrade = 0;
453 $moduleinfo->completiongradeitemnumber = null;
456 if (!isset($moduleinfo->conditiongradegroup)) {
457 $moduleinfo->conditiongradegroup = array();
459 if (!isset($moduleinfo->conditionfieldgroup)) {
460 $moduleinfo->conditionfieldgroup = array();
462 if (!isset($moduleinfo->visibleoncoursepage)) {
463 $moduleinfo->visibleoncoursepage = 1;
466 if (!isset($moduleinfo->downloadcontent)) {
467 $moduleinfo->downloadcontent = DOWNLOAD_COURSE_CONTENT_ENABLED;
470 return $moduleinfo;
474 * Check that the user can add a module. Also returns some information like the module, context and course section info.
475 * The fucntion create the course section if it doesn't exist.
477 * @param object $course the course of the module
478 * @param object $modulename the module name
479 * @param object $section the section of the module
480 * @return array list containing module, context, course section.
481 * @throws moodle_exception if user is not allowed to perform the action or module is not allowed in this course
483 function can_add_moduleinfo($course, $modulename, $section) {
484 global $DB;
486 $module = $DB->get_record('modules', array('name'=>$modulename), '*', MUST_EXIST);
488 $context = context_course::instance($course->id);
489 require_capability('moodle/course:manageactivities', $context);
491 course_create_sections_if_missing($course, $section);
492 $cw = get_fast_modinfo($course)->get_section_info($section);
494 if (!course_allowed_module($course, $module->name)) {
495 print_error('moduledisable');
498 return array($module, $context, $cw);
502 * Check if user is allowed to update module info and returns related item/data to the module.
504 * @param object $cm course module
505 * @return array - list of course module, context, module, moduleinfo, and course section.
506 * @throws moodle_exception if user is not allowed to perform the action
508 function can_update_moduleinfo($cm) {
509 global $DB;
511 // Check the $USER has the right capability.
512 $context = context_module::instance($cm->id);
513 require_capability('moodle/course:manageactivities', $context);
515 // Check module exists.
516 $module = $DB->get_record('modules', array('id'=>$cm->module), '*', MUST_EXIST);
518 // Check the moduleinfo exists.
519 $data = $DB->get_record($module->name, array('id'=>$cm->instance), '*', MUST_EXIST);
521 // Check the course section exists.
522 $cw = $DB->get_record('course_sections', array('id'=>$cm->section), '*', MUST_EXIST);
524 return array($cm, $context, $module, $data, $cw);
529 * Update the module info.
530 * This function doesn't check the user capabilities. It updates the course module and the module instance.
531 * Then execute common action to create/update module process (trigger event, rebuild cache, save plagiarism settings...).
533 * @param object $cm course module
534 * @param object $moduleinfo module info
535 * @param object $course course of the module
536 * @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.
537 * @return array list of course module and module info.
539 function update_moduleinfo($cm, $moduleinfo, $course, $mform = null) {
540 global $DB, $CFG;
542 $data = new stdClass();
543 if ($mform) {
544 $data = $mform->get_data();
547 // Attempt to include module library before we make any changes to DB.
548 include_modulelib($moduleinfo->modulename);
550 $moduleinfo->course = $course->id;
551 $moduleinfo = set_moduleinfo_defaults($moduleinfo);
553 if (!empty($course->groupmodeforce) or !isset($moduleinfo->groupmode)) {
554 $moduleinfo->groupmode = $cm->groupmode; // Keep original.
557 // Update course module first.
558 $cm->groupmode = $moduleinfo->groupmode;
559 if (isset($moduleinfo->groupingid)) {
560 $cm->groupingid = $moduleinfo->groupingid;
563 $completion = new completion_info($course);
564 if ($completion->is_enabled()) {
565 // Completion settings that would affect users who have already completed
566 // the activity may be locked; if so, these should not be updated.
567 if (!empty($moduleinfo->completionunlocked)) {
568 $cm->completion = $moduleinfo->completion;
569 $cm->completionpassgrade = $moduleinfo->completionpassgrade ?? 0;
570 if ($moduleinfo->completiongradeitemnumber === '') {
571 $cm->completiongradeitemnumber = null;
572 } else {
573 $cm->completiongradeitemnumber = $moduleinfo->completiongradeitemnumber;
575 $cm->completionview = $moduleinfo->completionview;
577 // The expected date does not affect users who have completed the activity,
578 // so it is safe to update it regardless of the lock status.
579 $cm->completionexpected = $moduleinfo->completionexpected;
581 if (!empty($CFG->enableavailability)) {
582 // This code is used both when submitting the form, which uses a long
583 // name to avoid clashes, and by unit test code which uses the real
584 // name in the table.
585 if (property_exists($moduleinfo, 'availabilityconditionsjson')) {
586 if ($moduleinfo->availabilityconditionsjson !== '') {
587 $cm->availability = $moduleinfo->availabilityconditionsjson;
588 } else {
589 $cm->availability = null;
591 } else if (property_exists($moduleinfo, 'availability')) {
592 $cm->availability = $moduleinfo->availability;
594 // If there is any availability data, verify it.
595 if ($cm->availability) {
596 $tree = new \core_availability\tree(json_decode($cm->availability));
597 // Save time and database space by setting null if the only data
598 // is an empty tree.
599 if ($tree->is_empty()) {
600 $cm->availability = null;
604 if (isset($moduleinfo->showdescription)) {
605 $cm->showdescription = $moduleinfo->showdescription;
606 } else {
607 $cm->showdescription = 0;
610 $DB->update_record('course_modules', $cm);
612 $modcontext = context_module::instance($moduleinfo->coursemodule);
614 // Update embedded links and save files.
615 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
616 $moduleinfo->intro = file_save_draft_area_files($moduleinfo->introeditor['itemid'], $modcontext->id,
617 'mod_'.$moduleinfo->modulename, 'intro', 0,
618 array('subdirs'=>true), $moduleinfo->introeditor['text']);
619 $moduleinfo->introformat = $moduleinfo->introeditor['format'];
620 unset($moduleinfo->introeditor);
622 // Get the a copy of the grade_item before it is modified incase we need to scale the grades.
623 $oldgradeitem = null;
624 $newgradeitem = null;
625 if (!empty($data->grade_rescalegrades) && $data->grade_rescalegrades == 'yes') {
626 // Fetch the grade item before it is updated.
627 $oldgradeitem = grade_item::fetch(array('itemtype' => 'mod',
628 'itemmodule' => $moduleinfo->modulename,
629 'iteminstance' => $moduleinfo->instance,
630 'itemnumber' => 0,
631 'courseid' => $moduleinfo->course));
634 $updateinstancefunction = $moduleinfo->modulename."_update_instance";
635 if (!$updateinstancefunction($moduleinfo, $mform)) {
636 print_error('cannotupdatemod', '', course_get_url($course, $cm->section), $moduleinfo->modulename);
639 // This needs to happen AFTER the grademin/grademax have already been updated.
640 if (!empty($data->grade_rescalegrades) && $data->grade_rescalegrades == 'yes') {
641 // Get the grade_item after the update call the activity to scale the grades.
642 $newgradeitem = grade_item::fetch(array('itemtype' => 'mod',
643 'itemmodule' => $moduleinfo->modulename,
644 'iteminstance' => $moduleinfo->instance,
645 'itemnumber' => 0,
646 'courseid' => $moduleinfo->course));
647 if ($newgradeitem && $oldgradeitem->gradetype == GRADE_TYPE_VALUE && $newgradeitem->gradetype == GRADE_TYPE_VALUE) {
648 $params = array(
649 $course,
650 $cm,
651 $oldgradeitem->grademin,
652 $oldgradeitem->grademax,
653 $newgradeitem->grademin,
654 $newgradeitem->grademax
656 if (!component_callback('mod_' . $moduleinfo->modulename, 'rescale_activity_grades', $params)) {
657 print_error('cannotreprocessgrades', '', course_get_url($course, $cm->section), $moduleinfo->modulename);
662 // Make sure visibility is set correctly (in particular in calendar).
663 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
664 set_coursemodule_visible($moduleinfo->coursemodule, $moduleinfo->visible, $moduleinfo->visibleoncoursepage);
667 if (isset($moduleinfo->cmidnumber)) { // Label.
668 // Set cm idnumber - uniqueness is already verified by form validation.
669 set_coursemodule_idnumber($moduleinfo->coursemodule, $moduleinfo->cmidnumber);
672 if (isset($moduleinfo->downloadcontent)) {
673 set_downloadcontent($moduleinfo->coursemodule, $moduleinfo->downloadcontent);
676 // Update module tags.
677 if (core_tag_tag::is_enabled('core', 'course_modules') && isset($moduleinfo->tags)) {
678 core_tag_tag::set_item_tags('core', 'course_modules', $moduleinfo->coursemodule, $modcontext, $moduleinfo->tags);
681 // Now that module is fully updated, also update completion data if required.
682 // (this will wipe all user completion data and recalculate it)
683 if ($completion->is_enabled() && !empty($moduleinfo->completionunlocked)) {
684 // Rebuild course cache before resetting completion states to ensure that the cm_info attributes are up to date.
685 course_modinfo::build_course_cache($course);
686 // Fetch this course module's info.
687 $cminfo = cm_info::create($cm);
688 $completion->reset_all_state($cminfo);
690 $cm->name = $moduleinfo->name;
691 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
693 $moduleinfo = edit_module_post_actions($moduleinfo, $course);
695 return array($cm, $moduleinfo);
699 * Include once the module lib file.
701 * @param string $modulename module name of the lib to include
702 * @throws moodle_exception if lib.php file for the module does not exist
704 function include_modulelib($modulename) {
705 global $CFG;
706 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
707 if (file_exists($modlib)) {
708 include_once($modlib);
709 } else {
710 throw new moodle_exception('modulemissingcode', '', '', $modlib);
715 * Get module information data required for updating the module.
717 * @param stdClass $cm course module object
718 * @param stdClass $course course object
719 * @return array required data for updating a module
720 * @since Moodle 3.2
722 function get_moduleinfo_data($cm, $course) {
723 global $CFG;
725 list($cm, $context, $module, $data, $cw) = can_update_moduleinfo($cm);
727 $data->coursemodule = $cm->id;
728 $data->section = $cw->section; // The section number itself - relative!!! (section column in course_sections)
729 $data->visible = $cm->visible; //?? $cw->visible ? $cm->visible : 0; // section hiding overrides
730 $data->visibleoncoursepage = $cm->visibleoncoursepage;
731 $data->cmidnumber = $cm->idnumber; // The cm IDnumber
732 $data->groupmode = groups_get_activity_groupmode($cm); // locked later if forced
733 $data->groupingid = $cm->groupingid;
734 $data->course = $course->id;
735 $data->module = $module->id;
736 $data->modulename = $module->name;
737 $data->instance = $cm->instance;
738 $data->completion = $cm->completion;
739 $data->completionview = $cm->completionview;
740 $data->completionexpected = $cm->completionexpected;
741 $data->completionusegrade = is_null($cm->completiongradeitemnumber) ? 0 : 1;
742 $data->completionpassgrade = $cm->completionpassgrade;
743 $data->completiongradeitemnumber = $cm->completiongradeitemnumber;
744 $data->showdescription = $cm->showdescription;
745 $data->downloadcontent = $cm->downloadcontent;
746 $data->tags = core_tag_tag::get_item_tags_array('core', 'course_modules', $cm->id);
747 if (!empty($CFG->enableavailability)) {
748 $data->availabilityconditionsjson = $cm->availability;
751 if (plugin_supports('mod', $data->modulename, FEATURE_MOD_INTRO, true)) {
752 $draftid_editor = file_get_submitted_draft_itemid('introeditor');
753 $currentintro = file_prepare_draft_area($draftid_editor, $context->id, 'mod_'.$data->modulename, 'intro', 0, array('subdirs'=>true), $data->intro);
754 $data->introeditor = array('text'=>$currentintro, 'format'=>$data->introformat, 'itemid'=>$draftid_editor);
757 if (plugin_supports('mod', $data->modulename, FEATURE_ADVANCED_GRADING, false)
758 and has_capability('moodle/grade:managegradingforms', $context)) {
759 require_once($CFG->dirroot.'/grade/grading/lib.php');
760 $gradingman = get_grading_manager($context, 'mod_'.$data->modulename);
761 $data->_advancedgradingdata['methods'] = $gradingman->get_available_methods();
762 $areas = $gradingman->get_available_areas();
764 foreach ($areas as $areaname => $areatitle) {
765 $gradingman->set_area($areaname);
766 $method = $gradingman->get_active_method();
767 $data->_advancedgradingdata['areas'][$areaname] = array(
768 'title' => $areatitle,
769 'method' => $method,
771 $formfield = 'advancedgradingmethod_'.$areaname;
772 $data->{$formfield} = $method;
776 $component = "mod_{$data->modulename}";
777 $items = grade_item::fetch_all([
778 'itemtype' => 'mod',
779 'itemmodule' => $data->modulename,
780 'iteminstance' => $data->instance,
781 'courseid' => $course->id,
784 if ($items) {
785 // Add existing outcomes.
786 foreach ($items as $item) {
787 if (!empty($item->outcomeid)) {
788 $data->{'outcome_' . $item->outcomeid} = 1;
789 } else if (isset($item->gradepass)) {
790 $gradepassfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $item->itemnumber, 'gradepass');
791 $data->{$gradepassfieldname} = format_float($item->gradepass, $item->get_decimals());
796 // set category if present
797 $gradecat = [];
798 foreach ($items as $item) {
799 if (!isset($gradecat[$item->itemnumber])) {
800 $gradecat[$item->itemnumber] = $item->categoryid;
802 if ($gradecat[$item->itemnumber] != $item->categoryid) {
803 // Mixed categories.
804 $gradecat[$item->itemnumber] = false;
807 foreach ($gradecat as $itemnumber => $cat) {
808 if ($cat !== false) {
809 $gradecatfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'gradecat');
810 // Do not set if mixed categories present.
811 $data->{$gradecatfieldname} = $cat;
815 return array($cm, $context, $module, $data, $cw);
819 * Prepare the standard module information for a new module instance.
821 * @param stdClass $course course object
822 * @param string $modulename module name
823 * @param int $section section number
824 * @return array module information about other required data
825 * @since Moodle 3.2
827 function prepare_new_moduleinfo_data($course, $modulename, $section) {
828 global $CFG;
830 list($module, $context, $cw) = can_add_moduleinfo($course, $modulename, $section);
832 $cm = null;
834 $data = new stdClass();
835 $data->section = $section; // The section number itself - relative!!! (section column in course_sections)
836 $data->visible = $cw->visible;
837 $data->course = $course->id;
838 $data->module = $module->id;
839 $data->modulename = $module->name;
840 $data->groupmode = $course->groupmode;
841 $data->groupingid = $course->defaultgroupingid;
842 $data->id = '';
843 $data->instance = '';
844 $data->coursemodule = '';
845 $data->downloadcontent = DOWNLOAD_COURSE_CONTENT_ENABLED;
847 // Apply completion defaults.
848 $defaults = \core_completion\manager::get_default_completion($course, $module);
849 foreach ($defaults as $key => $value) {
850 $data->$key = $value;
853 if (plugin_supports('mod', $data->modulename, FEATURE_MOD_INTRO, true)) {
854 $draftid_editor = file_get_submitted_draft_itemid('introeditor');
855 file_prepare_draft_area($draftid_editor, null, null, null, null, array('subdirs'=>true));
856 $data->introeditor = array('text'=>'', 'format'=>FORMAT_HTML, 'itemid'=>$draftid_editor); // TODO: add better default
859 if (plugin_supports('mod', $data->modulename, FEATURE_ADVANCED_GRADING, false)
860 and has_capability('moodle/grade:managegradingforms', $context)) {
861 require_once($CFG->dirroot.'/grade/grading/lib.php');
863 $data->_advancedgradingdata['methods'] = grading_manager::available_methods();
864 $areas = grading_manager::available_areas('mod_'.$module->name);
866 foreach ($areas as $areaname => $areatitle) {
867 $data->_advancedgradingdata['areas'][$areaname] = array(
868 'title' => $areatitle,
869 'method' => '',
871 $formfield = 'advancedgradingmethod_'.$areaname;
872 $data->{$formfield} = '';
876 return array($module, $context, $cw, $cm, $data);