MDL-62852 policy: Display policy audience in the viewall.php page
[moodle.git] / course / modlib.php
blob4d2348eff32fbcb558cbbd5e120802ccc54a2431
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 if (isset($moduleinfo->visibleoncoursepage)) {
65 $newcm->visibleoncoursepage = $moduleinfo->visibleoncoursepage;
67 if (isset($moduleinfo->cmidnumber)) {
68 $newcm->idnumber = $moduleinfo->cmidnumber;
70 $newcm->groupmode = $moduleinfo->groupmode;
71 $newcm->groupingid = $moduleinfo->groupingid;
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;
79 if(!empty($CFG->enableavailability)) {
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;
88 } else if (property_exists($moduleinfo, 'availability')) {
89 $newcm->availability = $moduleinfo->availability;
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;
101 if (isset($moduleinfo->showdescription)) {
102 $newcm->showdescription = $moduleinfo->showdescription;
103 } else {
104 $newcm->showdescription = 0;
107 // From this point we make database changes, so start transaction.
108 $transaction = $DB->start_delegated_transaction();
110 if (!$moduleinfo->coursemodule = add_course_module($newcm)) {
111 print_error('cannotaddcoursemodule');
114 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true) &&
115 isset($moduleinfo->introeditor)) {
116 $introeditor = $moduleinfo->introeditor;
117 unset($moduleinfo->introeditor);
118 $moduleinfo->intro = $introeditor['text'];
119 $moduleinfo->introformat = $introeditor['format'];
122 $addinstancefunction = $moduleinfo->modulename."_add_instance";
123 try {
124 $returnfromfunc = $addinstancefunction($moduleinfo, $mform);
125 } catch (moodle_exception $e) {
126 $returnfromfunc = $e;
128 if (!$returnfromfunc or !is_number($returnfromfunc)) {
129 // Undo everything we can. This is not necessary for databases which
130 // support transactions, but improves consistency for other databases.
131 context_helper::delete_instance(CONTEXT_MODULE, $moduleinfo->coursemodule);
132 $DB->delete_records('course_modules', array('id'=>$moduleinfo->coursemodule));
134 if ($returnfromfunc instanceof moodle_exception) {
135 throw $returnfromfunc;
136 } else if (!is_number($returnfromfunc)) {
137 print_error('invalidfunction', '', course_get_url($course, $moduleinfo->section));
138 } else {
139 print_error('cannotaddnewmodule', '', course_get_url($course, $moduleinfo->section), $moduleinfo->modulename);
143 $moduleinfo->instance = $returnfromfunc;
145 $DB->set_field('course_modules', 'instance', $returnfromfunc, array('id'=>$moduleinfo->coursemodule));
147 // Update embedded links and save files.
148 $modcontext = context_module::instance($moduleinfo->coursemodule);
149 if (!empty($introeditor)) {
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;
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));
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);
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);
168 // Trigger event based on the action we did.
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);
174 $event->trigger();
176 $moduleinfo = edit_module_post_actions($moduleinfo, $course);
177 $transaction->allow_commit();
179 return $moduleinfo;
183 * Hook for plugins to take action when a module is created or updated.
185 * @param stdClass $moduleinfo the module info
186 * @param stdClass $course the course of the module
188 * @return stdClass moduleinfo updated by plugins.
190 function 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);
197 return $moduleinfo;
201 * Common create/update module module actions that need to be processed as soon as a module is created/updaded.
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.
205 * @param object $moduleinfo the module info
206 * @param object $course the course of the module
208 * @return object moduleinfo update with grading management info
210 function edit_module_post_actions($moduleinfo, $course) {
211 global $CFG;
212 require_once($CFG->libdir.'/gradelib.php');
214 $modcontext = context_module::instance($moduleinfo->coursemodule);
215 $hasgrades = plugin_supports('mod', $moduleinfo->modulename, FEATURE_GRADE_HAS_GRADE, false);
216 $hasoutcomes = plugin_supports('mod', $moduleinfo->modulename, FEATURE_GRADE_OUTCOMES, true);
218 // Sync idnumber with grade_item.
219 if ($hasgrades && $grade_item = grade_item::fetch(array('itemtype'=>'mod', 'itemmodule'=>$moduleinfo->modulename,
220 'iteminstance'=>$moduleinfo->instance, 'itemnumber'=>0, 'courseid'=>$course->id))) {
221 $gradeupdate = false;
222 if ($grade_item->idnumber != $moduleinfo->cmidnumber) {
223 $grade_item->idnumber = $moduleinfo->cmidnumber;
224 $gradeupdate = true;
226 if (isset($moduleinfo->gradepass) && $grade_item->gradepass != $moduleinfo->gradepass) {
227 $grade_item->gradepass = $moduleinfo->gradepass;
228 $gradeupdate = true;
230 if ($gradeupdate) {
231 $grade_item->update();
235 if ($hasgrades) {
236 $items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$moduleinfo->modulename,
237 'iteminstance'=>$moduleinfo->instance, 'courseid'=>$course->id));
238 } else {
239 $items = array();
242 // Create parent category if requested and move to correct parent category.
243 if ($items and isset($moduleinfo->gradecat)) {
244 if ($moduleinfo->gradecat == -1) {
245 $grade_category = new grade_category();
246 $grade_category->courseid = $course->id;
247 $grade_category->fullname = $moduleinfo->name;
248 $grade_category->insert();
249 if ($grade_item) {
250 $parent = $grade_item->get_parent_category();
251 $grade_category->set_parent($parent->id);
253 $moduleinfo->gradecat = $grade_category->id;
256 foreach ($items as $itemid=>$unused) {
257 $items[$itemid]->set_parent($moduleinfo->gradecat);
258 if ($itemid == $grade_item->id) {
259 // Use updated grade_item.
260 $grade_item = $items[$itemid];
265 require_once($CFG->libdir.'/grade/grade_outcome.php');
266 // Add outcomes if requested.
267 if ($hasoutcomes && $outcomes = grade_outcome::fetch_all_available($course->id)) {
268 $grade_items = array();
270 // Outcome grade_item.itemnumber start at 1000, there is nothing above outcomes.
271 $max_itemnumber = 999;
272 if ($items) {
273 foreach($items as $item) {
274 if ($item->itemnumber > $max_itemnumber) {
275 $max_itemnumber = $item->itemnumber;
280 foreach($outcomes as $outcome) {
281 $elname = 'outcome_'.$outcome->id;
283 if (property_exists($moduleinfo, $elname) and $moduleinfo->$elname) {
284 // So we have a request for new outcome grade item?
285 if ($items) {
286 $outcomeexists = false;
287 foreach($items as $item) {
288 if ($item->outcomeid == $outcome->id) {
289 $outcomeexists = true;
290 break;
293 if ($outcomeexists) {
294 continue;
298 $max_itemnumber++;
300 $outcome_item = new grade_item();
301 $outcome_item->courseid = $course->id;
302 $outcome_item->itemtype = 'mod';
303 $outcome_item->itemmodule = $moduleinfo->modulename;
304 $outcome_item->iteminstance = $moduleinfo->instance;
305 $outcome_item->itemnumber = $max_itemnumber;
306 $outcome_item->itemname = $outcome->fullname;
307 $outcome_item->outcomeid = $outcome->id;
308 $outcome_item->gradetype = GRADE_TYPE_SCALE;
309 $outcome_item->scaleid = $outcome->scaleid;
310 $outcome_item->insert();
312 // Move the new outcome into correct category and fix sortorder if needed.
313 if ($grade_item) {
314 $outcome_item->set_parent($grade_item->categoryid);
315 $outcome_item->move_after_sortorder($grade_item->sortorder);
317 } else if (isset($moduleinfo->gradecat)) {
318 $outcome_item->set_parent($moduleinfo->gradecat);
324 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_ADVANCED_GRADING, false)
325 and has_capability('moodle/grade:managegradingforms', $modcontext)) {
326 require_once($CFG->dirroot.'/grade/grading/lib.php');
327 $gradingman = get_grading_manager($modcontext, 'mod_'.$moduleinfo->modulename);
328 $showgradingmanagement = false;
329 foreach ($gradingman->get_available_areas() as $areaname => $aretitle) {
330 $formfield = 'advancedgradingmethod_'.$areaname;
331 if (isset($moduleinfo->{$formfield})) {
332 $gradingman->set_area($areaname);
333 $methodchanged = $gradingman->set_active_method($moduleinfo->{$formfield});
334 if (empty($moduleinfo->{$formfield})) {
335 // Going back to the simple direct grading is not a reason to open the management screen.
336 $methodchanged = false;
338 $showgradingmanagement = $showgradingmanagement || $methodchanged;
341 // Update grading management information.
342 $moduleinfo->gradingman = $gradingman;
343 $moduleinfo->showgradingmanagement = $showgradingmanagement;
346 rebuild_course_cache($course->id, true);
347 if ($hasgrades) {
348 grade_regrade_final_grades($course->id);
350 require_once($CFG->libdir.'/plagiarismlib.php');
351 plagiarism_save_form_elements($moduleinfo);
353 // Allow plugins to extend the course module form.
354 $moduleinfo = plugin_extend_coursemodule_edit_post_actions($moduleinfo, $course);
356 return $moduleinfo;
361 * Set module info default values for the unset module attributs.
363 * @param object $moduleinfo the current known data of the module
364 * @return object the completed module info
366 function set_moduleinfo_defaults($moduleinfo) {
368 if (empty($moduleinfo->coursemodule)) {
369 // Add.
370 $cm = null;
371 $moduleinfo->instance = '';
372 $moduleinfo->coursemodule = '';
373 } else {
374 // Update.
375 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule, 0, false, MUST_EXIST);
376 $moduleinfo->instance = $cm->instance;
377 $moduleinfo->coursemodule = $cm->id;
379 // For safety.
380 $moduleinfo->modulename = clean_param($moduleinfo->modulename, PARAM_PLUGIN);
382 if (!isset($moduleinfo->groupingid)) {
383 $moduleinfo->groupingid = 0;
386 if (!isset($moduleinfo->name)) { // Label.
387 $moduleinfo->name = $moduleinfo->modulename;
390 if (!isset($moduleinfo->completion)) {
391 $moduleinfo->completion = COMPLETION_DISABLED;
393 if (!isset($moduleinfo->completionview)) {
394 $moduleinfo->completionview = COMPLETION_VIEW_NOT_REQUIRED;
396 if (!isset($moduleinfo->completionexpected)) {
397 $moduleinfo->completionexpected = 0;
400 // Convert the 'use grade' checkbox into a grade-item number: 0 if checked, null if not.
401 if (isset($moduleinfo->completionusegrade) && $moduleinfo->completionusegrade) {
402 $moduleinfo->completiongradeitemnumber = 0;
403 } else {
404 $moduleinfo->completiongradeitemnumber = null;
407 if (!isset($moduleinfo->conditiongradegroup)) {
408 $moduleinfo->conditiongradegroup = array();
410 if (!isset($moduleinfo->conditionfieldgroup)) {
411 $moduleinfo->conditionfieldgroup = array();
414 return $moduleinfo;
418 * Check that the user can add a module. Also returns some information like the module, context and course section info.
419 * The fucntion create the course section if it doesn't exist.
421 * @param object $course the course of the module
422 * @param object $modulename the module name
423 * @param object $section the section of the module
424 * @return array list containing module, context, course section.
425 * @throws moodle_exception if user is not allowed to perform the action or module is not allowed in this course
427 function can_add_moduleinfo($course, $modulename, $section) {
428 global $DB;
430 $module = $DB->get_record('modules', array('name'=>$modulename), '*', MUST_EXIST);
432 $context = context_course::instance($course->id);
433 require_capability('moodle/course:manageactivities', $context);
435 course_create_sections_if_missing($course, $section);
436 $cw = get_fast_modinfo($course)->get_section_info($section);
438 if (!course_allowed_module($course, $module->name)) {
439 print_error('moduledisable');
442 return array($module, $context, $cw);
446 * Check if user is allowed to update module info and returns related item/data to the module.
448 * @param object $cm course module
449 * @return array - list of course module, context, module, moduleinfo, and course section.
450 * @throws moodle_exception if user is not allowed to perform the action
452 function can_update_moduleinfo($cm) {
453 global $DB;
455 // Check the $USER has the right capability.
456 $context = context_module::instance($cm->id);
457 require_capability('moodle/course:manageactivities', $context);
459 // Check module exists.
460 $module = $DB->get_record('modules', array('id'=>$cm->module), '*', MUST_EXIST);
462 // Check the moduleinfo exists.
463 $data = $DB->get_record($module->name, array('id'=>$cm->instance), '*', MUST_EXIST);
465 // Check the course section exists.
466 $cw = $DB->get_record('course_sections', array('id'=>$cm->section), '*', MUST_EXIST);
468 return array($cm, $context, $module, $data, $cw);
473 * Update the module info.
474 * This function doesn't check the user capabilities. It updates the course module and the module instance.
475 * Then execute common action to create/update module process (trigger event, rebuild cache, save plagiarism settings...).
477 * @param object $cm course module
478 * @param object $moduleinfo module info
479 * @param object $course course of the module
480 * @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.
481 * @return array list of course module and module info.
483 function update_moduleinfo($cm, $moduleinfo, $course, $mform = null) {
484 global $DB, $CFG;
486 $data = new stdClass();
487 if ($mform) {
488 $data = $mform->get_data();
491 // Attempt to include module library before we make any changes to DB.
492 include_modulelib($moduleinfo->modulename);
494 $moduleinfo->course = $course->id;
495 $moduleinfo = set_moduleinfo_defaults($moduleinfo);
497 if (!empty($course->groupmodeforce) or !isset($moduleinfo->groupmode)) {
498 $moduleinfo->groupmode = $cm->groupmode; // Keep original.
501 // Update course module first.
502 $cm->groupmode = $moduleinfo->groupmode;
503 if (isset($moduleinfo->groupingid)) {
504 $cm->groupingid = $moduleinfo->groupingid;
507 $completion = new completion_info($course);
508 if ($completion->is_enabled()) {
509 // Completion settings that would affect users who have already completed
510 // the activity may be locked; if so, these should not be updated.
511 if (!empty($moduleinfo->completionunlocked)) {
512 $cm->completion = $moduleinfo->completion;
513 $cm->completiongradeitemnumber = $moduleinfo->completiongradeitemnumber;
514 $cm->completionview = $moduleinfo->completionview;
516 // The expected date does not affect users who have completed the activity,
517 // so it is safe to update it regardless of the lock status.
518 $cm->completionexpected = $moduleinfo->completionexpected;
520 if (!empty($CFG->enableavailability)) {
521 // This code is used both when submitting the form, which uses a long
522 // name to avoid clashes, and by unit test code which uses the real
523 // name in the table.
524 if (property_exists($moduleinfo, 'availabilityconditionsjson')) {
525 if ($moduleinfo->availabilityconditionsjson !== '') {
526 $cm->availability = $moduleinfo->availabilityconditionsjson;
527 } else {
528 $cm->availability = null;
530 } else if (property_exists($moduleinfo, 'availability')) {
531 $cm->availability = $moduleinfo->availability;
533 // If there is any availability data, verify it.
534 if ($cm->availability) {
535 $tree = new \core_availability\tree(json_decode($cm->availability));
536 // Save time and database space by setting null if the only data
537 // is an empty tree.
538 if ($tree->is_empty()) {
539 $cm->availability = null;
543 if (isset($moduleinfo->showdescription)) {
544 $cm->showdescription = $moduleinfo->showdescription;
545 } else {
546 $cm->showdescription = 0;
549 $DB->update_record('course_modules', $cm);
551 $modcontext = context_module::instance($moduleinfo->coursemodule);
553 // Update embedded links and save files.
554 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
555 $moduleinfo->intro = file_save_draft_area_files($moduleinfo->introeditor['itemid'], $modcontext->id,
556 'mod_'.$moduleinfo->modulename, 'intro', 0,
557 array('subdirs'=>true), $moduleinfo->introeditor['text']);
558 $moduleinfo->introformat = $moduleinfo->introeditor['format'];
559 unset($moduleinfo->introeditor);
561 // Get the a copy of the grade_item before it is modified incase we need to scale the grades.
562 $oldgradeitem = null;
563 $newgradeitem = null;
564 if (!empty($data->grade_rescalegrades) && $data->grade_rescalegrades == 'yes') {
565 // Fetch the grade item before it is updated.
566 $oldgradeitem = grade_item::fetch(array('itemtype' => 'mod',
567 'itemmodule' => $moduleinfo->modulename,
568 'iteminstance' => $moduleinfo->instance,
569 'itemnumber' => 0,
570 'courseid' => $moduleinfo->course));
573 $updateinstancefunction = $moduleinfo->modulename."_update_instance";
574 if (!$updateinstancefunction($moduleinfo, $mform)) {
575 print_error('cannotupdatemod', '', course_get_url($course, $cm->section), $moduleinfo->modulename);
578 // This needs to happen AFTER the grademin/grademax have already been updated.
579 if (!empty($data->grade_rescalegrades) && $data->grade_rescalegrades == 'yes') {
580 // Get the grade_item after the update call the activity to scale the grades.
581 $newgradeitem = grade_item::fetch(array('itemtype' => 'mod',
582 'itemmodule' => $moduleinfo->modulename,
583 'iteminstance' => $moduleinfo->instance,
584 'itemnumber' => 0,
585 'courseid' => $moduleinfo->course));
586 if ($newgradeitem && $oldgradeitem->gradetype == GRADE_TYPE_VALUE && $newgradeitem->gradetype == GRADE_TYPE_VALUE) {
587 $params = array(
588 $course,
589 $cm,
590 $oldgradeitem->grademin,
591 $oldgradeitem->grademax,
592 $newgradeitem->grademin,
593 $newgradeitem->grademax
595 if (!component_callback('mod_' . $moduleinfo->modulename, 'rescale_activity_grades', $params)) {
596 print_error('cannotreprocessgrades', '', course_get_url($course, $cm->section), $moduleinfo->modulename);
601 // Make sure visibility is set correctly (in particular in calendar).
602 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
603 set_coursemodule_visible($moduleinfo->coursemodule, $moduleinfo->visible, $moduleinfo->visibleoncoursepage);
606 if (isset($moduleinfo->cmidnumber)) { // Label.
607 // Set cm idnumber - uniqueness is already verified by form validation.
608 set_coursemodule_idnumber($moduleinfo->coursemodule, $moduleinfo->cmidnumber);
611 // Update module tags.
612 if (core_tag_tag::is_enabled('core', 'course_modules') && isset($moduleinfo->tags)) {
613 core_tag_tag::set_item_tags('core', 'course_modules', $moduleinfo->coursemodule, $modcontext, $moduleinfo->tags);
616 // Now that module is fully updated, also update completion data if required.
617 // (this will wipe all user completion data and recalculate it)
618 if ($completion->is_enabled() && !empty($moduleinfo->completionunlocked)) {
619 $completion->reset_all_state($cm);
621 $cm->name = $moduleinfo->name;
622 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
624 $moduleinfo = edit_module_post_actions($moduleinfo, $course);
626 return array($cm, $moduleinfo);
630 * Include once the module lib file.
632 * @param string $modulename module name of the lib to include
633 * @throws moodle_exception if lib.php file for the module does not exist
635 function include_modulelib($modulename) {
636 global $CFG;
637 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
638 if (file_exists($modlib)) {
639 include_once($modlib);
640 } else {
641 throw new moodle_exception('modulemissingcode', '', '', $modlib);
646 * Get module information data required for updating the module.
648 * @param stdClass $cm course module object
649 * @param stdClass $course course object
650 * @return array required data for updating a module
651 * @since Moodle 3.2
653 function get_moduleinfo_data($cm, $course) {
654 global $CFG;
656 list($cm, $context, $module, $data, $cw) = can_update_moduleinfo($cm);
658 $data->coursemodule = $cm->id;
659 $data->section = $cw->section; // The section number itself - relative!!! (section column in course_sections)
660 $data->visible = $cm->visible; //?? $cw->visible ? $cm->visible : 0; // section hiding overrides
661 $data->visibleoncoursepage = $cm->visibleoncoursepage;
662 $data->cmidnumber = $cm->idnumber; // The cm IDnumber
663 $data->groupmode = groups_get_activity_groupmode($cm); // locked later if forced
664 $data->groupingid = $cm->groupingid;
665 $data->course = $course->id;
666 $data->module = $module->id;
667 $data->modulename = $module->name;
668 $data->instance = $cm->instance;
669 $data->completion = $cm->completion;
670 $data->completionview = $cm->completionview;
671 $data->completionexpected = $cm->completionexpected;
672 $data->completionusegrade = is_null($cm->completiongradeitemnumber) ? 0 : 1;
673 $data->showdescription = $cm->showdescription;
674 $data->tags = core_tag_tag::get_item_tags_array('core', 'course_modules', $cm->id);
675 if (!empty($CFG->enableavailability)) {
676 $data->availabilityconditionsjson = $cm->availability;
679 if (plugin_supports('mod', $data->modulename, FEATURE_MOD_INTRO, true)) {
680 $draftid_editor = file_get_submitted_draft_itemid('introeditor');
681 $currentintro = file_prepare_draft_area($draftid_editor, $context->id, 'mod_'.$data->modulename, 'intro', 0, array('subdirs'=>true), $data->intro);
682 $data->introeditor = array('text'=>$currentintro, 'format'=>$data->introformat, 'itemid'=>$draftid_editor);
685 if (plugin_supports('mod', $data->modulename, FEATURE_ADVANCED_GRADING, false)
686 and has_capability('moodle/grade:managegradingforms', $context)) {
687 require_once($CFG->dirroot.'/grade/grading/lib.php');
688 $gradingman = get_grading_manager($context, 'mod_'.$data->modulename);
689 $data->_advancedgradingdata['methods'] = $gradingman->get_available_methods();
690 $areas = $gradingman->get_available_areas();
692 foreach ($areas as $areaname => $areatitle) {
693 $gradingman->set_area($areaname);
694 $method = $gradingman->get_active_method();
695 $data->_advancedgradingdata['areas'][$areaname] = array(
696 'title' => $areatitle,
697 'method' => $method,
699 $formfield = 'advancedgradingmethod_'.$areaname;
700 $data->{$formfield} = $method;
704 if ($items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$data->modulename,
705 'iteminstance'=>$data->instance, 'courseid'=>$course->id))) {
706 // Add existing outcomes.
707 foreach ($items as $item) {
708 if (!empty($item->outcomeid)) {
709 $data->{'outcome_' . $item->outcomeid} = 1;
710 } else if (isset($item->gradepass)) {
711 $decimalpoints = $item->get_decimals();
712 $data->gradepass = format_float($item->gradepass, $decimalpoints);
716 // set category if present
717 $gradecat = false;
718 foreach ($items as $item) {
719 if ($gradecat === false) {
720 $gradecat = $item->categoryid;
721 continue;
723 if ($gradecat != $item->categoryid) {
724 //mixed categories
725 $gradecat = false;
726 break;
729 if ($gradecat !== false) {
730 // do not set if mixed categories present
731 $data->gradecat = $gradecat;
734 return array($cm, $context, $module, $data, $cw);
738 * Prepare the standard module information for a new module instance.
740 * @param stdClass $course course object
741 * @param string $modulename module name
742 * @param int $section section number
743 * @return array module information about other required data
744 * @since Moodle 3.2
746 function prepare_new_moduleinfo_data($course, $modulename, $section) {
747 global $CFG;
749 list($module, $context, $cw) = can_add_moduleinfo($course, $modulename, $section);
751 $cm = null;
753 $data = new stdClass();
754 $data->section = $section; // The section number itself - relative!!! (section column in course_sections)
755 $data->visible = $cw->visible;
756 $data->course = $course->id;
757 $data->module = $module->id;
758 $data->modulename = $module->name;
759 $data->groupmode = $course->groupmode;
760 $data->groupingid = $course->defaultgroupingid;
761 $data->id = '';
762 $data->instance = '';
763 $data->coursemodule = '';
765 // Apply completion defaults.
766 $defaults = \core_completion\manager::get_default_completion($course, $module);
767 foreach ($defaults as $key => $value) {
768 $data->$key = $value;
771 if (plugin_supports('mod', $data->modulename, FEATURE_MOD_INTRO, true)) {
772 $draftid_editor = file_get_submitted_draft_itemid('introeditor');
773 file_prepare_draft_area($draftid_editor, null, null, null, null, array('subdirs'=>true));
774 $data->introeditor = array('text'=>'', 'format'=>FORMAT_HTML, 'itemid'=>$draftid_editor); // TODO: add better default
777 if (plugin_supports('mod', $data->modulename, FEATURE_ADVANCED_GRADING, false)
778 and has_capability('moodle/grade:managegradingforms', $context)) {
779 require_once($CFG->dirroot.'/grade/grading/lib.php');
781 $data->_advancedgradingdata['methods'] = grading_manager::available_methods();
782 $areas = grading_manager::available_areas('mod_'.$module->name);
784 foreach ($areas as $areaname => $areatitle) {
785 $data->_advancedgradingdata['areas'][$areaname] = array(
786 'title' => $areatitle,
787 'method' => '',
789 $formfield = 'advancedgradingmethod_'.$areaname;
790 $data->{$formfield} = '';
794 return array($module, $context, $cw, $cm, $data);