MDL-42400 tool_generator: save db query in module generation
[moodle.git] / course / modlib.php
CommitLineData
80fe0c19
JM
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.
13//
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/>.
16
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.
22 *
23 * @copyright 2013 Jerome Mouneyrac
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 * @package core_course
26 */
27
28defined('MOODLE_INTERNAL') || die;
29
30require_once($CFG->dirroot.'/course/lib.php');
31
32/**
33 * Add course module.
34 *
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.
38 *
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
43 */
44function add_moduleinfo($moduleinfo, $course, $mform = null) {
45 global $DB, $CFG;
46
b4b75872
MG
47 // Attempt to include module library before we make any changes to DB.
48 include_modulelib($moduleinfo->modulename);
49
80fe0c19
JM
50 $moduleinfo->course = $course->id;
51 $moduleinfo = set_moduleinfo_defaults($moduleinfo);
52
53 if (!empty($course->groupmodeforce) or !isset($moduleinfo->groupmode)) {
54 $moduleinfo->groupmode = 0; // Do not set groupmode.
55 }
56
8f2913b9 57 // First add course_module record because we need the context.
80fe0c19
JM
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;
7c69ab5d 63 $newcm->visibleold = $moduleinfo->visible;
80fe0c19
JM
64 $newcm->groupmode = $moduleinfo->groupmode;
65 $newcm->groupingid = $moduleinfo->groupingid;
66 $newcm->groupmembersonly = $moduleinfo->groupmembersonly;
67 $completion = new completion_info($course);
68 if ($completion->is_enabled()) {
69 $newcm->completion = $moduleinfo->completion;
70 $newcm->completiongradeitemnumber = $moduleinfo->completiongradeitemnumber;
71 $newcm->completionview = $moduleinfo->completionview;
72 $newcm->completionexpected = $moduleinfo->completionexpected;
73 }
74 if(!empty($CFG->enableavailability)) {
75 $newcm->availablefrom = $moduleinfo->availablefrom;
76 $newcm->availableuntil = $moduleinfo->availableuntil;
77 $newcm->showavailability = $moduleinfo->showavailability;
78 }
79 if (isset($moduleinfo->showdescription)) {
80 $newcm->showdescription = $moduleinfo->showdescription;
81 } else {
82 $newcm->showdescription = 0;
83 }
84
85 if (!$moduleinfo->coursemodule = add_course_module($newcm)) {
86 print_error('cannotaddcoursemodule');
87 }
88
7fbe33fc
MG
89 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true) &&
90 isset($moduleinfo->introeditor)) {
80fe0c19
JM
91 $introeditor = $moduleinfo->introeditor;
92 unset($moduleinfo->introeditor);
93 $moduleinfo->intro = $introeditor['text'];
94 $moduleinfo->introformat = $introeditor['format'];
95 }
96
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);
c592eea2 102 context_helper::delete_instance(CONTEXT_MODULE, $moduleinfo->coursemodule);
80fe0c19
JM
103 $DB->delete_records('course_modules', array('id'=>$moduleinfo->coursemodule));
104
105 if (!is_number($returnfromfunc)) {
b4b75872 106 print_error('invalidfunction', '', course_get_url($course, $moduleinfo->section));
80fe0c19 107 } else {
b4b75872 108 print_error('cannotaddnewmodule', '', course_get_url($course, $moduleinfo->section), $moduleinfo->modulename);
80fe0c19
JM
109 }
110 }
111
112 $moduleinfo->instance = $returnfromfunc;
113
114 $DB->set_field('course_modules', 'instance', $returnfromfunc, array('id'=>$moduleinfo->coursemodule));
115
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));
123 }
124
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);
128
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);
132
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);
136 }
137
138 // Set up conditions.
139 if ($CFG->enableavailability) {
140 condition_info::update_cm_from_form((object)array('id'=>$moduleinfo->coursemodule), $moduleinfo, false);
141 }
142
63deb5c3
AA
143 // Trigger event based on the action we did.
144 $event = \core\event\course_module_created::create(array(
145 'courseid' => $course->id,
146 'context' => $modcontext,
147 'objectid' => $moduleinfo->coursemodule,
148 'other' => array(
149 'modulename' => $moduleinfo->modulename,
150 'name' => $moduleinfo->name,
151 'instanceid' => $moduleinfo->instance
152 )
153 ));
154 $event->trigger();
80fe0c19 155
80fe0c19
JM
156 add_to_log($course->id, $moduleinfo->modulename, "add",
157 "view.php?id=$moduleinfo->coursemodule",
158 "$moduleinfo->instance", $moduleinfo->coursemodule);
159
63deb5c3 160 $moduleinfo = edit_module_post_actions($moduleinfo, $course);
80fe0c19
JM
161
162 return $moduleinfo;
163}
164
165
166/**
167 * Common create/update module module actions that need to be processed as soon as a module is created/updaded.
63deb5c3
AA
168 * For example:create grade parent category, add outcomes, rebuild caches, regrade, save plagiarism settings...
169 * Please note this api does not trigger events as of MOODLE 2.6. Please trigger events before calling this api.
80fe0c19
JM
170 *
171 * @param object $moduleinfo the module info
172 * @param object $course the course of the module
80fe0c19 173 *
63deb5c3 174 * @return object moduleinfo update with grading management info
80fe0c19 175 */
63deb5c3
AA
176function edit_module_post_actions($moduleinfo, $course) {
177 global $CFG;
80fe0c19
JM
178
179 $modcontext = context_module::instance($moduleinfo->coursemodule);
180
80fe0c19
JM
181 // Sync idnumber with grade_item.
182 if ($grade_item = grade_item::fetch(array('itemtype'=>'mod', 'itemmodule'=>$moduleinfo->modulename,
183 'iteminstance'=>$moduleinfo->instance, 'itemnumber'=>0, 'courseid'=>$course->id))) {
184 if ($grade_item->idnumber != $moduleinfo->cmidnumber) {
185 $grade_item->idnumber = $moduleinfo->cmidnumber;
186 $grade_item->update();
187 }
188 }
189
190 $items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$moduleinfo->modulename,
191 'iteminstance'=>$moduleinfo->instance, 'courseid'=>$course->id));
192
193 // Create parent category if requested and move to correct parent category.
194 if ($items and isset($moduleinfo->gradecat)) {
195 if ($moduleinfo->gradecat == -1) {
196 $grade_category = new grade_category();
197 $grade_category->courseid = $course->id;
198 $grade_category->fullname = $moduleinfo->name;
199 $grade_category->insert();
200 if ($grade_item) {
201 $parent = $grade_item->get_parent_category();
202 $grade_category->set_parent($parent->id);
203 }
204 $moduleinfo->gradecat = $grade_category->id;
205 }
206 foreach ($items as $itemid=>$unused) {
207 $items[$itemid]->set_parent($moduleinfo->gradecat);
208 if ($itemid == $grade_item->id) {
209 // Use updated grade_item.
210 $grade_item = $items[$itemid];
211 }
212 }
213 }
214
215 // Add outcomes if requested.
216 if ($outcomes = grade_outcome::fetch_all_available($course->id)) {
217 $grade_items = array();
218
219 // Outcome grade_item.itemnumber start at 1000, there is nothing above outcomes.
220 $max_itemnumber = 999;
221 if ($items) {
222 foreach($items as $item) {
223 if ($item->itemnumber > $max_itemnumber) {
224 $max_itemnumber = $item->itemnumber;
225 }
226 }
227 }
228
229 foreach($outcomes as $outcome) {
230 $elname = 'outcome_'.$outcome->id;
231
232 if (property_exists($moduleinfo, $elname) and $moduleinfo->$elname) {
233 // So we have a request for new outcome grade item?
234 if ($items) {
3b2a6bf5 235 $outcomeexists = false;
80fe0c19
JM
236 foreach($items as $item) {
237 if ($item->outcomeid == $outcome->id) {
3b2a6bf5
DW
238 $outcomeexists = true;
239 break;
80fe0c19
JM
240 }
241 }
3b2a6bf5
DW
242 if ($outcomeexists) {
243 continue;
244 }
80fe0c19
JM
245 }
246
247 $max_itemnumber++;
248
249 $outcome_item = new grade_item();
250 $outcome_item->courseid = $course->id;
251 $outcome_item->itemtype = 'mod';
252 $outcome_item->itemmodule = $moduleinfo->modulename;
253 $outcome_item->iteminstance = $moduleinfo->instance;
254 $outcome_item->itemnumber = $max_itemnumber;
255 $outcome_item->itemname = $outcome->fullname;
256 $outcome_item->outcomeid = $outcome->id;
257 $outcome_item->gradetype = GRADE_TYPE_SCALE;
258 $outcome_item->scaleid = $outcome->scaleid;
259 $outcome_item->insert();
260
261 // Move the new outcome into correct category and fix sortorder if needed.
262 if ($grade_item) {
263 $outcome_item->set_parent($grade_item->categoryid);
264 $outcome_item->move_after_sortorder($grade_item->sortorder);
265
266 } else if (isset($moduleinfo->gradecat)) {
267 $outcome_item->set_parent($moduleinfo->gradecat);
268 }
269 }
270 }
271 }
272
273 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_ADVANCED_GRADING, false)
274 and has_capability('moodle/grade:managegradingforms', $modcontext)) {
275 require_once($CFG->dirroot.'/grade/grading/lib.php');
276 $gradingman = get_grading_manager($modcontext, 'mod_'.$moduleinfo->modulename);
277 $showgradingmanagement = false;
278 foreach ($gradingman->get_available_areas() as $areaname => $aretitle) {
279 $formfield = 'advancedgradingmethod_'.$areaname;
280 if (isset($moduleinfo->{$formfield})) {
281 $gradingman->set_area($areaname);
282 $methodchanged = $gradingman->set_active_method($moduleinfo->{$formfield});
283 if (empty($moduleinfo->{$formfield})) {
284 // Going back to the simple direct grading is not a reason to open the management screen.
285 $methodchanged = false;
286 }
287 $showgradingmanagement = $showgradingmanagement || $methodchanged;
288 }
289 }
290 // Update grading management information.
291 $moduleinfo->gradingman = $gradingman;
292 $moduleinfo->showgradingmanagement = $showgradingmanagement;
293 }
294
295 rebuild_course_cache($course->id);
296 grade_regrade_final_grades($course->id);
297 require_once($CFG->libdir.'/plagiarismlib.php');
8f2913b9 298 plagiarism_save_form_elements($moduleinfo);
80fe0c19
JM
299
300 return $moduleinfo;
301}
302
303
304/**
305 * Set module info default values for the unset module attributs.
306 *
307 * @param object $moduleinfo the current known data of the module
308 * @return object the completed module info
309 */
310function set_moduleinfo_defaults($moduleinfo) {
80fe0c19
JM
311
312 if (empty($moduleinfo->coursemodule)) {
313 // Add.
314 $cm = null;
315 $moduleinfo->instance = '';
316 $moduleinfo->coursemodule = '';
317 } else {
318 // Update.
319 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule, 0, false, MUST_EXIST);
320 $moduleinfo->instance = $cm->instance;
321 $moduleinfo->coursemodule = $cm->id;
322 }
8f2913b9
DW
323 // For safety.
324 $moduleinfo->modulename = clean_param($moduleinfo->modulename, PARAM_PLUGIN);
80fe0c19
JM
325
326 if (!isset($moduleinfo->groupingid)) {
327 $moduleinfo->groupingid = 0;
328 }
329
330 if (!isset($moduleinfo->groupmembersonly)) {
331 $moduleinfo->groupmembersonly = 0;
332 }
333
334 if (!isset($moduleinfo->name)) { // Label.
335 $moduleinfo->name = $moduleinfo->modulename;
336 }
337
338 if (!isset($moduleinfo->completion)) {
339 $moduleinfo->completion = COMPLETION_DISABLED;
340 }
341 if (!isset($moduleinfo->completionview)) {
342 $moduleinfo->completionview = COMPLETION_VIEW_NOT_REQUIRED;
343 }
344
345 // Convert the 'use grade' checkbox into a grade-item number: 0 if checked, null if not.
346 if (isset($moduleinfo->completionusegrade) && $moduleinfo->completionusegrade) {
347 $moduleinfo->completiongradeitemnumber = 0;
348 } else {
349 $moduleinfo->completiongradeitemnumber = null;
350 }
351
352 return $moduleinfo;
353}
354
355/**
356 * Check that the user can add a module. Also returns some information like the module, context and course section info.
357 * The fucntion create the course section if it doesn't exist.
358 *
359 * @param object $course the course of the module
360 * @param object $modulename the module name
361 * @param object $section the section of the module
362 * @return array list containing module, context, course section.
b4b75872 363 * @throws moodle_exception if user is not allowed to perform the action or module is not allowed in this course
80fe0c19
JM
364 */
365function can_add_moduleinfo($course, $modulename, $section) {
366 global $DB;
367
368 $module = $DB->get_record('modules', array('name'=>$modulename), '*', MUST_EXIST);
369
370 $context = context_course::instance($course->id);
371 require_capability('moodle/course:manageactivities', $context);
372
373 course_create_sections_if_missing($course, $section);
374 $cw = get_fast_modinfo($course)->get_section_info($section);
375
376 if (!course_allowed_module($course, $module->name)) {
377 print_error('moduledisable');
378 }
379
380 return array($module, $context, $cw);
381}
382
383/**
384 * Check if user is allowed to update module info and returns related item/data to the module.
385 *
386 * @param object $cm course module
387 * @return array - list of course module, context, module, moduleinfo, and course section.
b4b75872 388 * @throws moodle_exception if user is not allowed to perform the action
80fe0c19
JM
389 */
390function can_update_moduleinfo($cm) {
391 global $DB;
392
393 // Check the $USER has the right capability.
394 $context = context_module::instance($cm->id);
395 require_capability('moodle/course:manageactivities', $context);
396
397 // Check module exists.
398 $module = $DB->get_record('modules', array('id'=>$cm->module), '*', MUST_EXIST);
399
400 // Check the moduleinfo exists.
401 $data = $DB->get_record($module->name, array('id'=>$cm->instance), '*', MUST_EXIST);
402
403 // Check the course section exists.
404 $cw = $DB->get_record('course_sections', array('id'=>$cm->section), '*', MUST_EXIST);
405
406 return array($cm, $context, $module, $data, $cw);
407}
408
409
410/**
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...).
414 *
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.
420 */
421function update_moduleinfo($cm, $moduleinfo, $course, $mform = null) {
422 global $DB, $CFG;
423
b4b75872
MG
424 // Attempt to include module library before we make any changes to DB.
425 include_modulelib($moduleinfo->modulename);
426
80fe0c19
JM
427 $moduleinfo->course = $course->id;
428 $moduleinfo = set_moduleinfo_defaults($moduleinfo);
429
430 if (!empty($course->groupmodeforce) or !isset($moduleinfo->groupmode)) {
431 $moduleinfo->groupmode = $cm->groupmode; // Keep original.
432 }
433
434 // Update course module first.
435 $cm->groupmode = $moduleinfo->groupmode;
436 if (isset($moduleinfo->groupingid)) {
437 $cm->groupingid = $moduleinfo->groupingid;
438 }
439 if (isset($moduleinfo->groupmembersonly)) {
440 $cm->groupmembersonly = $moduleinfo->groupmembersonly;
441 }
442
443 $completion = new completion_info($course);
a9f5fc15 444 if ($completion->is_enabled() && !empty($moduleinfo->completionunlocked)) {
80fe0c19
JM
445 // Update completion settings.
446 $cm->completion = $moduleinfo->completion;
447 $cm->completiongradeitemnumber = $moduleinfo->completiongradeitemnumber;
448 $cm->completionview = $moduleinfo->completionview;
449 $cm->completionexpected = $moduleinfo->completionexpected;
450 }
451 if (!empty($CFG->enableavailability)) {
452 $cm->availablefrom = $moduleinfo->availablefrom;
453 $cm->availableuntil = $moduleinfo->availableuntil;
454 $cm->showavailability = $moduleinfo->showavailability;
455 condition_info::update_cm_from_form($cm,$moduleinfo,true);
456 }
457 if (isset($moduleinfo->showdescription)) {
458 $cm->showdescription = $moduleinfo->showdescription;
459 } else {
460 $cm->showdescription = 0;
461 }
462
8f2913b9 463 $DB->update_record('course_modules', $cm);
80fe0c19 464
8f2913b9 465 $modcontext = context_module::instance($moduleinfo->coursemodule);
80fe0c19 466
8f2913b9
DW
467 // Update embedded links and save files.
468 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
469 $moduleinfo->intro = file_save_draft_area_files($moduleinfo->introeditor['itemid'], $modcontext->id,
470 'mod_'.$moduleinfo->modulename, 'intro', 0,
471 array('subdirs'=>true), $moduleinfo->introeditor['text']);
472 $moduleinfo->introformat = $moduleinfo->introeditor['format'];
473 unset($moduleinfo->introeditor);
474 }
475 $updateinstancefunction = $moduleinfo->modulename."_update_instance";
476 if (!$updateinstancefunction($moduleinfo, $mform)) {
477 print_error('cannotupdatemod', '', course_get_url($course, $cw->section), $moduleinfo->modulename);
478 }
80fe0c19 479
8f2913b9
DW
480 // Make sure visibility is set correctly (in particular in calendar).
481 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
482 set_coursemodule_visible($moduleinfo->coursemodule, $moduleinfo->visible);
483 }
80fe0c19 484
8f2913b9
DW
485 if (isset($moduleinfo->cmidnumber)) { // Label.
486 // Set cm idnumber - uniqueness is already verified by form validation.
487 set_coursemodule_idnumber($moduleinfo->coursemodule, $moduleinfo->cmidnumber);
488 }
80fe0c19 489
8f2913b9
DW
490 // Now that module is fully updated, also update completion data if required.
491 // (this will wipe all user completion data and recalculate it)
492 if ($completion->is_enabled() && !empty($moduleinfo->completionunlocked)) {
493 $completion->reset_all_state($cm);
494 }
80fe0c19 495
63deb5c3
AA
496 // Trigger event based on the action we did.
497 $event = \core\event\course_module_updated::create(array(
498 'courseid' => $course->id,
499 'context' => $modcontext,
500 'objectid' => $moduleinfo->coursemodule,
501 'other' => array(
502 'modulename' => $moduleinfo->modulename,
503 'name' => $moduleinfo->name,
504 'instanceid' => $moduleinfo->instance
505 )
506 ));
507 $event->trigger();
508
8f2913b9
DW
509 add_to_log($course->id, $moduleinfo->modulename, "update",
510 "view.php?id=$moduleinfo->coursemodule",
511 "$moduleinfo->instance", $moduleinfo->coursemodule);
80fe0c19 512
63deb5c3 513 $moduleinfo = edit_module_post_actions($moduleinfo, $course);
80fe0c19 514
8f2913b9 515 return array($cm, $moduleinfo);
80fe0c19
JM
516}
517
518/**
519 * Include once the module lib file.
520 *
521 * @param string $modulename module name of the lib to include
b4b75872 522 * @throws moodle_exception if lib.php file for the module does not exist
80fe0c19
JM
523 */
524function include_modulelib($modulename) {
525 global $CFG;
526 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
527 if (file_exists($modlib)) {
528 include_once($modlib);
529 } else {
530 throw new moodle_exception('modulemissingcode', '', '', $modlib);
531 }
532}
533