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
;
221 $gradecategory = $grade_item->get_parent_category();
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 if (!empty($moduleinfo->add
)) {
229 if (grade_category
::aggregation_uses_aggregationcoef($gradecategory->aggregation
)) {
230 if ($gradecategory->aggregation
== GRADE_AGGREGATE_WEIGHTED_MEAN
) {
231 $grade_item->aggregationcoef
= 1;
233 $grade_item->aggregationcoef
= 0;
235 $grade_item->update();
241 require_once($CFG->libdir
.'/grade/grade_outcome.php');
242 // Add outcomes if requested.
243 if ($hasoutcomes && $outcomes = grade_outcome
::fetch_all_available($course->id
)) {
244 $grade_items = array();
246 // Outcome grade_item.itemnumber start at 1000, there is nothing above outcomes.
247 $max_itemnumber = 999;
249 foreach($items as $item) {
250 if ($item->itemnumber
> $max_itemnumber) {
251 $max_itemnumber = $item->itemnumber
;
256 foreach($outcomes as $outcome) {
257 $elname = 'outcome_'.$outcome->id
;
259 if (property_exists($moduleinfo, $elname) and $moduleinfo->$elname) {
260 // So we have a request for new outcome grade item?
262 $outcomeexists = false;
263 foreach($items as $item) {
264 if ($item->outcomeid
== $outcome->id
) {
265 $outcomeexists = true;
269 if ($outcomeexists) {
276 $outcome_item = new grade_item();
277 $outcome_item->courseid
= $course->id
;
278 $outcome_item->itemtype
= 'mod';
279 $outcome_item->itemmodule
= $moduleinfo->modulename
;
280 $outcome_item->iteminstance
= $moduleinfo->instance
;
281 $outcome_item->itemnumber
= $max_itemnumber;
282 $outcome_item->itemname
= $outcome->fullname
;
283 $outcome_item->outcomeid
= $outcome->id
;
284 $outcome_item->gradetype
= GRADE_TYPE_SCALE
;
285 $outcome_item->scaleid
= $outcome->scaleid
;
286 $outcome_item->insert();
288 // Move the new outcome into correct category and fix sortorder if needed.
290 $outcome_item->set_parent($grade_item->categoryid
);
291 $outcome_item->move_after_sortorder($grade_item->sortorder
);
293 } else if (isset($moduleinfo->gradecat
)) {
294 $outcome_item->set_parent($moduleinfo->gradecat
);
296 $gradecategory = $outcome_item->get_parent_category();
297 if ($outcomeexists == false) {
298 if (grade_category
::aggregation_uses_aggregationcoef($gradecategory->aggregation
)) {
299 if ($gradecategory->aggregation
== GRADE_AGGREGATE_WEIGHTED_MEAN
) {
300 $outcome_item->aggregationcoef
= 1;
302 $outcome_item->aggregationcoef
= 0;
304 $outcome_item->update();
311 if (plugin_supports('mod', $moduleinfo->modulename
, FEATURE_ADVANCED_GRADING
, false)
312 and has_capability('moodle/grade:managegradingforms', $modcontext)) {
313 require_once($CFG->dirroot
.'/grade/grading/lib.php');
314 $gradingman = get_grading_manager($modcontext, 'mod_'.$moduleinfo->modulename
);
315 $showgradingmanagement = false;
316 foreach ($gradingman->get_available_areas() as $areaname => $aretitle) {
317 $formfield = 'advancedgradingmethod_'.$areaname;
318 if (isset($moduleinfo->{$formfield})) {
319 $gradingman->set_area($areaname);
320 $methodchanged = $gradingman->set_active_method($moduleinfo->{$formfield});
321 if (empty($moduleinfo->{$formfield})) {
322 // Going back to the simple direct grading is not a reason to open the management screen.
323 $methodchanged = false;
325 $showgradingmanagement = $showgradingmanagement ||
$methodchanged;
328 // Update grading management information.
329 $moduleinfo->gradingman
= $gradingman;
330 $moduleinfo->showgradingmanagement
= $showgradingmanagement;
333 rebuild_course_cache($course->id
, true);
335 grade_regrade_final_grades($course->id
);
337 require_once($CFG->libdir
.'/plagiarismlib.php');
338 plagiarism_save_form_elements($moduleinfo);
345 * Set module info default values for the unset module attributs.
347 * @param object $moduleinfo the current known data of the module
348 * @return object the completed module info
350 function set_moduleinfo_defaults($moduleinfo) {
352 if (empty($moduleinfo->coursemodule
)) {
355 $moduleinfo->instance
= '';
356 $moduleinfo->coursemodule
= '';
359 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule
, 0, false, MUST_EXIST
);
360 $moduleinfo->instance
= $cm->instance
;
361 $moduleinfo->coursemodule
= $cm->id
;
364 $moduleinfo->modulename
= clean_param($moduleinfo->modulename
, PARAM_PLUGIN
);
366 if (!isset($moduleinfo->groupingid
)) {
367 $moduleinfo->groupingid
= 0;
370 if (!isset($moduleinfo->groupmembersonly
)) {
371 $moduleinfo->groupmembersonly
= 0;
374 if (!isset($moduleinfo->name
)) { // Label.
375 $moduleinfo->name
= $moduleinfo->modulename
;
378 if (!isset($moduleinfo->completion
)) {
379 $moduleinfo->completion
= COMPLETION_DISABLED
;
381 if (!isset($moduleinfo->completionview
)) {
382 $moduleinfo->completionview
= COMPLETION_VIEW_NOT_REQUIRED
;
384 if (!isset($moduleinfo->completionexpected
)) {
385 $moduleinfo->completionexpected
= 0;
388 // Convert the 'use grade' checkbox into a grade-item number: 0 if checked, null if not.
389 if (isset($moduleinfo->completionusegrade
) && $moduleinfo->completionusegrade
) {
390 $moduleinfo->completiongradeitemnumber
= 0;
392 $moduleinfo->completiongradeitemnumber
= null;
395 if (!isset($moduleinfo->conditiongradegroup
)) {
396 $moduleinfo->conditiongradegroup
= array();
398 if (!isset($moduleinfo->conditionfieldgroup
)) {
399 $moduleinfo->conditionfieldgroup
= array();
406 * Check that the user can add a module. Also returns some information like the module, context and course section info.
407 * The fucntion create the course section if it doesn't exist.
409 * @param object $course the course of the module
410 * @param object $modulename the module name
411 * @param object $section the section of the module
412 * @return array list containing module, context, course section.
413 * @throws moodle_exception if user is not allowed to perform the action or module is not allowed in this course
415 function can_add_moduleinfo($course, $modulename, $section) {
418 $module = $DB->get_record('modules', array('name'=>$modulename), '*', MUST_EXIST
);
420 $context = context_course
::instance($course->id
);
421 require_capability('moodle/course:manageactivities', $context);
423 course_create_sections_if_missing($course, $section);
424 $cw = get_fast_modinfo($course)->get_section_info($section);
426 if (!course_allowed_module($course, $module->name
)) {
427 print_error('moduledisable');
430 return array($module, $context, $cw);
434 * Check if user is allowed to update module info and returns related item/data to the module.
436 * @param object $cm course module
437 * @return array - list of course module, context, module, moduleinfo, and course section.
438 * @throws moodle_exception if user is not allowed to perform the action
440 function can_update_moduleinfo($cm) {
443 // Check the $USER has the right capability.
444 $context = context_module
::instance($cm->id
);
445 require_capability('moodle/course:manageactivities', $context);
447 // Check module exists.
448 $module = $DB->get_record('modules', array('id'=>$cm->module
), '*', MUST_EXIST
);
450 // Check the moduleinfo exists.
451 $data = $DB->get_record($module->name
, array('id'=>$cm->instance
), '*', MUST_EXIST
);
453 // Check the course section exists.
454 $cw = $DB->get_record('course_sections', array('id'=>$cm->section
), '*', MUST_EXIST
);
456 return array($cm, $context, $module, $data, $cw);
461 * Update the module info.
462 * This function doesn't check the user capabilities. It updates the course module and the module instance.
463 * Then execute common action to create/update module process (trigger event, rebuild cache, save plagiarism settings...).
465 * @param object $cm course module
466 * @param object $moduleinfo module info
467 * @param object $course course of the module
468 * @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.
469 * @return array list of course module and module info.
471 function update_moduleinfo($cm, $moduleinfo, $course, $mform = null) {
474 // Attempt to include module library before we make any changes to DB.
475 include_modulelib($moduleinfo->modulename
);
477 $moduleinfo->course
= $course->id
;
478 $moduleinfo = set_moduleinfo_defaults($moduleinfo);
480 if (!empty($course->groupmodeforce
) or !isset($moduleinfo->groupmode
)) {
481 $moduleinfo->groupmode
= $cm->groupmode
; // Keep original.
484 // Update course module first.
485 $cm->groupmode
= $moduleinfo->groupmode
;
486 if (isset($moduleinfo->groupingid
)) {
487 $cm->groupingid
= $moduleinfo->groupingid
;
489 if (isset($moduleinfo->groupmembersonly
)) {
490 $cm->groupmembersonly
= $moduleinfo->groupmembersonly
;
493 $completion = new completion_info($course);
494 if ($completion->is_enabled() && !empty($moduleinfo->completionunlocked
)) {
495 // Update completion settings.
496 $cm->completion
= $moduleinfo->completion
;
497 $cm->completiongradeitemnumber
= $moduleinfo->completiongradeitemnumber
;
498 $cm->completionview
= $moduleinfo->completionview
;
499 $cm->completionexpected
= $moduleinfo->completionexpected
;
501 if (!empty($CFG->enableavailability
)) {
502 // This code is used both when submitting the form, which uses a long
503 // name to avoid clashes, and by unit test code which uses the real
504 // name in the table.
505 if (property_exists($moduleinfo, 'availabilityconditionsjson')) {
506 if ($moduleinfo->availabilityconditionsjson
!== '') {
507 $cm->availability
= $moduleinfo->availabilityconditionsjson
;
509 $cm->availability
= null;
511 } else if (property_exists($moduleinfo, 'availability')) {
512 $cm->availability
= $moduleinfo->availability
;
514 // If there is any availability data, verify it.
515 if ($cm->availability
) {
516 $tree = new \core_availability\tree
(json_decode($cm->availability
));
517 // Save time and database space by setting null if the only data
519 if ($tree->is_empty()) {
520 $cm->availability
= null;
524 if (isset($moduleinfo->showdescription
)) {
525 $cm->showdescription
= $moduleinfo->showdescription
;
527 $cm->showdescription
= 0;
530 $DB->update_record('course_modules', $cm);
532 $modcontext = context_module
::instance($moduleinfo->coursemodule
);
534 // Update embedded links and save files.
535 if (plugin_supports('mod', $moduleinfo->modulename
, FEATURE_MOD_INTRO
, true)) {
536 $moduleinfo->intro
= file_save_draft_area_files($moduleinfo->introeditor
['itemid'], $modcontext->id
,
537 'mod_'.$moduleinfo->modulename
, 'intro', 0,
538 array('subdirs'=>true), $moduleinfo->introeditor
['text']);
539 $moduleinfo->introformat
= $moduleinfo->introeditor
['format'];
540 unset($moduleinfo->introeditor
);
542 $updateinstancefunction = $moduleinfo->modulename
."_update_instance";
543 if (!$updateinstancefunction($moduleinfo, $mform)) {
544 print_error('cannotupdatemod', '', course_get_url($course, $cw->section
), $moduleinfo->modulename
);
547 // Make sure visibility is set correctly (in particular in calendar).
548 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
549 set_coursemodule_visible($moduleinfo->coursemodule
, $moduleinfo->visible
);
552 if (isset($moduleinfo->cmidnumber
)) { // Label.
553 // Set cm idnumber - uniqueness is already verified by form validation.
554 set_coursemodule_idnumber($moduleinfo->coursemodule
, $moduleinfo->cmidnumber
);
557 // Now that module is fully updated, also update completion data if required.
558 // (this will wipe all user completion data and recalculate it)
559 if ($completion->is_enabled() && !empty($moduleinfo->completionunlocked
)) {
560 $completion->reset_all_state($cm);
562 $cm->name
= $moduleinfo->name
;
563 \core\event\course_module_updated
::create_from_cm($cm, $modcontext)->trigger();
565 $moduleinfo = edit_module_post_actions($moduleinfo, $course);
567 return array($cm, $moduleinfo);
571 * Include once the module lib file.
573 * @param string $modulename module name of the lib to include
574 * @throws moodle_exception if lib.php file for the module does not exist
576 function include_modulelib($modulename) {
578 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
579 if (file_exists($modlib)) {
580 include_once($modlib);
582 throw new moodle_exception('modulemissingcode', '', '', $modlib);