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 $moduleinfo->course
= $course->id
;
48 $moduleinfo = set_moduleinfo_defaults($moduleinfo);
50 if (!empty($course->groupmodeforce
) or !isset($moduleinfo->groupmode
)) {
51 $moduleinfo->groupmode
= 0; // Do not set groupmode.
54 if (!course_allowed_module($course, $moduleinfo->modulename
)) {
55 print_error('moduledisable', '', '', $moduleinfo->modulename
);
58 // First add course_module record because we need the context.
59 $newcm = new stdClass();
60 $newcm->course
= $course->id
;
61 $newcm->module
= $moduleinfo->module
;
62 $newcm->instance
= 0; // Not known yet, will be updated later (this is similar to restore code).
63 $newcm->visible
= $moduleinfo->visible
;
64 $newcm->visibleold
= $moduleinfo->visible
;
65 $newcm->groupmode
= $moduleinfo->groupmode
;
66 $newcm->groupingid
= $moduleinfo->groupingid
;
67 $newcm->groupmembersonly
= $moduleinfo->groupmembersonly
;
68 $completion = new completion_info($course);
69 if ($completion->is_enabled()) {
70 $newcm->completion
= $moduleinfo->completion
;
71 $newcm->completiongradeitemnumber
= $moduleinfo->completiongradeitemnumber
;
72 $newcm->completionview
= $moduleinfo->completionview
;
73 $newcm->completionexpected
= $moduleinfo->completionexpected
;
75 if(!empty($CFG->enableavailability
)) {
76 $newcm->availablefrom
= $moduleinfo->availablefrom
;
77 $newcm->availableuntil
= $moduleinfo->availableuntil
;
78 $newcm->showavailability
= $moduleinfo->showavailability
;
80 if (isset($moduleinfo->showdescription
)) {
81 $newcm->showdescription
= $moduleinfo->showdescription
;
83 $newcm->showdescription
= 0;
86 // From this point we make database changes, so start transaction.
87 $transaction = $DB->start_delegated_transaction();
89 if (!$moduleinfo->coursemodule
= add_course_module($newcm)) {
90 print_error('cannotaddcoursemodule');
93 if (plugin_supports('mod', $moduleinfo->modulename
, FEATURE_MOD_INTRO
, true)) {
94 $introeditor = $moduleinfo->introeditor
;
95 unset($moduleinfo->introeditor
);
96 $moduleinfo->intro
= $introeditor['text'];
97 $moduleinfo->introformat
= $introeditor['format'];
100 $addinstancefunction = $moduleinfo->modulename
."_add_instance";
102 $returnfromfunc = $addinstancefunction($moduleinfo, $mform);
103 } catch (moodle_exception
$e) {
104 $returnfromfunc = $e;
106 if (!$returnfromfunc or !is_number($returnfromfunc)) {
107 // Undo everything we can. This is not necessary for databases which
108 // support transactions, but improves consistency for other databases.
109 $modcontext = context_module
::instance($moduleinfo->coursemodule
);
110 delete_context(CONTEXT_MODULE
, $moduleinfo->coursemodule
);
111 $DB->delete_records('course_modules', array('id'=>$moduleinfo->coursemodule
));
113 if ($e instanceof moodle_exception
) {
115 } else if (!is_number($returnfromfunc)) {
116 print_error('invalidfunction', '', course_get_url($course, $cw->section
));
118 print_error('cannotaddnewmodule', '', course_get_url($course, $cw->section
), $moduleinfo->modulename
);
122 $moduleinfo->instance
= $returnfromfunc;
124 $DB->set_field('course_modules', 'instance', $returnfromfunc, array('id'=>$moduleinfo->coursemodule
));
126 // Update embedded links and save files.
127 $modcontext = context_module
::instance($moduleinfo->coursemodule
);
128 if (!empty($introeditor)) {
129 $moduleinfo->intro
= file_save_draft_area_files($introeditor['itemid'], $modcontext->id
,
130 'mod_'.$moduleinfo->modulename
, 'intro', 0,
131 array('subdirs'=>true), $introeditor['text']);
132 $DB->set_field($moduleinfo->modulename
, 'intro', $moduleinfo->intro
, array('id'=>$moduleinfo->instance
));
135 // Course_modules and course_sections each contain a reference to each other.
136 // So we have to update one of them twice.
137 $sectionid = course_add_cm_to_section($course, $moduleinfo->coursemodule
, $moduleinfo->section
);
139 // Make sure visibility is set correctly (in particular in calendar).
140 // Note: allow them to set it even without moodle/course:activityvisibility.
141 set_coursemodule_visible($moduleinfo->coursemodule
, $moduleinfo->visible
);
143 if (isset($moduleinfo->cmidnumber
)) { // Label.
144 // Set cm idnumber - uniqueness is already verified by form validation.
145 set_coursemodule_idnumber($moduleinfo->coursemodule
, $moduleinfo->cmidnumber
);
148 // Set up conditions.
149 if ($CFG->enableavailability
) {
150 condition_info
::update_cm_from_form((object)array('id'=>$moduleinfo->coursemodule
), $moduleinfo, false);
153 $eventname = 'mod_created';
155 add_to_log($course->id
, "course", "add mod",
156 "../mod/$moduleinfo->modulename/view.php?id=$moduleinfo->coursemodule",
157 "$moduleinfo->modulename $moduleinfo->instance");
158 add_to_log($course->id
, $moduleinfo->modulename
, "add",
159 "view.php?id=$moduleinfo->coursemodule",
160 "$moduleinfo->instance", $moduleinfo->coursemodule
);
162 $moduleinfo = edit_module_post_actions($moduleinfo, $course, 'mod_created');
163 $transaction->allow_commit();
170 * Common create/update module module actions that need to be processed as soon as a module is created/updaded.
171 * For example: trigger event, create grade parent category, add outcomes, rebuild caches, regrade, save plagiarism settings...
173 * @param object $moduleinfo the module info
174 * @param object $course the course of the module
175 * @param string $eventname the event name to trigger
177 * return object moduleinfo update with grading management info
179 function edit_module_post_actions($moduleinfo, $course, $eventname) {
182 $modcontext = context_module
::instance($moduleinfo->coursemodule
);
184 // Trigger mod_created/mod_updated event with information about this module.
185 $eventdata = new stdClass();
186 $eventdata->modulename
= $moduleinfo->modulename
;
187 $eventdata->name
= $moduleinfo->name
;
188 $eventdata->cmid
= $moduleinfo->coursemodule
;
189 $eventdata->courseid
= $course->id
;
190 $eventdata->userid
= $USER->id
;
191 events_trigger($eventname, $eventdata);
193 // Sync idnumber with grade_item.
194 if ($grade_item = grade_item
::fetch(array('itemtype'=>'mod', 'itemmodule'=>$moduleinfo->modulename
,
195 'iteminstance'=>$moduleinfo->instance
, 'itemnumber'=>0, 'courseid'=>$course->id
))) {
196 if ($grade_item->idnumber
!= $moduleinfo->cmidnumber
) {
197 $grade_item->idnumber
= $moduleinfo->cmidnumber
;
198 $grade_item->update();
202 $items = grade_item
::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$moduleinfo->modulename
,
203 'iteminstance'=>$moduleinfo->instance
, 'courseid'=>$course->id
));
205 // Create parent category if requested and move to correct parent category.
206 if ($items and isset($moduleinfo->gradecat
)) {
207 if ($moduleinfo->gradecat
== -1) {
208 $grade_category = new grade_category();
209 $grade_category->courseid
= $course->id
;
210 $grade_category->fullname
= $moduleinfo->name
;
211 $grade_category->insert();
213 $parent = $grade_item->get_parent_category();
214 $grade_category->set_parent($parent->id
);
216 $moduleinfo->gradecat
= $grade_category->id
;
218 foreach ($items as $itemid=>$unused) {
219 $items[$itemid]->set_parent($moduleinfo->gradecat
);
220 if ($itemid == $grade_item->id
) {
221 // Use updated grade_item.
222 $grade_item = $items[$itemid];
227 // Add outcomes if requested.
228 if ($outcomes = grade_outcome
::fetch_all_available($course->id
)) {
229 $grade_items = array();
231 // Outcome grade_item.itemnumber start at 1000, there is nothing above outcomes.
232 $max_itemnumber = 999;
234 foreach($items as $item) {
235 if ($item->itemnumber
> $max_itemnumber) {
236 $max_itemnumber = $item->itemnumber
;
241 foreach($outcomes as $outcome) {
242 $elname = 'outcome_'.$outcome->id
;
244 if (property_exists($moduleinfo, $elname) and $moduleinfo->$elname) {
245 // So we have a request for new outcome grade item?
247 $outcomeexists = false;
248 foreach($items as $item) {
249 if ($item->outcomeid
== $outcome->id
) {
250 $outcomeexists = true;
254 if ($outcomeexists) {
261 $outcome_item = new grade_item();
262 $outcome_item->courseid
= $course->id
;
263 $outcome_item->itemtype
= 'mod';
264 $outcome_item->itemmodule
= $moduleinfo->modulename
;
265 $outcome_item->iteminstance
= $moduleinfo->instance
;
266 $outcome_item->itemnumber
= $max_itemnumber;
267 $outcome_item->itemname
= $outcome->fullname
;
268 $outcome_item->outcomeid
= $outcome->id
;
269 $outcome_item->gradetype
= GRADE_TYPE_SCALE
;
270 $outcome_item->scaleid
= $outcome->scaleid
;
271 $outcome_item->insert();
273 // Move the new outcome into correct category and fix sortorder if needed.
275 $outcome_item->set_parent($grade_item->categoryid
);
276 $outcome_item->move_after_sortorder($grade_item->sortorder
);
278 } else if (isset($moduleinfo->gradecat
)) {
279 $outcome_item->set_parent($moduleinfo->gradecat
);
285 if (plugin_supports('mod', $moduleinfo->modulename
, FEATURE_ADVANCED_GRADING
, false)
286 and has_capability('moodle/grade:managegradingforms', $modcontext)) {
287 require_once($CFG->dirroot
.'/grade/grading/lib.php');
288 $gradingman = get_grading_manager($modcontext, 'mod_'.$moduleinfo->modulename
);
289 $showgradingmanagement = false;
290 foreach ($gradingman->get_available_areas() as $areaname => $aretitle) {
291 $formfield = 'advancedgradingmethod_'.$areaname;
292 if (isset($moduleinfo->{$formfield})) {
293 $gradingman->set_area($areaname);
294 $methodchanged = $gradingman->set_active_method($moduleinfo->{$formfield});
295 if (empty($moduleinfo->{$formfield})) {
296 // Going back to the simple direct grading is not a reason to open the management screen.
297 $methodchanged = false;
299 $showgradingmanagement = $showgradingmanagement ||
$methodchanged;
302 // Update grading management information.
303 $moduleinfo->gradingman
= $gradingman;
304 $moduleinfo->showgradingmanagement
= $showgradingmanagement;
307 rebuild_course_cache($course->id
);
308 grade_regrade_final_grades($course->id
);
309 require_once($CFG->libdir
.'/plagiarismlib.php');
310 plagiarism_save_form_elements($moduleinfo);
317 * Set module info default values for the unset module attributs.
319 * @param object $moduleinfo the current known data of the module
320 * @return object the completed module info
322 function set_moduleinfo_defaults($moduleinfo) {
325 if (empty($moduleinfo->coursemodule
)) {
328 $moduleinfo->instance
= '';
329 $moduleinfo->coursemodule
= '';
332 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule
, 0, false, MUST_EXIST
);
333 $moduleinfo->instance
= $cm->instance
;
334 $moduleinfo->coursemodule
= $cm->id
;
337 $moduleinfo->modulename
= clean_param($moduleinfo->modulename
, PARAM_PLUGIN
);
339 if (!isset($moduleinfo->groupingid
)) {
340 $moduleinfo->groupingid
= 0;
343 if (!isset($moduleinfo->groupmembersonly
)) {
344 $moduleinfo->groupmembersonly
= 0;
347 if (!isset($moduleinfo->name
)) { // Label.
348 $moduleinfo->name
= $moduleinfo->modulename
;
351 if (!isset($moduleinfo->completion
)) {
352 $moduleinfo->completion
= COMPLETION_DISABLED
;
354 if (!isset($moduleinfo->completionview
)) {
355 $moduleinfo->completionview
= COMPLETION_VIEW_NOT_REQUIRED
;
358 // Convert the 'use grade' checkbox into a grade-item number: 0 if checked, null if not.
359 if (isset($moduleinfo->completionusegrade
) && $moduleinfo->completionusegrade
) {
360 $moduleinfo->completiongradeitemnumber
= 0;
362 $moduleinfo->completiongradeitemnumber
= null;
369 * Check that the user can add a module. Also returns some information like the module, context and course section info.
370 * The fucntion create the course section if it doesn't exist.
372 * @param object $course the course of the module
373 * @param object $modulename the module name
374 * @param object $section the section of the module
375 * @return array list containing module, context, course section.
377 function can_add_moduleinfo($course, $modulename, $section) {
380 $module = $DB->get_record('modules', array('name'=>$modulename), '*', MUST_EXIST
);
382 $context = context_course
::instance($course->id
);
383 require_capability('moodle/course:manageactivities', $context);
385 course_create_sections_if_missing($course, $section);
386 $cw = get_fast_modinfo($course)->get_section_info($section);
388 if (!course_allowed_module($course, $module->name
)) {
389 print_error('moduledisable');
392 return array($module, $context, $cw);
396 * Check if user is allowed to update module info and returns related item/data to the module.
398 * @param object $cm course module
399 * @return array - list of course module, context, module, moduleinfo, and course section.
401 function can_update_moduleinfo($cm) {
404 // Check the $USER has the right capability.
405 $context = context_module
::instance($cm->id
);
406 require_capability('moodle/course:manageactivities', $context);
408 // Check module exists.
409 $module = $DB->get_record('modules', array('id'=>$cm->module
), '*', MUST_EXIST
);
411 // Check the moduleinfo exists.
412 $data = $DB->get_record($module->name
, array('id'=>$cm->instance
), '*', MUST_EXIST
);
414 // Check the course section exists.
415 $cw = $DB->get_record('course_sections', array('id'=>$cm->section
), '*', MUST_EXIST
);
417 return array($cm, $context, $module, $data, $cw);
422 * Update the module info.
423 * This function doesn't check the user capabilities. It updates the course module and the module instance.
424 * Then execute common action to create/update module process (trigger event, rebuild cache, save plagiarism settings...).
426 * @param object $cm course module
427 * @param object $moduleinfo module info
428 * @param object $course course of the module
429 * @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.
430 * @return array list of course module and module info.
432 function update_moduleinfo($cm, $moduleinfo, $course, $mform = null) {
435 $moduleinfo->course
= $course->id
;
436 $moduleinfo = set_moduleinfo_defaults($moduleinfo);
438 if (!empty($course->groupmodeforce
) or !isset($moduleinfo->groupmode
)) {
439 $moduleinfo->groupmode
= $cm->groupmode
; // Keep original.
442 // Update course module first.
443 $cm->groupmode
= $moduleinfo->groupmode
;
444 if (isset($moduleinfo->groupingid
)) {
445 $cm->groupingid
= $moduleinfo->groupingid
;
447 if (isset($moduleinfo->groupmembersonly
)) {
448 $cm->groupmembersonly
= $moduleinfo->groupmembersonly
;
451 $completion = new completion_info($course);
452 if ($completion->is_enabled() && !empty($moduleinfo->completionunlocked
)) {
453 // Update completion settings.
454 $cm->completion
= $moduleinfo->completion
;
455 $cm->completiongradeitemnumber
= $moduleinfo->completiongradeitemnumber
;
456 $cm->completionview
= $moduleinfo->completionview
;
457 $cm->completionexpected
= $moduleinfo->completionexpected
;
459 if (!empty($CFG->enableavailability
)) {
460 $cm->availablefrom
= $moduleinfo->availablefrom
;
461 $cm->availableuntil
= $moduleinfo->availableuntil
;
462 $cm->showavailability
= $moduleinfo->showavailability
;
463 condition_info
::update_cm_from_form($cm,$moduleinfo,true);
465 if (isset($moduleinfo->showdescription
)) {
466 $cm->showdescription
= $moduleinfo->showdescription
;
468 $cm->showdescription
= 0;
471 $DB->update_record('course_modules', $cm);
473 $modcontext = context_module
::instance($moduleinfo->coursemodule
);
475 // Update embedded links and save files.
476 if (plugin_supports('mod', $moduleinfo->modulename
, FEATURE_MOD_INTRO
, true)) {
477 $moduleinfo->intro
= file_save_draft_area_files($moduleinfo->introeditor
['itemid'], $modcontext->id
,
478 'mod_'.$moduleinfo->modulename
, 'intro', 0,
479 array('subdirs'=>true), $moduleinfo->introeditor
['text']);
480 $moduleinfo->introformat
= $moduleinfo->introeditor
['format'];
481 unset($moduleinfo->introeditor
);
483 $updateinstancefunction = $moduleinfo->modulename
."_update_instance";
484 if (!$updateinstancefunction($moduleinfo, $mform)) {
485 print_error('cannotupdatemod', '', course_get_url($course, $cw->section
), $moduleinfo->modulename
);
488 // Make sure visibility is set correctly (in particular in calendar).
489 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
490 set_coursemodule_visible($moduleinfo->coursemodule
, $moduleinfo->visible
);
493 if (isset($moduleinfo->cmidnumber
)) { // Label.
494 // Set cm idnumber - uniqueness is already verified by form validation.
495 set_coursemodule_idnumber($moduleinfo->coursemodule
, $moduleinfo->cmidnumber
);
498 // Now that module is fully updated, also update completion data if required.
499 // (this will wipe all user completion data and recalculate it)
500 if ($completion->is_enabled() && !empty($moduleinfo->completionunlocked
)) {
501 $completion->reset_all_state($cm);
504 add_to_log($course->id
, "course", "update mod",
505 "../mod/$moduleinfo->modulename/view.php?id=$moduleinfo->coursemodule",
506 "$moduleinfo->modulename $moduleinfo->instance");
507 add_to_log($course->id
, $moduleinfo->modulename
, "update",
508 "view.php?id=$moduleinfo->coursemodule",
509 "$moduleinfo->instance", $moduleinfo->coursemodule
);
511 $moduleinfo = edit_module_post_actions($moduleinfo, $course, 'mod_updated');
513 return array($cm, $moduleinfo);
517 * Include once the module lib file.
519 * @param string $modulename module name of the lib to include
521 function include_modulelib($modulename) {
523 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
524 if (file_exists($modlib)) {
525 include_once($modlib);
527 throw new moodle_exception('modulemissingcode', '', '', $modlib);