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 $newcm->groupmembersonly
= $moduleinfo->groupmembersonly
;
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
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
94 if ($tree->is_empty()) {
95 $newcm->availability
= null;
99 if (isset($moduleinfo->showdescription
)) {
100 $newcm->showdescription
= $moduleinfo->showdescription
;
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";
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 $modcontext = context_module
::instance($moduleinfo->coursemodule
);
130 context_helper
::delete_instance(CONTEXT_MODULE
, $moduleinfo->coursemodule
);
131 $DB->delete_records('course_modules', array('id'=>$moduleinfo->coursemodule
));
133 if ($e instanceof moodle_exception
) {
135 } else if (!is_number($returnfromfunc)) {
136 print_error('invalidfunction', '', course_get_url($course, $moduleinfo->section
));
138 print_error('cannotaddnewmodule', '', course_get_url($course, $moduleinfo->section
), $moduleinfo->modulename
);
142 $moduleinfo->instance
= $returnfromfunc;
144 $DB->set_field('course_modules', 'instance', $returnfromfunc, array('id'=>$moduleinfo->coursemodule
));
146 // Update embedded links and save files.
147 $modcontext = context_module
::instance($moduleinfo->coursemodule
);
148 if (!empty($introeditor)) {
149 $moduleinfo->intro
= file_save_draft_area_files($introeditor['itemid'], $modcontext->id
,
150 'mod_'.$moduleinfo->modulename
, 'intro', 0,
151 array('subdirs'=>true), $introeditor['text']);
152 $DB->set_field($moduleinfo->modulename
, 'intro', $moduleinfo->intro
, array('id'=>$moduleinfo->instance
));
155 // Course_modules and course_sections each contain a reference to each other.
156 // So we have to update one of them twice.
157 $sectionid = course_add_cm_to_section($course, $moduleinfo->coursemodule
, $moduleinfo->section
);
159 // Trigger event based on the action we did.
160 // Api create_from_cm expects modname and id property, and we don't want to modify $moduleinfo since we are returning it.
161 $eventdata = clone $moduleinfo;
162 $eventdata->modname
= $eventdata->modulename
;
163 $eventdata->id
= $eventdata->coursemodule
;
164 $event = \core\event\course_module_created
::create_from_cm($eventdata, $modcontext);
167 $moduleinfo = edit_module_post_actions($moduleinfo, $course);
168 $transaction->allow_commit();
175 * Common create/update module module actions that need to be processed as soon as a module is created/updaded.
176 * For example:create grade parent category, add outcomes, rebuild caches, regrade, save plagiarism settings...
177 * Please note this api does not trigger events as of MOODLE 2.6. Please trigger events before calling this api.
179 * @param object $moduleinfo the module info
180 * @param object $course the course of the module
182 * @return object moduleinfo update with grading management info
184 function edit_module_post_actions($moduleinfo, $course) {
186 require_once($CFG->libdir
.'/gradelib.php');
188 $modcontext = context_module
::instance($moduleinfo->coursemodule
);
189 $hasgrades = plugin_supports('mod', $moduleinfo->modulename
, FEATURE_GRADE_HAS_GRADE
, false);
190 $hasoutcomes = plugin_supports('mod', $moduleinfo->modulename
, FEATURE_GRADE_OUTCOMES
, true);
192 // Sync idnumber with grade_item.
193 if ($hasgrades && $grade_item = grade_item
::fetch(array('itemtype'=>'mod', 'itemmodule'=>$moduleinfo->modulename
,
194 'iteminstance'=>$moduleinfo->instance
, 'itemnumber'=>0, 'courseid'=>$course->id
))) {
195 if ($grade_item->idnumber
!= $moduleinfo->cmidnumber
) {
196 $grade_item->idnumber
= $moduleinfo->cmidnumber
;
197 $grade_item->update();
202 $items = grade_item
::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$moduleinfo->modulename
,
203 'iteminstance'=>$moduleinfo->instance
, 'courseid'=>$course->id
));
208 // Create parent category if requested and move to correct parent category.
209 if ($items and isset($moduleinfo->gradecat
)) {
210 if ($moduleinfo->gradecat
== -1) {
211 $grade_category = new grade_category();
212 $grade_category->courseid
= $course->id
;
213 $grade_category->fullname
= $moduleinfo->name
;
214 $grade_category->insert();
216 $parent = $grade_item->get_parent_category();
217 $grade_category->set_parent($parent->id
);
219 $moduleinfo->gradecat
= $grade_category->id
;
222 foreach ($items as $itemid=>$unused) {
223 $items[$itemid]->set_parent($moduleinfo->gradecat
);
224 if ($itemid == $grade_item->id
) {
225 // Use updated grade_item.
226 $grade_item = $items[$itemid];
228 $gradecategory = $grade_item->get_parent_category();
229 if (!empty($moduleinfo->add
)) {
230 if (grade_category
::aggregation_uses_aggregationcoef($gradecategory->aggregation
)) {
231 if ($gradecategory->aggregation
== GRADE_AGGREGATE_WEIGHTED_MEAN
) {
232 $grade_item->aggregationcoef
= 1;
234 $grade_item->aggregationcoef
= 0;
236 $grade_item->update();
242 require_once($CFG->libdir
.'/grade/grade_outcome.php');
243 // Add outcomes if requested.
244 if ($hasoutcomes && $outcomes = grade_outcome
::fetch_all_available($course->id
)) {
245 $grade_items = array();
247 // Outcome grade_item.itemnumber start at 1000, there is nothing above outcomes.
248 $max_itemnumber = 999;
250 foreach($items as $item) {
251 if ($item->itemnumber
> $max_itemnumber) {
252 $max_itemnumber = $item->itemnumber
;
257 foreach($outcomes as $outcome) {
258 $elname = 'outcome_'.$outcome->id
;
260 if (property_exists($moduleinfo, $elname) and $moduleinfo->$elname) {
261 // So we have a request for new outcome grade item?
263 $outcomeexists = false;
264 foreach($items as $item) {
265 if ($item->outcomeid
== $outcome->id
) {
266 $outcomeexists = true;
270 if ($outcomeexists) {
277 $outcome_item = new grade_item();
278 $outcome_item->courseid
= $course->id
;
279 $outcome_item->itemtype
= 'mod';
280 $outcome_item->itemmodule
= $moduleinfo->modulename
;
281 $outcome_item->iteminstance
= $moduleinfo->instance
;
282 $outcome_item->itemnumber
= $max_itemnumber;
283 $outcome_item->itemname
= $outcome->fullname
;
284 $outcome_item->outcomeid
= $outcome->id
;
285 $outcome_item->gradetype
= GRADE_TYPE_SCALE
;
286 $outcome_item->scaleid
= $outcome->scaleid
;
287 $outcome_item->insert();
289 // Move the new outcome into correct category and fix sortorder if needed.
291 $outcome_item->set_parent($grade_item->categoryid
);
292 $outcome_item->move_after_sortorder($grade_item->sortorder
);
294 } else if (isset($moduleinfo->gradecat
)) {
295 $outcome_item->set_parent($moduleinfo->gradecat
);
297 $gradecategory = $outcome_item->get_parent_category();
298 if ($outcomeexists == false) {
299 if (grade_category
::aggregation_uses_aggregationcoef($gradecategory->aggregation
)) {
300 if ($gradecategory->aggregation
== GRADE_AGGREGATE_WEIGHTED_MEAN
) {
301 $outcome_item->aggregationcoef
= 1;
303 $outcome_item->aggregationcoef
= 0;
305 $outcome_item->update();
312 if (plugin_supports('mod', $moduleinfo->modulename
, FEATURE_ADVANCED_GRADING
, false)
313 and has_capability('moodle/grade:managegradingforms', $modcontext)) {
314 require_once($CFG->dirroot
.'/grade/grading/lib.php');
315 $gradingman = get_grading_manager($modcontext, 'mod_'.$moduleinfo->modulename
);
316 $showgradingmanagement = false;
317 foreach ($gradingman->get_available_areas() as $areaname => $aretitle) {
318 $formfield = 'advancedgradingmethod_'.$areaname;
319 if (isset($moduleinfo->{$formfield})) {
320 $gradingman->set_area($areaname);
321 $methodchanged = $gradingman->set_active_method($moduleinfo->{$formfield});
322 if (empty($moduleinfo->{$formfield})) {
323 // Going back to the simple direct grading is not a reason to open the management screen.
324 $methodchanged = false;
326 $showgradingmanagement = $showgradingmanagement ||
$methodchanged;
329 // Update grading management information.
330 $moduleinfo->gradingman
= $gradingman;
331 $moduleinfo->showgradingmanagement
= $showgradingmanagement;
334 rebuild_course_cache($course->id
, true);
336 grade_regrade_final_grades($course->id
);
338 require_once($CFG->libdir
.'/plagiarismlib.php');
339 plagiarism_save_form_elements($moduleinfo);
346 * Set module info default values for the unset module attributs.
348 * @param object $moduleinfo the current known data of the module
349 * @return object the completed module info
351 function set_moduleinfo_defaults($moduleinfo) {
353 if (empty($moduleinfo->coursemodule
)) {
356 $moduleinfo->instance
= '';
357 $moduleinfo->coursemodule
= '';
360 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule
, 0, false, MUST_EXIST
);
361 $moduleinfo->instance
= $cm->instance
;
362 $moduleinfo->coursemodule
= $cm->id
;
365 $moduleinfo->modulename
= clean_param($moduleinfo->modulename
, PARAM_PLUGIN
);
367 if (!isset($moduleinfo->groupingid
)) {
368 $moduleinfo->groupingid
= 0;
371 if (!isset($moduleinfo->groupmembersonly
)) {
372 $moduleinfo->groupmembersonly
= 0;
375 if (!isset($moduleinfo->name
)) { // Label.
376 $moduleinfo->name
= $moduleinfo->modulename
;
379 if (!isset($moduleinfo->completion
)) {
380 $moduleinfo->completion
= COMPLETION_DISABLED
;
382 if (!isset($moduleinfo->completionview
)) {
383 $moduleinfo->completionview
= COMPLETION_VIEW_NOT_REQUIRED
;
385 if (!isset($moduleinfo->completionexpected
)) {
386 $moduleinfo->completionexpected
= 0;
389 // Convert the 'use grade' checkbox into a grade-item number: 0 if checked, null if not.
390 if (isset($moduleinfo->completionusegrade
) && $moduleinfo->completionusegrade
) {
391 $moduleinfo->completiongradeitemnumber
= 0;
393 $moduleinfo->completiongradeitemnumber
= null;
396 if (!isset($moduleinfo->conditiongradegroup
)) {
397 $moduleinfo->conditiongradegroup
= array();
399 if (!isset($moduleinfo->conditionfieldgroup
)) {
400 $moduleinfo->conditionfieldgroup
= array();
407 * Check that the user can add a module. Also returns some information like the module, context and course section info.
408 * The fucntion create the course section if it doesn't exist.
410 * @param object $course the course of the module
411 * @param object $modulename the module name
412 * @param object $section the section of the module
413 * @return array list containing module, context, course section.
414 * @throws moodle_exception if user is not allowed to perform the action or module is not allowed in this course
416 function can_add_moduleinfo($course, $modulename, $section) {
419 $module = $DB->get_record('modules', array('name'=>$modulename), '*', MUST_EXIST
);
421 $context = context_course
::instance($course->id
);
422 require_capability('moodle/course:manageactivities', $context);
424 course_create_sections_if_missing($course, $section);
425 $cw = get_fast_modinfo($course)->get_section_info($section);
427 if (!course_allowed_module($course, $module->name
)) {
428 print_error('moduledisable');
431 return array($module, $context, $cw);
435 * Check if user is allowed to update module info and returns related item/data to the module.
437 * @param object $cm course module
438 * @return array - list of course module, context, module, moduleinfo, and course section.
439 * @throws moodle_exception if user is not allowed to perform the action
441 function can_update_moduleinfo($cm) {
444 // Check the $USER has the right capability.
445 $context = context_module
::instance($cm->id
);
446 require_capability('moodle/course:manageactivities', $context);
448 // Check module exists.
449 $module = $DB->get_record('modules', array('id'=>$cm->module
), '*', MUST_EXIST
);
451 // Check the moduleinfo exists.
452 $data = $DB->get_record($module->name
, array('id'=>$cm->instance
), '*', MUST_EXIST
);
454 // Check the course section exists.
455 $cw = $DB->get_record('course_sections', array('id'=>$cm->section
), '*', MUST_EXIST
);
457 return array($cm, $context, $module, $data, $cw);
462 * Update the module info.
463 * This function doesn't check the user capabilities. It updates the course module and the module instance.
464 * Then execute common action to create/update module process (trigger event, rebuild cache, save plagiarism settings...).
466 * @param object $cm course module
467 * @param object $moduleinfo module info
468 * @param object $course course of the module
469 * @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.
470 * @return array list of course module and module info.
472 function update_moduleinfo($cm, $moduleinfo, $course, $mform = null) {
475 // Attempt to include module library before we make any changes to DB.
476 include_modulelib($moduleinfo->modulename
);
478 $moduleinfo->course
= $course->id
;
479 $moduleinfo = set_moduleinfo_defaults($moduleinfo);
481 if (!empty($course->groupmodeforce
) or !isset($moduleinfo->groupmode
)) {
482 $moduleinfo->groupmode
= $cm->groupmode
; // Keep original.
485 // Update course module first.
486 $cm->groupmode
= $moduleinfo->groupmode
;
487 if (isset($moduleinfo->groupingid
)) {
488 $cm->groupingid
= $moduleinfo->groupingid
;
490 if (isset($moduleinfo->groupmembersonly
)) {
491 $cm->groupmembersonly
= $moduleinfo->groupmembersonly
;
494 $completion = new completion_info($course);
495 if ($completion->is_enabled()) {
496 // Completion settings that would affect users who have already completed
497 // the activity may be locked; if so, these should not be updated.
498 if (!empty($moduleinfo->completionunlocked
)) {
499 $cm->completion
= $moduleinfo->completion
;
500 $cm->completiongradeitemnumber
= $moduleinfo->completiongradeitemnumber
;
501 $cm->completionview
= $moduleinfo->completionview
;
503 // The expected date does not affect users who have completed the activity,
504 // so it is safe to update it regardless of the lock status.
505 $cm->completionexpected
= $moduleinfo->completionexpected
;
507 if (!empty($CFG->enableavailability
)) {
508 // This code is used both when submitting the form, which uses a long
509 // name to avoid clashes, and by unit test code which uses the real
510 // name in the table.
511 if (property_exists($moduleinfo, 'availabilityconditionsjson')) {
512 if ($moduleinfo->availabilityconditionsjson
!== '') {
513 $cm->availability
= $moduleinfo->availabilityconditionsjson
;
515 $cm->availability
= null;
517 } else if (property_exists($moduleinfo, 'availability')) {
518 $cm->availability
= $moduleinfo->availability
;
520 // If there is any availability data, verify it.
521 if ($cm->availability
) {
522 $tree = new \core_availability\tree
(json_decode($cm->availability
));
523 // Save time and database space by setting null if the only data
525 if ($tree->is_empty()) {
526 $cm->availability
= null;
530 if (isset($moduleinfo->showdescription
)) {
531 $cm->showdescription
= $moduleinfo->showdescription
;
533 $cm->showdescription
= 0;
536 $DB->update_record('course_modules', $cm);
538 $modcontext = context_module
::instance($moduleinfo->coursemodule
);
540 // Update embedded links and save files.
541 if (plugin_supports('mod', $moduleinfo->modulename
, FEATURE_MOD_INTRO
, true)) {
542 $moduleinfo->intro
= file_save_draft_area_files($moduleinfo->introeditor
['itemid'], $modcontext->id
,
543 'mod_'.$moduleinfo->modulename
, 'intro', 0,
544 array('subdirs'=>true), $moduleinfo->introeditor
['text']);
545 $moduleinfo->introformat
= $moduleinfo->introeditor
['format'];
546 unset($moduleinfo->introeditor
);
548 $updateinstancefunction = $moduleinfo->modulename
."_update_instance";
549 if (!$updateinstancefunction($moduleinfo, $mform)) {
550 print_error('cannotupdatemod', '', course_get_url($course, $cw->section
), $moduleinfo->modulename
);
553 // Make sure visibility is set correctly (in particular in calendar).
554 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
555 set_coursemodule_visible($moduleinfo->coursemodule
, $moduleinfo->visible
);
558 if (isset($moduleinfo->cmidnumber
)) { // Label.
559 // Set cm idnumber - uniqueness is already verified by form validation.
560 set_coursemodule_idnumber($moduleinfo->coursemodule
, $moduleinfo->cmidnumber
);
563 // Now that module is fully updated, also update completion data if required.
564 // (this will wipe all user completion data and recalculate it)
565 if ($completion->is_enabled() && !empty($moduleinfo->completionunlocked
)) {
566 $completion->reset_all_state($cm);
568 $cm->name
= $moduleinfo->name
;
569 \core\event\course_module_updated
::create_from_cm($cm, $modcontext)->trigger();
571 $moduleinfo = edit_module_post_actions($moduleinfo, $course);
573 return array($cm, $moduleinfo);
577 * Include once the module lib file.
579 * @param string $modulename module name of the lib to include
580 * @throws moodle_exception if lib.php file for the module does not exist
582 function include_modulelib($modulename) {
584 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
585 if (file_exists($modlib)) {
586 include_once($modlib);
588 throw new moodle_exception('modulemissingcode', '', '', $modlib);