MDL-58543 upgrade: Replay 4 steps missed for some combinations
[moodle.git] / course / modlib.php
blob68ed661ad6aab1c1982116897d545fdd201d8f84
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->visibleoncoursepage = $moduleinfo->visibleoncoursepage;
64 $newcm->visibleold = $moduleinfo->visible;
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();
412 return $moduleinfo;
416 * Check that the user can add a module. Also returns some information like the module, context and course section info.
417 * The fucntion create the course section if it doesn't exist.
419 * @param object $course the course of the module
420 * @param object $modulename the module name
421 * @param object $section the section of the module
422 * @return array list containing module, context, course section.
423 * @throws moodle_exception if user is not allowed to perform the action or module is not allowed in this course
425 function can_add_moduleinfo($course, $modulename, $section) {
426 global $DB;
428 $module = $DB->get_record('modules', array('name'=>$modulename), '*', MUST_EXIST);
430 $context = context_course::instance($course->id);
431 require_capability('moodle/course:manageactivities', $context);
433 course_create_sections_if_missing($course, $section);
434 $cw = get_fast_modinfo($course)->get_section_info($section);
436 if (!course_allowed_module($course, $module->name)) {
437 print_error('moduledisable');
440 return array($module, $context, $cw);
444 * Check if user is allowed to update module info and returns related item/data to the module.
446 * @param object $cm course module
447 * @return array - list of course module, context, module, moduleinfo, and course section.
448 * @throws moodle_exception if user is not allowed to perform the action
450 function can_update_moduleinfo($cm) {
451 global $DB;
453 // Check the $USER has the right capability.
454 $context = context_module::instance($cm->id);
455 require_capability('moodle/course:manageactivities', $context);
457 // Check module exists.
458 $module = $DB->get_record('modules', array('id'=>$cm->module), '*', MUST_EXIST);
460 // Check the moduleinfo exists.
461 $data = $DB->get_record($module->name, array('id'=>$cm->instance), '*', MUST_EXIST);
463 // Check the course section exists.
464 $cw = $DB->get_record('course_sections', array('id'=>$cm->section), '*', MUST_EXIST);
466 return array($cm, $context, $module, $data, $cw);
471 * Update the module info.
472 * This function doesn't check the user capabilities. It updates the course module and the module instance.
473 * Then execute common action to create/update module process (trigger event, rebuild cache, save plagiarism settings...).
475 * @param object $cm course module
476 * @param object $moduleinfo module info
477 * @param object $course course of the module
478 * @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.
479 * @return array list of course module and module info.
481 function update_moduleinfo($cm, $moduleinfo, $course, $mform = null) {
482 global $DB, $CFG;
484 $data = new stdClass();
485 if ($mform) {
486 $data = $mform->get_data();
489 // Attempt to include module library before we make any changes to DB.
490 include_modulelib($moduleinfo->modulename);
492 $moduleinfo->course = $course->id;
493 $moduleinfo = set_moduleinfo_defaults($moduleinfo);
495 if (!empty($course->groupmodeforce) or !isset($moduleinfo->groupmode)) {
496 $moduleinfo->groupmode = $cm->groupmode; // Keep original.
499 // Update course module first.
500 $cm->groupmode = $moduleinfo->groupmode;
501 if (isset($moduleinfo->groupingid)) {
502 $cm->groupingid = $moduleinfo->groupingid;
505 $completion = new completion_info($course);
506 if ($completion->is_enabled()) {
507 // Completion settings that would affect users who have already completed
508 // the activity may be locked; if so, these should not be updated.
509 if (!empty($moduleinfo->completionunlocked)) {
510 $cm->completion = $moduleinfo->completion;
511 $cm->completiongradeitemnumber = $moduleinfo->completiongradeitemnumber;
512 $cm->completionview = $moduleinfo->completionview;
514 // The expected date does not affect users who have completed the activity,
515 // so it is safe to update it regardless of the lock status.
516 $cm->completionexpected = $moduleinfo->completionexpected;
518 if (!empty($CFG->enableavailability)) {
519 // This code is used both when submitting the form, which uses a long
520 // name to avoid clashes, and by unit test code which uses the real
521 // name in the table.
522 if (property_exists($moduleinfo, 'availabilityconditionsjson')) {
523 if ($moduleinfo->availabilityconditionsjson !== '') {
524 $cm->availability = $moduleinfo->availabilityconditionsjson;
525 } else {
526 $cm->availability = null;
528 } else if (property_exists($moduleinfo, 'availability')) {
529 $cm->availability = $moduleinfo->availability;
531 // If there is any availability data, verify it.
532 if ($cm->availability) {
533 $tree = new \core_availability\tree(json_decode($cm->availability));
534 // Save time and database space by setting null if the only data
535 // is an empty tree.
536 if ($tree->is_empty()) {
537 $cm->availability = null;
541 if (isset($moduleinfo->showdescription)) {
542 $cm->showdescription = $moduleinfo->showdescription;
543 } else {
544 $cm->showdescription = 0;
547 $DB->update_record('course_modules', $cm);
549 $modcontext = context_module::instance($moduleinfo->coursemodule);
551 // Update embedded links and save files.
552 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
553 $moduleinfo->intro = file_save_draft_area_files($moduleinfo->introeditor['itemid'], $modcontext->id,
554 'mod_'.$moduleinfo->modulename, 'intro', 0,
555 array('subdirs'=>true), $moduleinfo->introeditor['text']);
556 $moduleinfo->introformat = $moduleinfo->introeditor['format'];
557 unset($moduleinfo->introeditor);
559 // Get the a copy of the grade_item before it is modified incase we need to scale the grades.
560 $oldgradeitem = null;
561 $newgradeitem = null;
562 if (!empty($data->grade_rescalegrades) && $data->grade_rescalegrades == 'yes') {
563 // Fetch the grade item before it is updated.
564 $oldgradeitem = grade_item::fetch(array('itemtype' => 'mod',
565 'itemmodule' => $moduleinfo->modulename,
566 'iteminstance' => $moduleinfo->instance,
567 'itemnumber' => 0,
568 'courseid' => $moduleinfo->course));
571 $updateinstancefunction = $moduleinfo->modulename."_update_instance";
572 if (!$updateinstancefunction($moduleinfo, $mform)) {
573 print_error('cannotupdatemod', '', course_get_url($course, $cm->section), $moduleinfo->modulename);
576 // This needs to happen AFTER the grademin/grademax have already been updated.
577 if (!empty($data->grade_rescalegrades) && $data->grade_rescalegrades == 'yes') {
578 // Get the grade_item after the update call the activity to scale the grades.
579 $newgradeitem = grade_item::fetch(array('itemtype' => 'mod',
580 'itemmodule' => $moduleinfo->modulename,
581 'iteminstance' => $moduleinfo->instance,
582 'itemnumber' => 0,
583 'courseid' => $moduleinfo->course));
584 if ($newgradeitem && $oldgradeitem->gradetype == GRADE_TYPE_VALUE && $newgradeitem->gradetype == GRADE_TYPE_VALUE) {
585 $params = array(
586 $course,
587 $cm,
588 $oldgradeitem->grademin,
589 $oldgradeitem->grademax,
590 $newgradeitem->grademin,
591 $newgradeitem->grademax
593 if (!component_callback('mod_' . $moduleinfo->modulename, 'rescale_activity_grades', $params)) {
594 print_error('cannotreprocessgrades', '', course_get_url($course, $cm->section), $moduleinfo->modulename);
599 // Make sure visibility is set correctly (in particular in calendar).
600 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
601 set_coursemodule_visible($moduleinfo->coursemodule, $moduleinfo->visible, $moduleinfo->visibleoncoursepage);
604 if (isset($moduleinfo->cmidnumber)) { // Label.
605 // Set cm idnumber - uniqueness is already verified by form validation.
606 set_coursemodule_idnumber($moduleinfo->coursemodule, $moduleinfo->cmidnumber);
609 // Update module tags.
610 if (core_tag_tag::is_enabled('core', 'course_modules') && isset($moduleinfo->tags)) {
611 core_tag_tag::set_item_tags('core', 'course_modules', $moduleinfo->coursemodule, $modcontext, $moduleinfo->tags);
614 // Now that module is fully updated, also update completion data if required.
615 // (this will wipe all user completion data and recalculate it)
616 if ($completion->is_enabled() && !empty($moduleinfo->completionunlocked)) {
617 $completion->reset_all_state($cm);
619 $cm->name = $moduleinfo->name;
620 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
622 $moduleinfo = edit_module_post_actions($moduleinfo, $course);
624 return array($cm, $moduleinfo);
628 * Include once the module lib file.
630 * @param string $modulename module name of the lib to include
631 * @throws moodle_exception if lib.php file for the module does not exist
633 function include_modulelib($modulename) {
634 global $CFG;
635 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
636 if (file_exists($modlib)) {
637 include_once($modlib);
638 } else {
639 throw new moodle_exception('modulemissingcode', '', '', $modlib);
644 * Get module information data required for updating the module.
646 * @param stdClass $cm course module object
647 * @param stdClass $course course object
648 * @return array required data for updating a module
649 * @since Moodle 3.2
651 function get_moduleinfo_data($cm, $course) {
652 global $CFG;
654 list($cm, $context, $module, $data, $cw) = can_update_moduleinfo($cm);
656 $data->coursemodule = $cm->id;
657 $data->section = $cw->section; // The section number itself - relative!!! (section column in course_sections)
658 $data->visible = $cm->visible; //?? $cw->visible ? $cm->visible : 0; // section hiding overrides
659 $data->visibleoncoursepage = $cm->visibleoncoursepage;
660 $data->cmidnumber = $cm->idnumber; // The cm IDnumber
661 $data->groupmode = groups_get_activity_groupmode($cm); // locked later if forced
662 $data->groupingid = $cm->groupingid;
663 $data->course = $course->id;
664 $data->module = $module->id;
665 $data->modulename = $module->name;
666 $data->instance = $cm->instance;
667 $data->completion = $cm->completion;
668 $data->completionview = $cm->completionview;
669 $data->completionexpected = $cm->completionexpected;
670 $data->completionusegrade = is_null($cm->completiongradeitemnumber) ? 0 : 1;
671 $data->showdescription = $cm->showdescription;
672 $data->tags = core_tag_tag::get_item_tags_array('core', 'course_modules', $cm->id);
673 if (!empty($CFG->enableavailability)) {
674 $data->availabilityconditionsjson = $cm->availability;
677 if (plugin_supports('mod', $data->modulename, FEATURE_MOD_INTRO, true)) {
678 $draftid_editor = file_get_submitted_draft_itemid('introeditor');
679 $currentintro = file_prepare_draft_area($draftid_editor, $context->id, 'mod_'.$data->modulename, 'intro', 0, array('subdirs'=>true), $data->intro);
680 $data->introeditor = array('text'=>$currentintro, 'format'=>$data->introformat, 'itemid'=>$draftid_editor);
683 if (plugin_supports('mod', $data->modulename, FEATURE_ADVANCED_GRADING, false)
684 and has_capability('moodle/grade:managegradingforms', $context)) {
685 require_once($CFG->dirroot.'/grade/grading/lib.php');
686 $gradingman = get_grading_manager($context, 'mod_'.$data->modulename);
687 $data->_advancedgradingdata['methods'] = $gradingman->get_available_methods();
688 $areas = $gradingman->get_available_areas();
690 foreach ($areas as $areaname => $areatitle) {
691 $gradingman->set_area($areaname);
692 $method = $gradingman->get_active_method();
693 $data->_advancedgradingdata['areas'][$areaname] = array(
694 'title' => $areatitle,
695 'method' => $method,
697 $formfield = 'advancedgradingmethod_'.$areaname;
698 $data->{$formfield} = $method;
702 if ($items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$data->modulename,
703 'iteminstance'=>$data->instance, 'courseid'=>$course->id))) {
704 // Add existing outcomes.
705 foreach ($items as $item) {
706 if (!empty($item->outcomeid)) {
707 $data->{'outcome_' . $item->outcomeid} = 1;
708 } else if (isset($item->gradepass)) {
709 $decimalpoints = $item->get_decimals();
710 $data->gradepass = format_float($item->gradepass, $decimalpoints);
714 // set category if present
715 $gradecat = false;
716 foreach ($items as $item) {
717 if ($gradecat === false) {
718 $gradecat = $item->categoryid;
719 continue;
721 if ($gradecat != $item->categoryid) {
722 //mixed categories
723 $gradecat = false;
724 break;
727 if ($gradecat !== false) {
728 // do not set if mixed categories present
729 $data->gradecat = $gradecat;
732 return array($cm, $context, $module, $data, $cw);
736 * Prepare the standard module information for a new module instance.
738 * @param stdClass $course course object
739 * @param string $modulename module name
740 * @param int $section section number
741 * @return array module information about other required data
742 * @since Moodle 3.2
744 function prepare_new_moduleinfo_data($course, $modulename, $section) {
745 global $CFG;
747 list($module, $context, $cw) = can_add_moduleinfo($course, $modulename, $section);
749 $cm = null;
751 $data = new stdClass();
752 $data->section = $section; // The section number itself - relative!!! (section column in course_sections)
753 $data->visible = $cw->visible;
754 $data->course = $course->id;
755 $data->module = $module->id;
756 $data->modulename = $module->name;
757 $data->groupmode = $course->groupmode;
758 $data->groupingid = $course->defaultgroupingid;
759 $data->id = '';
760 $data->instance = '';
761 $data->coursemodule = '';
763 if (plugin_supports('mod', $data->modulename, FEATURE_MOD_INTRO, true)) {
764 $draftid_editor = file_get_submitted_draft_itemid('introeditor');
765 file_prepare_draft_area($draftid_editor, null, null, null, null, array('subdirs'=>true));
766 $data->introeditor = array('text'=>'', 'format'=>FORMAT_HTML, 'itemid'=>$draftid_editor); // TODO: add better default
769 if (plugin_supports('mod', $data->modulename, FEATURE_ADVANCED_GRADING, false)
770 and has_capability('moodle/grade:managegradingforms', $context)) {
771 require_once($CFG->dirroot.'/grade/grading/lib.php');
773 $data->_advancedgradingdata['methods'] = grading_manager::available_methods();
774 $areas = grading_manager::available_areas('mod_'.$module->name);
776 foreach ($areas as $areaname => $areatitle) {
777 $data->_advancedgradingdata['areas'][$areaname] = array(
778 'title' => $areatitle,
779 'method' => '',
781 $formfield = 'advancedgradingmethod_'.$areaname;
782 $data->{$formfield} = '';
786 return array($module, $context, $cw, $cm, $data);