Merge branch 'MDL-44065-master' of https://github.com/sammarshallou/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
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;
449d1fa3
MG
64 if (isset($moduleinfo->cmidnumber)) {
65 $newcm->idnumber = $moduleinfo->cmidnumber;
66 }
80fe0c19
JM
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;
76 }
77 if(!empty($CFG->enableavailability)) {
78 $newcm->availablefrom = $moduleinfo->availablefrom;
79 $newcm->availableuntil = $moduleinfo->availableuntil;
80 $newcm->showavailability = $moduleinfo->showavailability;
81 }
82 if (isset($moduleinfo->showdescription)) {
83 $newcm->showdescription = $moduleinfo->showdescription;
84 } else {
85 $newcm->showdescription = 0;
86 }
87
5c3a54c4 88 // From this point we make database changes, so start transaction.
89 $transaction = $DB->start_delegated_transaction();
90
80fe0c19
JM
91 if (!$moduleinfo->coursemodule = add_course_module($newcm)) {
92 print_error('cannotaddcoursemodule');
93 }
94
7fbe33fc
MG
95 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true) &&
96 isset($moduleinfo->introeditor)) {
80fe0c19
JM
97 $introeditor = $moduleinfo->introeditor;
98 unset($moduleinfo->introeditor);
99 $moduleinfo->intro = $introeditor['text'];
100 $moduleinfo->introformat = $introeditor['format'];
101 }
102
103 $addinstancefunction = $moduleinfo->modulename."_add_instance";
5c3a54c4 104 try {
105 $returnfromfunc = $addinstancefunction($moduleinfo, $mform);
106 } catch (moodle_exception $e) {
107 $returnfromfunc = $e;
108 }
80fe0c19 109 if (!$returnfromfunc or !is_number($returnfromfunc)) {
5c3a54c4 110 // Undo everything we can. This is not necessary for databases which
111 // support transactions, but improves consistency for other databases.
80fe0c19 112 $modcontext = context_module::instance($moduleinfo->coursemodule);
c592eea2 113 context_helper::delete_instance(CONTEXT_MODULE, $moduleinfo->coursemodule);
80fe0c19
JM
114 $DB->delete_records('course_modules', array('id'=>$moduleinfo->coursemodule));
115
5c3a54c4 116 if ($e instanceof moodle_exception) {
117 throw $e;
118 } else if (!is_number($returnfromfunc)) {
b4b75872 119 print_error('invalidfunction', '', course_get_url($course, $moduleinfo->section));
80fe0c19 120 } else {
b4b75872 121 print_error('cannotaddnewmodule', '', course_get_url($course, $moduleinfo->section), $moduleinfo->modulename);
80fe0c19
JM
122 }
123 }
124
125 $moduleinfo->instance = $returnfromfunc;
126
127 $DB->set_field('course_modules', 'instance', $returnfromfunc, array('id'=>$moduleinfo->coursemodule));
128
129 // Update embedded links and save files.
130 $modcontext = context_module::instance($moduleinfo->coursemodule);
131 if (!empty($introeditor)) {
132 $moduleinfo->intro = file_save_draft_area_files($introeditor['itemid'], $modcontext->id,
133 'mod_'.$moduleinfo->modulename, 'intro', 0,
134 array('subdirs'=>true), $introeditor['text']);
135 $DB->set_field($moduleinfo->modulename, 'intro', $moduleinfo->intro, array('id'=>$moduleinfo->instance));
136 }
137
138 // Course_modules and course_sections each contain a reference to each other.
139 // So we have to update one of them twice.
140 $sectionid = course_add_cm_to_section($course, $moduleinfo->coursemodule, $moduleinfo->section);
141
80fe0c19
JM
142 // Set up conditions.
143 if ($CFG->enableavailability) {
144 condition_info::update_cm_from_form((object)array('id'=>$moduleinfo->coursemodule), $moduleinfo, false);
145 }
146
63deb5c3
AA
147 // Trigger event based on the action we did.
148 $event = \core\event\course_module_created::create(array(
149 'courseid' => $course->id,
150 'context' => $modcontext,
151 'objectid' => $moduleinfo->coursemodule,
152 'other' => array(
153 'modulename' => $moduleinfo->modulename,
154 'name' => $moduleinfo->name,
155 'instanceid' => $moduleinfo->instance
156 )
157 ));
158 $event->trigger();
80fe0c19 159
80fe0c19
JM
160 add_to_log($course->id, $moduleinfo->modulename, "add",
161 "view.php?id=$moduleinfo->coursemodule",
162 "$moduleinfo->instance", $moduleinfo->coursemodule);
163
63deb5c3 164 $moduleinfo = edit_module_post_actions($moduleinfo, $course);
5c3a54c4 165 $transaction->allow_commit();
80fe0c19
JM
166
167 return $moduleinfo;
168}
169
170
171/**
172 * Common create/update module module actions that need to be processed as soon as a module is created/updaded.
63deb5c3
AA
173 * For example:create grade parent category, add outcomes, rebuild caches, regrade, save plagiarism settings...
174 * Please note this api does not trigger events as of MOODLE 2.6. Please trigger events before calling this api.
80fe0c19
JM
175 *
176 * @param object $moduleinfo the module info
177 * @param object $course the course of the module
80fe0c19 178 *
63deb5c3 179 * @return object moduleinfo update with grading management info
80fe0c19 180 */
63deb5c3
AA
181function edit_module_post_actions($moduleinfo, $course) {
182 global $CFG;
80fe0c19
JM
183
184 $modcontext = context_module::instance($moduleinfo->coursemodule);
449d1fa3
MG
185 $hasgrades = plugin_supports('mod', $moduleinfo->modulename, FEATURE_GRADE_HAS_GRADE, false);
186 $hasoutcomes = plugin_supports('mod', $moduleinfo->modulename, FEATURE_GRADE_OUTCOMES, true);
80fe0c19 187
80fe0c19 188 // Sync idnumber with grade_item.
449d1fa3 189 if ($hasgrades && $grade_item = grade_item::fetch(array('itemtype'=>'mod', 'itemmodule'=>$moduleinfo->modulename,
80fe0c19
JM
190 'iteminstance'=>$moduleinfo->instance, 'itemnumber'=>0, 'courseid'=>$course->id))) {
191 if ($grade_item->idnumber != $moduleinfo->cmidnumber) {
192 $grade_item->idnumber = $moduleinfo->cmidnumber;
193 $grade_item->update();
194 }
195 }
196
449d1fa3
MG
197 if ($hasgrades) {
198 $items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$moduleinfo->modulename,
80fe0c19 199 'iteminstance'=>$moduleinfo->instance, 'courseid'=>$course->id));
449d1fa3
MG
200 } else {
201 $items = array();
202 }
80fe0c19
JM
203
204 // Create parent category if requested and move to correct parent category.
205 if ($items and isset($moduleinfo->gradecat)) {
206 if ($moduleinfo->gradecat == -1) {
207 $grade_category = new grade_category();
208 $grade_category->courseid = $course->id;
209 $grade_category->fullname = $moduleinfo->name;
210 $grade_category->insert();
211 if ($grade_item) {
212 $parent = $grade_item->get_parent_category();
213 $grade_category->set_parent($parent->id);
214 }
215 $moduleinfo->gradecat = $grade_category->id;
216 }
217 foreach ($items as $itemid=>$unused) {
218 $items[$itemid]->set_parent($moduleinfo->gradecat);
219 if ($itemid == $grade_item->id) {
220 // Use updated grade_item.
221 $grade_item = $items[$itemid];
222 }
223 }
224 }
225
226 // Add outcomes if requested.
449d1fa3 227 if ($hasoutcomes && $outcomes = grade_outcome::fetch_all_available($course->id)) {
80fe0c19
JM
228 $grade_items = array();
229
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;
236 }
237 }
238 }
239
240 foreach($outcomes as $outcome) {
241 $elname = 'outcome_'.$outcome->id;
242
243 if (property_exists($moduleinfo, $elname) and $moduleinfo->$elname) {
244 // So we have a request for new outcome grade item?
245 if ($items) {
3b2a6bf5 246 $outcomeexists = false;
80fe0c19
JM
247 foreach($items as $item) {
248 if ($item->outcomeid == $outcome->id) {
3b2a6bf5
DW
249 $outcomeexists = true;
250 break;
80fe0c19
JM
251 }
252 }
3b2a6bf5
DW
253 if ($outcomeexists) {
254 continue;
255 }
80fe0c19
JM
256 }
257
258 $max_itemnumber++;
259
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();
271
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);
276
277 } else if (isset($moduleinfo->gradecat)) {
278 $outcome_item->set_parent($moduleinfo->gradecat);
279 }
280 }
281 }
282 }
283
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;
297 }
298 $showgradingmanagement = $showgradingmanagement || $methodchanged;
299 }
300 }
301 // Update grading management information.
302 $moduleinfo->gradingman = $gradingman;
303 $moduleinfo->showgradingmanagement = $showgradingmanagement;
304 }
305
449d1fa3
MG
306 rebuild_course_cache($course->id, true);
307 if ($hasgrades) {
308 grade_regrade_final_grades($course->id);
309 }
80fe0c19 310 require_once($CFG->libdir.'/plagiarismlib.php');
8f2913b9 311 plagiarism_save_form_elements($moduleinfo);
80fe0c19
JM
312
313 return $moduleinfo;
314}
315
316
317/**
318 * Set module info default values for the unset module attributs.
319 *
320 * @param object $moduleinfo the current known data of the module
321 * @return object the completed module info
322 */
323function set_moduleinfo_defaults($moduleinfo) {
80fe0c19
JM
324
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;
335 }
8f2913b9
DW
336 // For safety.
337 $moduleinfo->modulename = clean_param($moduleinfo->modulename, PARAM_PLUGIN);
80fe0c19
JM
338
339 if (!isset($moduleinfo->groupingid)) {
340 $moduleinfo->groupingid = 0;
341 }
342
343 if (!isset($moduleinfo->groupmembersonly)) {
344 $moduleinfo->groupmembersonly = 0;
345 }
346
347 if (!isset($moduleinfo->name)) { // Label.
348 $moduleinfo->name = $moduleinfo->modulename;
349 }
350
351 if (!isset($moduleinfo->completion)) {
352 $moduleinfo->completion = COMPLETION_DISABLED;
353 }
354 if (!isset($moduleinfo->completionview)) {
355 $moduleinfo->completionview = COMPLETION_VIEW_NOT_REQUIRED;
356 }
357
358 // Convert the 'use grade' checkbox into a grade-item number: 0 if checked, null if not.
359 if (isset($moduleinfo->completionusegrade) && $moduleinfo->completionusegrade) {
360 $moduleinfo->completiongradeitemnumber = 0;
361 } else {
362 $moduleinfo->completiongradeitemnumber = null;
363 }
364
365 return $moduleinfo;
366}
367
368/**
369 * Check that the user can add a module. Also returns some information like the module, context and course section info.
370 * The fucntion create the course section if it doesn't exist.
371 *
372 * @param object $course the course of the module
373 * @param object $modulename the module name
374 * @param object $section the section of the module
375 * @return array list containing module, context, course section.
b4b75872 376 * @throws moodle_exception if user is not allowed to perform the action or module is not allowed in this course
80fe0c19
JM
377 */
378function can_add_moduleinfo($course, $modulename, $section) {
379 global $DB;
380
381 $module = $DB->get_record('modules', array('name'=>$modulename), '*', MUST_EXIST);
382
383 $context = context_course::instance($course->id);
384 require_capability('moodle/course:manageactivities', $context);
385
386 course_create_sections_if_missing($course, $section);
387 $cw = get_fast_modinfo($course)->get_section_info($section);
388
389 if (!course_allowed_module($course, $module->name)) {
390 print_error('moduledisable');
391 }
392
393 return array($module, $context, $cw);
394}
395
396/**
397 * Check if user is allowed to update module info and returns related item/data to the module.
398 *
399 * @param object $cm course module
400 * @return array - list of course module, context, module, moduleinfo, and course section.
b4b75872 401 * @throws moodle_exception if user is not allowed to perform the action
80fe0c19
JM
402 */
403function can_update_moduleinfo($cm) {
404 global $DB;
405
406 // Check the $USER has the right capability.
407 $context = context_module::instance($cm->id);
408 require_capability('moodle/course:manageactivities', $context);
409
410 // Check module exists.
411 $module = $DB->get_record('modules', array('id'=>$cm->module), '*', MUST_EXIST);
412
413 // Check the moduleinfo exists.
414 $data = $DB->get_record($module->name, array('id'=>$cm->instance), '*', MUST_EXIST);
415
416 // Check the course section exists.
417 $cw = $DB->get_record('course_sections', array('id'=>$cm->section), '*', MUST_EXIST);
418
419 return array($cm, $context, $module, $data, $cw);
420}
421
422
423/**
424 * Update the module info.
425 * This function doesn't check the user capabilities. It updates the course module and the module instance.
426 * Then execute common action to create/update module process (trigger event, rebuild cache, save plagiarism settings...).
427 *
428 * @param object $cm course module
429 * @param object $moduleinfo module info
430 * @param object $course course of the module
431 * @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.
432 * @return array list of course module and module info.
433 */
434function update_moduleinfo($cm, $moduleinfo, $course, $mform = null) {
435 global $DB, $CFG;
436
b4b75872
MG
437 // Attempt to include module library before we make any changes to DB.
438 include_modulelib($moduleinfo->modulename);
439
80fe0c19
JM
440 $moduleinfo->course = $course->id;
441 $moduleinfo = set_moduleinfo_defaults($moduleinfo);
442
443 if (!empty($course->groupmodeforce) or !isset($moduleinfo->groupmode)) {
444 $moduleinfo->groupmode = $cm->groupmode; // Keep original.
445 }
446
447 // Update course module first.
448 $cm->groupmode = $moduleinfo->groupmode;
449 if (isset($moduleinfo->groupingid)) {
450 $cm->groupingid = $moduleinfo->groupingid;
451 }
452 if (isset($moduleinfo->groupmembersonly)) {
453 $cm->groupmembersonly = $moduleinfo->groupmembersonly;
454 }
455
456 $completion = new completion_info($course);
a9f5fc15 457 if ($completion->is_enabled() && !empty($moduleinfo->completionunlocked)) {
80fe0c19
JM
458 // Update completion settings.
459 $cm->completion = $moduleinfo->completion;
460 $cm->completiongradeitemnumber = $moduleinfo->completiongradeitemnumber;
461 $cm->completionview = $moduleinfo->completionview;
462 $cm->completionexpected = $moduleinfo->completionexpected;
463 }
464 if (!empty($CFG->enableavailability)) {
465 $cm->availablefrom = $moduleinfo->availablefrom;
466 $cm->availableuntil = $moduleinfo->availableuntil;
467 $cm->showavailability = $moduleinfo->showavailability;
468 condition_info::update_cm_from_form($cm,$moduleinfo,true);
469 }
470 if (isset($moduleinfo->showdescription)) {
471 $cm->showdescription = $moduleinfo->showdescription;
472 } else {
473 $cm->showdescription = 0;
474 }
475
8f2913b9 476 $DB->update_record('course_modules', $cm);
80fe0c19 477
8f2913b9 478 $modcontext = context_module::instance($moduleinfo->coursemodule);
80fe0c19 479
8f2913b9
DW
480 // Update embedded links and save files.
481 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
482 $moduleinfo->intro = file_save_draft_area_files($moduleinfo->introeditor['itemid'], $modcontext->id,
483 'mod_'.$moduleinfo->modulename, 'intro', 0,
484 array('subdirs'=>true), $moduleinfo->introeditor['text']);
485 $moduleinfo->introformat = $moduleinfo->introeditor['format'];
486 unset($moduleinfo->introeditor);
487 }
488 $updateinstancefunction = $moduleinfo->modulename."_update_instance";
489 if (!$updateinstancefunction($moduleinfo, $mform)) {
490 print_error('cannotupdatemod', '', course_get_url($course, $cw->section), $moduleinfo->modulename);
491 }
80fe0c19 492
8f2913b9
DW
493 // Make sure visibility is set correctly (in particular in calendar).
494 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
495 set_coursemodule_visible($moduleinfo->coursemodule, $moduleinfo->visible);
496 }
80fe0c19 497
8f2913b9
DW
498 if (isset($moduleinfo->cmidnumber)) { // Label.
499 // Set cm idnumber - uniqueness is already verified by form validation.
500 set_coursemodule_idnumber($moduleinfo->coursemodule, $moduleinfo->cmidnumber);
501 }
80fe0c19 502
8f2913b9
DW
503 // Now that module is fully updated, also update completion data if required.
504 // (this will wipe all user completion data and recalculate it)
505 if ($completion->is_enabled() && !empty($moduleinfo->completionunlocked)) {
506 $completion->reset_all_state($cm);
507 }
80fe0c19 508
63deb5c3
AA
509 // Trigger event based on the action we did.
510 $event = \core\event\course_module_updated::create(array(
511 'courseid' => $course->id,
512 'context' => $modcontext,
513 'objectid' => $moduleinfo->coursemodule,
514 'other' => array(
515 'modulename' => $moduleinfo->modulename,
516 'name' => $moduleinfo->name,
517 'instanceid' => $moduleinfo->instance
518 )
519 ));
520 $event->trigger();
521
8f2913b9
DW
522 add_to_log($course->id, $moduleinfo->modulename, "update",
523 "view.php?id=$moduleinfo->coursemodule",
524 "$moduleinfo->instance", $moduleinfo->coursemodule);
80fe0c19 525
63deb5c3 526 $moduleinfo = edit_module_post_actions($moduleinfo, $course);
80fe0c19 527
8f2913b9 528 return array($cm, $moduleinfo);
80fe0c19
JM
529}
530
531/**
532 * Include once the module lib file.
533 *
534 * @param string $modulename module name of the lib to include
b4b75872 535 * @throws moodle_exception if lib.php file for the module does not exist
80fe0c19
JM
536 */
537function include_modulelib($modulename) {
538 global $CFG;
539 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
540 if (file_exists($modlib)) {
541 include_once($modlib);
542 } else {
543 throw new moodle_exception('modulemissingcode', '', '', $modlib);
544 }
545}
546