2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
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');
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) {
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->cmidnumber
)) {
65 $newcm->idnumber
= $moduleinfo->cmidnumber
;
67 $newcm->groupmode
= $moduleinfo->groupmode
;
68 $newcm->groupingid
= $moduleinfo->groupingid
;
69 $completion = new completion_info($course);
70 if ($completion->is_enabled()) {
71 $newcm->completion
= $moduleinfo->completion
;
72 $newcm->completiongradeitemnumber
= $moduleinfo->completiongradeitemnumber
;
73 $newcm->completionview
= $moduleinfo->completionview
;
74 $newcm->completionexpected
= $moduleinfo->completionexpected
;
76 if(!empty($CFG->enableavailability
)) {
77 // This code is used both when submitting the form, which uses a long
78 // name to avoid clashes, and by unit test code which uses the real
80 $newcm->availability
= null;
81 if (property_exists($moduleinfo, 'availabilityconditionsjson')) {
82 if ($moduleinfo->availabilityconditionsjson
!== '') {
83 $newcm->availability
= $moduleinfo->availabilityconditionsjson
;
85 } else if (property_exists($moduleinfo, 'availability')) {
86 $newcm->availability
= $moduleinfo->availability
;
88 // If there is any availability data, verify it.
89 if ($newcm->availability
) {
90 $tree = new \core_availability\tree
(json_decode($newcm->availability
));
91 // Save time and database space by setting null if the only data
93 if ($tree->is_empty()) {
94 $newcm->availability
= null;
98 if (isset($moduleinfo->showdescription
)) {
99 $newcm->showdescription
= $moduleinfo->showdescription
;
101 $newcm->showdescription
= 0;
104 // From this point we make database changes, so start transaction.
105 $transaction = $DB->start_delegated_transaction();
107 if (!$moduleinfo->coursemodule
= add_course_module($newcm)) {
108 print_error('cannotaddcoursemodule');
111 if (plugin_supports('mod', $moduleinfo->modulename
, FEATURE_MOD_INTRO
, true) &&
112 isset($moduleinfo->introeditor
)) {
113 $introeditor = $moduleinfo->introeditor
;
114 unset($moduleinfo->introeditor
);
115 $moduleinfo->intro
= $introeditor['text'];
116 $moduleinfo->introformat
= $introeditor['format'];
119 $addinstancefunction = $moduleinfo->modulename
."_add_instance";
121 $returnfromfunc = $addinstancefunction($moduleinfo, $mform);
122 } catch (moodle_exception
$e) {
123 $returnfromfunc = $e;
125 if (!$returnfromfunc or !is_number($returnfromfunc)) {
126 // Undo everything we can. This is not necessary for databases which
127 // support transactions, but improves consistency for other databases.
128 $modcontext = context_module
::instance($moduleinfo->coursemodule
);
129 context_helper
::delete_instance(CONTEXT_MODULE
, $moduleinfo->coursemodule
);
130 $DB->delete_records('course_modules', array('id'=>$moduleinfo->coursemodule
));
132 if ($e instanceof moodle_exception
) {
134 } else if (!is_number($returnfromfunc)) {
135 print_error('invalidfunction', '', course_get_url($course, $moduleinfo->section
));
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 $moduleinfo->intro
= file_save_draft_area_files($introeditor['itemid'], $modcontext->id
,
149 'mod_'.$moduleinfo->modulename
, 'intro', 0,
150 array('subdirs'=>true), $introeditor['text']);
151 $DB->set_field($moduleinfo->modulename
, 'intro', $moduleinfo->intro
, array('id'=>$moduleinfo->instance
));
154 // Course_modules and course_sections each contain a reference to each other.
155 // So we have to update one of them twice.
156 $sectionid = course_add_cm_to_section($course, $moduleinfo->coursemodule
, $moduleinfo->section
);
158 // Trigger event based on the action we did.
159 // Api create_from_cm expects modname and id property, and we don't want to modify $moduleinfo since we are returning it.
160 $eventdata = clone $moduleinfo;
161 $eventdata->modname
= $eventdata->modulename
;
162 $eventdata->id
= $eventdata->coursemodule
;
163 $event = \core\event\course_module_created
::create_from_cm($eventdata, $modcontext);
166 $moduleinfo = edit_module_post_actions($moduleinfo, $course);
167 $transaction->allow_commit();
174 * Common create/update module module actions that need to be processed as soon as a module is created/updaded.
175 * For example:create grade parent category, add outcomes, rebuild caches, regrade, save plagiarism settings...
176 * Please note this api does not trigger events as of MOODLE 2.6. Please trigger events before calling this api.
178 * @param object $moduleinfo the module info
179 * @param object $course the course of the module
181 * @return object moduleinfo update with grading management info
183 function edit_module_post_actions($moduleinfo, $course) {
185 require_once($CFG->libdir
.'/gradelib.php');
187 $modcontext = context_module
::instance($moduleinfo->coursemodule
);
188 $hasgrades = plugin_supports('mod', $moduleinfo->modulename
, FEATURE_GRADE_HAS_GRADE
, false);
189 $hasoutcomes = plugin_supports('mod', $moduleinfo->modulename
, FEATURE_GRADE_OUTCOMES
, true);
191 // Sync idnumber with grade_item.
192 if ($hasgrades && $grade_item = grade_item
::fetch(array('itemtype'=>'mod', 'itemmodule'=>$moduleinfo->modulename
,
193 'iteminstance'=>$moduleinfo->instance
, 'itemnumber'=>0, 'courseid'=>$course->id
))) {
194 if ($grade_item->idnumber
!= $moduleinfo->cmidnumber
) {
195 $grade_item->idnumber
= $moduleinfo->cmidnumber
;
196 $grade_item->update();
201 $items = grade_item
::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$moduleinfo->modulename
,
202 'iteminstance'=>$moduleinfo->instance
, 'courseid'=>$course->id
));
207 // Create parent category if requested and move to correct parent category.
208 if ($items and isset($moduleinfo->gradecat
)) {
209 if ($moduleinfo->gradecat
== -1) {
210 $grade_category = new grade_category();
211 $grade_category->courseid
= $course->id
;
212 $grade_category->fullname
= $moduleinfo->name
;
213 $grade_category->insert();
215 $parent = $grade_item->get_parent_category();
216 $grade_category->set_parent($parent->id
);
218 $moduleinfo->gradecat
= $grade_category->id
;
220 $gradecategory = $grade_item->get_parent_category();
221 foreach ($items as $itemid=>$unused) {
222 $items[$itemid]->set_parent($moduleinfo->gradecat
);
223 if ($itemid == $grade_item->id
) {
224 // Use updated grade_item.
225 $grade_item = $items[$itemid];
227 if (!empty($moduleinfo->add
)) {
228 if (grade_category
::aggregation_uses_aggregationcoef($gradecategory->aggregation
)) {
229 if ($gradecategory->aggregation
== GRADE_AGGREGATE_WEIGHTED_MEAN
) {
230 $grade_item->aggregationcoef
= 1;
232 $grade_item->aggregationcoef
= 0;
234 $grade_item->update();
240 require_once($CFG->libdir
.'/grade/grade_outcome.php');
241 // Add outcomes if requested.
242 if ($hasoutcomes && $outcomes = grade_outcome
::fetch_all_available($course->id
)) {
243 $grade_items = array();
245 // Outcome grade_item.itemnumber start at 1000, there is nothing above outcomes.
246 $max_itemnumber = 999;
248 foreach($items as $item) {
249 if ($item->itemnumber
> $max_itemnumber) {
250 $max_itemnumber = $item->itemnumber
;
255 foreach($outcomes as $outcome) {
256 $elname = 'outcome_'.$outcome->id
;
258 if (property_exists($moduleinfo, $elname) and $moduleinfo->$elname) {
259 // So we have a request for new outcome grade item?
261 $outcomeexists = false;
262 foreach($items as $item) {
263 if ($item->outcomeid
== $outcome->id
) {
264 $outcomeexists = true;
268 if ($outcomeexists) {
275 $outcome_item = new grade_item();
276 $outcome_item->courseid
= $course->id
;
277 $outcome_item->itemtype
= 'mod';
278 $outcome_item->itemmodule
= $moduleinfo->modulename
;
279 $outcome_item->iteminstance
= $moduleinfo->instance
;
280 $outcome_item->itemnumber
= $max_itemnumber;
281 $outcome_item->itemname
= $outcome->fullname
;
282 $outcome_item->outcomeid
= $outcome->id
;
283 $outcome_item->gradetype
= GRADE_TYPE_SCALE
;
284 $outcome_item->scaleid
= $outcome->scaleid
;
285 $outcome_item->insert();
287 // Move the new outcome into correct category and fix sortorder if needed.
289 $outcome_item->set_parent($grade_item->categoryid
);
290 $outcome_item->move_after_sortorder($grade_item->sortorder
);
292 } else if (isset($moduleinfo->gradecat
)) {
293 $outcome_item->set_parent($moduleinfo->gradecat
);
295 $gradecategory = $outcome_item->get_parent_category();
296 if ($outcomeexists == false) {
297 if (grade_category
::aggregation_uses_aggregationcoef($gradecategory->aggregation
)) {
298 if ($gradecategory->aggregation
== GRADE_AGGREGATE_WEIGHTED_MEAN
) {
299 $outcome_item->aggregationcoef
= 1;
301 $outcome_item->aggregationcoef
= 0;
303 $outcome_item->update();
310 if (plugin_supports('mod', $moduleinfo->modulename
, FEATURE_ADVANCED_GRADING
, false)
311 and has_capability('moodle/grade:managegradingforms', $modcontext)) {
312 require_once($CFG->dirroot
.'/grade/grading/lib.php');
313 $gradingman = get_grading_manager($modcontext, 'mod_'.$moduleinfo->modulename
);
314 $showgradingmanagement = false;
315 foreach ($gradingman->get_available_areas() as $areaname => $aretitle) {
316 $formfield = 'advancedgradingmethod_'.$areaname;
317 if (isset($moduleinfo->{$formfield})) {
318 $gradingman->set_area($areaname);
319 $methodchanged = $gradingman->set_active_method($moduleinfo->{$formfield});
320 if (empty($moduleinfo->{$formfield})) {
321 // Going back to the simple direct grading is not a reason to open the management screen.
322 $methodchanged = false;
324 $showgradingmanagement = $showgradingmanagement ||
$methodchanged;
327 // Update grading management information.
328 $moduleinfo->gradingman
= $gradingman;
329 $moduleinfo->showgradingmanagement
= $showgradingmanagement;
332 rebuild_course_cache($course->id
, true);
334 grade_regrade_final_grades($course->id
);
336 require_once($CFG->libdir
.'/plagiarismlib.php');
337 plagiarism_save_form_elements($moduleinfo);
344 * Set module info default values for the unset module attributs.
346 * @param object $moduleinfo the current known data of the module
347 * @return object the completed module info
349 function set_moduleinfo_defaults($moduleinfo) {
351 if (empty($moduleinfo->coursemodule
)) {
354 $moduleinfo->instance
= '';
355 $moduleinfo->coursemodule
= '';
358 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule
, 0, false, MUST_EXIST
);
359 $moduleinfo->instance
= $cm->instance
;
360 $moduleinfo->coursemodule
= $cm->id
;
363 $moduleinfo->modulename
= clean_param($moduleinfo->modulename
, PARAM_PLUGIN
);
365 if (!isset($moduleinfo->groupingid
)) {
366 $moduleinfo->groupingid
= 0;
369 if (!isset($moduleinfo->name
)) { // Label.
370 $moduleinfo->name
= $moduleinfo->modulename
;
373 if (!isset($moduleinfo->completion
)) {
374 $moduleinfo->completion
= COMPLETION_DISABLED
;
376 if (!isset($moduleinfo->completionview
)) {
377 $moduleinfo->completionview
= COMPLETION_VIEW_NOT_REQUIRED
;
379 if (!isset($moduleinfo->completionexpected
)) {
380 $moduleinfo->completionexpected
= 0;
383 // Convert the 'use grade' checkbox into a grade-item number: 0 if checked, null if not.
384 if (isset($moduleinfo->completionusegrade
) && $moduleinfo->completionusegrade
) {
385 $moduleinfo->completiongradeitemnumber
= 0;
387 $moduleinfo->completiongradeitemnumber
= null;
390 if (!isset($moduleinfo->conditiongradegroup
)) {
391 $moduleinfo->conditiongradegroup
= array();
393 if (!isset($moduleinfo->conditionfieldgroup
)) {
394 $moduleinfo->conditionfieldgroup
= array();
401 * Check that the user can add a module. Also returns some information like the module, context and course section info.
402 * The fucntion create the course section if it doesn't exist.
404 * @param object $course the course of the module
405 * @param object $modulename the module name
406 * @param object $section the section of the module
407 * @return array list containing module, context, course section.
408 * @throws moodle_exception if user is not allowed to perform the action or module is not allowed in this course
410 function can_add_moduleinfo($course, $modulename, $section) {
413 $module = $DB->get_record('modules', array('name'=>$modulename), '*', MUST_EXIST
);
415 $context = context_course
::instance($course->id
);
416 require_capability('moodle/course:manageactivities', $context);
418 course_create_sections_if_missing($course, $section);
419 $cw = get_fast_modinfo($course)->get_section_info($section);
421 if (!course_allowed_module($course, $module->name
)) {
422 print_error('moduledisable');
425 return array($module, $context, $cw);
429 * Check if user is allowed to update module info and returns related item/data to the module.
431 * @param object $cm course module
432 * @return array - list of course module, context, module, moduleinfo, and course section.
433 * @throws moodle_exception if user is not allowed to perform the action
435 function can_update_moduleinfo($cm) {
438 // Check the $USER has the right capability.
439 $context = context_module
::instance($cm->id
);
440 require_capability('moodle/course:manageactivities', $context);
442 // Check module exists.
443 $module = $DB->get_record('modules', array('id'=>$cm->module
), '*', MUST_EXIST
);
445 // Check the moduleinfo exists.
446 $data = $DB->get_record($module->name
, array('id'=>$cm->instance
), '*', MUST_EXIST
);
448 // Check the course section exists.
449 $cw = $DB->get_record('course_sections', array('id'=>$cm->section
), '*', MUST_EXIST
);
451 return array($cm, $context, $module, $data, $cw);
456 * Update the module info.
457 * This function doesn't check the user capabilities. It updates the course module and the module instance.
458 * Then execute common action to create/update module process (trigger event, rebuild cache, save plagiarism settings...).
460 * @param object $cm course module
461 * @param object $moduleinfo module info
462 * @param object $course course of the module
463 * @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.
464 * @return array list of course module and module info.
466 function update_moduleinfo($cm, $moduleinfo, $course, $mform = null) {
469 // Attempt to include module library before we make any changes to DB.
470 include_modulelib($moduleinfo->modulename
);
472 $moduleinfo->course
= $course->id
;
473 $moduleinfo = set_moduleinfo_defaults($moduleinfo);
475 if (!empty($course->groupmodeforce
) or !isset($moduleinfo->groupmode
)) {
476 $moduleinfo->groupmode
= $cm->groupmode
; // Keep original.
479 // Update course module first.
480 $cm->groupmode
= $moduleinfo->groupmode
;
481 if (isset($moduleinfo->groupingid
)) {
482 $cm->groupingid
= $moduleinfo->groupingid
;
485 $completion = new completion_info($course);
486 if ($completion->is_enabled()) {
487 // Completion settings that would affect users who have already completed
488 // the activity may be locked; if so, these should not be updated.
489 if (!empty($moduleinfo->completionunlocked
)) {
490 $cm->completion
= $moduleinfo->completion
;
491 $cm->completiongradeitemnumber
= $moduleinfo->completiongradeitemnumber
;
492 $cm->completionview
= $moduleinfo->completionview
;
494 // The expected date does not affect users who have completed the activity,
495 // so it is safe to update it regardless of the lock status.
496 $cm->completionexpected
= $moduleinfo->completionexpected
;
498 if (!empty($CFG->enableavailability
)) {
499 // This code is used both when submitting the form, which uses a long
500 // name to avoid clashes, and by unit test code which uses the real
501 // name in the table.
502 if (property_exists($moduleinfo, 'availabilityconditionsjson')) {
503 if ($moduleinfo->availabilityconditionsjson
!== '') {
504 $cm->availability
= $moduleinfo->availabilityconditionsjson
;
506 $cm->availability
= null;
508 } else if (property_exists($moduleinfo, 'availability')) {
509 $cm->availability
= $moduleinfo->availability
;
511 // If there is any availability data, verify it.
512 if ($cm->availability
) {
513 $tree = new \core_availability\tree
(json_decode($cm->availability
));
514 // Save time and database space by setting null if the only data
516 if ($tree->is_empty()) {
517 $cm->availability
= null;
521 if (isset($moduleinfo->showdescription
)) {
522 $cm->showdescription
= $moduleinfo->showdescription
;
524 $cm->showdescription
= 0;
527 $DB->update_record('course_modules', $cm);
529 $modcontext = context_module
::instance($moduleinfo->coursemodule
);
531 // Update embedded links and save files.
532 if (plugin_supports('mod', $moduleinfo->modulename
, FEATURE_MOD_INTRO
, true)) {
533 $moduleinfo->intro
= file_save_draft_area_files($moduleinfo->introeditor
['itemid'], $modcontext->id
,
534 'mod_'.$moduleinfo->modulename
, 'intro', 0,
535 array('subdirs'=>true), $moduleinfo->introeditor
['text']);
536 $moduleinfo->introformat
= $moduleinfo->introeditor
['format'];
537 unset($moduleinfo->introeditor
);
539 $updateinstancefunction = $moduleinfo->modulename
."_update_instance";
540 if (!$updateinstancefunction($moduleinfo, $mform)) {
541 print_error('cannotupdatemod', '', course_get_url($course, $cw->section
), $moduleinfo->modulename
);
544 // Make sure visibility is set correctly (in particular in calendar).
545 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
546 set_coursemodule_visible($moduleinfo->coursemodule
, $moduleinfo->visible
);
549 if (isset($moduleinfo->cmidnumber
)) { // Label.
550 // Set cm idnumber - uniqueness is already verified by form validation.
551 set_coursemodule_idnumber($moduleinfo->coursemodule
, $moduleinfo->cmidnumber
);
554 // Now that module is fully updated, also update completion data if required.
555 // (this will wipe all user completion data and recalculate it)
556 if ($completion->is_enabled() && !empty($moduleinfo->completionunlocked
)) {
557 $completion->reset_all_state($cm);
559 $cm->name
= $moduleinfo->name
;
560 \core\event\course_module_updated
::create_from_cm($cm, $modcontext)->trigger();
562 $moduleinfo = edit_module_post_actions($moduleinfo, $course);
564 return array($cm, $moduleinfo);
568 * Include once the module lib file.
570 * @param string $modulename module name of the lib to include
571 * @throws moodle_exception if lib.php file for the module does not exist
573 function include_modulelib($modulename) {
575 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
576 if (file_exists($modlib)) {
577 include_once($modlib);
579 throw new moodle_exception('modulemissingcode', '', '', $modlib);