Merge branch 'MDL-50176' of git://github.com/aolley/moodle
[moodle.git] / course / modlib.php
blob3d492644c532fcb4fc8d4a8479e0566559a3667e
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];
235 $gradecategory = $grade_item->get_parent_category();
236 if (!empty($moduleinfo->add)) {
237 if (grade_category::aggregation_uses_aggregationcoef($gradecategory->aggregation)) {
238 if ($gradecategory->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN) {
239 $grade_item->aggregationcoef = 1;
240 } else {
241 $grade_item->aggregationcoef = 0;
243 $grade_item->update();
249 require_once($CFG->libdir.'/grade/grade_outcome.php');
250 // Add outcomes if requested.
251 if ($hasoutcomes && $outcomes = grade_outcome::fetch_all_available($course->id)) {
252 $grade_items = array();
254 // Outcome grade_item.itemnumber start at 1000, there is nothing above outcomes.
255 $max_itemnumber = 999;
256 if ($items) {
257 foreach($items as $item) {
258 if ($item->itemnumber > $max_itemnumber) {
259 $max_itemnumber = $item->itemnumber;
264 foreach($outcomes as $outcome) {
265 $elname = 'outcome_'.$outcome->id;
267 if (property_exists($moduleinfo, $elname) and $moduleinfo->$elname) {
268 // So we have a request for new outcome grade item?
269 if ($items) {
270 $outcomeexists = false;
271 foreach($items as $item) {
272 if ($item->outcomeid == $outcome->id) {
273 $outcomeexists = true;
274 break;
277 if ($outcomeexists) {
278 continue;
282 $max_itemnumber++;
284 $outcome_item = new grade_item();
285 $outcome_item->courseid = $course->id;
286 $outcome_item->itemtype = 'mod';
287 $outcome_item->itemmodule = $moduleinfo->modulename;
288 $outcome_item->iteminstance = $moduleinfo->instance;
289 $outcome_item->itemnumber = $max_itemnumber;
290 $outcome_item->itemname = $outcome->fullname;
291 $outcome_item->outcomeid = $outcome->id;
292 $outcome_item->gradetype = GRADE_TYPE_SCALE;
293 $outcome_item->scaleid = $outcome->scaleid;
294 $outcome_item->insert();
296 // Move the new outcome into correct category and fix sortorder if needed.
297 if ($grade_item) {
298 $outcome_item->set_parent($grade_item->categoryid);
299 $outcome_item->move_after_sortorder($grade_item->sortorder);
301 } else if (isset($moduleinfo->gradecat)) {
302 $outcome_item->set_parent($moduleinfo->gradecat);
304 $gradecategory = $outcome_item->get_parent_category();
305 if ($outcomeexists == false) {
306 if (grade_category::aggregation_uses_aggregationcoef($gradecategory->aggregation)) {
307 if ($gradecategory->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN) {
308 $outcome_item->aggregationcoef = 1;
309 } else {
310 $outcome_item->aggregationcoef = 0;
312 $outcome_item->update();
319 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_ADVANCED_GRADING, false)
320 and has_capability('moodle/grade:managegradingforms', $modcontext)) {
321 require_once($CFG->dirroot.'/grade/grading/lib.php');
322 $gradingman = get_grading_manager($modcontext, 'mod_'.$moduleinfo->modulename);
323 $showgradingmanagement = false;
324 foreach ($gradingman->get_available_areas() as $areaname => $aretitle) {
325 $formfield = 'advancedgradingmethod_'.$areaname;
326 if (isset($moduleinfo->{$formfield})) {
327 $gradingman->set_area($areaname);
328 $methodchanged = $gradingman->set_active_method($moduleinfo->{$formfield});
329 if (empty($moduleinfo->{$formfield})) {
330 // Going back to the simple direct grading is not a reason to open the management screen.
331 $methodchanged = false;
333 $showgradingmanagement = $showgradingmanagement || $methodchanged;
336 // Update grading management information.
337 $moduleinfo->gradingman = $gradingman;
338 $moduleinfo->showgradingmanagement = $showgradingmanagement;
341 rebuild_course_cache($course->id, true);
342 if ($hasgrades) {
343 grade_regrade_final_grades($course->id);
345 require_once($CFG->libdir.'/plagiarismlib.php');
346 plagiarism_save_form_elements($moduleinfo);
348 return $moduleinfo;
353 * Set module info default values for the unset module attributs.
355 * @param object $moduleinfo the current known data of the module
356 * @return object the completed module info
358 function set_moduleinfo_defaults($moduleinfo) {
360 if (empty($moduleinfo->coursemodule)) {
361 // Add.
362 $cm = null;
363 $moduleinfo->instance = '';
364 $moduleinfo->coursemodule = '';
365 } else {
366 // Update.
367 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule, 0, false, MUST_EXIST);
368 $moduleinfo->instance = $cm->instance;
369 $moduleinfo->coursemodule = $cm->id;
371 // For safety.
372 $moduleinfo->modulename = clean_param($moduleinfo->modulename, PARAM_PLUGIN);
374 if (!isset($moduleinfo->groupingid)) {
375 $moduleinfo->groupingid = 0;
378 if (!isset($moduleinfo->name)) { // Label.
379 $moduleinfo->name = $moduleinfo->modulename;
382 if (!isset($moduleinfo->completion)) {
383 $moduleinfo->completion = COMPLETION_DISABLED;
385 if (!isset($moduleinfo->completionview)) {
386 $moduleinfo->completionview = COMPLETION_VIEW_NOT_REQUIRED;
388 if (!isset($moduleinfo->completionexpected)) {
389 $moduleinfo->completionexpected = 0;
392 // Convert the 'use grade' checkbox into a grade-item number: 0 if checked, null if not.
393 if (isset($moduleinfo->completionusegrade) && $moduleinfo->completionusegrade) {
394 $moduleinfo->completiongradeitemnumber = 0;
395 } else {
396 $moduleinfo->completiongradeitemnumber = null;
399 if (!isset($moduleinfo->conditiongradegroup)) {
400 $moduleinfo->conditiongradegroup = array();
402 if (!isset($moduleinfo->conditionfieldgroup)) {
403 $moduleinfo->conditionfieldgroup = array();
406 return $moduleinfo;
410 * Check that the user can add a module. Also returns some information like the module, context and course section info.
411 * The fucntion create the course section if it doesn't exist.
413 * @param object $course the course of the module
414 * @param object $modulename the module name
415 * @param object $section the section of the module
416 * @return array list containing module, context, course section.
417 * @throws moodle_exception if user is not allowed to perform the action or module is not allowed in this course
419 function can_add_moduleinfo($course, $modulename, $section) {
420 global $DB;
422 $module = $DB->get_record('modules', array('name'=>$modulename), '*', MUST_EXIST);
424 $context = context_course::instance($course->id);
425 require_capability('moodle/course:manageactivities', $context);
427 course_create_sections_if_missing($course, $section);
428 $cw = get_fast_modinfo($course)->get_section_info($section);
430 if (!course_allowed_module($course, $module->name)) {
431 print_error('moduledisable');
434 return array($module, $context, $cw);
438 * Check if user is allowed to update module info and returns related item/data to the module.
440 * @param object $cm course module
441 * @return array - list of course module, context, module, moduleinfo, and course section.
442 * @throws moodle_exception if user is not allowed to perform the action
444 function can_update_moduleinfo($cm) {
445 global $DB;
447 // Check the $USER has the right capability.
448 $context = context_module::instance($cm->id);
449 require_capability('moodle/course:manageactivities', $context);
451 // Check module exists.
452 $module = $DB->get_record('modules', array('id'=>$cm->module), '*', MUST_EXIST);
454 // Check the moduleinfo exists.
455 $data = $DB->get_record($module->name, array('id'=>$cm->instance), '*', MUST_EXIST);
457 // Check the course section exists.
458 $cw = $DB->get_record('course_sections', array('id'=>$cm->section), '*', MUST_EXIST);
460 return array($cm, $context, $module, $data, $cw);
465 * Update the module info.
466 * This function doesn't check the user capabilities. It updates the course module and the module instance.
467 * Then execute common action to create/update module process (trigger event, rebuild cache, save plagiarism settings...).
469 * @param object $cm course module
470 * @param object $moduleinfo module info
471 * @param object $course course of the module
472 * @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.
473 * @return array list of course module and module info.
475 function update_moduleinfo($cm, $moduleinfo, $course, $mform = null) {
476 global $DB, $CFG;
478 // Attempt to include module library before we make any changes to DB.
479 include_modulelib($moduleinfo->modulename);
481 $moduleinfo->course = $course->id;
482 $moduleinfo = set_moduleinfo_defaults($moduleinfo);
484 if (!empty($course->groupmodeforce) or !isset($moduleinfo->groupmode)) {
485 $moduleinfo->groupmode = $cm->groupmode; // Keep original.
488 // Update course module first.
489 $cm->groupmode = $moduleinfo->groupmode;
490 if (isset($moduleinfo->groupingid)) {
491 $cm->groupingid = $moduleinfo->groupingid;
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;
514 } else {
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
524 // is an empty tree.
525 if ($tree->is_empty()) {
526 $cm->availability = null;
530 if (isset($moduleinfo->showdescription)) {
531 $cm->showdescription = $moduleinfo->showdescription;
532 } else {
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) {
583 global $CFG;
584 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
585 if (file_exists($modlib)) {
586 include_once($modlib);
587 } else {
588 throw new moodle_exception('modulemissingcode', '', '', $modlib);