MDL-66079 core_grades: Add support for multiple grade items in an activity
[moodle.git] / course / modlib.php
CommitLineData
80fe0c19
JM
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.
13//
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/>.
16
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.
22 *
23 * @copyright 2013 Jerome Mouneyrac
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 * @package core_course
26 */
27
28defined('MOODLE_INTERNAL') || die;
29
fcc88fdd
AN
30use \core_grades\component_gradeitems;
31
80fe0c19
JM
32require_once($CFG->dirroot.'/course/lib.php');
33
34/**
35 * Add course module.
36 *
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.
40 *
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
45 */
46function add_moduleinfo($moduleinfo, $course, $mform = null) {
47 global $DB, $CFG;
48
b4b75872
MG
49 // Attempt to include module library before we make any changes to DB.
50 include_modulelib($moduleinfo->modulename);
51
80fe0c19
JM
52 $moduleinfo->course = $course->id;
53 $moduleinfo = set_moduleinfo_defaults($moduleinfo);
54
55 if (!empty($course->groupmodeforce) or !isset($moduleinfo->groupmode)) {
56 $moduleinfo->groupmode = 0; // Do not set groupmode.
57 }
58
8f2913b9 59 // First add course_module record because we need the context.
80fe0c19
JM
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;
7c69ab5d 65 $newcm->visibleold = $moduleinfo->visible;
78ef2ac1 66 $newcm->visibleoncoursepage = $moduleinfo->visibleoncoursepage;
449d1fa3
MG
67 if (isset($moduleinfo->cmidnumber)) {
68 $newcm->idnumber = $moduleinfo->cmidnumber;
69 }
80fe0c19
JM
70 $newcm->groupmode = $moduleinfo->groupmode;
71 $newcm->groupingid = $moduleinfo->groupingid;
80fe0c19
JM
72 $completion = new completion_info($course);
73 if ($completion->is_enabled()) {
74 $newcm->completion = $moduleinfo->completion;
75 $newcm->completiongradeitemnumber = $moduleinfo->completiongradeitemnumber;
76 $newcm->completionview = $moduleinfo->completionview;
77 $newcm->completionexpected = $moduleinfo->completionexpected;
78 }
79 if(!empty($CFG->enableavailability)) {
400c0fd2 80 // This code is used both when submitting the form, which uses a long
81 // name to avoid clashes, and by unit test code which uses the real
82 // name in the table.
83 $newcm->availability = null;
84 if (property_exists($moduleinfo, 'availabilityconditionsjson')) {
85 if ($moduleinfo->availabilityconditionsjson !== '') {
86 $newcm->availability = $moduleinfo->availabilityconditionsjson;
87 }
88 } else if (property_exists($moduleinfo, 'availability')) {
89 $newcm->availability = $moduleinfo->availability;
90 }
06c06038 91 // If there is any availability data, verify it.
92 if ($newcm->availability) {
93 $tree = new \core_availability\tree(json_decode($newcm->availability));
94 // Save time and database space by setting null if the only data
95 // is an empty tree.
96 if ($tree->is_empty()) {
97 $newcm->availability = null;
98 }
99 }
80fe0c19
JM
100 }
101 if (isset($moduleinfo->showdescription)) {
102 $newcm->showdescription = $moduleinfo->showdescription;
103 } else {
104 $newcm->showdescription = 0;
105 }
106
5c3a54c4 107 // From this point we make database changes, so start transaction.
108 $transaction = $DB->start_delegated_transaction();
109
80fe0c19
JM
110 if (!$moduleinfo->coursemodule = add_course_module($newcm)) {
111 print_error('cannotaddcoursemodule');
112 }
113
7fbe33fc
MG
114 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true) &&
115 isset($moduleinfo->introeditor)) {
80fe0c19
JM
116 $introeditor = $moduleinfo->introeditor;
117 unset($moduleinfo->introeditor);
118 $moduleinfo->intro = $introeditor['text'];
119 $moduleinfo->introformat = $introeditor['format'];
120 }
121
122 $addinstancefunction = $moduleinfo->modulename."_add_instance";
5c3a54c4 123 try {
124 $returnfromfunc = $addinstancefunction($moduleinfo, $mform);
125 } catch (moodle_exception $e) {
126 $returnfromfunc = $e;
127 }
80fe0c19 128 if (!$returnfromfunc or !is_number($returnfromfunc)) {
5c3a54c4 129 // Undo everything we can. This is not necessary for databases which
130 // support transactions, but improves consistency for other databases.
c592eea2 131 context_helper::delete_instance(CONTEXT_MODULE, $moduleinfo->coursemodule);
80fe0c19
JM
132 $DB->delete_records('course_modules', array('id'=>$moduleinfo->coursemodule));
133
70a557db 134 if ($returnfromfunc instanceof moodle_exception) {
135 throw $returnfromfunc;
5c3a54c4 136 } else if (!is_number($returnfromfunc)) {
b4b75872 137 print_error('invalidfunction', '', course_get_url($course, $moduleinfo->section));
80fe0c19 138 } else {
b4b75872 139 print_error('cannotaddnewmodule', '', course_get_url($course, $moduleinfo->section), $moduleinfo->modulename);
80fe0c19
JM
140 }
141 }
142
143 $moduleinfo->instance = $returnfromfunc;
144
145 $DB->set_field('course_modules', 'instance', $returnfromfunc, array('id'=>$moduleinfo->coursemodule));
146
147 // Update embedded links and save files.
148 $modcontext = context_module::instance($moduleinfo->coursemodule);
149 if (!empty($introeditor)) {
4fc74fe5
DB
150 // This will respect a module that has set a value for intro in it's modname_add_instance() function.
151 $introeditor['text'] = $moduleinfo->intro;
152
80fe0c19
JM
153 $moduleinfo->intro = file_save_draft_area_files($introeditor['itemid'], $modcontext->id,
154 'mod_'.$moduleinfo->modulename, 'intro', 0,
155 array('subdirs'=>true), $introeditor['text']);
156 $DB->set_field($moduleinfo->modulename, 'intro', $moduleinfo->intro, array('id'=>$moduleinfo->instance));
157 }
158
dffcf46f
NK
159 // Add module tags.
160 if (core_tag_tag::is_enabled('core', 'course_modules') && isset($moduleinfo->tags)) {
161 core_tag_tag::set_item_tags('core', 'course_modules', $moduleinfo->coursemodule, $modcontext, $moduleinfo->tags);
162 }
163
80fe0c19
JM
164 // Course_modules and course_sections each contain a reference to each other.
165 // So we have to update one of them twice.
166 $sectionid = course_add_cm_to_section($course, $moduleinfo->coursemodule, $moduleinfo->section);
167
63deb5c3 168 // Trigger event based on the action we did.
e20d3069
AA
169 // Api create_from_cm expects modname and id property, and we don't want to modify $moduleinfo since we are returning it.
170 $eventdata = clone $moduleinfo;
171 $eventdata->modname = $eventdata->modulename;
172 $eventdata->id = $eventdata->coursemodule;
173 $event = \core\event\course_module_created::create_from_cm($eventdata, $modcontext);
63deb5c3 174 $event->trigger();
80fe0c19 175
63deb5c3 176 $moduleinfo = edit_module_post_actions($moduleinfo, $course);
5c3a54c4 177 $transaction->allow_commit();
80fe0c19
JM
178
179 return $moduleinfo;
180}
181
8995c270
DW
182/**
183 * Hook for plugins to take action when a module is created or updated.
184 *
185 * @param stdClass $moduleinfo the module info
186 * @param stdClass $course the course of the module
187 *
188 * @return stdClass moduleinfo updated by plugins.
189 */
190function plugin_extend_coursemodule_edit_post_actions($moduleinfo, $course) {
191 $callbacks = get_plugins_with_function('coursemodule_edit_post_actions', 'lib.php');
192 foreach ($callbacks as $type => $plugins) {
193 foreach ($plugins as $plugin => $pluginfunction) {
194 $moduleinfo = $pluginfunction($moduleinfo, $course);
195 }
196 }
197 return $moduleinfo;
198}
80fe0c19
JM
199
200/**
201 * Common create/update module module actions that need to be processed as soon as a module is created/updaded.
63deb5c3
AA
202 * For example:create grade parent category, add outcomes, rebuild caches, regrade, save plagiarism settings...
203 * Please note this api does not trigger events as of MOODLE 2.6. Please trigger events before calling this api.
80fe0c19
JM
204 *
205 * @param object $moduleinfo the module info
206 * @param object $course the course of the module
80fe0c19 207 *
63deb5c3 208 * @return object moduleinfo update with grading management info
80fe0c19 209 */
63deb5c3
AA
210function edit_module_post_actions($moduleinfo, $course) {
211 global $CFG;
3e6adca9 212 require_once($CFG->libdir.'/gradelib.php');
80fe0c19
JM
213
214 $modcontext = context_module::instance($moduleinfo->coursemodule);
449d1fa3
MG
215 $hasgrades = plugin_supports('mod', $moduleinfo->modulename, FEATURE_GRADE_HAS_GRADE, false);
216 $hasoutcomes = plugin_supports('mod', $moduleinfo->modulename, FEATURE_GRADE_OUTCOMES, true);
80fe0c19 217
fcc88fdd
AN
218 $items = grade_item::fetch_all([
219 'itemtype' => 'mod',
220 'itemmodule' => $moduleinfo->modulename,
221 'iteminstance' => $moduleinfo->instance,
222 'courseid' => $course->id,
223 ]);
80fe0c19
JM
224
225 // Create parent category if requested and move to correct parent category.
fcc88fdd
AN
226 $component = "mod_{$moduleinfo->modulename}";
227 if ($items) {
228 foreach ($items as $item) {
229 $update = false;
230
231 // Sync idnumber with grade_item.
232 // Note: This only happens for itemnumber 0 at this time.
233 if ($item->itemnumber == 0 && ($item->idnumber != $moduleinfo->cmidnumber)) {
234 $item->idnumber = $moduleinfo->cmidnumber;
235 $update = true;
80fe0c19 236 }
595b911a 237
fcc88fdd
AN
238 // Determine the grade category.
239 $gradecatfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $item->itemnumber, 'gradecat');
240 if (property_exists($moduleinfo, $gradecatfieldname)) {
241 $gradecat = $moduleinfo->$gradecatfieldname;
242 if ($gradecat == -1) {
243 $gradecategory = new grade_category();
244 $gradecategory->courseid = $course->id;
245 $gradecategory->fullname = $moduleinfo->name;
246 $gradecategory->insert();
247
248 $parent = $item->get_parent_category();
249 $gradecategory->set_parent($parent->id);
250 $gradecat = $gradecategory->id;
251 }
252
253 $oldgradecat = null;
254 if ($parent = $item->get_parent_category()) {
255 $oldgradecat = $parent->id;
256 }
257 if ($oldgradecat != $gradecat) {
258 $item->set_parent($gradecat);
259 $update = true;
260 }
261 }
262
263 // Determine the gradepass.
264 $gradepassfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $item->itemnumber, 'gradepass');
265 if (isset($moduleinfo->{$gradepassfieldname})) {
266 $gradepass = $moduleinfo->{$gradepassfieldname};
267 if (null !== $gradepass && $gradepass != $item->gradepass) {
268 $item->gradepass = $gradepass;
269 $update = true;
270 }
271 }
272
273 if ($update) {
274 $item->update();
80fe0c19
JM
275 }
276 }
277 }
278
2cd29dd6 279 require_once($CFG->libdir.'/grade/grade_outcome.php');
80fe0c19 280 // Add outcomes if requested.
449d1fa3 281 if ($hasoutcomes && $outcomes = grade_outcome::fetch_all_available($course->id)) {
80fe0c19
JM
282 // Outcome grade_item.itemnumber start at 1000, there is nothing above outcomes.
283 $max_itemnumber = 999;
284 if ($items) {
285 foreach($items as $item) {
286 if ($item->itemnumber > $max_itemnumber) {
287 $max_itemnumber = $item->itemnumber;
288 }
289 }
290 }
291
292 foreach($outcomes as $outcome) {
293 $elname = 'outcome_'.$outcome->id;
294
295 if (property_exists($moduleinfo, $elname) and $moduleinfo->$elname) {
fcc88fdd 296 // Check if this is a new outcome grade item.
80fe0c19 297 if ($items) {
3b2a6bf5 298 $outcomeexists = false;
80fe0c19
JM
299 foreach($items as $item) {
300 if ($item->outcomeid == $outcome->id) {
3b2a6bf5
DW
301 $outcomeexists = true;
302 break;
80fe0c19
JM
303 }
304 }
3b2a6bf5
DW
305 if ($outcomeexists) {
306 continue;
307 }
80fe0c19
JM
308 }
309
310 $max_itemnumber++;
311
fcc88fdd
AN
312 $outcomeitem = new grade_item();
313 $outcomeitem->courseid = $course->id;
314 $outcomeitem->itemtype = 'mod';
315 $outcomeitem->itemmodule = $moduleinfo->modulename;
316 $outcomeitem->iteminstance = $moduleinfo->instance;
317 $outcomeitem->itemnumber = $max_itemnumber;
318 $outcomeitem->itemname = $outcome->fullname;
319 $outcomeitem->outcomeid = $outcome->id;
320 $outcomeitem->gradetype = GRADE_TYPE_SCALE;
321 $outcomeitem->scaleid = $outcome->scaleid;
322 $outcomeitem->insert();
80fe0c19 323
fcc88fdd
AN
324 if ($items) {
325 // Move the new outcome into the same category and immediately after the first grade item.
326 $item = reset($items);
327 $outcomeitem->set_parent($item->categoryid);
328 $outcomeitem->move_after_sortorder($item->sortorder);
80fe0c19 329 } else if (isset($moduleinfo->gradecat)) {
fcc88fdd 330 $outcomeitem->set_parent($moduleinfo->gradecat);
80fe0c19
JM
331 }
332 }
333 }
334 }
335
336 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_ADVANCED_GRADING, false)
337 and has_capability('moodle/grade:managegradingforms', $modcontext)) {
338 require_once($CFG->dirroot.'/grade/grading/lib.php');
339 $gradingman = get_grading_manager($modcontext, 'mod_'.$moduleinfo->modulename);
340 $showgradingmanagement = false;
341 foreach ($gradingman->get_available_areas() as $areaname => $aretitle) {
342 $formfield = 'advancedgradingmethod_'.$areaname;
343 if (isset($moduleinfo->{$formfield})) {
344 $gradingman->set_area($areaname);
345 $methodchanged = $gradingman->set_active_method($moduleinfo->{$formfield});
346 if (empty($moduleinfo->{$formfield})) {
347 // Going back to the simple direct grading is not a reason to open the management screen.
348 $methodchanged = false;
349 }
350 $showgradingmanagement = $showgradingmanagement || $methodchanged;
351 }
352 }
353 // Update grading management information.
354 $moduleinfo->gradingman = $gradingman;
355 $moduleinfo->showgradingmanagement = $showgradingmanagement;
356 }
357
449d1fa3
MG
358 rebuild_course_cache($course->id, true);
359 if ($hasgrades) {
360 grade_regrade_final_grades($course->id);
361 }
80fe0c19 362 require_once($CFG->libdir.'/plagiarismlib.php');
8f2913b9 363 plagiarism_save_form_elements($moduleinfo);
80fe0c19 364
8995c270
DW
365 // Allow plugins to extend the course module form.
366 $moduleinfo = plugin_extend_coursemodule_edit_post_actions($moduleinfo, $course);
367
80fe0c19
JM
368 return $moduleinfo;
369}
370
80fe0c19
JM
371/**
372 * Set module info default values for the unset module attributs.
373 *
374 * @param object $moduleinfo the current known data of the module
375 * @return object the completed module info
376 */
377function set_moduleinfo_defaults($moduleinfo) {
80fe0c19
JM
378
379 if (empty($moduleinfo->coursemodule)) {
380 // Add.
381 $cm = null;
382 $moduleinfo->instance = '';
383 $moduleinfo->coursemodule = '';
384 } else {
385 // Update.
386 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule, 0, false, MUST_EXIST);
387 $moduleinfo->instance = $cm->instance;
388 $moduleinfo->coursemodule = $cm->id;
389 }
8f2913b9
DW
390 // For safety.
391 $moduleinfo->modulename = clean_param($moduleinfo->modulename, PARAM_PLUGIN);
80fe0c19
JM
392
393 if (!isset($moduleinfo->groupingid)) {
394 $moduleinfo->groupingid = 0;
395 }
396
80fe0c19
JM
397 if (!isset($moduleinfo->name)) { // Label.
398 $moduleinfo->name = $moduleinfo->modulename;
399 }
400
401 if (!isset($moduleinfo->completion)) {
402 $moduleinfo->completion = COMPLETION_DISABLED;
403 }
404 if (!isset($moduleinfo->completionview)) {
405 $moduleinfo->completionview = COMPLETION_VIEW_NOT_REQUIRED;
406 }
6f9354be
MG
407 if (!isset($moduleinfo->completionexpected)) {
408 $moduleinfo->completionexpected = 0;
409 }
80fe0c19
JM
410
411 // Convert the 'use grade' checkbox into a grade-item number: 0 if checked, null if not.
412 if (isset($moduleinfo->completionusegrade) && $moduleinfo->completionusegrade) {
413 $moduleinfo->completiongradeitemnumber = 0;
414 } else {
415 $moduleinfo->completiongradeitemnumber = null;
416 }
417
6f9354be
MG
418 if (!isset($moduleinfo->conditiongradegroup)) {
419 $moduleinfo->conditiongradegroup = array();
420 }
421 if (!isset($moduleinfo->conditionfieldgroup)) {
422 $moduleinfo->conditionfieldgroup = array();
423 }
78ef2ac1
PEK
424 if (!isset($moduleinfo->visibleoncoursepage)) {
425 $moduleinfo->visibleoncoursepage = 1;
426 }
6f9354be 427
80fe0c19
JM
428 return $moduleinfo;
429}
430
431/**
432 * Check that the user can add a module. Also returns some information like the module, context and course section info.
433 * The fucntion create the course section if it doesn't exist.
434 *
435 * @param object $course the course of the module
436 * @param object $modulename the module name
437 * @param object $section the section of the module
438 * @return array list containing module, context, course section.
b4b75872 439 * @throws moodle_exception if user is not allowed to perform the action or module is not allowed in this course
80fe0c19
JM
440 */
441function can_add_moduleinfo($course, $modulename, $section) {
442 global $DB;
443
444 $module = $DB->get_record('modules', array('name'=>$modulename), '*', MUST_EXIST);
445
446 $context = context_course::instance($course->id);
447 require_capability('moodle/course:manageactivities', $context);
448
449 course_create_sections_if_missing($course, $section);
450 $cw = get_fast_modinfo($course)->get_section_info($section);
451
452 if (!course_allowed_module($course, $module->name)) {
453 print_error('moduledisable');
454 }
455
456 return array($module, $context, $cw);
457}
458
459/**
460 * Check if user is allowed to update module info and returns related item/data to the module.
461 *
462 * @param object $cm course module
463 * @return array - list of course module, context, module, moduleinfo, and course section.
b4b75872 464 * @throws moodle_exception if user is not allowed to perform the action
80fe0c19
JM
465 */
466function can_update_moduleinfo($cm) {
467 global $DB;
468
469 // Check the $USER has the right capability.
470 $context = context_module::instance($cm->id);
471 require_capability('moodle/course:manageactivities', $context);
472
473 // Check module exists.
474 $module = $DB->get_record('modules', array('id'=>$cm->module), '*', MUST_EXIST);
475
476 // Check the moduleinfo exists.
477 $data = $DB->get_record($module->name, array('id'=>$cm->instance), '*', MUST_EXIST);
478
479 // Check the course section exists.
480 $cw = $DB->get_record('course_sections', array('id'=>$cm->section), '*', MUST_EXIST);
481
482 return array($cm, $context, $module, $data, $cw);
483}
484
485
486/**
487 * Update the module info.
488 * This function doesn't check the user capabilities. It updates the course module and the module instance.
489 * Then execute common action to create/update module process (trigger event, rebuild cache, save plagiarism settings...).
490 *
491 * @param object $cm course module
492 * @param object $moduleinfo module info
493 * @param object $course course of the module
494 * @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.
495 * @return array list of course module and module info.
496 */
497function update_moduleinfo($cm, $moduleinfo, $course, $mform = null) {
498 global $DB, $CFG;
499
d629c601
DW
500 $data = new stdClass();
501 if ($mform) {
502 $data = $mform->get_data();
503 }
504
b4b75872
MG
505 // Attempt to include module library before we make any changes to DB.
506 include_modulelib($moduleinfo->modulename);
507
80fe0c19
JM
508 $moduleinfo->course = $course->id;
509 $moduleinfo = set_moduleinfo_defaults($moduleinfo);
510
511 if (!empty($course->groupmodeforce) or !isset($moduleinfo->groupmode)) {
512 $moduleinfo->groupmode = $cm->groupmode; // Keep original.
513 }
514
515 // Update course module first.
516 $cm->groupmode = $moduleinfo->groupmode;
517 if (isset($moduleinfo->groupingid)) {
518 $cm->groupingid = $moduleinfo->groupingid;
519 }
80fe0c19
JM
520
521 $completion = new completion_info($course);
af729c3f 522 if ($completion->is_enabled()) {
523 // Completion settings that would affect users who have already completed
524 // the activity may be locked; if so, these should not be updated.
525 if (!empty($moduleinfo->completionunlocked)) {
526 $cm->completion = $moduleinfo->completion;
527 $cm->completiongradeitemnumber = $moduleinfo->completiongradeitemnumber;
528 $cm->completionview = $moduleinfo->completionview;
529 }
530 // The expected date does not affect users who have completed the activity,
531 // so it is safe to update it regardless of the lock status.
532 $cm->completionexpected = $moduleinfo->completionexpected;
80fe0c19
JM
533 }
534 if (!empty($CFG->enableavailability)) {
400c0fd2 535 // This code is used both when submitting the form, which uses a long
536 // name to avoid clashes, and by unit test code which uses the real
537 // name in the table.
538 if (property_exists($moduleinfo, 'availabilityconditionsjson')) {
539 if ($moduleinfo->availabilityconditionsjson !== '') {
540 $cm->availability = $moduleinfo->availabilityconditionsjson;
541 } else {
542 $cm->availability = null;
543 }
544 } else if (property_exists($moduleinfo, 'availability')) {
545 $cm->availability = $moduleinfo->availability;
546 }
06c06038 547 // If there is any availability data, verify it.
548 if ($cm->availability) {
549 $tree = new \core_availability\tree(json_decode($cm->availability));
550 // Save time and database space by setting null if the only data
551 // is an empty tree.
552 if ($tree->is_empty()) {
553 $cm->availability = null;
554 }
555 }
80fe0c19
JM
556 }
557 if (isset($moduleinfo->showdescription)) {
558 $cm->showdescription = $moduleinfo->showdescription;
559 } else {
560 $cm->showdescription = 0;
561 }
562
8f2913b9 563 $DB->update_record('course_modules', $cm);
80fe0c19 564
8f2913b9 565 $modcontext = context_module::instance($moduleinfo->coursemodule);
80fe0c19 566
8f2913b9
DW
567 // Update embedded links and save files.
568 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
569 $moduleinfo->intro = file_save_draft_area_files($moduleinfo->introeditor['itemid'], $modcontext->id,
570 'mod_'.$moduleinfo->modulename, 'intro', 0,
571 array('subdirs'=>true), $moduleinfo->introeditor['text']);
572 $moduleinfo->introformat = $moduleinfo->introeditor['format'];
573 unset($moduleinfo->introeditor);
574 }
d629c601
DW
575 // Get the a copy of the grade_item before it is modified incase we need to scale the grades.
576 $oldgradeitem = null;
577 $newgradeitem = null;
e7c71c18 578 if (!empty($data->grade_rescalegrades) && $data->grade_rescalegrades == 'yes') {
d629c601
DW
579 // Fetch the grade item before it is updated.
580 $oldgradeitem = grade_item::fetch(array('itemtype' => 'mod',
581 'itemmodule' => $moduleinfo->modulename,
582 'iteminstance' => $moduleinfo->instance,
583 'itemnumber' => 0,
584 'courseid' => $moduleinfo->course));
585 }
586
8f2913b9
DW
587 $updateinstancefunction = $moduleinfo->modulename."_update_instance";
588 if (!$updateinstancefunction($moduleinfo, $mform)) {
d629c601
DW
589 print_error('cannotupdatemod', '', course_get_url($course, $cm->section), $moduleinfo->modulename);
590 }
591
592 // This needs to happen AFTER the grademin/grademax have already been updated.
e7c71c18 593 if (!empty($data->grade_rescalegrades) && $data->grade_rescalegrades == 'yes') {
d629c601
DW
594 // Get the grade_item after the update call the activity to scale the grades.
595 $newgradeitem = grade_item::fetch(array('itemtype' => 'mod',
596 'itemmodule' => $moduleinfo->modulename,
597 'iteminstance' => $moduleinfo->instance,
598 'itemnumber' => 0,
599 'courseid' => $moduleinfo->course));
600 if ($newgradeitem && $oldgradeitem->gradetype == GRADE_TYPE_VALUE && $newgradeitem->gradetype == GRADE_TYPE_VALUE) {
601 $params = array(
602 $course,
603 $cm,
604 $oldgradeitem->grademin,
605 $oldgradeitem->grademax,
606 $newgradeitem->grademin,
607 $newgradeitem->grademax
608 );
609 if (!component_callback('mod_' . $moduleinfo->modulename, 'rescale_activity_grades', $params)) {
610 print_error('cannotreprocessgrades', '', course_get_url($course, $cm->section), $moduleinfo->modulename);
611 }
612 }
8f2913b9 613 }
80fe0c19 614
8f2913b9
DW
615 // Make sure visibility is set correctly (in particular in calendar).
616 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
8341055e 617 set_coursemodule_visible($moduleinfo->coursemodule, $moduleinfo->visible, $moduleinfo->visibleoncoursepage);
8f2913b9 618 }
80fe0c19 619
8f2913b9
DW
620 if (isset($moduleinfo->cmidnumber)) { // Label.
621 // Set cm idnumber - uniqueness is already verified by form validation.
622 set_coursemodule_idnumber($moduleinfo->coursemodule, $moduleinfo->cmidnumber);
623 }
80fe0c19 624
dffcf46f
NK
625 // Update module tags.
626 if (core_tag_tag::is_enabled('core', 'course_modules') && isset($moduleinfo->tags)) {
627 core_tag_tag::set_item_tags('core', 'course_modules', $moduleinfo->coursemodule, $modcontext, $moduleinfo->tags);
628 }
629
8f2913b9
DW
630 // Now that module is fully updated, also update completion data if required.
631 // (this will wipe all user completion data and recalculate it)
632 if ($completion->is_enabled() && !empty($moduleinfo->completionunlocked)) {
633 $completion->reset_all_state($cm);
634 }
9e533215
SL
635 $cm->name = $moduleinfo->name;
636 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
63deb5c3 637
63deb5c3 638 $moduleinfo = edit_module_post_actions($moduleinfo, $course);
80fe0c19 639
8f2913b9 640 return array($cm, $moduleinfo);
80fe0c19
JM
641}
642
643/**
644 * Include once the module lib file.
645 *
646 * @param string $modulename module name of the lib to include
b4b75872 647 * @throws moodle_exception if lib.php file for the module does not exist
80fe0c19
JM
648 */
649function include_modulelib($modulename) {
650 global $CFG;
651 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
652 if (file_exists($modlib)) {
653 include_once($modlib);
654 } else {
655 throw new moodle_exception('modulemissingcode', '', '', $modlib);
656 }
657}
658
796876b0
JL
659/**
660 * Get module information data required for updating the module.
661 *
662 * @param stdClass $cm course module object
663 * @param stdClass $course course object
664 * @return array required data for updating a module
665 * @since Moodle 3.2
666 */
667function get_moduleinfo_data($cm, $course) {
668 global $CFG;
669
670 list($cm, $context, $module, $data, $cw) = can_update_moduleinfo($cm);
671
672 $data->coursemodule = $cm->id;
673 $data->section = $cw->section; // The section number itself - relative!!! (section column in course_sections)
674 $data->visible = $cm->visible; //?? $cw->visible ? $cm->visible : 0; // section hiding overrides
8341055e 675 $data->visibleoncoursepage = $cm->visibleoncoursepage;
796876b0
JL
676 $data->cmidnumber = $cm->idnumber; // The cm IDnumber
677 $data->groupmode = groups_get_activity_groupmode($cm); // locked later if forced
678 $data->groupingid = $cm->groupingid;
679 $data->course = $course->id;
680 $data->module = $module->id;
681 $data->modulename = $module->name;
682 $data->instance = $cm->instance;
683 $data->completion = $cm->completion;
684 $data->completionview = $cm->completionview;
685 $data->completionexpected = $cm->completionexpected;
686 $data->completionusegrade = is_null($cm->completiongradeitemnumber) ? 0 : 1;
687 $data->showdescription = $cm->showdescription;
688 $data->tags = core_tag_tag::get_item_tags_array('core', 'course_modules', $cm->id);
689 if (!empty($CFG->enableavailability)) {
690 $data->availabilityconditionsjson = $cm->availability;
691 }
692
693 if (plugin_supports('mod', $data->modulename, FEATURE_MOD_INTRO, true)) {
694 $draftid_editor = file_get_submitted_draft_itemid('introeditor');
695 $currentintro = file_prepare_draft_area($draftid_editor, $context->id, 'mod_'.$data->modulename, 'intro', 0, array('subdirs'=>true), $data->intro);
696 $data->introeditor = array('text'=>$currentintro, 'format'=>$data->introformat, 'itemid'=>$draftid_editor);
697 }
698
699 if (plugin_supports('mod', $data->modulename, FEATURE_ADVANCED_GRADING, false)
700 and has_capability('moodle/grade:managegradingforms', $context)) {
701 require_once($CFG->dirroot.'/grade/grading/lib.php');
702 $gradingman = get_grading_manager($context, 'mod_'.$data->modulename);
703 $data->_advancedgradingdata['methods'] = $gradingman->get_available_methods();
704 $areas = $gradingman->get_available_areas();
705
706 foreach ($areas as $areaname => $areatitle) {
707 $gradingman->set_area($areaname);
708 $method = $gradingman->get_active_method();
709 $data->_advancedgradingdata['areas'][$areaname] = array(
710 'title' => $areatitle,
711 'method' => $method,
712 );
713 $formfield = 'advancedgradingmethod_'.$areaname;
714 $data->{$formfield} = $method;
715 }
716 }
717
fcc88fdd
AN
718 $component = "mod_{$data->modulename}";
719 $items = grade_item::fetch_all([
720 'itemtype' => 'mod',
721 'itemmodule' => $data->modulename,
722 'iteminstance' => $data->instance,
723 'courseid' => $course->id,
724 ]);
725
726 if ($items) {
796876b0
JL
727 // Add existing outcomes.
728 foreach ($items as $item) {
729 if (!empty($item->outcomeid)) {
730 $data->{'outcome_' . $item->outcomeid} = 1;
16e62ecc 731 } else if (isset($item->gradepass)) {
fcc88fdd
AN
732 $gradepassfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $item->itemnumber, 'gradepass');
733 $data->{$gradepassfieldname} = format_float($item->gradepass, $item->get_decimals());
796876b0 734 }
fcc88fdd 735
796876b0
JL
736 }
737
738 // set category if present
fcc88fdd 739 $gradecat = [];
796876b0 740 foreach ($items as $item) {
fcc88fdd
AN
741 if (!isset($gradecat[$item->itemnumber])) {
742 $gradecat[$item->itemnumber] = $item->categoryid;
796876b0 743 }
fcc88fdd
AN
744 if ($gradecat[$item->itemnumber] != $item->categoryid) {
745 // Mixed categories.
746 $gradecat[$item->itemnumber] = false;
796876b0
JL
747 }
748 }
fcc88fdd
AN
749 foreach ($gradecat as $itemnumber => $cat) {
750 if ($cat !== false) {
751 $gradecatfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'gradecat');
752 // Do not set if mixed categories present.
753 $data->{$gradecatfieldname} = $cat;
754 }
796876b0
JL
755 }
756 }
757 return array($cm, $context, $module, $data, $cw);
758}
759
760/**
761 * Prepare the standard module information for a new module instance.
762 *
763 * @param stdClass $course course object
764 * @param string $modulename module name
765 * @param int $section section number
766 * @return array module information about other required data
767 * @since Moodle 3.2
768 */
769function prepare_new_moduleinfo_data($course, $modulename, $section) {
770 global $CFG;
771
772 list($module, $context, $cw) = can_add_moduleinfo($course, $modulename, $section);
773
774 $cm = null;
775
776 $data = new stdClass();
777 $data->section = $section; // The section number itself - relative!!! (section column in course_sections)
778 $data->visible = $cw->visible;
779 $data->course = $course->id;
780 $data->module = $module->id;
781 $data->modulename = $module->name;
782 $data->groupmode = $course->groupmode;
783 $data->groupingid = $course->defaultgroupingid;
784 $data->id = '';
785 $data->instance = '';
786 $data->coursemodule = '';
787
7f53e8aa
MG
788 // Apply completion defaults.
789 $defaults = \core_completion\manager::get_default_completion($course, $module);
790 foreach ($defaults as $key => $value) {
791 $data->$key = $value;
792 }
793
796876b0
JL
794 if (plugin_supports('mod', $data->modulename, FEATURE_MOD_INTRO, true)) {
795 $draftid_editor = file_get_submitted_draft_itemid('introeditor');
796 file_prepare_draft_area($draftid_editor, null, null, null, null, array('subdirs'=>true));
797 $data->introeditor = array('text'=>'', 'format'=>FORMAT_HTML, 'itemid'=>$draftid_editor); // TODO: add better default
798 }
799
800 if (plugin_supports('mod', $data->modulename, FEATURE_ADVANCED_GRADING, false)
801 and has_capability('moodle/grade:managegradingforms', $context)) {
802 require_once($CFG->dirroot.'/grade/grading/lib.php');
803
804 $data->_advancedgradingdata['methods'] = grading_manager::available_methods();
805 $areas = grading_manager::available_areas('mod_'.$module->name);
806
807 foreach ($areas as $areaname => $areatitle) {
808 $data->_advancedgradingdata['areas'][$areaname] = array(
809 'title' => $areatitle,
810 'method' => '',
811 );
812 $formfield = 'advancedgradingmethod_'.$areaname;
813 $data->{$formfield} = '';
814 }
815 }
816
817 return array($module, $context, $cw, $cm, $data);
818}