MDL-50516 mod_lesson: prevented user from repeating question
[moodle.git] / course / modlib.php
blob89588dc47e0f587d09ef6f864fa28cf6c6fa13d6
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 // 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
79 // name in the table.
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
92 // is an empty tree.
93 if ($tree->is_empty()) {
94 $newcm->availability = null;
98 if (isset($moduleinfo->showdescription)) {
99 $newcm->showdescription = $moduleinfo->showdescription;
100 } else {
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";
120 try {
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) {
133 throw $e;
134 } else if (!is_number($returnfromfunc)) {
135 print_error('invalidfunction', '', course_get_url($course, $moduleinfo->section));
136 } else {
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);
164 $event->trigger();
166 $moduleinfo = edit_module_post_actions($moduleinfo, $course);
167 $transaction->allow_commit();
169 return $moduleinfo;
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) {
184 global $CFG;
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 $gradeupdate = false;
195 if ($grade_item->idnumber != $moduleinfo->cmidnumber) {
196 $grade_item->idnumber = $moduleinfo->cmidnumber;
197 $gradeupdate = true;
199 if (isset($moduleinfo->gradepass) && $grade_item->gradepass != $moduleinfo->gradepass) {
200 $grade_item->gradepass = $moduleinfo->gradepass;
201 $gradeupdate = true;
203 if ($gradeupdate) {
204 $grade_item->update();
208 if ($hasgrades) {
209 $items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$moduleinfo->modulename,
210 'iteminstance'=>$moduleinfo->instance, 'courseid'=>$course->id));
211 } else {
212 $items = array();
215 // Create parent category if requested and move to correct parent category.
216 if ($items and isset($moduleinfo->gradecat)) {
217 if ($moduleinfo->gradecat == -1) {
218 $grade_category = new grade_category();
219 $grade_category->courseid = $course->id;
220 $grade_category->fullname = $moduleinfo->name;
221 $grade_category->insert();
222 if ($grade_item) {
223 $parent = $grade_item->get_parent_category();
224 $grade_category->set_parent($parent->id);
226 $moduleinfo->gradecat = $grade_category->id;
229 foreach ($items as $itemid=>$unused) {
230 $items[$itemid]->set_parent($moduleinfo->gradecat);
231 if ($itemid == $grade_item->id) {
232 // Use updated grade_item.
233 $grade_item = $items[$itemid];
238 require_once($CFG->libdir.'/grade/grade_outcome.php');
239 // Add outcomes if requested.
240 if ($hasoutcomes && $outcomes = grade_outcome::fetch_all_available($course->id)) {
241 $grade_items = array();
243 // Outcome grade_item.itemnumber start at 1000, there is nothing above outcomes.
244 $max_itemnumber = 999;
245 if ($items) {
246 foreach($items as $item) {
247 if ($item->itemnumber > $max_itemnumber) {
248 $max_itemnumber = $item->itemnumber;
253 foreach($outcomes as $outcome) {
254 $elname = 'outcome_'.$outcome->id;
256 if (property_exists($moduleinfo, $elname) and $moduleinfo->$elname) {
257 // So we have a request for new outcome grade item?
258 if ($items) {
259 $outcomeexists = false;
260 foreach($items as $item) {
261 if ($item->outcomeid == $outcome->id) {
262 $outcomeexists = true;
263 break;
266 if ($outcomeexists) {
267 continue;
271 $max_itemnumber++;
273 $outcome_item = new grade_item();
274 $outcome_item->courseid = $course->id;
275 $outcome_item->itemtype = 'mod';
276 $outcome_item->itemmodule = $moduleinfo->modulename;
277 $outcome_item->iteminstance = $moduleinfo->instance;
278 $outcome_item->itemnumber = $max_itemnumber;
279 $outcome_item->itemname = $outcome->fullname;
280 $outcome_item->outcomeid = $outcome->id;
281 $outcome_item->gradetype = GRADE_TYPE_SCALE;
282 $outcome_item->scaleid = $outcome->scaleid;
283 $outcome_item->insert();
285 // Move the new outcome into correct category and fix sortorder if needed.
286 if ($grade_item) {
287 $outcome_item->set_parent($grade_item->categoryid);
288 $outcome_item->move_after_sortorder($grade_item->sortorder);
290 } else if (isset($moduleinfo->gradecat)) {
291 $outcome_item->set_parent($moduleinfo->gradecat);
297 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_ADVANCED_GRADING, false)
298 and has_capability('moodle/grade:managegradingforms', $modcontext)) {
299 require_once($CFG->dirroot.'/grade/grading/lib.php');
300 $gradingman = get_grading_manager($modcontext, 'mod_'.$moduleinfo->modulename);
301 $showgradingmanagement = false;
302 foreach ($gradingman->get_available_areas() as $areaname => $aretitle) {
303 $formfield = 'advancedgradingmethod_'.$areaname;
304 if (isset($moduleinfo->{$formfield})) {
305 $gradingman->set_area($areaname);
306 $methodchanged = $gradingman->set_active_method($moduleinfo->{$formfield});
307 if (empty($moduleinfo->{$formfield})) {
308 // Going back to the simple direct grading is not a reason to open the management screen.
309 $methodchanged = false;
311 $showgradingmanagement = $showgradingmanagement || $methodchanged;
314 // Update grading management information.
315 $moduleinfo->gradingman = $gradingman;
316 $moduleinfo->showgradingmanagement = $showgradingmanagement;
319 rebuild_course_cache($course->id, true);
320 if ($hasgrades) {
321 grade_regrade_final_grades($course->id);
323 require_once($CFG->libdir.'/plagiarismlib.php');
324 plagiarism_save_form_elements($moduleinfo);
326 return $moduleinfo;
331 * Set module info default values for the unset module attributs.
333 * @param object $moduleinfo the current known data of the module
334 * @return object the completed module info
336 function set_moduleinfo_defaults($moduleinfo) {
338 if (empty($moduleinfo->coursemodule)) {
339 // Add.
340 $cm = null;
341 $moduleinfo->instance = '';
342 $moduleinfo->coursemodule = '';
343 } else {
344 // Update.
345 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule, 0, false, MUST_EXIST);
346 $moduleinfo->instance = $cm->instance;
347 $moduleinfo->coursemodule = $cm->id;
349 // For safety.
350 $moduleinfo->modulename = clean_param($moduleinfo->modulename, PARAM_PLUGIN);
352 if (!isset($moduleinfo->groupingid)) {
353 $moduleinfo->groupingid = 0;
356 if (!isset($moduleinfo->name)) { // Label.
357 $moduleinfo->name = $moduleinfo->modulename;
360 if (!isset($moduleinfo->completion)) {
361 $moduleinfo->completion = COMPLETION_DISABLED;
363 if (!isset($moduleinfo->completionview)) {
364 $moduleinfo->completionview = COMPLETION_VIEW_NOT_REQUIRED;
366 if (!isset($moduleinfo->completionexpected)) {
367 $moduleinfo->completionexpected = 0;
370 // Convert the 'use grade' checkbox into a grade-item number: 0 if checked, null if not.
371 if (isset($moduleinfo->completionusegrade) && $moduleinfo->completionusegrade) {
372 $moduleinfo->completiongradeitemnumber = 0;
373 } else {
374 $moduleinfo->completiongradeitemnumber = null;
377 if (!isset($moduleinfo->conditiongradegroup)) {
378 $moduleinfo->conditiongradegroup = array();
380 if (!isset($moduleinfo->conditionfieldgroup)) {
381 $moduleinfo->conditionfieldgroup = array();
384 return $moduleinfo;
388 * Check that the user can add a module. Also returns some information like the module, context and course section info.
389 * The fucntion create the course section if it doesn't exist.
391 * @param object $course the course of the module
392 * @param object $modulename the module name
393 * @param object $section the section of the module
394 * @return array list containing module, context, course section.
395 * @throws moodle_exception if user is not allowed to perform the action or module is not allowed in this course
397 function can_add_moduleinfo($course, $modulename, $section) {
398 global $DB;
400 $module = $DB->get_record('modules', array('name'=>$modulename), '*', MUST_EXIST);
402 $context = context_course::instance($course->id);
403 require_capability('moodle/course:manageactivities', $context);
405 course_create_sections_if_missing($course, $section);
406 $cw = get_fast_modinfo($course)->get_section_info($section);
408 if (!course_allowed_module($course, $module->name)) {
409 print_error('moduledisable');
412 return array($module, $context, $cw);
416 * Check if user is allowed to update module info and returns related item/data to the module.
418 * @param object $cm course module
419 * @return array - list of course module, context, module, moduleinfo, and course section.
420 * @throws moodle_exception if user is not allowed to perform the action
422 function can_update_moduleinfo($cm) {
423 global $DB;
425 // Check the $USER has the right capability.
426 $context = context_module::instance($cm->id);
427 require_capability('moodle/course:manageactivities', $context);
429 // Check module exists.
430 $module = $DB->get_record('modules', array('id'=>$cm->module), '*', MUST_EXIST);
432 // Check the moduleinfo exists.
433 $data = $DB->get_record($module->name, array('id'=>$cm->instance), '*', MUST_EXIST);
435 // Check the course section exists.
436 $cw = $DB->get_record('course_sections', array('id'=>$cm->section), '*', MUST_EXIST);
438 return array($cm, $context, $module, $data, $cw);
443 * Update the module info.
444 * This function doesn't check the user capabilities. It updates the course module and the module instance.
445 * Then execute common action to create/update module process (trigger event, rebuild cache, save plagiarism settings...).
447 * @param object $cm course module
448 * @param object $moduleinfo module info
449 * @param object $course course of the module
450 * @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.
451 * @return array list of course module and module info.
453 function update_moduleinfo($cm, $moduleinfo, $course, $mform = null) {
454 global $DB, $CFG;
456 // Attempt to include module library before we make any changes to DB.
457 include_modulelib($moduleinfo->modulename);
459 $moduleinfo->course = $course->id;
460 $moduleinfo = set_moduleinfo_defaults($moduleinfo);
462 if (!empty($course->groupmodeforce) or !isset($moduleinfo->groupmode)) {
463 $moduleinfo->groupmode = $cm->groupmode; // Keep original.
466 // Update course module first.
467 $cm->groupmode = $moduleinfo->groupmode;
468 if (isset($moduleinfo->groupingid)) {
469 $cm->groupingid = $moduleinfo->groupingid;
472 $completion = new completion_info($course);
473 if ($completion->is_enabled()) {
474 // Completion settings that would affect users who have already completed
475 // the activity may be locked; if so, these should not be updated.
476 if (!empty($moduleinfo->completionunlocked)) {
477 $cm->completion = $moduleinfo->completion;
478 $cm->completiongradeitemnumber = $moduleinfo->completiongradeitemnumber;
479 $cm->completionview = $moduleinfo->completionview;
481 // The expected date does not affect users who have completed the activity,
482 // so it is safe to update it regardless of the lock status.
483 $cm->completionexpected = $moduleinfo->completionexpected;
485 if (!empty($CFG->enableavailability)) {
486 // This code is used both when submitting the form, which uses a long
487 // name to avoid clashes, and by unit test code which uses the real
488 // name in the table.
489 if (property_exists($moduleinfo, 'availabilityconditionsjson')) {
490 if ($moduleinfo->availabilityconditionsjson !== '') {
491 $cm->availability = $moduleinfo->availabilityconditionsjson;
492 } else {
493 $cm->availability = null;
495 } else if (property_exists($moduleinfo, 'availability')) {
496 $cm->availability = $moduleinfo->availability;
498 // If there is any availability data, verify it.
499 if ($cm->availability) {
500 $tree = new \core_availability\tree(json_decode($cm->availability));
501 // Save time and database space by setting null if the only data
502 // is an empty tree.
503 if ($tree->is_empty()) {
504 $cm->availability = null;
508 if (isset($moduleinfo->showdescription)) {
509 $cm->showdescription = $moduleinfo->showdescription;
510 } else {
511 $cm->showdescription = 0;
514 $DB->update_record('course_modules', $cm);
516 $modcontext = context_module::instance($moduleinfo->coursemodule);
518 // Update embedded links and save files.
519 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
520 $moduleinfo->intro = file_save_draft_area_files($moduleinfo->introeditor['itemid'], $modcontext->id,
521 'mod_'.$moduleinfo->modulename, 'intro', 0,
522 array('subdirs'=>true), $moduleinfo->introeditor['text']);
523 $moduleinfo->introformat = $moduleinfo->introeditor['format'];
524 unset($moduleinfo->introeditor);
526 $updateinstancefunction = $moduleinfo->modulename."_update_instance";
527 if (!$updateinstancefunction($moduleinfo, $mform)) {
528 print_error('cannotupdatemod', '', course_get_url($course, $cw->section), $moduleinfo->modulename);
531 // Make sure visibility is set correctly (in particular in calendar).
532 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
533 set_coursemodule_visible($moduleinfo->coursemodule, $moduleinfo->visible);
536 if (isset($moduleinfo->cmidnumber)) { // Label.
537 // Set cm idnumber - uniqueness is already verified by form validation.
538 set_coursemodule_idnumber($moduleinfo->coursemodule, $moduleinfo->cmidnumber);
541 // Now that module is fully updated, also update completion data if required.
542 // (this will wipe all user completion data and recalculate it)
543 if ($completion->is_enabled() && !empty($moduleinfo->completionunlocked)) {
544 $completion->reset_all_state($cm);
546 $cm->name = $moduleinfo->name;
547 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
549 $moduleinfo = edit_module_post_actions($moduleinfo, $course);
551 return array($cm, $moduleinfo);
555 * Include once the module lib file.
557 * @param string $modulename module name of the lib to include
558 * @throws moodle_exception if lib.php file for the module does not exist
560 function include_modulelib($modulename) {
561 global $CFG;
562 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
563 if (file_exists($modlib)) {
564 include_once($modlib);
565 } else {
566 throw new moodle_exception('modulemissingcode', '', '', $modlib);