MDL-37079 switch the modedit.php functions into course/modedit.php
[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
47 $moduleinfo->course = $course->id;
48 $moduleinfo = set_moduleinfo_defaults($moduleinfo);
49
50 if (!empty($course->groupmodeforce) or !isset($moduleinfo->groupmode)) {
51 $moduleinfo->groupmode = 0; // Do not set groupmode.
52 }
53
54 if (!course_allowed_module($course, $moduleinfo->modulename)) {
55 print_error('moduledisable', '', '', $moduleinfo->modulename);
56 }
57
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->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
89 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
90 $introeditor = $moduleinfo->introeditor;
91 unset($moduleinfo->introeditor);
92 $moduleinfo->intro = $introeditor['text'];
93 $moduleinfo->introformat = $introeditor['format'];
94 }
95
96 $addinstancefunction = $moduleinfo->modulename."_add_instance";
97 $returnfromfunc = $addinstancefunction($moduleinfo, $mform);
98 if (!$returnfromfunc or !is_number($returnfromfunc)) {
99 // Undo everything we can.
100 $modcontext = context_module::instance($moduleinfo->coursemodule);
101 delete_context(CONTEXT_MODULE, $moduleinfo->coursemodule);
102 $DB->delete_records('course_modules', array('id'=>$moduleinfo->coursemodule));
103
104 if (!is_number($returnfromfunc)) {
105 print_error('invalidfunction', '', course_get_url($course, $cw->section));
106 } else {
107 print_error('cannotaddnewmodule', '', course_get_url($course, $cw->section), $moduleinfo->modulename);
108 }
109 }
110
111 $moduleinfo->instance = $returnfromfunc;
112
113 $DB->set_field('course_modules', 'instance', $returnfromfunc, array('id'=>$moduleinfo->coursemodule));
114
115 // Update embedded links and save files.
116 $modcontext = context_module::instance($moduleinfo->coursemodule);
117 if (!empty($introeditor)) {
118 $moduleinfo->intro = file_save_draft_area_files($introeditor['itemid'], $modcontext->id,
119 'mod_'.$moduleinfo->modulename, 'intro', 0,
120 array('subdirs'=>true), $introeditor['text']);
121 $DB->set_field($moduleinfo->modulename, 'intro', $moduleinfo->intro, array('id'=>$moduleinfo->instance));
122 }
123
124 // Course_modules and course_sections each contain a reference to each other.
125 // So we have to update one of them twice.
126 $sectionid = course_add_cm_to_section($course, $moduleinfo->coursemodule, $moduleinfo->section);
127
128 // Make sure visibility is set correctly (in particular in calendar).
129 // Note: allow them to set it even without moodle/course:activityvisibility.
130 set_coursemodule_visible($moduleinfo->coursemodule, $moduleinfo->visible);
131
132 if (isset($moduleinfo->cmidnumber)) { // Label.
133 // Set cm idnumber - uniqueness is already verified by form validation.
134 set_coursemodule_idnumber($moduleinfo->coursemodule, $moduleinfo->cmidnumber);
135 }
136
137 // Set up conditions.
138 if ($CFG->enableavailability) {
139 condition_info::update_cm_from_form((object)array('id'=>$moduleinfo->coursemodule), $moduleinfo, false);
140 }
141
142 $eventname = 'mod_created';
143
144 add_to_log($course->id, "course", "add mod",
145 "../mod/$moduleinfo->modulename/view.php?id=$moduleinfo->coursemodule",
146 "$moduleinfo->modulename $moduleinfo->instance");
147 add_to_log($course->id, $moduleinfo->modulename, "add",
148 "view.php?id=$moduleinfo->coursemodule",
149 "$moduleinfo->instance", $moduleinfo->coursemodule);
150
151 $moduleinfo = edit_module_post_actions($moduleinfo, $course, 'mod_created');
152
153 return $moduleinfo;
154}
155
156
157/**
158 * Common create/update module module actions that need to be processed as soon as a module is created/updaded.
159 * For example: trigger event, create grade parent category, add outcomes, rebuild caches, regrade, save plagiarism settings...
160 *
161 * @param object $moduleinfo the module info
162 * @param object $course the course of the module
163 * @param string $eventname the event name to trigger
164 *
165 * return object moduleinfo update with grading management info
166 */
167function edit_module_post_actions($moduleinfo, $course, $eventname) {
168 global $USER, $CFG;
169
170 $modcontext = context_module::instance($moduleinfo->coursemodule);
171
172 // Trigger mod_created/mod_updated event with information about this module.
173 $eventdata = new stdClass();
174 $eventdata->modulename = $moduleinfo->modulename;
175 $eventdata->name = $moduleinfo->name;
176 $eventdata->cmid = $moduleinfo->coursemodule;
177 $eventdata->courseid = $course->id;
178 $eventdata->userid = $USER->id;
179 events_trigger($eventname, $eventdata);
180
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) {
235 foreach($items as $item) {
236 if ($item->outcomeid == $outcome->id) {
237 // Outcome aready exists.
238 continue 2;
239 }
240 }
241 }
242
243 $max_itemnumber++;
244
245 $outcome_item = new grade_item();
246 $outcome_item->courseid = $course->id;
247 $outcome_item->itemtype = 'mod';
248 $outcome_item->itemmodule = $moduleinfo->modulename;
249 $outcome_item->iteminstance = $moduleinfo->instance;
250 $outcome_item->itemnumber = $max_itemnumber;
251 $outcome_item->itemname = $outcome->fullname;
252 $outcome_item->outcomeid = $outcome->id;
253 $outcome_item->gradetype = GRADE_TYPE_SCALE;
254 $outcome_item->scaleid = $outcome->scaleid;
255 $outcome_item->insert();
256
257 // Move the new outcome into correct category and fix sortorder if needed.
258 if ($grade_item) {
259 $outcome_item->set_parent($grade_item->categoryid);
260 $outcome_item->move_after_sortorder($grade_item->sortorder);
261
262 } else if (isset($moduleinfo->gradecat)) {
263 $outcome_item->set_parent($moduleinfo->gradecat);
264 }
265 }
266 }
267 }
268
269 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_ADVANCED_GRADING, false)
270 and has_capability('moodle/grade:managegradingforms', $modcontext)) {
271 require_once($CFG->dirroot.'/grade/grading/lib.php');
272 $gradingman = get_grading_manager($modcontext, 'mod_'.$moduleinfo->modulename);
273 $showgradingmanagement = false;
274 foreach ($gradingman->get_available_areas() as $areaname => $aretitle) {
275 $formfield = 'advancedgradingmethod_'.$areaname;
276 if (isset($moduleinfo->{$formfield})) {
277 $gradingman->set_area($areaname);
278 $methodchanged = $gradingman->set_active_method($moduleinfo->{$formfield});
279 if (empty($moduleinfo->{$formfield})) {
280 // Going back to the simple direct grading is not a reason to open the management screen.
281 $methodchanged = false;
282 }
283 $showgradingmanagement = $showgradingmanagement || $methodchanged;
284 }
285 }
286 // Update grading management information.
287 $moduleinfo->gradingman = $gradingman;
288 $moduleinfo->showgradingmanagement = $showgradingmanagement;
289 }
290
291 rebuild_course_cache($course->id);
292 grade_regrade_final_grades($course->id);
293 require_once($CFG->libdir.'/plagiarismlib.php');
294 plagiarism_save_form_elements($moduleinfo); //save plagiarism settings
295
296 return $moduleinfo;
297}
298
299
300/**
301 * Set module info default values for the unset module attributs.
302 *
303 * @param object $moduleinfo the current known data of the module
304 * @return object the completed module info
305 */
306function set_moduleinfo_defaults($moduleinfo) {
307 global $DB;
308
309 if (empty($moduleinfo->coursemodule)) {
310 // Add.
311 $cm = null;
312 $moduleinfo->instance = '';
313 $moduleinfo->coursemodule = '';
314 } else {
315 // Update.
316 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule, 0, false, MUST_EXIST);
317 $moduleinfo->instance = $cm->instance;
318 $moduleinfo->coursemodule = $cm->id;
319 }
320
321 $moduleinfo->modulename = clean_param($moduleinfo->modulename, PARAM_PLUGIN); // For safety
322
323 if (!isset($moduleinfo->groupingid)) {
324 $moduleinfo->groupingid = 0;
325 }
326
327 if (!isset($moduleinfo->groupmembersonly)) {
328 $moduleinfo->groupmembersonly = 0;
329 }
330
331 if (!isset($moduleinfo->name)) { // Label.
332 $moduleinfo->name = $moduleinfo->modulename;
333 }
334
335 if (!isset($moduleinfo->completion)) {
336 $moduleinfo->completion = COMPLETION_DISABLED;
337 }
338 if (!isset($moduleinfo->completionview)) {
339 $moduleinfo->completionview = COMPLETION_VIEW_NOT_REQUIRED;
340 }
341
342 // Convert the 'use grade' checkbox into a grade-item number: 0 if checked, null if not.
343 if (isset($moduleinfo->completionusegrade) && $moduleinfo->completionusegrade) {
344 $moduleinfo->completiongradeitemnumber = 0;
345 } else {
346 $moduleinfo->completiongradeitemnumber = null;
347 }
348
349 return $moduleinfo;
350}
351
352/**
353 * Check that the user can add a module. Also returns some information like the module, context and course section info.
354 * The fucntion create the course section if it doesn't exist.
355 *
356 * @param object $course the course of the module
357 * @param object $modulename the module name
358 * @param object $section the section of the module
359 * @return array list containing module, context, course section.
360 */
361function can_add_moduleinfo($course, $modulename, $section) {
362 global $DB;
363
364 $module = $DB->get_record('modules', array('name'=>$modulename), '*', MUST_EXIST);
365
366 $context = context_course::instance($course->id);
367 require_capability('moodle/course:manageactivities', $context);
368
369 course_create_sections_if_missing($course, $section);
370 $cw = get_fast_modinfo($course)->get_section_info($section);
371
372 if (!course_allowed_module($course, $module->name)) {
373 print_error('moduledisable');
374 }
375
376 return array($module, $context, $cw);
377}
378
379/**
380 * Check if user is allowed to update module info and returns related item/data to the module.
381 *
382 * @param object $cm course module
383 * @return array - list of course module, context, module, moduleinfo, and course section.
384 */
385function can_update_moduleinfo($cm) {
386 global $DB;
387
388 // Check the $USER has the right capability.
389 $context = context_module::instance($cm->id);
390 require_capability('moodle/course:manageactivities', $context);
391
392 // Check module exists.
393 $module = $DB->get_record('modules', array('id'=>$cm->module), '*', MUST_EXIST);
394
395 // Check the moduleinfo exists.
396 $data = $DB->get_record($module->name, array('id'=>$cm->instance), '*', MUST_EXIST);
397
398 // Check the course section exists.
399 $cw = $DB->get_record('course_sections', array('id'=>$cm->section), '*', MUST_EXIST);
400
401 return array($cm, $context, $module, $data, $cw);
402}
403
404
405/**
406 * Update the module info.
407 * This function doesn't check the user capabilities. It updates the course module and the module instance.
408 * Then execute common action to create/update module process (trigger event, rebuild cache, save plagiarism settings...).
409 *
410 * @param object $cm course module
411 * @param object $moduleinfo module info
412 * @param object $course course of the module
413 * @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.
414 * @return array list of course module and module info.
415 */
416function update_moduleinfo($cm, $moduleinfo, $course, $mform = null) {
417 global $DB, $CFG;
418
419 $moduleinfo->course = $course->id;
420 $moduleinfo = set_moduleinfo_defaults($moduleinfo);
421
422 if (!empty($course->groupmodeforce) or !isset($moduleinfo->groupmode)) {
423 $moduleinfo->groupmode = $cm->groupmode; // Keep original.
424 }
425
426 // Update course module first.
427 $cm->groupmode = $moduleinfo->groupmode;
428 if (isset($moduleinfo->groupingid)) {
429 $cm->groupingid = $moduleinfo->groupingid;
430 }
431 if (isset($moduleinfo->groupmembersonly)) {
432 $cm->groupmembersonly = $moduleinfo->groupmembersonly;
433 }
434
435 $completion = new completion_info($course);
436 if ($completion->is_enabled()) {
437 // Update completion settings.
438 $cm->completion = $moduleinfo->completion;
439 $cm->completiongradeitemnumber = $moduleinfo->completiongradeitemnumber;
440 $cm->completionview = $moduleinfo->completionview;
441 $cm->completionexpected = $moduleinfo->completionexpected;
442 }
443 if (!empty($CFG->enableavailability)) {
444 $cm->availablefrom = $moduleinfo->availablefrom;
445 $cm->availableuntil = $moduleinfo->availableuntil;
446 $cm->showavailability = $moduleinfo->showavailability;
447 condition_info::update_cm_from_form($cm,$moduleinfo,true);
448 }
449 if (isset($moduleinfo->showdescription)) {
450 $cm->showdescription = $moduleinfo->showdescription;
451 } else {
452 $cm->showdescription = 0;
453 }
454
455 $DB->update_record('course_modules', $cm);
456
457 $modcontext = context_module::instance($moduleinfo->coursemodule);
458
459 // update embedded links and save files.
460 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
461 $moduleinfo->intro = file_save_draft_area_files($moduleinfo->introeditor['itemid'], $modcontext->id,
462 'mod_'.$moduleinfo->modulename, 'intro', 0,
463 array('subdirs'=>true), $moduleinfo->introeditor['text']);
464 $moduleinfo->introformat = $moduleinfo->introeditor['format'];
465 unset($moduleinfo->introeditor);
466 }
467 $updateinstancefunction = $moduleinfo->modulename."_update_instance";
468 if (!$updateinstancefunction($moduleinfo, $mform)) {
469 print_error('cannotupdatemod', '', course_get_url($course, $cw->section), $moduleinfo->modulename);
470 }
471
472 // Make sure visibility is set correctly (in particular in calendar).
473 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
474 set_coursemodule_visible($moduleinfo->coursemodule, $moduleinfo->visible);
475 }
476
477 if (isset($moduleinfo->cmidnumber)) { // Label.
478 // Set cm idnumber - uniqueness is already verified by form validation.
479 set_coursemodule_idnumber($moduleinfo->coursemodule, $moduleinfo->cmidnumber);
480 }
481
482 // Now that module is fully updated, also update completion data if required.
483 // (this will wipe all user completion data and recalculate it)
484 if ($completion->is_enabled() && !empty($moduleinfo->completionunlocked)) {
485 $completion->reset_all_state($cm);
486 }
487
488 add_to_log($course->id, "course", "update mod",
489 "../mod/$moduleinfo->modulename/view.php?id=$moduleinfo->coursemodule",
490 "$moduleinfo->modulename $moduleinfo->instance");
491 add_to_log($course->id, $moduleinfo->modulename, "update",
492 "view.php?id=$moduleinfo->coursemodule",
493 "$moduleinfo->instance", $moduleinfo->coursemodule);
494
495 $moduleinfo = edit_module_post_actions($moduleinfo, $course, 'mod_updated');
496
497 return array($cm, $moduleinfo);
498}
499
500/**
501 * Include once the module lib file.
502 *
503 * @param string $modulename module name of the lib to include
504 */
505function include_modulelib($modulename) {
506 global $CFG;
507 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
508 if (file_exists($modlib)) {
509 include_once($modlib);
510 } else {
511 throw new moodle_exception('modulemissingcode', '', '', $modlib);
512 }
513}
514