Merge branch 'MDL-37079-master2' of git://github.com/mouneyrac/moodle
[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);
37550a52 131 $DB->set_field('course_modules', 'visibleold', 1, array('id' => $moduleinfo->coursemodule));
80fe0c19
JM
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
143 $eventname = 'mod_created';
144
145 add_to_log($course->id, "course", "add mod",
146 "../mod/$moduleinfo->modulename/view.php?id=$moduleinfo->coursemodule",
147 "$moduleinfo->modulename $moduleinfo->instance");
148 add_to_log($course->id, $moduleinfo->modulename, "add",
149 "view.php?id=$moduleinfo->coursemodule",
150 "$moduleinfo->instance", $moduleinfo->coursemodule);
151
152 $moduleinfo = edit_module_post_actions($moduleinfo, $course, 'mod_created');
153
154 return $moduleinfo;
155}
156
157
158/**
159 * Common create/update module module actions that need to be processed as soon as a module is created/updaded.
160 * For example: trigger event, create grade parent category, add outcomes, rebuild caches, regrade, save plagiarism settings...
161 *
162 * @param object $moduleinfo the module info
163 * @param object $course the course of the module
164 * @param string $eventname the event name to trigger
165 *
166 * return object moduleinfo update with grading management info
167 */
168function edit_module_post_actions($moduleinfo, $course, $eventname) {
169 global $USER, $CFG;
170
171 $modcontext = context_module::instance($moduleinfo->coursemodule);
172
173 // Trigger mod_created/mod_updated event with information about this module.
174 $eventdata = new stdClass();
175 $eventdata->modulename = $moduleinfo->modulename;
176 $eventdata->name = $moduleinfo->name;
177 $eventdata->cmid = $moduleinfo->coursemodule;
178 $eventdata->courseid = $course->id;
179 $eventdata->userid = $USER->id;
180 events_trigger($eventname, $eventdata);
181
182 // Sync idnumber with grade_item.
183 if ($grade_item = grade_item::fetch(array('itemtype'=>'mod', 'itemmodule'=>$moduleinfo->modulename,
184 'iteminstance'=>$moduleinfo->instance, 'itemnumber'=>0, 'courseid'=>$course->id))) {
185 if ($grade_item->idnumber != $moduleinfo->cmidnumber) {
186 $grade_item->idnumber = $moduleinfo->cmidnumber;
187 $grade_item->update();
188 }
189 }
190
191 $items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$moduleinfo->modulename,
192 'iteminstance'=>$moduleinfo->instance, 'courseid'=>$course->id));
193
194 // Create parent category if requested and move to correct parent category.
195 if ($items and isset($moduleinfo->gradecat)) {
196 if ($moduleinfo->gradecat == -1) {
197 $grade_category = new grade_category();
198 $grade_category->courseid = $course->id;
199 $grade_category->fullname = $moduleinfo->name;
200 $grade_category->insert();
201 if ($grade_item) {
202 $parent = $grade_item->get_parent_category();
203 $grade_category->set_parent($parent->id);
204 }
205 $moduleinfo->gradecat = $grade_category->id;
206 }
207 foreach ($items as $itemid=>$unused) {
208 $items[$itemid]->set_parent($moduleinfo->gradecat);
209 if ($itemid == $grade_item->id) {
210 // Use updated grade_item.
211 $grade_item = $items[$itemid];
212 }
213 }
214 }
215
216 // Add outcomes if requested.
217 if ($outcomes = grade_outcome::fetch_all_available($course->id)) {
218 $grade_items = array();
219
220 // Outcome grade_item.itemnumber start at 1000, there is nothing above outcomes.
221 $max_itemnumber = 999;
222 if ($items) {
223 foreach($items as $item) {
224 if ($item->itemnumber > $max_itemnumber) {
225 $max_itemnumber = $item->itemnumber;
226 }
227 }
228 }
229
230 foreach($outcomes as $outcome) {
231 $elname = 'outcome_'.$outcome->id;
232
233 if (property_exists($moduleinfo, $elname) and $moduleinfo->$elname) {
234 // So we have a request for new outcome grade item?
235 if ($items) {
236 foreach($items as $item) {
237 if ($item->outcomeid == $outcome->id) {
238 // Outcome aready exists.
239 continue 2;
240 }
241 }
242 }
243
244 $max_itemnumber++;
245
246 $outcome_item = new grade_item();
247 $outcome_item->courseid = $course->id;
248 $outcome_item->itemtype = 'mod';
249 $outcome_item->itemmodule = $moduleinfo->modulename;
250 $outcome_item->iteminstance = $moduleinfo->instance;
251 $outcome_item->itemnumber = $max_itemnumber;
252 $outcome_item->itemname = $outcome->fullname;
253 $outcome_item->outcomeid = $outcome->id;
254 $outcome_item->gradetype = GRADE_TYPE_SCALE;
255 $outcome_item->scaleid = $outcome->scaleid;
256 $outcome_item->insert();
257
258 // Move the new outcome into correct category and fix sortorder if needed.
259 if ($grade_item) {
260 $outcome_item->set_parent($grade_item->categoryid);
261 $outcome_item->move_after_sortorder($grade_item->sortorder);
262
263 } else if (isset($moduleinfo->gradecat)) {
264 $outcome_item->set_parent($moduleinfo->gradecat);
265 }
266 }
267 }
268 }
269
270 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_ADVANCED_GRADING, false)
271 and has_capability('moodle/grade:managegradingforms', $modcontext)) {
272 require_once($CFG->dirroot.'/grade/grading/lib.php');
273 $gradingman = get_grading_manager($modcontext, 'mod_'.$moduleinfo->modulename);
274 $showgradingmanagement = false;
275 foreach ($gradingman->get_available_areas() as $areaname => $aretitle) {
276 $formfield = 'advancedgradingmethod_'.$areaname;
277 if (isset($moduleinfo->{$formfield})) {
278 $gradingman->set_area($areaname);
279 $methodchanged = $gradingman->set_active_method($moduleinfo->{$formfield});
280 if (empty($moduleinfo->{$formfield})) {
281 // Going back to the simple direct grading is not a reason to open the management screen.
282 $methodchanged = false;
283 }
284 $showgradingmanagement = $showgradingmanagement || $methodchanged;
285 }
286 }
287 // Update grading management information.
288 $moduleinfo->gradingman = $gradingman;
289 $moduleinfo->showgradingmanagement = $showgradingmanagement;
290 }
291
292 rebuild_course_cache($course->id);
293 grade_regrade_final_grades($course->id);
294 require_once($CFG->libdir.'/plagiarismlib.php');
295 plagiarism_save_form_elements($moduleinfo); //save plagiarism settings
296
297 return $moduleinfo;
298}
299
300
301/**
302 * Set module info default values for the unset module attributs.
303 *
304 * @param object $moduleinfo the current known data of the module
305 * @return object the completed module info
306 */
307function set_moduleinfo_defaults($moduleinfo) {
308 global $DB;
309
310 if (empty($moduleinfo->coursemodule)) {
311 // Add.
312 $cm = null;
313 $moduleinfo->instance = '';
314 $moduleinfo->coursemodule = '';
315 } else {
316 // Update.
317 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule, 0, false, MUST_EXIST);
318 $moduleinfo->instance = $cm->instance;
319 $moduleinfo->coursemodule = $cm->id;
320 }
321
322 $moduleinfo->modulename = clean_param($moduleinfo->modulename, PARAM_PLUGIN); // For safety
323
324 if (!isset($moduleinfo->groupingid)) {
325 $moduleinfo->groupingid = 0;
326 }
327
328 if (!isset($moduleinfo->groupmembersonly)) {
329 $moduleinfo->groupmembersonly = 0;
330 }
331
332 if (!isset($moduleinfo->name)) { // Label.
333 $moduleinfo->name = $moduleinfo->modulename;
334 }
335
336 if (!isset($moduleinfo->completion)) {
337 $moduleinfo->completion = COMPLETION_DISABLED;
338 }
339 if (!isset($moduleinfo->completionview)) {
340 $moduleinfo->completionview = COMPLETION_VIEW_NOT_REQUIRED;
341 }
342
343 // Convert the 'use grade' checkbox into a grade-item number: 0 if checked, null if not.
344 if (isset($moduleinfo->completionusegrade) && $moduleinfo->completionusegrade) {
345 $moduleinfo->completiongradeitemnumber = 0;
346 } else {
347 $moduleinfo->completiongradeitemnumber = null;
348 }
349
350 return $moduleinfo;
351}
352
353/**
354 * Check that the user can add a module. Also returns some information like the module, context and course section info.
355 * The fucntion create the course section if it doesn't exist.
356 *
357 * @param object $course the course of the module
358 * @param object $modulename the module name
359 * @param object $section the section of the module
360 * @return array list containing module, context, course section.
361 */
362function can_add_moduleinfo($course, $modulename, $section) {
363 global $DB;
364
365 $module = $DB->get_record('modules', array('name'=>$modulename), '*', MUST_EXIST);
366
367 $context = context_course::instance($course->id);
368 require_capability('moodle/course:manageactivities', $context);
369
370 course_create_sections_if_missing($course, $section);
371 $cw = get_fast_modinfo($course)->get_section_info($section);
372
373 if (!course_allowed_module($course, $module->name)) {
374 print_error('moduledisable');
375 }
376
377 return array($module, $context, $cw);
378}
379
380/**
381 * Check if user is allowed to update module info and returns related item/data to the module.
382 *
383 * @param object $cm course module
384 * @return array - list of course module, context, module, moduleinfo, and course section.
385 */
386function can_update_moduleinfo($cm) {
387 global $DB;
388
389 // Check the $USER has the right capability.
390 $context = context_module::instance($cm->id);
391 require_capability('moodle/course:manageactivities', $context);
392
393 // Check module exists.
394 $module = $DB->get_record('modules', array('id'=>$cm->module), '*', MUST_EXIST);
395
396 // Check the moduleinfo exists.
397 $data = $DB->get_record($module->name, array('id'=>$cm->instance), '*', MUST_EXIST);
398
399 // Check the course section exists.
400 $cw = $DB->get_record('course_sections', array('id'=>$cm->section), '*', MUST_EXIST);
401
402 return array($cm, $context, $module, $data, $cw);
403}
404
405
406/**
407 * Update the module info.
408 * This function doesn't check the user capabilities. It updates the course module and the module instance.
409 * Then execute common action to create/update module process (trigger event, rebuild cache, save plagiarism settings...).
410 *
411 * @param object $cm course module
412 * @param object $moduleinfo module info
413 * @param object $course course of the module
414 * @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.
415 * @return array list of course module and module info.
416 */
417function update_moduleinfo($cm, $moduleinfo, $course, $mform = null) {
418 global $DB, $CFG;
419
420 $moduleinfo->course = $course->id;
421 $moduleinfo = set_moduleinfo_defaults($moduleinfo);
422
423 if (!empty($course->groupmodeforce) or !isset($moduleinfo->groupmode)) {
424 $moduleinfo->groupmode = $cm->groupmode; // Keep original.
425 }
426
427 // Update course module first.
428 $cm->groupmode = $moduleinfo->groupmode;
429 if (isset($moduleinfo->groupingid)) {
430 $cm->groupingid = $moduleinfo->groupingid;
431 }
432 if (isset($moduleinfo->groupmembersonly)) {
433 $cm->groupmembersonly = $moduleinfo->groupmembersonly;
434 }
435
436 $completion = new completion_info($course);
437 if ($completion->is_enabled()) {
438 // Update completion settings.
439 $cm->completion = $moduleinfo->completion;
440 $cm->completiongradeitemnumber = $moduleinfo->completiongradeitemnumber;
441 $cm->completionview = $moduleinfo->completionview;
442 $cm->completionexpected = $moduleinfo->completionexpected;
443 }
444 if (!empty($CFG->enableavailability)) {
445 $cm->availablefrom = $moduleinfo->availablefrom;
446 $cm->availableuntil = $moduleinfo->availableuntil;
447 $cm->showavailability = $moduleinfo->showavailability;
448 condition_info::update_cm_from_form($cm,$moduleinfo,true);
449 }
450 if (isset($moduleinfo->showdescription)) {
451 $cm->showdescription = $moduleinfo->showdescription;
452 } else {
453 $cm->showdescription = 0;
454 }
455
456 $DB->update_record('course_modules', $cm);
457
458 $modcontext = context_module::instance($moduleinfo->coursemodule);
459
460 // update embedded links and save files.
461 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
462 $moduleinfo->intro = file_save_draft_area_files($moduleinfo->introeditor['itemid'], $modcontext->id,
463 'mod_'.$moduleinfo->modulename, 'intro', 0,
464 array('subdirs'=>true), $moduleinfo->introeditor['text']);
465 $moduleinfo->introformat = $moduleinfo->introeditor['format'];
466 unset($moduleinfo->introeditor);
467 }
468 $updateinstancefunction = $moduleinfo->modulename."_update_instance";
469 if (!$updateinstancefunction($moduleinfo, $mform)) {
470 print_error('cannotupdatemod', '', course_get_url($course, $cw->section), $moduleinfo->modulename);
471 }
472
473 // Make sure visibility is set correctly (in particular in calendar).
474 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
475 set_coursemodule_visible($moduleinfo->coursemodule, $moduleinfo->visible);
476 }
477
478 if (isset($moduleinfo->cmidnumber)) { // Label.
479 // Set cm idnumber - uniqueness is already verified by form validation.
480 set_coursemodule_idnumber($moduleinfo->coursemodule, $moduleinfo->cmidnumber);
481 }
482
483 // Now that module is fully updated, also update completion data if required.
484 // (this will wipe all user completion data and recalculate it)
485 if ($completion->is_enabled() && !empty($moduleinfo->completionunlocked)) {
486 $completion->reset_all_state($cm);
487 }
488
489 add_to_log($course->id, "course", "update mod",
490 "../mod/$moduleinfo->modulename/view.php?id=$moduleinfo->coursemodule",
491 "$moduleinfo->modulename $moduleinfo->instance");
492 add_to_log($course->id, $moduleinfo->modulename, "update",
493 "view.php?id=$moduleinfo->coursemodule",
494 "$moduleinfo->instance", $moduleinfo->coursemodule);
495
496 $moduleinfo = edit_module_post_actions($moduleinfo, $course, 'mod_updated');
497
498 return array($cm, $moduleinfo);
499}
500
501/**
502 * Include once the module lib file.
503 *
504 * @param string $modulename module name of the lib to include
505 */
506function include_modulelib($modulename) {
507 global $CFG;
508 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
509 if (file_exists($modlib)) {
510 include_once($modlib);
511 } else {
512 throw new moodle_exception('modulemissingcode', '', '', $modlib);
513 }
514}
515