Merge branch 'install_35_STABLE' of https://git.in.moodle.com/amosbot/moodle-install...
[moodle.git] / course / modlib.php
blobcaf3868bbe1f49bbbbeedcf076483196f527c3cf
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 require_once($CFG->dirroot.'/course/lib.php');
32 /**
33 * Add course module.
35 * The function does not check user capabilities.
36 * The function creates course module, module instance, add the module to the correct section.
37 * It also trigger common action that need to be done after adding/updating a module.
39 * @param object $moduleinfo the moudle data
40 * @param object $course the course of the module
41 * @param object $mform this is required by an existing hack to deal with files during MODULENAME_add_instance()
42 * @return object the updated module info
44 function add_moduleinfo($moduleinfo, $course, $mform = null) {
45 global $DB, $CFG;
47 // Attempt to include module library before we make any changes to DB.
48 include_modulelib($moduleinfo->modulename);
50 $moduleinfo->course = $course->id;
51 $moduleinfo = set_moduleinfo_defaults($moduleinfo);
53 if (!empty($course->groupmodeforce) or !isset($moduleinfo->groupmode)) {
54 $moduleinfo->groupmode = 0; // Do not set groupmode.
57 // First add course_module record because we need the context.
58 $newcm = new stdClass();
59 $newcm->course = $course->id;
60 $newcm->module = $moduleinfo->module;
61 $newcm->instance = 0; // Not known yet, will be updated later (this is similar to restore code).
62 $newcm->visible = $moduleinfo->visible;
63 $newcm->visibleold = $moduleinfo->visible;
64 $newcm->visibleoncoursepage = $moduleinfo->visibleoncoursepage;
65 if (isset($moduleinfo->cmidnumber)) {
66 $newcm->idnumber = $moduleinfo->cmidnumber;
68 $newcm->groupmode = $moduleinfo->groupmode;
69 $newcm->groupingid = $moduleinfo->groupingid;
70 $completion = new completion_info($course);
71 if ($completion->is_enabled()) {
72 $newcm->completion = $moduleinfo->completion;
73 $newcm->completiongradeitemnumber = $moduleinfo->completiongradeitemnumber;
74 $newcm->completionview = $moduleinfo->completionview;
75 $newcm->completionexpected = $moduleinfo->completionexpected;
77 if(!empty($CFG->enableavailability)) {
78 // This code is used both when submitting the form, which uses a long
79 // name to avoid clashes, and by unit test code which uses the real
80 // name in the table.
81 $newcm->availability = null;
82 if (property_exists($moduleinfo, 'availabilityconditionsjson')) {
83 if ($moduleinfo->availabilityconditionsjson !== '') {
84 $newcm->availability = $moduleinfo->availabilityconditionsjson;
86 } else if (property_exists($moduleinfo, 'availability')) {
87 $newcm->availability = $moduleinfo->availability;
89 // If there is any availability data, verify it.
90 if ($newcm->availability) {
91 $tree = new \core_availability\tree(json_decode($newcm->availability));
92 // Save time and database space by setting null if the only data
93 // is an empty tree.
94 if ($tree->is_empty()) {
95 $newcm->availability = null;
99 if (isset($moduleinfo->showdescription)) {
100 $newcm->showdescription = $moduleinfo->showdescription;
101 } else {
102 $newcm->showdescription = 0;
105 // From this point we make database changes, so start transaction.
106 $transaction = $DB->start_delegated_transaction();
108 if (!$moduleinfo->coursemodule = add_course_module($newcm)) {
109 print_error('cannotaddcoursemodule');
112 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true) &&
113 isset($moduleinfo->introeditor)) {
114 $introeditor = $moduleinfo->introeditor;
115 unset($moduleinfo->introeditor);
116 $moduleinfo->intro = $introeditor['text'];
117 $moduleinfo->introformat = $introeditor['format'];
120 $addinstancefunction = $moduleinfo->modulename."_add_instance";
121 try {
122 $returnfromfunc = $addinstancefunction($moduleinfo, $mform);
123 } catch (moodle_exception $e) {
124 $returnfromfunc = $e;
126 if (!$returnfromfunc or !is_number($returnfromfunc)) {
127 // Undo everything we can. This is not necessary for databases which
128 // support transactions, but improves consistency for other databases.
129 context_helper::delete_instance(CONTEXT_MODULE, $moduleinfo->coursemodule);
130 $DB->delete_records('course_modules', array('id'=>$moduleinfo->coursemodule));
132 if ($returnfromfunc instanceof moodle_exception) {
133 throw $returnfromfunc;
134 } else if (!is_number($returnfromfunc)) {
135 print_error('invalidfunction', '', course_get_url($course, $moduleinfo->section));
136 } else {
137 print_error('cannotaddnewmodule', '', course_get_url($course, $moduleinfo->section), $moduleinfo->modulename);
141 $moduleinfo->instance = $returnfromfunc;
143 $DB->set_field('course_modules', 'instance', $returnfromfunc, array('id'=>$moduleinfo->coursemodule));
145 // Update embedded links and save files.
146 $modcontext = context_module::instance($moduleinfo->coursemodule);
147 if (!empty($introeditor)) {
148 // This will respect a module that has set a value for intro in it's modname_add_instance() function.
149 $introeditor['text'] = $moduleinfo->intro;
151 $moduleinfo->intro = file_save_draft_area_files($introeditor['itemid'], $modcontext->id,
152 'mod_'.$moduleinfo->modulename, 'intro', 0,
153 array('subdirs'=>true), $introeditor['text']);
154 $DB->set_field($moduleinfo->modulename, 'intro', $moduleinfo->intro, array('id'=>$moduleinfo->instance));
157 // Add module tags.
158 if (core_tag_tag::is_enabled('core', 'course_modules') && isset($moduleinfo->tags)) {
159 core_tag_tag::set_item_tags('core', 'course_modules', $moduleinfo->coursemodule, $modcontext, $moduleinfo->tags);
162 // Course_modules and course_sections each contain a reference to each other.
163 // So we have to update one of them twice.
164 $sectionid = course_add_cm_to_section($course, $moduleinfo->coursemodule, $moduleinfo->section);
166 // Trigger event based on the action we did.
167 // Api create_from_cm expects modname and id property, and we don't want to modify $moduleinfo since we are returning it.
168 $eventdata = clone $moduleinfo;
169 $eventdata->modname = $eventdata->modulename;
170 $eventdata->id = $eventdata->coursemodule;
171 $event = \core\event\course_module_created::create_from_cm($eventdata, $modcontext);
172 $event->trigger();
174 $moduleinfo = edit_module_post_actions($moduleinfo, $course);
175 $transaction->allow_commit();
177 return $moduleinfo;
181 * Hook for plugins to take action when a module is created or updated.
183 * @param stdClass $moduleinfo the module info
184 * @param stdClass $course the course of the module
186 * @return stdClass moduleinfo updated by plugins.
188 function plugin_extend_coursemodule_edit_post_actions($moduleinfo, $course) {
189 $callbacks = get_plugins_with_function('coursemodule_edit_post_actions', 'lib.php');
190 foreach ($callbacks as $type => $plugins) {
191 foreach ($plugins as $plugin => $pluginfunction) {
192 $moduleinfo = $pluginfunction($moduleinfo, $course);
195 return $moduleinfo;
199 * Common create/update module module actions that need to be processed as soon as a module is created/updaded.
200 * For example:create grade parent category, add outcomes, rebuild caches, regrade, save plagiarism settings...
201 * Please note this api does not trigger events as of MOODLE 2.6. Please trigger events before calling this api.
203 * @param object $moduleinfo the module info
204 * @param object $course the course of the module
206 * @return object moduleinfo update with grading management info
208 function edit_module_post_actions($moduleinfo, $course) {
209 global $CFG;
210 require_once($CFG->libdir.'/gradelib.php');
212 $modcontext = context_module::instance($moduleinfo->coursemodule);
213 $hasgrades = plugin_supports('mod', $moduleinfo->modulename, FEATURE_GRADE_HAS_GRADE, false);
214 $hasoutcomes = plugin_supports('mod', $moduleinfo->modulename, FEATURE_GRADE_OUTCOMES, true);
216 // Sync idnumber with grade_item.
217 if ($hasgrades && $grade_item = grade_item::fetch(array('itemtype'=>'mod', 'itemmodule'=>$moduleinfo->modulename,
218 'iteminstance'=>$moduleinfo->instance, 'itemnumber'=>0, 'courseid'=>$course->id))) {
219 $gradeupdate = false;
220 if ($grade_item->idnumber != $moduleinfo->cmidnumber) {
221 $grade_item->idnumber = $moduleinfo->cmidnumber;
222 $gradeupdate = true;
224 if (isset($moduleinfo->gradepass) && $grade_item->gradepass != $moduleinfo->gradepass) {
225 $grade_item->gradepass = $moduleinfo->gradepass;
226 $gradeupdate = true;
228 if ($gradeupdate) {
229 $grade_item->update();
233 if ($hasgrades) {
234 $items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$moduleinfo->modulename,
235 'iteminstance'=>$moduleinfo->instance, 'courseid'=>$course->id));
236 } else {
237 $items = array();
240 // Create parent category if requested and move to correct parent category.
241 if ($items and isset($moduleinfo->gradecat)) {
242 if ($moduleinfo->gradecat == -1) {
243 $grade_category = new grade_category();
244 $grade_category->courseid = $course->id;
245 $grade_category->fullname = $moduleinfo->name;
246 $grade_category->insert();
247 if ($grade_item) {
248 $parent = $grade_item->get_parent_category();
249 $grade_category->set_parent($parent->id);
251 $moduleinfo->gradecat = $grade_category->id;
254 foreach ($items as $itemid=>$unused) {
255 $items[$itemid]->set_parent($moduleinfo->gradecat);
256 if ($itemid == $grade_item->id) {
257 // Use updated grade_item.
258 $grade_item = $items[$itemid];
263 require_once($CFG->libdir.'/grade/grade_outcome.php');
264 // Add outcomes if requested.
265 if ($hasoutcomes && $outcomes = grade_outcome::fetch_all_available($course->id)) {
266 $grade_items = array();
268 // Outcome grade_item.itemnumber start at 1000, there is nothing above outcomes.
269 $max_itemnumber = 999;
270 if ($items) {
271 foreach($items as $item) {
272 if ($item->itemnumber > $max_itemnumber) {
273 $max_itemnumber = $item->itemnumber;
278 foreach($outcomes as $outcome) {
279 $elname = 'outcome_'.$outcome->id;
281 if (property_exists($moduleinfo, $elname) and $moduleinfo->$elname) {
282 // So we have a request for new outcome grade item?
283 if ($items) {
284 $outcomeexists = false;
285 foreach($items as $item) {
286 if ($item->outcomeid == $outcome->id) {
287 $outcomeexists = true;
288 break;
291 if ($outcomeexists) {
292 continue;
296 $max_itemnumber++;
298 $outcome_item = new grade_item();
299 $outcome_item->courseid = $course->id;
300 $outcome_item->itemtype = 'mod';
301 $outcome_item->itemmodule = $moduleinfo->modulename;
302 $outcome_item->iteminstance = $moduleinfo->instance;
303 $outcome_item->itemnumber = $max_itemnumber;
304 $outcome_item->itemname = $outcome->fullname;
305 $outcome_item->outcomeid = $outcome->id;
306 $outcome_item->gradetype = GRADE_TYPE_SCALE;
307 $outcome_item->scaleid = $outcome->scaleid;
308 $outcome_item->insert();
310 // Move the new outcome into correct category and fix sortorder if needed.
311 if ($grade_item) {
312 $outcome_item->set_parent($grade_item->categoryid);
313 $outcome_item->move_after_sortorder($grade_item->sortorder);
315 } else if (isset($moduleinfo->gradecat)) {
316 $outcome_item->set_parent($moduleinfo->gradecat);
322 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_ADVANCED_GRADING, false)
323 and has_capability('moodle/grade:managegradingforms', $modcontext)) {
324 require_once($CFG->dirroot.'/grade/grading/lib.php');
325 $gradingman = get_grading_manager($modcontext, 'mod_'.$moduleinfo->modulename);
326 $showgradingmanagement = false;
327 foreach ($gradingman->get_available_areas() as $areaname => $aretitle) {
328 $formfield = 'advancedgradingmethod_'.$areaname;
329 if (isset($moduleinfo->{$formfield})) {
330 $gradingman->set_area($areaname);
331 $methodchanged = $gradingman->set_active_method($moduleinfo->{$formfield});
332 if (empty($moduleinfo->{$formfield})) {
333 // Going back to the simple direct grading is not a reason to open the management screen.
334 $methodchanged = false;
336 $showgradingmanagement = $showgradingmanagement || $methodchanged;
339 // Update grading management information.
340 $moduleinfo->gradingman = $gradingman;
341 $moduleinfo->showgradingmanagement = $showgradingmanagement;
344 rebuild_course_cache($course->id, true);
345 if ($hasgrades) {
346 grade_regrade_final_grades($course->id);
348 require_once($CFG->libdir.'/plagiarismlib.php');
349 plagiarism_save_form_elements($moduleinfo);
351 // Allow plugins to extend the course module form.
352 $moduleinfo = plugin_extend_coursemodule_edit_post_actions($moduleinfo, $course);
354 return $moduleinfo;
359 * Set module info default values for the unset module attributs.
361 * @param object $moduleinfo the current known data of the module
362 * @return object the completed module info
364 function set_moduleinfo_defaults($moduleinfo) {
366 if (empty($moduleinfo->coursemodule)) {
367 // Add.
368 $cm = null;
369 $moduleinfo->instance = '';
370 $moduleinfo->coursemodule = '';
371 } else {
372 // Update.
373 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule, 0, false, MUST_EXIST);
374 $moduleinfo->instance = $cm->instance;
375 $moduleinfo->coursemodule = $cm->id;
377 // For safety.
378 $moduleinfo->modulename = clean_param($moduleinfo->modulename, PARAM_PLUGIN);
380 if (!isset($moduleinfo->groupingid)) {
381 $moduleinfo->groupingid = 0;
384 if (!isset($moduleinfo->name)) { // Label.
385 $moduleinfo->name = $moduleinfo->modulename;
388 if (!isset($moduleinfo->completion)) {
389 $moduleinfo->completion = COMPLETION_DISABLED;
391 if (!isset($moduleinfo->completionview)) {
392 $moduleinfo->completionview = COMPLETION_VIEW_NOT_REQUIRED;
394 if (!isset($moduleinfo->completionexpected)) {
395 $moduleinfo->completionexpected = 0;
398 // Convert the 'use grade' checkbox into a grade-item number: 0 if checked, null if not.
399 if (isset($moduleinfo->completionusegrade) && $moduleinfo->completionusegrade) {
400 $moduleinfo->completiongradeitemnumber = 0;
401 } else {
402 $moduleinfo->completiongradeitemnumber = null;
405 if (!isset($moduleinfo->conditiongradegroup)) {
406 $moduleinfo->conditiongradegroup = array();
408 if (!isset($moduleinfo->conditionfieldgroup)) {
409 $moduleinfo->conditionfieldgroup = array();
411 if (!isset($moduleinfo->visibleoncoursepage)) {
412 $moduleinfo->visibleoncoursepage = 1;
415 return $moduleinfo;
419 * Check that the user can add a module. Also returns some information like the module, context and course section info.
420 * The fucntion create the course section if it doesn't exist.
422 * @param object $course the course of the module
423 * @param object $modulename the module name
424 * @param object $section the section of the module
425 * @return array list containing module, context, course section.
426 * @throws moodle_exception if user is not allowed to perform the action or module is not allowed in this course
428 function can_add_moduleinfo($course, $modulename, $section) {
429 global $DB;
431 $module = $DB->get_record('modules', array('name'=>$modulename), '*', MUST_EXIST);
433 $context = context_course::instance($course->id);
434 require_capability('moodle/course:manageactivities', $context);
436 course_create_sections_if_missing($course, $section);
437 $cw = get_fast_modinfo($course)->get_section_info($section);
439 if (!course_allowed_module($course, $module->name)) {
440 print_error('moduledisable');
443 return array($module, $context, $cw);
447 * Check if user is allowed to update module info and returns related item/data to the module.
449 * @param object $cm course module
450 * @return array - list of course module, context, module, moduleinfo, and course section.
451 * @throws moodle_exception if user is not allowed to perform the action
453 function can_update_moduleinfo($cm) {
454 global $DB;
456 // Check the $USER has the right capability.
457 $context = context_module::instance($cm->id);
458 require_capability('moodle/course:manageactivities', $context);
460 // Check module exists.
461 $module = $DB->get_record('modules', array('id'=>$cm->module), '*', MUST_EXIST);
463 // Check the moduleinfo exists.
464 $data = $DB->get_record($module->name, array('id'=>$cm->instance), '*', MUST_EXIST);
466 // Check the course section exists.
467 $cw = $DB->get_record('course_sections', array('id'=>$cm->section), '*', MUST_EXIST);
469 return array($cm, $context, $module, $data, $cw);
474 * Update the module info.
475 * This function doesn't check the user capabilities. It updates the course module and the module instance.
476 * Then execute common action to create/update module process (trigger event, rebuild cache, save plagiarism settings...).
478 * @param object $cm course module
479 * @param object $moduleinfo module info
480 * @param object $course course of the module
481 * @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.
482 * @return array list of course module and module info.
484 function update_moduleinfo($cm, $moduleinfo, $course, $mform = null) {
485 global $DB, $CFG;
487 $data = new stdClass();
488 if ($mform) {
489 $data = $mform->get_data();
492 // Attempt to include module library before we make any changes to DB.
493 include_modulelib($moduleinfo->modulename);
495 $moduleinfo->course = $course->id;
496 $moduleinfo = set_moduleinfo_defaults($moduleinfo);
498 if (!empty($course->groupmodeforce) or !isset($moduleinfo->groupmode)) {
499 $moduleinfo->groupmode = $cm->groupmode; // Keep original.
502 // Update course module first.
503 $cm->groupmode = $moduleinfo->groupmode;
504 if (isset($moduleinfo->groupingid)) {
505 $cm->groupingid = $moduleinfo->groupingid;
508 $completion = new completion_info($course);
509 if ($completion->is_enabled()) {
510 // Completion settings that would affect users who have already completed
511 // the activity may be locked; if so, these should not be updated.
512 if (!empty($moduleinfo->completionunlocked)) {
513 $cm->completion = $moduleinfo->completion;
514 $cm->completiongradeitemnumber = $moduleinfo->completiongradeitemnumber;
515 $cm->completionview = $moduleinfo->completionview;
517 // The expected date does not affect users who have completed the activity,
518 // so it is safe to update it regardless of the lock status.
519 $cm->completionexpected = $moduleinfo->completionexpected;
521 if (!empty($CFG->enableavailability)) {
522 // This code is used both when submitting the form, which uses a long
523 // name to avoid clashes, and by unit test code which uses the real
524 // name in the table.
525 if (property_exists($moduleinfo, 'availabilityconditionsjson')) {
526 if ($moduleinfo->availabilityconditionsjson !== '') {
527 $cm->availability = $moduleinfo->availabilityconditionsjson;
528 } else {
529 $cm->availability = null;
531 } else if (property_exists($moduleinfo, 'availability')) {
532 $cm->availability = $moduleinfo->availability;
534 // If there is any availability data, verify it.
535 if ($cm->availability) {
536 $tree = new \core_availability\tree(json_decode($cm->availability));
537 // Save time and database space by setting null if the only data
538 // is an empty tree.
539 if ($tree->is_empty()) {
540 $cm->availability = null;
544 if (isset($moduleinfo->showdescription)) {
545 $cm->showdescription = $moduleinfo->showdescription;
546 } else {
547 $cm->showdescription = 0;
550 $DB->update_record('course_modules', $cm);
552 $modcontext = context_module::instance($moduleinfo->coursemodule);
554 // Update embedded links and save files.
555 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
556 $moduleinfo->intro = file_save_draft_area_files($moduleinfo->introeditor['itemid'], $modcontext->id,
557 'mod_'.$moduleinfo->modulename, 'intro', 0,
558 array('subdirs'=>true), $moduleinfo->introeditor['text']);
559 $moduleinfo->introformat = $moduleinfo->introeditor['format'];
560 unset($moduleinfo->introeditor);
562 // Get the a copy of the grade_item before it is modified incase we need to scale the grades.
563 $oldgradeitem = null;
564 $newgradeitem = null;
565 if (!empty($data->grade_rescalegrades) && $data->grade_rescalegrades == 'yes') {
566 // Fetch the grade item before it is updated.
567 $oldgradeitem = grade_item::fetch(array('itemtype' => 'mod',
568 'itemmodule' => $moduleinfo->modulename,
569 'iteminstance' => $moduleinfo->instance,
570 'itemnumber' => 0,
571 'courseid' => $moduleinfo->course));
574 $updateinstancefunction = $moduleinfo->modulename."_update_instance";
575 if (!$updateinstancefunction($moduleinfo, $mform)) {
576 print_error('cannotupdatemod', '', course_get_url($course, $cm->section), $moduleinfo->modulename);
579 // This needs to happen AFTER the grademin/grademax have already been updated.
580 if (!empty($data->grade_rescalegrades) && $data->grade_rescalegrades == 'yes') {
581 // Get the grade_item after the update call the activity to scale the grades.
582 $newgradeitem = grade_item::fetch(array('itemtype' => 'mod',
583 'itemmodule' => $moduleinfo->modulename,
584 'iteminstance' => $moduleinfo->instance,
585 'itemnumber' => 0,
586 'courseid' => $moduleinfo->course));
587 if ($newgradeitem && $oldgradeitem->gradetype == GRADE_TYPE_VALUE && $newgradeitem->gradetype == GRADE_TYPE_VALUE) {
588 $params = array(
589 $course,
590 $cm,
591 $oldgradeitem->grademin,
592 $oldgradeitem->grademax,
593 $newgradeitem->grademin,
594 $newgradeitem->grademax
596 if (!component_callback('mod_' . $moduleinfo->modulename, 'rescale_activity_grades', $params)) {
597 print_error('cannotreprocessgrades', '', course_get_url($course, $cm->section), $moduleinfo->modulename);
602 // Make sure visibility is set correctly (in particular in calendar).
603 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
604 set_coursemodule_visible($moduleinfo->coursemodule, $moduleinfo->visible, $moduleinfo->visibleoncoursepage);
607 if (isset($moduleinfo->cmidnumber)) { // Label.
608 // Set cm idnumber - uniqueness is already verified by form validation.
609 set_coursemodule_idnumber($moduleinfo->coursemodule, $moduleinfo->cmidnumber);
612 // Update module tags.
613 if (core_tag_tag::is_enabled('core', 'course_modules') && isset($moduleinfo->tags)) {
614 core_tag_tag::set_item_tags('core', 'course_modules', $moduleinfo->coursemodule, $modcontext, $moduleinfo->tags);
617 // Now that module is fully updated, also update completion data if required.
618 // (this will wipe all user completion data and recalculate it)
619 if ($completion->is_enabled() && !empty($moduleinfo->completionunlocked)) {
620 $completion->reset_all_state($cm);
622 $cm->name = $moduleinfo->name;
623 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
625 $moduleinfo = edit_module_post_actions($moduleinfo, $course);
627 return array($cm, $moduleinfo);
631 * Include once the module lib file.
633 * @param string $modulename module name of the lib to include
634 * @throws moodle_exception if lib.php file for the module does not exist
636 function include_modulelib($modulename) {
637 global $CFG;
638 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
639 if (file_exists($modlib)) {
640 include_once($modlib);
641 } else {
642 throw new moodle_exception('modulemissingcode', '', '', $modlib);
647 * Get module information data required for updating the module.
649 * @param stdClass $cm course module object
650 * @param stdClass $course course object
651 * @return array required data for updating a module
652 * @since Moodle 3.2
654 function get_moduleinfo_data($cm, $course) {
655 global $CFG;
657 list($cm, $context, $module, $data, $cw) = can_update_moduleinfo($cm);
659 $data->coursemodule = $cm->id;
660 $data->section = $cw->section; // The section number itself - relative!!! (section column in course_sections)
661 $data->visible = $cm->visible; //?? $cw->visible ? $cm->visible : 0; // section hiding overrides
662 $data->visibleoncoursepage = $cm->visibleoncoursepage;
663 $data->cmidnumber = $cm->idnumber; // The cm IDnumber
664 $data->groupmode = groups_get_activity_groupmode($cm); // locked later if forced
665 $data->groupingid = $cm->groupingid;
666 $data->course = $course->id;
667 $data->module = $module->id;
668 $data->modulename = $module->name;
669 $data->instance = $cm->instance;
670 $data->completion = $cm->completion;
671 $data->completionview = $cm->completionview;
672 $data->completionexpected = $cm->completionexpected;
673 $data->completionusegrade = is_null($cm->completiongradeitemnumber) ? 0 : 1;
674 $data->showdescription = $cm->showdescription;
675 $data->tags = core_tag_tag::get_item_tags_array('core', 'course_modules', $cm->id);
676 if (!empty($CFG->enableavailability)) {
677 $data->availabilityconditionsjson = $cm->availability;
680 if (plugin_supports('mod', $data->modulename, FEATURE_MOD_INTRO, true)) {
681 $draftid_editor = file_get_submitted_draft_itemid('introeditor');
682 $currentintro = file_prepare_draft_area($draftid_editor, $context->id, 'mod_'.$data->modulename, 'intro', 0, array('subdirs'=>true), $data->intro);
683 $data->introeditor = array('text'=>$currentintro, 'format'=>$data->introformat, 'itemid'=>$draftid_editor);
686 if (plugin_supports('mod', $data->modulename, FEATURE_ADVANCED_GRADING, false)
687 and has_capability('moodle/grade:managegradingforms', $context)) {
688 require_once($CFG->dirroot.'/grade/grading/lib.php');
689 $gradingman = get_grading_manager($context, 'mod_'.$data->modulename);
690 $data->_advancedgradingdata['methods'] = $gradingman->get_available_methods();
691 $areas = $gradingman->get_available_areas();
693 foreach ($areas as $areaname => $areatitle) {
694 $gradingman->set_area($areaname);
695 $method = $gradingman->get_active_method();
696 $data->_advancedgradingdata['areas'][$areaname] = array(
697 'title' => $areatitle,
698 'method' => $method,
700 $formfield = 'advancedgradingmethod_'.$areaname;
701 $data->{$formfield} = $method;
705 if ($items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$data->modulename,
706 'iteminstance'=>$data->instance, 'courseid'=>$course->id))) {
707 // Add existing outcomes.
708 foreach ($items as $item) {
709 if (!empty($item->outcomeid)) {
710 $data->{'outcome_' . $item->outcomeid} = 1;
711 } else if (isset($item->gradepass)) {
712 $decimalpoints = $item->get_decimals();
713 $data->gradepass = format_float($item->gradepass, $decimalpoints);
717 // set category if present
718 $gradecat = false;
719 foreach ($items as $item) {
720 if ($gradecat === false) {
721 $gradecat = $item->categoryid;
722 continue;
724 if ($gradecat != $item->categoryid) {
725 //mixed categories
726 $gradecat = false;
727 break;
730 if ($gradecat !== false) {
731 // do not set if mixed categories present
732 $data->gradecat = $gradecat;
735 return array($cm, $context, $module, $data, $cw);
739 * Prepare the standard module information for a new module instance.
741 * @param stdClass $course course object
742 * @param string $modulename module name
743 * @param int $section section number
744 * @return array module information about other required data
745 * @since Moodle 3.2
747 function prepare_new_moduleinfo_data($course, $modulename, $section) {
748 global $CFG;
750 list($module, $context, $cw) = can_add_moduleinfo($course, $modulename, $section);
752 $cm = null;
754 $data = new stdClass();
755 $data->section = $section; // The section number itself - relative!!! (section column in course_sections)
756 $data->visible = $cw->visible;
757 $data->course = $course->id;
758 $data->module = $module->id;
759 $data->modulename = $module->name;
760 $data->groupmode = $course->groupmode;
761 $data->groupingid = $course->defaultgroupingid;
762 $data->id = '';
763 $data->instance = '';
764 $data->coursemodule = '';
766 // Apply completion defaults.
767 $defaults = \core_completion\manager::get_default_completion($course, $module);
768 foreach ($defaults as $key => $value) {
769 $data->$key = $value;
772 if (plugin_supports('mod', $data->modulename, FEATURE_MOD_INTRO, true)) {
773 $draftid_editor = file_get_submitted_draft_itemid('introeditor');
774 file_prepare_draft_area($draftid_editor, null, null, null, null, array('subdirs'=>true));
775 $data->introeditor = array('text'=>'', 'format'=>FORMAT_HTML, 'itemid'=>$draftid_editor); // TODO: add better default
778 if (plugin_supports('mod', $data->modulename, FEATURE_ADVANCED_GRADING, false)
779 and has_capability('moodle/grade:managegradingforms', $context)) {
780 require_once($CFG->dirroot.'/grade/grading/lib.php');
782 $data->_advancedgradingdata['methods'] = grading_manager::available_methods();
783 $areas = grading_manager::available_areas('mod_'.$module->name);
785 foreach ($areas as $areaname => $areatitle) {
786 $data->_advancedgradingdata['areas'][$areaname] = array(
787 'title' => $areatitle,
788 'method' => '',
790 $formfield = 'advancedgradingmethod_'.$areaname;
791 $data->{$formfield} = '';
795 return array($module, $context, $cw, $cm, $data);