MDL-38713 course: correctly set visibleold on mod creation
[moodle.git] / course / modlib.php
blob614ac8aabfb9acd067a1abf46e710657e7f6305f
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 $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;
82 } else {
83 $newcm->showdescription = 0;
86 if (!$moduleinfo->coursemodule = add_course_module($newcm)) {
87 print_error('cannotaddcoursemodule');
90 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
91 $introeditor = $moduleinfo->introeditor;
92 unset($moduleinfo->introeditor);
93 $moduleinfo->intro = $introeditor['text'];
94 $moduleinfo->introformat = $introeditor['format'];
97 $addinstancefunction = $moduleinfo->modulename."_add_instance";
98 $returnfromfunc = $addinstancefunction($moduleinfo, $mform);
99 if (!$returnfromfunc or !is_number($returnfromfunc)) {
100 // Undo everything we can.
101 $modcontext = context_module::instance($moduleinfo->coursemodule);
102 delete_context(CONTEXT_MODULE, $moduleinfo->coursemodule);
103 $DB->delete_records('course_modules', array('id'=>$moduleinfo->coursemodule));
105 if (!is_number($returnfromfunc)) {
106 print_error('invalidfunction', '', course_get_url($course, $cw->section));
107 } else {
108 print_error('cannotaddnewmodule', '', course_get_url($course, $cw->section), $moduleinfo->modulename);
112 $moduleinfo->instance = $returnfromfunc;
114 $DB->set_field('course_modules', 'instance', $returnfromfunc, array('id'=>$moduleinfo->coursemodule));
116 // Update embedded links and save files.
117 $modcontext = context_module::instance($moduleinfo->coursemodule);
118 if (!empty($introeditor)) {
119 $moduleinfo->intro = file_save_draft_area_files($introeditor['itemid'], $modcontext->id,
120 'mod_'.$moduleinfo->modulename, 'intro', 0,
121 array('subdirs'=>true), $introeditor['text']);
122 $DB->set_field($moduleinfo->modulename, 'intro', $moduleinfo->intro, array('id'=>$moduleinfo->instance));
125 // Course_modules and course_sections each contain a reference to each other.
126 // So we have to update one of them twice.
127 $sectionid = course_add_cm_to_section($course, $moduleinfo->coursemodule, $moduleinfo->section);
129 // Make sure visibility is set correctly (in particular in calendar).
130 // Note: allow them to set it even without moodle/course:activityvisibility.
131 set_coursemodule_visible($moduleinfo->coursemodule, $moduleinfo->visible);
133 if (isset($moduleinfo->cmidnumber)) { // Label.
134 // Set cm idnumber - uniqueness is already verified by form validation.
135 set_coursemodule_idnumber($moduleinfo->coursemodule, $moduleinfo->cmidnumber);
138 // Set up conditions.
139 if ($CFG->enableavailability) {
140 condition_info::update_cm_from_form((object)array('id'=>$moduleinfo->coursemodule), $moduleinfo, false);
143 $eventname = 'mod_created';
145 add_to_log($course->id, "course", "add mod",
146 "../mod/$moduleinfo->modulename/view.php?id=$moduleinfo->coursemodule",
147 "$moduleinfo->modulename $moduleinfo->instance");
148 add_to_log($course->id, $moduleinfo->modulename, "add",
149 "view.php?id=$moduleinfo->coursemodule",
150 "$moduleinfo->instance", $moduleinfo->coursemodule);
152 $moduleinfo = edit_module_post_actions($moduleinfo, $course, 'mod_created');
154 return $moduleinfo;
159 * Common create/update module module actions that need to be processed as soon as a module is created/updaded.
160 * For example: trigger event, create grade parent category, add outcomes, rebuild caches, regrade, save plagiarism settings...
162 * @param object $moduleinfo the module info
163 * @param object $course the course of the module
164 * @param string $eventname the event name to trigger
166 * return object moduleinfo update with grading management info
168 function edit_module_post_actions($moduleinfo, $course, $eventname) {
169 global $USER, $CFG;
171 $modcontext = context_module::instance($moduleinfo->coursemodule);
173 // Trigger mod_created/mod_updated event with information about this module.
174 $eventdata = new stdClass();
175 $eventdata->modulename = $moduleinfo->modulename;
176 $eventdata->name = $moduleinfo->name;
177 $eventdata->cmid = $moduleinfo->coursemodule;
178 $eventdata->courseid = $course->id;
179 $eventdata->userid = $USER->id;
180 events_trigger($eventname, $eventdata);
182 // Sync idnumber with grade_item.
183 if ($grade_item = grade_item::fetch(array('itemtype'=>'mod', 'itemmodule'=>$moduleinfo->modulename,
184 'iteminstance'=>$moduleinfo->instance, 'itemnumber'=>0, 'courseid'=>$course->id))) {
185 if ($grade_item->idnumber != $moduleinfo->cmidnumber) {
186 $grade_item->idnumber = $moduleinfo->cmidnumber;
187 $grade_item->update();
191 $items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$moduleinfo->modulename,
192 'iteminstance'=>$moduleinfo->instance, 'courseid'=>$course->id));
194 // Create parent category if requested and move to correct parent category.
195 if ($items and isset($moduleinfo->gradecat)) {
196 if ($moduleinfo->gradecat == -1) {
197 $grade_category = new grade_category();
198 $grade_category->courseid = $course->id;
199 $grade_category->fullname = $moduleinfo->name;
200 $grade_category->insert();
201 if ($grade_item) {
202 $parent = $grade_item->get_parent_category();
203 $grade_category->set_parent($parent->id);
205 $moduleinfo->gradecat = $grade_category->id;
207 foreach ($items as $itemid=>$unused) {
208 $items[$itemid]->set_parent($moduleinfo->gradecat);
209 if ($itemid == $grade_item->id) {
210 // Use updated grade_item.
211 $grade_item = $items[$itemid];
216 // Add outcomes if requested.
217 if ($outcomes = grade_outcome::fetch_all_available($course->id)) {
218 $grade_items = array();
220 // Outcome grade_item.itemnumber start at 1000, there is nothing above outcomes.
221 $max_itemnumber = 999;
222 if ($items) {
223 foreach($items as $item) {
224 if ($item->itemnumber > $max_itemnumber) {
225 $max_itemnumber = $item->itemnumber;
230 foreach($outcomes as $outcome) {
231 $elname = 'outcome_'.$outcome->id;
233 if (property_exists($moduleinfo, $elname) and $moduleinfo->$elname) {
234 // So we have a request for new outcome grade item?
235 if ($items) {
236 $outcomeexists = false;
237 foreach($items as $item) {
238 if ($item->outcomeid == $outcome->id) {
239 $outcomeexists = true;
240 break;
243 if ($outcomeexists) {
244 continue;
248 $max_itemnumber++;
250 $outcome_item = new grade_item();
251 $outcome_item->courseid = $course->id;
252 $outcome_item->itemtype = 'mod';
253 $outcome_item->itemmodule = $moduleinfo->modulename;
254 $outcome_item->iteminstance = $moduleinfo->instance;
255 $outcome_item->itemnumber = $max_itemnumber;
256 $outcome_item->itemname = $outcome->fullname;
257 $outcome_item->outcomeid = $outcome->id;
258 $outcome_item->gradetype = GRADE_TYPE_SCALE;
259 $outcome_item->scaleid = $outcome->scaleid;
260 $outcome_item->insert();
262 // Move the new outcome into correct category and fix sortorder if needed.
263 if ($grade_item) {
264 $outcome_item->set_parent($grade_item->categoryid);
265 $outcome_item->move_after_sortorder($grade_item->sortorder);
267 } else if (isset($moduleinfo->gradecat)) {
268 $outcome_item->set_parent($moduleinfo->gradecat);
274 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_ADVANCED_GRADING, false)
275 and has_capability('moodle/grade:managegradingforms', $modcontext)) {
276 require_once($CFG->dirroot.'/grade/grading/lib.php');
277 $gradingman = get_grading_manager($modcontext, 'mod_'.$moduleinfo->modulename);
278 $showgradingmanagement = false;
279 foreach ($gradingman->get_available_areas() as $areaname => $aretitle) {
280 $formfield = 'advancedgradingmethod_'.$areaname;
281 if (isset($moduleinfo->{$formfield})) {
282 $gradingman->set_area($areaname);
283 $methodchanged = $gradingman->set_active_method($moduleinfo->{$formfield});
284 if (empty($moduleinfo->{$formfield})) {
285 // Going back to the simple direct grading is not a reason to open the management screen.
286 $methodchanged = false;
288 $showgradingmanagement = $showgradingmanagement || $methodchanged;
291 // Update grading management information.
292 $moduleinfo->gradingman = $gradingman;
293 $moduleinfo->showgradingmanagement = $showgradingmanagement;
296 rebuild_course_cache($course->id);
297 grade_regrade_final_grades($course->id);
298 require_once($CFG->libdir.'/plagiarismlib.php');
299 plagiarism_save_form_elements($moduleinfo);
301 return $moduleinfo;
306 * Set module info default values for the unset module attributs.
308 * @param object $moduleinfo the current known data of the module
309 * @return object the completed module info
311 function set_moduleinfo_defaults($moduleinfo) {
312 global $DB;
314 if (empty($moduleinfo->coursemodule)) {
315 // Add.
316 $cm = null;
317 $moduleinfo->instance = '';
318 $moduleinfo->coursemodule = '';
319 } else {
320 // Update.
321 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule, 0, false, MUST_EXIST);
322 $moduleinfo->instance = $cm->instance;
323 $moduleinfo->coursemodule = $cm->id;
325 // For safety.
326 $moduleinfo->modulename = clean_param($moduleinfo->modulename, PARAM_PLUGIN);
328 if (!isset($moduleinfo->groupingid)) {
329 $moduleinfo->groupingid = 0;
332 if (!isset($moduleinfo->groupmembersonly)) {
333 $moduleinfo->groupmembersonly = 0;
336 if (!isset($moduleinfo->name)) { // Label.
337 $moduleinfo->name = $moduleinfo->modulename;
340 if (!isset($moduleinfo->completion)) {
341 $moduleinfo->completion = COMPLETION_DISABLED;
343 if (!isset($moduleinfo->completionview)) {
344 $moduleinfo->completionview = COMPLETION_VIEW_NOT_REQUIRED;
347 // Convert the 'use grade' checkbox into a grade-item number: 0 if checked, null if not.
348 if (isset($moduleinfo->completionusegrade) && $moduleinfo->completionusegrade) {
349 $moduleinfo->completiongradeitemnumber = 0;
350 } else {
351 $moduleinfo->completiongradeitemnumber = null;
354 return $moduleinfo;
358 * Check that the user can add a module. Also returns some information like the module, context and course section info.
359 * The fucntion create the course section if it doesn't exist.
361 * @param object $course the course of the module
362 * @param object $modulename the module name
363 * @param object $section the section of the module
364 * @return array list containing module, context, course section.
366 function can_add_moduleinfo($course, $modulename, $section) {
367 global $DB;
369 $module = $DB->get_record('modules', array('name'=>$modulename), '*', MUST_EXIST);
371 $context = context_course::instance($course->id);
372 require_capability('moodle/course:manageactivities', $context);
374 course_create_sections_if_missing($course, $section);
375 $cw = get_fast_modinfo($course)->get_section_info($section);
377 if (!course_allowed_module($course, $module->name)) {
378 print_error('moduledisable');
381 return array($module, $context, $cw);
385 * Check if user is allowed to update module info and returns related item/data to the module.
387 * @param object $cm course module
388 * @return array - list of course module, context, module, moduleinfo, and course section.
390 function can_update_moduleinfo($cm) {
391 global $DB;
393 // Check the $USER has the right capability.
394 $context = context_module::instance($cm->id);
395 require_capability('moodle/course:manageactivities', $context);
397 // Check module exists.
398 $module = $DB->get_record('modules', array('id'=>$cm->module), '*', MUST_EXIST);
400 // Check the moduleinfo exists.
401 $data = $DB->get_record($module->name, array('id'=>$cm->instance), '*', MUST_EXIST);
403 // Check the course section exists.
404 $cw = $DB->get_record('course_sections', array('id'=>$cm->section), '*', MUST_EXIST);
406 return array($cm, $context, $module, $data, $cw);
411 * Update the module info.
412 * This function doesn't check the user capabilities. It updates the course module and the module instance.
413 * Then execute common action to create/update module process (trigger event, rebuild cache, save plagiarism settings...).
415 * @param object $cm course module
416 * @param object $moduleinfo module info
417 * @param object $course course of the module
418 * @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.
419 * @return array list of course module and module info.
421 function update_moduleinfo($cm, $moduleinfo, $course, $mform = null) {
422 global $DB, $CFG;
424 $moduleinfo->course = $course->id;
425 $moduleinfo = set_moduleinfo_defaults($moduleinfo);
427 if (!empty($course->groupmodeforce) or !isset($moduleinfo->groupmode)) {
428 $moduleinfo->groupmode = $cm->groupmode; // Keep original.
431 // Update course module first.
432 $cm->groupmode = $moduleinfo->groupmode;
433 if (isset($moduleinfo->groupingid)) {
434 $cm->groupingid = $moduleinfo->groupingid;
436 if (isset($moduleinfo->groupmembersonly)) {
437 $cm->groupmembersonly = $moduleinfo->groupmembersonly;
440 $completion = new completion_info($course);
441 if ($completion->is_enabled()) {
442 // Update completion settings.
443 $cm->completion = $moduleinfo->completion;
444 $cm->completiongradeitemnumber = $moduleinfo->completiongradeitemnumber;
445 $cm->completionview = $moduleinfo->completionview;
446 $cm->completionexpected = $moduleinfo->completionexpected;
448 if (!empty($CFG->enableavailability)) {
449 $cm->availablefrom = $moduleinfo->availablefrom;
450 $cm->availableuntil = $moduleinfo->availableuntil;
451 $cm->showavailability = $moduleinfo->showavailability;
452 condition_info::update_cm_from_form($cm,$moduleinfo,true);
454 if (isset($moduleinfo->showdescription)) {
455 $cm->showdescription = $moduleinfo->showdescription;
456 } else {
457 $cm->showdescription = 0;
460 $DB->update_record('course_modules', $cm);
462 $modcontext = context_module::instance($moduleinfo->coursemodule);
464 // Update embedded links and save files.
465 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
466 $moduleinfo->intro = file_save_draft_area_files($moduleinfo->introeditor['itemid'], $modcontext->id,
467 'mod_'.$moduleinfo->modulename, 'intro', 0,
468 array('subdirs'=>true), $moduleinfo->introeditor['text']);
469 $moduleinfo->introformat = $moduleinfo->introeditor['format'];
470 unset($moduleinfo->introeditor);
472 $updateinstancefunction = $moduleinfo->modulename."_update_instance";
473 if (!$updateinstancefunction($moduleinfo, $mform)) {
474 print_error('cannotupdatemod', '', course_get_url($course, $cw->section), $moduleinfo->modulename);
477 // Make sure visibility is set correctly (in particular in calendar).
478 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
479 set_coursemodule_visible($moduleinfo->coursemodule, $moduleinfo->visible);
482 if (isset($moduleinfo->cmidnumber)) { // Label.
483 // Set cm idnumber - uniqueness is already verified by form validation.
484 set_coursemodule_idnumber($moduleinfo->coursemodule, $moduleinfo->cmidnumber);
487 // Now that module is fully updated, also update completion data if required.
488 // (this will wipe all user completion data and recalculate it)
489 if ($completion->is_enabled() && !empty($moduleinfo->completionunlocked)) {
490 $completion->reset_all_state($cm);
493 add_to_log($course->id, "course", "update mod",
494 "../mod/$moduleinfo->modulename/view.php?id=$moduleinfo->coursemodule",
495 "$moduleinfo->modulename $moduleinfo->instance");
496 add_to_log($course->id, $moduleinfo->modulename, "update",
497 "view.php?id=$moduleinfo->coursemodule",
498 "$moduleinfo->instance", $moduleinfo->coursemodule);
500 $moduleinfo = edit_module_post_actions($moduleinfo, $course, 'mod_updated');
502 return array($cm, $moduleinfo);
506 * Include once the module lib file.
508 * @param string $modulename module name of the lib to include
510 function include_modulelib($modulename) {
511 global $CFG;
512 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
513 if (file_exists($modlib)) {
514 include_once($modlib);
515 } else {
516 throw new moodle_exception('modulemissingcode', '', '', $modlib);