MDL-45219 add \mod\chat\course_module_viewed event
[moodle.git] / course / modlib.php
blob454202e505fd80a61b4132a03976406859b8ae72
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 $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
80 // name in the table.
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;
90 if (isset($moduleinfo->showdescription)) {
91 $newcm->showdescription = $moduleinfo->showdescription;
92 } else {
93 $newcm->showdescription = 0;
96 // From this point we make database changes, so start transaction.
97 $transaction = $DB->start_delegated_transaction();
99 if (!$moduleinfo->coursemodule = add_course_module($newcm)) {
100 print_error('cannotaddcoursemodule');
103 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true) &&
104 isset($moduleinfo->introeditor)) {
105 $introeditor = $moduleinfo->introeditor;
106 unset($moduleinfo->introeditor);
107 $moduleinfo->intro = $introeditor['text'];
108 $moduleinfo->introformat = $introeditor['format'];
111 $addinstancefunction = $moduleinfo->modulename."_add_instance";
112 try {
113 $returnfromfunc = $addinstancefunction($moduleinfo, $mform);
114 } catch (moodle_exception $e) {
115 $returnfromfunc = $e;
117 if (!$returnfromfunc or !is_number($returnfromfunc)) {
118 // Undo everything we can. This is not necessary for databases which
119 // support transactions, but improves consistency for other databases.
120 $modcontext = context_module::instance($moduleinfo->coursemodule);
121 context_helper::delete_instance(CONTEXT_MODULE, $moduleinfo->coursemodule);
122 $DB->delete_records('course_modules', array('id'=>$moduleinfo->coursemodule));
124 if ($e instanceof moodle_exception) {
125 throw $e;
126 } else if (!is_number($returnfromfunc)) {
127 print_error('invalidfunction', '', course_get_url($course, $moduleinfo->section));
128 } else {
129 print_error('cannotaddnewmodule', '', course_get_url($course, $moduleinfo->section), $moduleinfo->modulename);
133 $moduleinfo->instance = $returnfromfunc;
135 $DB->set_field('course_modules', 'instance', $returnfromfunc, array('id'=>$moduleinfo->coursemodule));
137 // Update embedded links and save files.
138 $modcontext = context_module::instance($moduleinfo->coursemodule);
139 if (!empty($introeditor)) {
140 $moduleinfo->intro = file_save_draft_area_files($introeditor['itemid'], $modcontext->id,
141 'mod_'.$moduleinfo->modulename, 'intro', 0,
142 array('subdirs'=>true), $introeditor['text']);
143 $DB->set_field($moduleinfo->modulename, 'intro', $moduleinfo->intro, array('id'=>$moduleinfo->instance));
146 // Course_modules and course_sections each contain a reference to each other.
147 // So we have to update one of them twice.
148 $sectionid = course_add_cm_to_section($course, $moduleinfo->coursemodule, $moduleinfo->section);
150 // Trigger event based on the action we did.
151 $event = \core\event\course_module_created::create(array(
152 'courseid' => $course->id,
153 'context' => $modcontext,
154 'objectid' => $moduleinfo->coursemodule,
155 'other' => array(
156 'modulename' => $moduleinfo->modulename,
157 'name' => $moduleinfo->name,
158 'instanceid' => $moduleinfo->instance
161 $event->trigger();
163 $moduleinfo = edit_module_post_actions($moduleinfo, $course);
164 $transaction->allow_commit();
166 return $moduleinfo;
171 * Common create/update module module actions that need to be processed as soon as a module is created/updaded.
172 * For example:create grade parent category, add outcomes, rebuild caches, regrade, save plagiarism settings...
173 * Please note this api does not trigger events as of MOODLE 2.6. Please trigger events before calling this api.
175 * @param object $moduleinfo the module info
176 * @param object $course the course of the module
178 * @return object moduleinfo update with grading management info
180 function edit_module_post_actions($moduleinfo, $course) {
181 global $CFG;
183 $modcontext = context_module::instance($moduleinfo->coursemodule);
184 $hasgrades = plugin_supports('mod', $moduleinfo->modulename, FEATURE_GRADE_HAS_GRADE, false);
185 $hasoutcomes = plugin_supports('mod', $moduleinfo->modulename, FEATURE_GRADE_OUTCOMES, true);
187 // Sync idnumber with grade_item.
188 if ($hasgrades && $grade_item = grade_item::fetch(array('itemtype'=>'mod', 'itemmodule'=>$moduleinfo->modulename,
189 'iteminstance'=>$moduleinfo->instance, 'itemnumber'=>0, 'courseid'=>$course->id))) {
190 if ($grade_item->idnumber != $moduleinfo->cmidnumber) {
191 $grade_item->idnumber = $moduleinfo->cmidnumber;
192 $grade_item->update();
196 if ($hasgrades) {
197 $items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$moduleinfo->modulename,
198 'iteminstance'=>$moduleinfo->instance, 'courseid'=>$course->id));
199 } else {
200 $items = array();
203 // Create parent category if requested and move to correct parent category.
204 if ($items and isset($moduleinfo->gradecat)) {
205 if ($moduleinfo->gradecat == -1) {
206 $grade_category = new grade_category();
207 $grade_category->courseid = $course->id;
208 $grade_category->fullname = $moduleinfo->name;
209 $grade_category->insert();
210 if ($grade_item) {
211 $parent = $grade_item->get_parent_category();
212 $grade_category->set_parent($parent->id);
214 $moduleinfo->gradecat = $grade_category->id;
216 foreach ($items as $itemid=>$unused) {
217 $items[$itemid]->set_parent($moduleinfo->gradecat);
218 if ($itemid == $grade_item->id) {
219 // Use updated grade_item.
220 $grade_item = $items[$itemid];
225 require_once($CFG->libdir.'/grade/grade_outcome.php');
226 // Add outcomes if requested.
227 if ($hasoutcomes && $outcomes = grade_outcome::fetch_all_available($course->id)) {
228 $grade_items = array();
230 // Outcome grade_item.itemnumber start at 1000, there is nothing above outcomes.
231 $max_itemnumber = 999;
232 if ($items) {
233 foreach($items as $item) {
234 if ($item->itemnumber > $max_itemnumber) {
235 $max_itemnumber = $item->itemnumber;
240 foreach($outcomes as $outcome) {
241 $elname = 'outcome_'.$outcome->id;
243 if (property_exists($moduleinfo, $elname) and $moduleinfo->$elname) {
244 // So we have a request for new outcome grade item?
245 if ($items) {
246 $outcomeexists = false;
247 foreach($items as $item) {
248 if ($item->outcomeid == $outcome->id) {
249 $outcomeexists = true;
250 break;
253 if ($outcomeexists) {
254 continue;
258 $max_itemnumber++;
260 $outcome_item = new grade_item();
261 $outcome_item->courseid = $course->id;
262 $outcome_item->itemtype = 'mod';
263 $outcome_item->itemmodule = $moduleinfo->modulename;
264 $outcome_item->iteminstance = $moduleinfo->instance;
265 $outcome_item->itemnumber = $max_itemnumber;
266 $outcome_item->itemname = $outcome->fullname;
267 $outcome_item->outcomeid = $outcome->id;
268 $outcome_item->gradetype = GRADE_TYPE_SCALE;
269 $outcome_item->scaleid = $outcome->scaleid;
270 $outcome_item->insert();
272 // Move the new outcome into correct category and fix sortorder if needed.
273 if ($grade_item) {
274 $outcome_item->set_parent($grade_item->categoryid);
275 $outcome_item->move_after_sortorder($grade_item->sortorder);
277 } else if (isset($moduleinfo->gradecat)) {
278 $outcome_item->set_parent($moduleinfo->gradecat);
284 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_ADVANCED_GRADING, false)
285 and has_capability('moodle/grade:managegradingforms', $modcontext)) {
286 require_once($CFG->dirroot.'/grade/grading/lib.php');
287 $gradingman = get_grading_manager($modcontext, 'mod_'.$moduleinfo->modulename);
288 $showgradingmanagement = false;
289 foreach ($gradingman->get_available_areas() as $areaname => $aretitle) {
290 $formfield = 'advancedgradingmethod_'.$areaname;
291 if (isset($moduleinfo->{$formfield})) {
292 $gradingman->set_area($areaname);
293 $methodchanged = $gradingman->set_active_method($moduleinfo->{$formfield});
294 if (empty($moduleinfo->{$formfield})) {
295 // Going back to the simple direct grading is not a reason to open the management screen.
296 $methodchanged = false;
298 $showgradingmanagement = $showgradingmanagement || $methodchanged;
301 // Update grading management information.
302 $moduleinfo->gradingman = $gradingman;
303 $moduleinfo->showgradingmanagement = $showgradingmanagement;
306 rebuild_course_cache($course->id, true);
307 if ($hasgrades) {
308 grade_regrade_final_grades($course->id);
310 require_once($CFG->libdir.'/plagiarismlib.php');
311 plagiarism_save_form_elements($moduleinfo);
313 return $moduleinfo;
318 * Set module info default values for the unset module attributs.
320 * @param object $moduleinfo the current known data of the module
321 * @return object the completed module info
323 function set_moduleinfo_defaults($moduleinfo) {
325 if (empty($moduleinfo->coursemodule)) {
326 // Add.
327 $cm = null;
328 $moduleinfo->instance = '';
329 $moduleinfo->coursemodule = '';
330 } else {
331 // Update.
332 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule, 0, false, MUST_EXIST);
333 $moduleinfo->instance = $cm->instance;
334 $moduleinfo->coursemodule = $cm->id;
336 // For safety.
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;
357 if (!isset($moduleinfo->completionexpected)) {
358 $moduleinfo->completionexpected = 0;
361 // Convert the 'use grade' checkbox into a grade-item number: 0 if checked, null if not.
362 if (isset($moduleinfo->completionusegrade) && $moduleinfo->completionusegrade) {
363 $moduleinfo->completiongradeitemnumber = 0;
364 } else {
365 $moduleinfo->completiongradeitemnumber = null;
368 if (!isset($moduleinfo->conditiongradegroup)) {
369 $moduleinfo->conditiongradegroup = array();
371 if (!isset($moduleinfo->conditionfieldgroup)) {
372 $moduleinfo->conditionfieldgroup = array();
375 return $moduleinfo;
379 * Check that the user can add a module. Also returns some information like the module, context and course section info.
380 * The fucntion create the course section if it doesn't exist.
382 * @param object $course the course of the module
383 * @param object $modulename the module name
384 * @param object $section the section of the module
385 * @return array list containing module, context, course section.
386 * @throws moodle_exception if user is not allowed to perform the action or module is not allowed in this course
388 function can_add_moduleinfo($course, $modulename, $section) {
389 global $DB;
391 $module = $DB->get_record('modules', array('name'=>$modulename), '*', MUST_EXIST);
393 $context = context_course::instance($course->id);
394 require_capability('moodle/course:manageactivities', $context);
396 course_create_sections_if_missing($course, $section);
397 $cw = get_fast_modinfo($course)->get_section_info($section);
399 if (!course_allowed_module($course, $module->name)) {
400 print_error('moduledisable');
403 return array($module, $context, $cw);
407 * Check if user is allowed to update module info and returns related item/data to the module.
409 * @param object $cm course module
410 * @return array - list of course module, context, module, moduleinfo, and course section.
411 * @throws moodle_exception if user is not allowed to perform the action
413 function can_update_moduleinfo($cm) {
414 global $DB;
416 // Check the $USER has the right capability.
417 $context = context_module::instance($cm->id);
418 require_capability('moodle/course:manageactivities', $context);
420 // Check module exists.
421 $module = $DB->get_record('modules', array('id'=>$cm->module), '*', MUST_EXIST);
423 // Check the moduleinfo exists.
424 $data = $DB->get_record($module->name, array('id'=>$cm->instance), '*', MUST_EXIST);
426 // Check the course section exists.
427 $cw = $DB->get_record('course_sections', array('id'=>$cm->section), '*', MUST_EXIST);
429 return array($cm, $context, $module, $data, $cw);
434 * Update the module info.
435 * This function doesn't check the user capabilities. It updates the course module and the module instance.
436 * Then execute common action to create/update module process (trigger event, rebuild cache, save plagiarism settings...).
438 * @param object $cm course module
439 * @param object $moduleinfo module info
440 * @param object $course course of the module
441 * @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.
442 * @return array list of course module and module info.
444 function update_moduleinfo($cm, $moduleinfo, $course, $mform = null) {
445 global $DB, $CFG;
447 // Attempt to include module library before we make any changes to DB.
448 include_modulelib($moduleinfo->modulename);
450 $moduleinfo->course = $course->id;
451 $moduleinfo = set_moduleinfo_defaults($moduleinfo);
453 if (!empty($course->groupmodeforce) or !isset($moduleinfo->groupmode)) {
454 $moduleinfo->groupmode = $cm->groupmode; // Keep original.
457 // Update course module first.
458 $cm->groupmode = $moduleinfo->groupmode;
459 if (isset($moduleinfo->groupingid)) {
460 $cm->groupingid = $moduleinfo->groupingid;
462 if (isset($moduleinfo->groupmembersonly)) {
463 $cm->groupmembersonly = $moduleinfo->groupmembersonly;
466 $completion = new completion_info($course);
467 if ($completion->is_enabled() && !empty($moduleinfo->completionunlocked)) {
468 // Update completion settings.
469 $cm->completion = $moduleinfo->completion;
470 $cm->completiongradeitemnumber = $moduleinfo->completiongradeitemnumber;
471 $cm->completionview = $moduleinfo->completionview;
472 $cm->completionexpected = $moduleinfo->completionexpected;
474 if (!empty($CFG->enableavailability)) {
475 // This code is used both when submitting the form, which uses a long
476 // name to avoid clashes, and by unit test code which uses the real
477 // name in the table.
478 if (property_exists($moduleinfo, 'availabilityconditionsjson')) {
479 if ($moduleinfo->availabilityconditionsjson !== '') {
480 $cm->availability = $moduleinfo->availabilityconditionsjson;
481 } else {
482 $cm->availability = null;
484 } else if (property_exists($moduleinfo, 'availability')) {
485 $cm->availability = $moduleinfo->availability;
488 if (isset($moduleinfo->showdescription)) {
489 $cm->showdescription = $moduleinfo->showdescription;
490 } else {
491 $cm->showdescription = 0;
494 $DB->update_record('course_modules', $cm);
496 $modcontext = context_module::instance($moduleinfo->coursemodule);
498 // Update embedded links and save files.
499 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
500 $moduleinfo->intro = file_save_draft_area_files($moduleinfo->introeditor['itemid'], $modcontext->id,
501 'mod_'.$moduleinfo->modulename, 'intro', 0,
502 array('subdirs'=>true), $moduleinfo->introeditor['text']);
503 $moduleinfo->introformat = $moduleinfo->introeditor['format'];
504 unset($moduleinfo->introeditor);
506 $updateinstancefunction = $moduleinfo->modulename."_update_instance";
507 if (!$updateinstancefunction($moduleinfo, $mform)) {
508 print_error('cannotupdatemod', '', course_get_url($course, $cw->section), $moduleinfo->modulename);
511 // Make sure visibility is set correctly (in particular in calendar).
512 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
513 set_coursemodule_visible($moduleinfo->coursemodule, $moduleinfo->visible);
516 if (isset($moduleinfo->cmidnumber)) { // Label.
517 // Set cm idnumber - uniqueness is already verified by form validation.
518 set_coursemodule_idnumber($moduleinfo->coursemodule, $moduleinfo->cmidnumber);
521 // Now that module is fully updated, also update completion data if required.
522 // (this will wipe all user completion data and recalculate it)
523 if ($completion->is_enabled() && !empty($moduleinfo->completionunlocked)) {
524 $completion->reset_all_state($cm);
527 // Trigger event based on the action we did.
528 $event = \core\event\course_module_updated::create(array(
529 'courseid' => $course->id,
530 'context' => $modcontext,
531 'objectid' => $moduleinfo->coursemodule,
532 'other' => array(
533 'modulename' => $moduleinfo->modulename,
534 'name' => $moduleinfo->name,
535 'instanceid' => $moduleinfo->instance
538 $event->trigger();
540 $moduleinfo = edit_module_post_actions($moduleinfo, $course);
542 return array($cm, $moduleinfo);
546 * Include once the module lib file.
548 * @param string $modulename module name of the lib to include
549 * @throws moodle_exception if lib.php file for the module does not exist
551 function include_modulelib($modulename) {
552 global $CFG;
553 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
554 if (file_exists($modlib)) {
555 include_once($modlib);
556 } else {
557 throw new moodle_exception('modulemissingcode', '', '', $modlib);