2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
18 * Library of useful functions
20 * @copyright 1999 Martin Dougiamas http://dougiamas.com
21 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
22 * @package core_course
25 defined('MOODLE_INTERNAL') ||
die;
27 use core_course\external\course_summary_exporter
;
28 use core_courseformat\base
as course_format
;
29 use core\output\local\action_menu\subpanel
as action_menu_subpanel
;
31 require_once($CFG->libdir
.'/completionlib.php');
32 require_once($CFG->libdir
.'/filelib.php');
33 require_once($CFG->libdir
.'/datalib.php');
34 require_once($CFG->dirroot
.'/course/format/lib.php');
36 define('COURSE_MAX_LOGS_PER_PAGE', 1000); // Records.
37 define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds.
40 * Number of courses to display when summaries are included.
42 * @deprecated since 2.4, use $CFG->courseswithsummarieslimit instead.
44 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10);
46 // Max courses in log dropdown before switching to optional.
47 define('COURSE_MAX_COURSES_PER_DROPDOWN', 1000);
48 // Max users in log dropdown before switching to optional.
49 define('COURSE_MAX_USERS_PER_DROPDOWN', 1000);
50 define('FRONTPAGENEWS', '0');
51 define('FRONTPAGECATEGORYNAMES', '2');
52 define('FRONTPAGECATEGORYCOMBO', '4');
53 define('FRONTPAGEENROLLEDCOURSELIST', '5');
54 define('FRONTPAGEALLCOURSELIST', '6');
55 define('FRONTPAGECOURSESEARCH', '7');
56 // Important! Replaced with $CFG->frontpagecourselimit - maximum number of courses displayed on the frontpage.
57 define('EXCELROWS', 65535);
58 define('FIRSTUSEDEXCELROW', 3);
60 define('MOD_CLASS_ACTIVITY', 0);
61 define('MOD_CLASS_RESOURCE', 1);
63 define('COURSE_TIMELINE_ALLINCLUDINGHIDDEN', 'allincludinghidden');
64 define('COURSE_TIMELINE_ALL', 'all');
65 define('COURSE_TIMELINE_PAST', 'past');
66 define('COURSE_TIMELINE_INPROGRESS', 'inprogress');
67 define('COURSE_TIMELINE_FUTURE', 'future');
68 define('COURSE_TIMELINE_SEARCH', 'search');
69 define('COURSE_FAVOURITES', 'favourites');
70 define('COURSE_TIMELINE_HIDDEN', 'hidden');
71 define('COURSE_CUSTOMFIELD', 'customfield');
72 define('COURSE_DB_QUERY_LIMIT', 1000);
73 /** Searching for all courses that have no value for the specified custom field. */
74 define('COURSE_CUSTOMFIELD_EMPTY', -1);
76 // Course activity chooser footer default display option.
77 define('COURSE_CHOOSER_FOOTER_NONE', 'hidden');
79 // Download course content options.
80 define('DOWNLOAD_COURSE_CONTENT_DISABLED', 0);
81 define('DOWNLOAD_COURSE_CONTENT_ENABLED', 1);
82 define('DOWNLOAD_COURSE_CONTENT_SITE_DEFAULT', 2);
84 function make_log_url($module, $url) {
87 if (strpos($url, 'report/') === 0) {
88 // there is only one report type, course reports are deprecated
98 if (strpos($url, '../') === 0) {
99 $url = ltrim($url, '.');
101 $url = "/course/$url";
105 $url = "/calendar/$url";
109 $url = "/$module/$url";
122 $url = "/message/$url";
125 $url = "/notes/$url";
134 $url = "/grade/$url";
137 $url = "/mod/$module/$url";
141 //now let's sanitise urls - there might be some ugly nasties:-(
142 $parts = explode('?', $url);
143 $script = array_shift($parts);
144 if (strpos($script, 'http') === 0) {
145 $script = clean_param($script, PARAM_URL
);
147 $script = clean_param($script, PARAM_PATH
);
152 $query = implode('', $parts);
153 $query = str_replace('&', '&', $query); // both & and & are stored in db :-|
154 $parts = explode('&', $query);
155 $eq = urlencode('=');
156 foreach ($parts as $key=>$part) {
157 $part = urlencode(urldecode($part));
158 $part = str_replace($eq, '=', $part);
159 $parts[$key] = $part;
161 $query = '?'.implode('&', $parts);
164 return $script.$query;
168 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
169 $modname="", $modid=0, $modaction="", $groupid=0) {
172 // It is assumed that $date is the GMT time of midnight for that day,
173 // and so the next 86400 seconds worth of logs are printed.
175 /// Setup for group handling.
177 // TODO: I don't understand group/context/etc. enough to be able to do
178 // something interesting with it here
179 // What is the context of a remote course?
181 /// If the group mode is separate, and this user does not have editing privileges,
182 /// then only the user's group can be viewed.
183 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
184 // $groupid = get_current_group($course->id);
186 /// If this course doesn't have groups, no groupid can be specified.
187 //else if (!$course->groupmode) {
196 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
198 LEFT JOIN {user} u ON l.userid = u.id
202 $where .= "l.hostid = :hostid";
203 $params['hostid'] = $hostid;
205 // TODO: Is 1 really a magic number referring to the sitename?
206 if ($course != SITEID ||
$modid != 0) {
207 $where .= " AND l.course=:courseid";
208 $params['courseid'] = $course;
212 $where .= " AND l.module = :modname";
213 $params['modname'] = $modname;
216 if ('site_errors' === $modid) {
217 $where .= " AND ( l.action='error' OR l.action='infected' )";
219 //TODO: This assumes that modids are the same across sites... probably
221 $where .= " AND l.cmid = :modid";
222 $params['modid'] = $modid;
226 $firstletter = substr($modaction, 0, 1);
227 if ($firstletter == '-') {
228 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
229 $params['modaction'] = '%'.substr($modaction, 1).'%';
231 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
232 $params['modaction'] = '%'.$modaction.'%';
237 $where .= " AND l.userid = :user";
238 $params['user'] = $user;
242 $enddate = $date +
86400;
243 $where .= " AND l.time > :date AND l.time < :enddate";
244 $params['date'] = $date;
245 $params['enddate'] = $enddate;
249 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
250 if(!empty($result['totalcount'])) {
251 $where .= " ORDER BY $order";
252 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
254 $result['logs'] = array();
260 * Checks the integrity of the course data.
262 * In summary - compares course_sections.sequence and course_modules.section.
264 * More detailed, checks that:
265 * - course_sections.sequence contains each module id not more than once in the course
266 * - for each moduleid from course_sections.sequence the field course_modules.section
267 * refers to the same section id (this means course_sections.sequence is more
268 * important if they are different)
269 * - ($fullcheck only) each module in the course is present in one of
270 * course_sections.sequence
271 * - ($fullcheck only) removes non-existing course modules from section sequences
273 * If there are any mismatches, the changes are made and records are updated in DB.
275 * Course cache is NOT rebuilt if there are any errors!
277 * This function is used each time when course cache is being rebuilt with $fullcheck = false
278 * and in CLI script admin/cli/fix_course_sequence.php with $fullcheck = true
280 * @param int $courseid id of the course
281 * @param array $rawmods result of funciton {@link get_course_mods()} - containst
282 * the list of enabled course modules in the course. Retrieved from DB if not specified.
283 * Argument ignored in cashe of $fullcheck, the list is retrieved form DB anyway.
284 * @param array $sections records from course_sections table for this course.
285 * Retrieved from DB if not specified
286 * @param bool $fullcheck Will add orphaned modules to their sections and remove non-existing
287 * course modules from sequences. Only to be used in site maintenance mode when we are
288 * sure that another user is not in the middle of the process of moving/removing a module.
289 * @param bool $checkonly Only performs the check without updating DB, outputs all errors as debug messages.
290 * @return array array of messages with found problems. Empty output means everything is ok
292 function course_integrity_check($courseid, $rawmods = null, $sections = null, $fullcheck = false, $checkonly = false) {
295 if ($sections === null) {
296 $sections = $DB->get_records('course_sections', array('course' => $courseid), 'section', 'id,section,sequence');
299 // Retrieve all records from course_modules regardless of module type visibility.
300 $rawmods = $DB->get_records('course_modules', array('course' => $courseid), 'id', 'id,section');
302 if ($rawmods === null) {
303 $rawmods = get_course_mods($courseid);
305 if (!$fullcheck && (empty($sections) ||
empty($rawmods))) {
306 // If either of the arrays is empty, no modules are displayed anyway.
309 $debuggingprefix = 'Failed integrity check for course ['.$courseid.']. ';
311 // First make sure that each module id appears in section sequences only once.
312 // If it appears in several section sequences the last section wins.
313 // If it appears twice in one section sequence, the first occurence wins.
314 $modsection = array();
315 foreach ($sections as $sectionid => $section) {
316 $sections[$sectionid]->newsequence
= $section->sequence
;
317 if (!empty($section->sequence
)) {
318 $sequence = explode(",", $section->sequence
);
319 $sequenceunique = array_unique($sequence);
320 if (count($sequenceunique) != count($sequence)) {
321 // Some course module id appears in this section sequence more than once.
322 ksort($sequenceunique); // Preserve initial order of modules.
323 $sequence = array_values($sequenceunique);
324 $sections[$sectionid]->newsequence
= join(',', $sequence);
325 $messages[] = $debuggingprefix.'Sequence for course section ['.
326 $sectionid.'] is "'.$sections[$sectionid]->sequence
.'", must be "'.$sections[$sectionid]->newsequence
.'"';
328 foreach ($sequence as $cmid) {
329 if (array_key_exists($cmid, $modsection) && isset($rawmods[$cmid])) {
330 // Some course module id appears to be in more than one section's sequences.
331 $wrongsectionid = $modsection[$cmid];
332 $sections[$wrongsectionid]->newsequence
= trim(preg_replace("/,$cmid,/", ',', ','.$sections[$wrongsectionid]->newsequence
. ','), ',');
333 $messages[] = $debuggingprefix.'Course module ['.$cmid.'] must be removed from sequence of section ['.
334 $wrongsectionid.'] because it is also present in sequence of section ['.$sectionid.']';
336 $modsection[$cmid] = $sectionid;
341 // Add orphaned modules to their sections if they exist or to section 0 otherwise.
343 foreach ($rawmods as $cmid => $mod) {
344 if (!isset($modsection[$cmid])) {
345 // This is a module that is not mentioned in course_section.sequence at all.
346 // Add it to the section $mod->section or to the last available section.
347 if ($mod->section
&& isset($sections[$mod->section
])) {
348 $modsection[$cmid] = $mod->section
;
350 $firstsection = reset($sections);
351 $modsection[$cmid] = $firstsection->id
;
353 $sections[$modsection[$cmid]]->newsequence
= trim($sections[$modsection[$cmid]]->newsequence
.','.$cmid, ',');
354 $messages[] = $debuggingprefix.'Course module ['.$cmid.'] is missing from sequence of section ['.
355 $modsection[$cmid].']';
358 foreach ($modsection as $cmid => $sectionid) {
359 if (!isset($rawmods[$cmid])) {
360 // Section $sectionid refers to module id that does not exist.
361 $sections[$sectionid]->newsequence
= trim(preg_replace("/,$cmid,/", ',', ','.$sections[$sectionid]->newsequence
.','), ',');
362 $messages[] = $debuggingprefix.'Course module ['.$cmid.
363 '] does not exist but is present in the sequence of section ['.$sectionid.']';
368 // Update changed sections.
369 if (!$checkonly && !empty($messages)) {
370 foreach ($sections as $sectionid => $section) {
371 if ($section->newsequence
!== $section->sequence
) {
372 $DB->update_record('course_sections', array('id' => $sectionid, 'sequence' => $section->newsequence
));
377 // Now make sure that all modules point to the correct sections.
378 foreach ($rawmods as $cmid => $mod) {
379 if (isset($modsection[$cmid]) && $modsection[$cmid] != $mod->section
) {
381 $DB->update_record('course_modules', array('id' => $cmid, 'section' => $modsection[$cmid]));
383 $messages[] = $debuggingprefix.'Course module ['.$cmid.
384 '] points to section ['.$mod->section
.'] instead of ['.$modsection[$cmid].']';
392 * Returns an array where the key is the module name (component name without 'mod_')
393 * and the value is a lang_string object with a human-readable string.
395 * @param bool $plural If true, the function returns the plural forms of the names.
396 * @param bool $resetcache If true, the static cache will be reset
397 * @return lang_string[] Localised human-readable names of all used modules.
399 function get_module_types_names($plural = false, $resetcache = false) {
400 static $modnames = null;
402 if ($modnames === null ||
$resetcache) {
403 $modnames = array(0 => array(), 1 => array());
404 if ($allmods = $DB->get_records("modules")) {
405 foreach ($allmods as $mod) {
406 if (file_exists("$CFG->dirroot/mod/$mod->name/lib.php") && $mod->visible
) {
407 $modnames[0][$mod->name
] = get_string("modulename", "$mod->name", null, true);
408 $modnames[1][$mod->name
] = get_string("modulenameplural", "$mod->name", null, true);
413 return $modnames[(int)$plural];
417 * Set highlighted section. Only one section can be highlighted at the time.
419 * @param int $courseid course id
420 * @param int $marker highlight section with this number, 0 means remove higlightin
423 function course_set_marker($courseid, $marker) {
425 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
426 if ($COURSE && $COURSE->id
== $courseid) {
427 $COURSE->marker
= $marker;
429 core_courseformat\base
::reset_course_cache($courseid);
430 course_modinfo
::clear_instance_cache($courseid);
434 * For a given course section, marks it visible or hidden,
435 * and does the same for every activity in that section
437 * @param int $courseid course id
438 * @param int $sectionnumber The section number to adjust
439 * @param int $visibility The new visibility
440 * @return array A list of resources which were hidden in the section
442 function set_section_visible($courseid, $sectionnumber, $visibility) {
445 $resourcestotoggle = array();
446 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
447 course_update_section($courseid, $section, array('visible' => $visibility));
449 // Determine which modules are visible for AJAX update
450 $modules = !empty($section->sequence
) ?
explode(',', $section->sequence
) : array();
451 if (!empty($modules)) {
452 list($insql, $params) = $DB->get_in_or_equal($modules);
453 $select = 'id ' . $insql . ' AND visible = ?';
454 array_push($params, $visibility);
456 $select .= ' AND visibleold = 1';
458 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
461 return $resourcestotoggle;
465 * Return the course category context for the category with id $categoryid, except
466 * that if $categoryid is 0, return the system context.
468 * @param integer $categoryid a category id or 0.
469 * @return context the corresponding context
471 function get_category_or_system_context($categoryid) {
473 return context_coursecat
::instance($categoryid, IGNORE_MISSING
);
475 return context_system
::instance();
480 * Print the buttons relating to course requests.
482 * @param context $context current page context.
483 * @deprecated since Moodle 4.0
484 * @todo Final deprecation MDL-73976
486 function print_course_request_buttons($context) {
487 global $CFG, $DB, $OUTPUT;
488 debugging("print_course_request_buttons() is deprecated. " .
489 "This is replaced with the category_action_bar tertiary navigation.", DEBUG_DEVELOPER
);
490 if (empty($CFG->enablecourserequests
)) {
493 if (course_request
::can_request($context)) {
494 // Print a button to request a new course.
496 if ($context instanceof context_coursecat
) {
497 $params['category'] = $context->instanceid
;
499 echo $OUTPUT->single_button(new moodle_url('/course/request.php', $params),
500 get_string('requestcourse'), 'get');
502 /// Print a button to manage pending requests
503 if (has_capability('moodle/site:approvecourse', $context)) {
504 $disabled = !$DB->record_exists('course_request', array());
505 echo $OUTPUT->single_button(new moodle_url('/course/pending.php'), get_string('coursespending'), 'get', array('disabled' => $disabled));
510 * Does the user have permission to edit things in this category?
512 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
513 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
515 function can_edit_in_category($categoryid = 0) {
516 $context = get_category_or_system_context($categoryid);
517 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
520 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
522 function add_course_module($mod) {
525 $mod->added
= time();
528 $cmid = $DB->insert_record("course_modules", $mod);
529 rebuild_course_cache($mod->course
, true);
534 * Creates a course section and adds it to the specified position
536 * @param int|stdClass $courseorid course id or course object
537 * @param int $position position to add to, 0 means to the end. If position is greater than
538 * number of existing secitons, the section is added to the end. This will become sectionnum of the
539 * new section. All existing sections at this or bigger position will be shifted down.
540 * @param bool $skipcheck the check has already been made and we know that the section with this position does not exist
541 * @return stdClass created section object
543 function course_create_section($courseorid, $position = 0, $skipcheck = false) {
545 $courseid = is_object($courseorid) ?
$courseorid->id
: $courseorid;
547 // Find the last sectionnum among existing sections.
549 $lastsection = $position - 1;
551 $lastsection = (int)$DB->get_field_sql('SELECT max(section) from {course_sections} WHERE course = ?', [$courseid]);
554 // First add section to the end.
555 $cw = new stdClass();
556 $cw->course
= $courseid;
557 $cw->section
= $lastsection +
1;
559 $cw->summaryformat
= FORMAT_HTML
;
563 $cw->availability
= null;
564 $cw->timemodified
= time();
565 $cw->id
= $DB->insert_record("course_sections", $cw);
567 // Now move it to the specified position.
568 if ($position > 0 && $position <= $lastsection) {
569 $course = is_object($courseorid) ?
$courseorid : get_course($courseorid);
570 move_section_to($course, $cw->section
, $position, true);
571 $cw->section
= $position;
574 core\event\course_section_created
::create_from_section($cw)->trigger();
576 rebuild_course_cache($courseid, true);
581 * Creates missing course section(s) and rebuilds course cache
583 * @param int|stdClass $courseorid course id or course object
584 * @param int|array $sections list of relative section numbers to create
585 * @return bool if there were any sections created
587 function course_create_sections_if_missing($courseorid, $sections) {
588 if (!is_array($sections)) {
589 $sections = array($sections);
591 $existing = array_keys(get_fast_modinfo($courseorid)->get_section_info_all());
592 if ($newsections = array_diff($sections, $existing)) {
593 foreach ($newsections as $sectionnum) {
594 course_create_section($courseorid, $sectionnum, true);
602 * Adds an existing module to the section
604 * Updates both tables {course_sections} and {course_modules}
606 * Note: This function does not use modinfo PROVIDED that the section you are
607 * adding the module to already exists. If the section does not exist, it will
608 * build modinfo if necessary and create the section.
610 * @param int|stdClass $courseorid course id or course object
611 * @param int $cmid id of the module already existing in course_modules table
612 * @param int $sectionnum relative number of the section (field course_sections.section)
613 * If section does not exist it will be created
614 * @param int|stdClass $beforemod id or object with field id corresponding to the module
615 * before which the module needs to be included. Null for inserting in the
617 * @return int The course_sections ID where the module is inserted
619 function course_add_cm_to_section($courseorid, $cmid, $sectionnum, $beforemod = null) {
621 if (is_object($beforemod)) {
622 $beforemod = $beforemod->id
;
624 if (is_object($courseorid)) {
625 $courseid = $courseorid->id
;
627 $courseid = $courseorid;
629 // Do not try to use modinfo here, there is no guarantee it is valid!
630 $section = $DB->get_record('course_sections',
631 array('course' => $courseid, 'section' => $sectionnum), '*', IGNORE_MISSING
);
633 // This function call requires modinfo.
634 course_create_sections_if_missing($courseorid, $sectionnum);
635 $section = $DB->get_record('course_sections',
636 array('course' => $courseid, 'section' => $sectionnum), '*', MUST_EXIST
);
639 $modarray = explode(",", trim($section->sequence
));
640 if (empty($section->sequence
)) {
641 $newsequence = "$cmid";
642 } else if ($beforemod && ($key = array_keys($modarray, $beforemod))) {
643 $insertarray = array($cmid, $beforemod);
644 array_splice($modarray, $key[0], 1, $insertarray);
645 $newsequence = implode(",", $modarray);
647 $newsequence = "$section->sequence,$cmid";
649 $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id
));
650 $DB->set_field('course_modules', 'section', $section->id
, array('id' => $cmid));
651 rebuild_course_cache($courseid, true);
652 return $section->id
; // Return course_sections ID that was used.
656 * Change the group mode of a course module.
658 * Note: Do not forget to trigger the event \core\event\course_module_updated as it needs
659 * to be triggered manually, refer to {@link \core\event\course_module_updated::create_from_cm()}.
661 * @param int $id course module ID.
662 * @param int $groupmode the new groupmode value.
663 * @return bool True if the $groupmode was updated.
665 function set_coursemodule_groupmode($id, $groupmode) {
667 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST
);
668 if ($cm->groupmode
!= $groupmode) {
669 $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id
));
670 \course_modinfo
::purge_course_module_cache($cm->course
, $cm->id
);
671 rebuild_course_cache($cm->course
, false, true);
673 return ($cm->groupmode
!= $groupmode);
676 function set_coursemodule_idnumber($id, $idnumber) {
678 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST
);
679 if ($cm->idnumber
!= $idnumber) {
680 $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id
));
681 \course_modinfo
::purge_course_module_cache($cm->course
, $cm->id
);
682 rebuild_course_cache($cm->course
, false, true);
684 return ($cm->idnumber
!= $idnumber);
688 * Set downloadcontent value to course module.
690 * @param int $id The id of the module.
691 * @param bool $downloadcontent Whether the module can be downloaded when download course content is enabled.
692 * @return bool True if downloadcontent has been updated, false otherwise.
694 function set_downloadcontent(int $id, bool $downloadcontent): bool {
696 $cm = $DB->get_record('course_modules', ['id' => $id], 'id, course, downloadcontent', MUST_EXIST
);
697 if ($cm->downloadcontent
!= $downloadcontent) {
698 $DB->set_field('course_modules', 'downloadcontent', $downloadcontent, ['id' => $cm->id
]);
699 rebuild_course_cache($cm->course
, true);
701 return ($cm->downloadcontent
!= $downloadcontent);
705 * Set the visibility of a module and inherent properties.
707 * Note: Do not forget to trigger the event \core\event\course_module_updated as it needs
708 * to be triggered manually, refer to {@link \core\event\course_module_updated::create_from_cm()}.
710 * From 2.4 the parameter $prevstateoverrides has been removed, the logic it triggered
711 * has been moved to {@link set_section_visible()} which was the only place from which
712 * the parameter was used.
714 * @param int $id of the module
715 * @param int $visible state of the module
716 * @param int $visibleoncoursepage state of the module on the course page
717 * @return bool false when the module was not found, true otherwise
719 function set_coursemodule_visible($id, $visible, $visibleoncoursepage = 1) {
721 require_once($CFG->libdir
.'/gradelib.php');
722 require_once($CFG->dirroot
.'/calendar/lib.php');
724 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
728 // Create events and propagate visibility to associated grade items if the value has changed.
729 // Only do this if it's changed to avoid accidently overwriting manual showing/hiding of student grades.
730 if ($cm->visible
== $visible && $cm->visibleoncoursepage
== $visibleoncoursepage) {
734 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module
))) {
737 if (($cm->visible
!= $visible) &&
738 ($events = $DB->get_records('event', array('instance' => $cm->instance
, 'modulename' => $modulename)))) {
739 foreach($events as $event) {
741 $event = new calendar_event($event);
742 $event->toggle_visibility(true);
744 $event = new calendar_event($event);
745 $event->toggle_visibility(false);
750 // Updating visible and visibleold to keep them in sync. Only changing a section visibility will
751 // affect visibleold to allow for an original visibility restore. See set_section_visible().
752 $cminfo = new stdClass();
754 $cminfo->visible
= $visible;
755 $cminfo->visibleoncoursepage
= $visibleoncoursepage;
756 $cminfo->visibleold
= $visible;
757 $DB->update_record('course_modules', $cminfo);
759 // Hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there.
760 // Note that this must be done after updating the row in course_modules, in case
761 // the modules grade_item_update function needs to access $cm->visible.
762 if ($cm->visible
!= $visible &&
763 plugin_supports('mod', $modulename, FEATURE_CONTROLS_GRADE_VISIBILITY
) &&
764 component_callback_exists('mod_' . $modulename, 'grade_item_update')) {
765 $instance = $DB->get_record($modulename, array('id' => $cm->instance
), '*', MUST_EXIST
);
766 component_callback('mod_' . $modulename, 'grade_item_update', array($instance));
767 } else if ($cm->visible
!= $visible) {
768 $grade_items = grade_item
::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance
, 'courseid'=>$cm->course
));
770 foreach ($grade_items as $grade_item) {
771 $grade_item->set_hidden(!$visible);
776 \course_modinfo
::purge_course_module_cache($cm->course
, $cm->id
);
777 rebuild_course_cache($cm->course
, false, true);
782 * Changes the course module name
784 * @param int $id course module id
785 * @param string $name new value for a name
786 * @return bool whether a change was made
788 function set_coursemodule_name($id, $name) {
790 require_once($CFG->libdir
. '/gradelib.php');
792 $cm = get_coursemodule_from_id('', $id, 0, false, MUST_EXIST
);
794 $module = new \
stdClass();
795 $module->id
= $cm->instance
;
797 // Escape strings as they would be by mform.
798 if (!empty($CFG->formatstringstriptags
)) {
799 $module->name
= clean_param($name, PARAM_TEXT
);
801 $module->name
= clean_param($name, PARAM_CLEANHTML
);
803 if ($module->name
=== $cm->name ||
strval($module->name
) === '') {
806 if (\core_text
::strlen($module->name
) > 255) {
807 throw new \
moodle_exception('maximumchars', 'moodle', '', 255);
810 $module->timemodified
= time();
811 $DB->update_record($cm->modname
, $module);
812 $cm->name
= $module->name
;
813 \core\event\course_module_updated
::create_from_cm($cm)->trigger();
814 \course_modinfo
::purge_course_module_cache($cm->course
, $cm->id
);
815 rebuild_course_cache($cm->course
, false, true);
817 // Attempt to update the grade item if relevant.
818 $grademodule = $DB->get_record($cm->modname
, array('id' => $cm->instance
));
819 $grademodule->cmidnumber
= $cm->idnumber
;
820 $grademodule->modname
= $cm->modname
;
821 grade_update_mod_grades($grademodule);
823 // Update calendar events with the new name.
824 course_module_update_calendar_events($cm->modname
, $grademodule, $cm);
830 * This function will handle the whole deletion process of a module. This includes calling
831 * the modules delete_instance function, deleting files, events, grades, conditional data,
832 * the data in the course_module and course_sections table and adding a module deletion
835 * @param int $cmid the course module id
836 * @param bool $async whether or not to try to delete the module using an adhoc task. Async also depends on a plugin hook.
837 * @throws moodle_exception
840 function course_delete_module($cmid, $async = false) {
841 // Check the 'course_module_background_deletion_recommended' hook first.
842 // Only use asynchronous deletion if at least one plugin returns true and if async deletion has been requested.
843 // Both are checked because plugins should not be allowed to dictate the deletion behaviour, only support/decline it.
844 // It's up to plugins to handle things like whether or not they are enabled.
845 if ($async && $pluginsfunction = get_plugins_with_function('course_module_background_deletion_recommended')) {
846 foreach ($pluginsfunction as $plugintype => $plugins) {
847 foreach ($plugins as $pluginfunction) {
848 if ($pluginfunction()) {
849 return course_module_flag_for_async_deletion($cmid);
857 require_once($CFG->libdir
.'/gradelib.php');
858 require_once($CFG->libdir
.'/questionlib.php');
859 require_once($CFG->dirroot
.'/blog/lib.php');
860 require_once($CFG->dirroot
.'/calendar/lib.php');
862 // Get the course module.
863 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
867 // Get the module context.
868 $modcontext = context_module
::instance($cm->id
);
870 // Get the course module name.
871 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module
), MUST_EXIST
);
873 // Get the file location of the delete_instance function for this module.
874 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
876 // Include the file required to call the delete_instance function for this module.
877 if (file_exists($modlib)) {
878 require_once($modlib);
880 throw new moodle_exception('cannotdeletemodulemissinglib', '', '', null,
881 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
884 $deleteinstancefunction = $modulename . '_delete_instance';
886 // Ensure the delete_instance function exists for this module.
887 if (!function_exists($deleteinstancefunction)) {
888 throw new moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
889 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
892 // Allow plugins to use this course module before we completely delete it.
893 if ($pluginsfunction = get_plugins_with_function('pre_course_module_delete')) {
894 foreach ($pluginsfunction as $plugintype => $plugins) {
895 foreach ($plugins as $pluginfunction) {
896 $pluginfunction($cm);
901 // Call the delete_instance function, if it returns false throw an exception.
902 if (!$deleteinstancefunction($cm->instance
)) {
903 throw new moodle_exception('cannotdeletemoduleinstance', '', '', null,
904 "Cannot delete the module $modulename (instance).");
907 question_delete_activity($cm);
909 // Remove all module files in case modules forget to do that.
910 $fs = get_file_storage();
911 $fs->delete_area_files($modcontext->id
);
913 // Delete events from calendar.
914 if ($events = $DB->get_records('event', array('instance' => $cm->instance
, 'modulename' => $modulename))) {
915 $coursecontext = context_course
::instance($cm->course
);
916 foreach($events as $event) {
917 $event->context
= $coursecontext;
918 $calendarevent = calendar_event
::load($event);
919 $calendarevent->delete();
923 // Delete grade items, outcome items and grades attached to modules.
924 if ($grade_items = grade_item
::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $modulename,
925 'iteminstance' => $cm->instance
, 'courseid' => $cm->course
))) {
926 foreach ($grade_items as $grade_item) {
927 $grade_item->delete('moddelete');
931 // Delete associated blogs and blog tag instances.
932 blog_remove_associations_for_module($modcontext->id
);
934 // Delete completion and availability data; it is better to do this even if the
935 // features are not turned on, in case they were turned on previously (these will be
936 // very quick on an empty table).
937 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id
));
938 $DB->delete_records('course_modules_viewed', ['coursemoduleid' => $cm->id
]);
939 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id
,
940 'course' => $cm->course
,
941 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY
));
943 // Delete all tag instances associated with the instance of this module.
944 core_tag_tag
::delete_instances('mod_' . $modulename, null, $modcontext->id
);
945 core_tag_tag
::remove_all_item_tags('core', 'course_modules', $cm->id
);
947 // Notify the competency subsystem.
948 \core_competency\api
::hook_course_module_deleted($cm);
950 // Delete the context.
951 context_helper
::delete_instance(CONTEXT_MODULE
, $cm->id
);
953 // Delete the module from the course_modules table.
954 $DB->delete_records('course_modules', array('id' => $cm->id
));
956 // Delete module from that section.
957 if (!delete_mod_from_section($cm->id
, $cm->section
)) {
958 throw new moodle_exception('cannotdeletemodulefromsection', '', '', null,
959 "Cannot delete the module $modulename (instance) from section.");
962 // Trigger event for course module delete action.
963 $event = \core\event\course_module_deleted
::create(array(
964 'courseid' => $cm->course
,
965 'context' => $modcontext,
966 'objectid' => $cm->id
,
968 'modulename' => $modulename,
969 'instanceid' => $cm->instance
,
972 $event->add_record_snapshot('course_modules', $cm);
974 \course_modinfo
::purge_course_module_cache($cm->course
, $cm->id
);
975 rebuild_course_cache($cm->course
, false, true);
979 * Schedule a course module for deletion in the background using an adhoc task.
981 * This method should not be called directly. Instead, please use course_delete_module($cmid, true), to denote async deletion.
982 * The real deletion of the module is handled by the task, which calls 'course_delete_module($cmid)'.
984 * @param int $cmid the course module id.
985 * @return bool whether the module was successfully scheduled for deletion.
986 * @throws \moodle_exception
988 function course_module_flag_for_async_deletion($cmid) {
989 global $CFG, $DB, $USER;
990 require_once($CFG->libdir
.'/gradelib.php');
991 require_once($CFG->libdir
.'/questionlib.php');
992 require_once($CFG->dirroot
.'/blog/lib.php');
993 require_once($CFG->dirroot
.'/calendar/lib.php');
995 // Get the course module.
996 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
1000 // We need to be reasonably certain the deletion is going to succeed before we background the process.
1001 // Make the necessary delete_instance checks, etc. before proceeding further. Throw exceptions if required.
1003 // Get the course module name.
1004 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module
), MUST_EXIST
);
1006 // Get the file location of the delete_instance function for this module.
1007 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
1009 // Include the file required to call the delete_instance function for this module.
1010 if (file_exists($modlib)) {
1011 require_once($modlib);
1013 throw new \
moodle_exception('cannotdeletemodulemissinglib', '', '', null,
1014 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
1017 $deleteinstancefunction = $modulename . '_delete_instance';
1019 // Ensure the delete_instance function exists for this module.
1020 if (!function_exists($deleteinstancefunction)) {
1021 throw new \
moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
1022 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
1025 // We are going to defer the deletion as we can't be sure how long the module's pre_delete code will run for.
1026 $cm->deletioninprogress
= '1';
1027 $DB->update_record('course_modules', $cm);
1029 // Create an adhoc task for the deletion of the course module. The task takes an array of course modules for removal.
1030 $removaltask = new \core_course\task\
course_delete_modules();
1031 $removaltask->set_custom_data(array(
1032 'cms' => array($cm),
1033 'userid' => $USER->id
,
1034 'realuserid' => \core\session\manager
::get_realuser()->id
1037 // Queue the task for the next run.
1038 \core\task\manager
::queue_adhoc_task($removaltask);
1040 // Reset the course cache to hide the module.
1041 rebuild_course_cache($cm->course
, true);
1045 * Checks whether the given course has any course modules scheduled for adhoc deletion.
1047 * @param int $courseid the id of the course.
1048 * @param bool $onlygradable whether to check only gradable modules or all modules.
1049 * @return bool true if the course contains any modules pending deletion, false otherwise.
1051 function course_modules_pending_deletion(int $courseid, bool $onlygradable = false) : bool {
1052 if (empty($courseid)) {
1056 if ($onlygradable) {
1057 // Fetch modules with grade items.
1058 if (!$coursegradeitems = grade_item
::fetch_all(['itemtype' => 'mod', 'courseid' => $courseid])) {
1059 // Return early when there is none.
1064 $modinfo = get_fast_modinfo($courseid);
1065 foreach ($modinfo->get_cms() as $module) {
1066 if ($module->deletioninprogress
== '1') {
1067 if ($onlygradable) {
1068 // Check if the module being deleted is in the list of course modules with grade items.
1069 foreach ($coursegradeitems as $coursegradeitem) {
1070 if ($coursegradeitem->itemmodule
== $module->modname
&& $coursegradeitem->iteminstance
== $module->instance
) {
1071 // The module being deleted is within the gradable modules.
1084 * Checks whether the course module, as defined by modulename and instanceid, is scheduled for deletion within the given course.
1086 * @param int $courseid the course id.
1087 * @param string $modulename the module name. E.g. 'assign', 'book', etc.
1088 * @param int $instanceid the module instance id.
1089 * @return bool true if the course module is pending deletion, false otherwise.
1091 function course_module_instance_pending_deletion($courseid, $modulename, $instanceid) {
1092 if (empty($courseid) ||
empty($modulename) ||
empty($instanceid)) {
1095 $modinfo = get_fast_modinfo($courseid);
1096 $instances = $modinfo->get_instances_of($modulename);
1097 return isset($instances[$instanceid]) && $instances[$instanceid]->deletioninprogress
;
1100 function delete_mod_from_section($modid, $sectionid) {
1103 if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
1105 $modarray = explode(",", $section->sequence
);
1107 if ($key = array_keys ($modarray, $modid)) {
1108 array_splice($modarray, $key[0], 1);
1109 $newsequence = implode(",", $modarray);
1110 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id
));
1111 rebuild_course_cache($section->course
, true);
1122 * This function updates the calendar events from the information stored in the module table and the course
1125 * @param string $modulename Module name
1126 * @param stdClass $instance Module object. Either the $instance or the $cm must be supplied.
1127 * @param stdClass $cm Course module object. Either the $instance or the $cm must be supplied.
1128 * @return bool Returns true if calendar events are updated.
1129 * @since Moodle 3.3.4
1131 function course_module_update_calendar_events($modulename, $instance = null, $cm = null) {
1134 if (isset($instance) ||
isset($cm)) {
1136 if (!isset($instance)) {
1137 $instance = $DB->get_record($modulename, array('id' => $cm->instance
), '*', MUST_EXIST
);
1140 $cm = get_coursemodule_from_instance($modulename, $instance->id
, $instance->course
);
1143 course_module_calendar_event_update_process($instance, $cm);
1151 * Update all instances through out the site or in a course.
1153 * @param string $modulename Module type to update.
1154 * @param integer $courseid Course id to update events. 0 for the whole site.
1155 * @return bool Returns True if the update was successful.
1156 * @since Moodle 3.3.4
1158 function course_module_bulk_update_calendar_events($modulename, $courseid = 0) {
1163 if (!$instances = $DB->get_records($modulename, array('course' => $courseid))) {
1167 if (!$instances = $DB->get_records($modulename)) {
1172 foreach ($instances as $instance) {
1173 if ($cm = get_coursemodule_from_instance($modulename, $instance->id
, $instance->course
)) {
1174 course_module_calendar_event_update_process($instance, $cm);
1181 * Calendar events for a module instance are updated.
1183 * @param stdClass $instance Module instance object.
1184 * @param stdClass $cm Course Module object.
1185 * @since Moodle 3.3.4
1187 function course_module_calendar_event_update_process($instance, $cm) {
1188 // We need to call *_refresh_events() first because some modules delete 'old' events at the end of the code which
1189 // will remove the completion events.
1190 $refresheventsfunction = $cm->modname
. '_refresh_events';
1191 if (function_exists($refresheventsfunction)) {
1192 call_user_func($refresheventsfunction, $cm->course
, $instance, $cm);
1194 $completionexpected = (!empty($cm->completionexpected
)) ?
$cm->completionexpected
: null;
1195 \core_completion\api
::update_completion_date_event($cm->id
, $cm->modname
, $instance, $completionexpected);
1199 * Moves a section within a course, from a position to another.
1200 * Be very careful: $section and $destination refer to section number,
1203 * @param object $course
1204 * @param int $section Section number (not id!!!)
1205 * @param int $destination
1206 * @param bool $ignorenumsections
1207 * @return boolean Result
1209 function move_section_to($course, $section, $destination, $ignorenumsections = false) {
1210 /// Moves a whole course section up and down within the course
1213 if (!$destination && $destination != 0) {
1217 // compartibility with course formats using field 'numsections'
1218 $courseformatoptions = course_get_format($course)->get_format_options();
1219 if ((!$ignorenumsections && array_key_exists('numsections', $courseformatoptions) &&
1220 ($destination > $courseformatoptions['numsections'])) ||
($destination < 1)) {
1224 // Get all sections for this course and re-order them (2 of them should now share the same section number)
1225 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id
),
1226 'section ASC, id ASC', 'id, section')) {
1230 $movedsections = reorder_sections($sections, $section, $destination);
1232 // Update all sections. Do this in 2 steps to avoid breaking database
1233 // uniqueness constraint
1234 $transaction = $DB->start_delegated_transaction();
1235 foreach ($movedsections as $id => $position) {
1236 if ((int) $sections[$id] !== $position) {
1237 $DB->set_field('course_sections', 'section', -$position, ['id' => $id]);
1238 // Invalidate the section cache by given section id.
1239 course_modinfo
::purge_course_section_cache_by_id($course->id
, $id);
1242 foreach ($movedsections as $id => $position) {
1243 if ((int) $sections[$id] !== $position) {
1244 $DB->set_field('course_sections', 'section', $position, ['id' => $id]);
1245 // Invalidate the section cache by given section id.
1246 course_modinfo
::purge_course_section_cache_by_id($course->id
, $id);
1250 // If we move the highlighted section itself, then just highlight the destination.
1251 // Adjust the higlighted section location if we move something over it either direction.
1252 if ($section == $course->marker
) {
1253 course_set_marker($course->id
, $destination);
1254 } else if ($section > $course->marker
&& $course->marker
>= $destination) {
1255 course_set_marker($course->id
, $course->marker+
1);
1256 } else if ($section < $course->marker
&& $course->marker
<= $destination) {
1257 course_set_marker($course->id
, $course->marker
-1);
1260 $transaction->allow_commit();
1261 rebuild_course_cache($course->id
, true, true);
1266 * This method will delete a course section and may delete all modules inside it.
1268 * No permissions are checked here, use {@link course_can_delete_section()} to
1269 * check if section can actually be deleted.
1271 * @param int|stdClass $course
1272 * @param int|stdClass|section_info $section
1273 * @param bool $forcedeleteifnotempty if set to false section will not be deleted if it has modules in it.
1274 * @param bool $async whether or not to try to delete the section using an adhoc task. Async also depends on a plugin hook.
1275 * @return bool whether section was deleted
1277 function course_delete_section($course, $section, $forcedeleteifnotempty = true, $async = false) {
1280 // Prepare variables.
1281 $courseid = (is_object($course)) ?
$course->id
: (int)$course;
1282 $sectionnum = (is_object($section)) ?
$section->section
: (int)$section;
1283 $section = $DB->get_record('course_sections', array('course' => $courseid, 'section' => $sectionnum));
1285 // No section exists, can't proceed.
1289 // Check the 'course_module_background_deletion_recommended' hook first.
1290 // Only use asynchronous deletion if at least one plugin returns true and if async deletion has been requested.
1291 // Both are checked because plugins should not be allowed to dictate the deletion behaviour, only support/decline it.
1292 // It's up to plugins to handle things like whether or not they are enabled.
1293 if ($async && $pluginsfunction = get_plugins_with_function('course_module_background_deletion_recommended')) {
1294 foreach ($pluginsfunction as $plugintype => $plugins) {
1295 foreach ($plugins as $pluginfunction) {
1296 if ($pluginfunction()) {
1297 return course_delete_section_async($section, $forcedeleteifnotempty);
1303 $format = course_get_format($course);
1304 $sectionname = $format->get_section_name($section);
1307 $result = $format->delete_section($section, $forcedeleteifnotempty);
1309 // Trigger an event for course section deletion.
1311 $context = context_course
::instance($courseid);
1312 $event = \core\event\course_section_deleted
::create(
1314 'objectid' => $section->id
,
1315 'courseid' => $courseid,
1316 'context' => $context,
1318 'sectionnum' => $section->section
,
1319 'sectionname' => $sectionname,
1323 $event->add_record_snapshot('course_sections', $section);
1330 * Course section deletion, using an adhoc task for deletion of the modules it contains.
1331 * 1. Schedule all modules within the section for adhoc removal.
1332 * 2. Move all modules to course section 0.
1333 * 3. Delete the resulting empty section.
1335 * @param \stdClass $section the section to schedule for deletion.
1336 * @param bool $forcedeleteifnotempty whether to force section deletion if it contains modules.
1337 * @return bool true if the section was scheduled for deletion, false otherwise.
1339 function course_delete_section_async($section, $forcedeleteifnotempty = true) {
1342 // Objects only, and only valid ones.
1343 if (!is_object($section) ||
empty($section->id
)) {
1347 // Does the object currently exist in the DB for removal (check for stale objects).
1348 $section = $DB->get_record('course_sections', array('id' => $section->id
));
1349 if (!$section ||
!$section->section
) {
1350 // No section exists, or the section is 0. Can't proceed.
1354 // Check whether the section can be removed.
1355 if (!$forcedeleteifnotempty && (!empty($section->sequence
) ||
!empty($section->summary
))) {
1359 $format = course_get_format($section->course
);
1360 $sectionname = $format->get_section_name($section);
1362 // Flag those modules having no existing deletion flag. Some modules may have been scheduled for deletion manually, and we don't
1363 // want to create additional adhoc deletion tasks for these. Moving them to section 0 will suffice.
1364 $affectedmods = $DB->get_records_select('course_modules', 'course = ? AND section = ? AND deletioninprogress <> ?',
1365 [$section->course
, $section->id
, 1], '', 'id');
1366 $DB->set_field('course_modules', 'deletioninprogress', '1', ['course' => $section->course
, 'section' => $section->id
]);
1368 // Move all modules to section 0.
1369 $modules = $DB->get_records('course_modules', ['section' => $section->id
], '');
1370 $sectionzero = $DB->get_record('course_sections', ['course' => $section->course
, 'section' => '0']);
1371 foreach ($modules as $mod) {
1372 moveto_module($mod, $sectionzero);
1375 // Create and queue an adhoc task for the deletion of the modules.
1376 $removaltask = new \core_course\task\
course_delete_modules();
1378 'cms' => $affectedmods,
1379 'userid' => $USER->id
,
1380 'realuserid' => \core\session\manager
::get_realuser()->id
1382 $removaltask->set_custom_data($data);
1383 \core\task\manager
::queue_adhoc_task($removaltask);
1385 // Delete the now empty section, passing in only the section number, which forces the function to fetch a new object.
1386 // The refresh is needed because the section->sequence is now stale.
1387 $result = $format->delete_section($section->section
, $forcedeleteifnotempty);
1389 // Trigger an event for course section deletion.
1391 $context = \context_course
::instance($section->course
);
1392 $event = \core\event\course_section_deleted
::create(
1394 'objectid' => $section->id
,
1395 'courseid' => $section->course
,
1396 'context' => $context,
1398 'sectionnum' => $section->section
,
1399 'sectionname' => $sectionname,
1403 $event->add_record_snapshot('course_sections', $section);
1406 rebuild_course_cache($section->course
, true);
1412 * Updates the course section
1414 * This function does not check permissions or clean values - this has to be done prior to calling it.
1416 * @param int|stdClass $course
1417 * @param stdClass $section record from course_sections table - it will be updated with the new values
1418 * @param array|stdClass $data
1420 function course_update_section($course, $section, $data) {
1423 $courseid = (is_object($course)) ?
$course->id
: (int)$course;
1425 // Some fields can not be updated using this method.
1426 $data = array_diff_key((array)$data, array('id', 'course', 'section', 'sequence'));
1427 $changevisibility = (array_key_exists('visible', $data) && (bool)$data['visible'] != (bool)$section->visible
);
1428 if (array_key_exists('name', $data) && \core_text
::strlen($data['name']) > 255) {
1429 throw new moodle_exception('maximumchars', 'moodle', '', 255);
1432 // Update record in the DB and course format options.
1433 $data['id'] = $section->id
;
1434 $data['timemodified'] = time();
1435 $DB->update_record('course_sections', $data);
1436 // Invalidate the section cache by given section id.
1437 course_modinfo
::purge_course_section_cache_by_id($courseid, $section->id
);
1438 rebuild_course_cache($courseid, false, true);
1439 course_get_format($courseid)->update_section_format_options($data);
1441 // Update fields of the $section object.
1442 foreach ($data as $key => $value) {
1443 if (property_exists($section, $key)) {
1444 $section->$key = $value;
1448 // Trigger an event for course section update.
1449 $event = \core\event\course_section_updated
::create(
1451 'objectid' => $section->id
,
1452 'courseid' => $courseid,
1453 'context' => context_course
::instance($courseid),
1454 'other' => array('sectionnum' => $section->section
)
1459 // If section visibility was changed, hide the modules in this section too.
1460 if ($changevisibility && !empty($section->sequence
)) {
1461 $modules = explode(',', $section->sequence
);
1462 foreach ($modules as $moduleid) {
1463 if ($cm = get_coursemodule_from_id(null, $moduleid, $courseid)) {
1464 if ($data['visible']) {
1465 // As we unhide the section, we use the previously saved visibility stored in visibleold.
1466 set_coursemodule_visible($moduleid, $cm->visibleold
, $cm->visibleoncoursepage
);
1468 // We hide the section, so we hide the module but we store the original state in visibleold.
1469 set_coursemodule_visible($moduleid, 0, $cm->visibleoncoursepage
);
1470 $DB->set_field('course_modules', 'visibleold', $cm->visible
, ['id' => $moduleid]);
1471 \course_modinfo
::purge_course_module_cache($cm->course
, $cm->id
);
1473 \core\event\course_module_updated
::create_from_cm($cm)->trigger();
1476 rebuild_course_cache($courseid, false, true);
1481 * Checks if the current user can delete a section (if course format allows it and user has proper permissions).
1483 * @param int|stdClass $course
1484 * @param int|stdClass|section_info $section
1487 function course_can_delete_section($course, $section) {
1488 if (is_object($section)) {
1489 $section = $section->section
;
1492 // Not possible to delete 0-section.
1495 // Course format should allow to delete sections.
1496 if (!course_get_format($course)->can_delete_section($section)) {
1499 // Make sure user has capability to update course and move sections.
1500 $context = context_course
::instance(is_object($course) ?
$course->id
: $course);
1501 if (!has_all_capabilities(array('moodle/course:movesections', 'moodle/course:update'), $context)) {
1504 // Make sure user has capability to delete each activity in this section.
1505 $modinfo = get_fast_modinfo($course);
1506 if (!empty($modinfo->sections
[$section])) {
1507 foreach ($modinfo->sections
[$section] as $cmid) {
1508 if (!has_capability('moodle/course:manageactivities', context_module
::instance($cmid))) {
1517 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
1518 * an original position number and a target position number, rebuilds the array so that the
1519 * move is made without any duplication of section positions.
1520 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
1521 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
1523 * @param array $sections
1524 * @param int $origin_position
1525 * @param int $target_position
1528 function reorder_sections($sections, $origin_position, $target_position) {
1529 if (!is_array($sections)) {
1533 // We can't move section position 0
1534 if ($origin_position < 1) {
1535 echo "We can't move section position 0";
1539 // Locate origin section in sections array
1540 if (!$origin_key = array_search($origin_position, $sections)) {
1541 echo "searched position not in sections array";
1542 return false; // searched position not in sections array
1545 // Extract origin section
1546 $origin_section = $sections[$origin_key];
1547 unset($sections[$origin_key]);
1549 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
1551 $append_array = array();
1552 foreach ($sections as $id => $position) {
1554 $append_array[$id] = $position;
1555 unset($sections[$id]);
1557 if ($position == $target_position) {
1558 if ($target_position < $origin_position) {
1559 $append_array[$id] = $position;
1560 unset($sections[$id]);
1566 // Append moved section
1567 $sections[$origin_key] = $origin_section;
1569 // Append rest of array (if applicable)
1570 if (!empty($append_array)) {
1571 foreach ($append_array as $id => $position) {
1572 $sections[$id] = $position;
1576 // Renumber positions
1578 foreach ($sections as $id => $p) {
1579 $sections[$id] = $position;
1588 * Move the module object $mod to the specified $section
1589 * If $beforemod exists then that is the module
1590 * before which $modid should be inserted
1592 * @param stdClass|cm_info $mod
1593 * @param stdClass|section_info $section
1594 * @param int|stdClass $beforemod id or object with field id corresponding to the module
1595 * before which the module needs to be included. Null for inserting in the
1596 * end of the section
1597 * @return int new value for module visibility (0 or 1)
1599 function moveto_module($mod, $section, $beforemod=NULL) {
1600 global $OUTPUT, $DB;
1602 // Current module visibility state - return value of this function.
1603 $modvisible = $mod->visible
;
1605 // Remove original module from original section.
1606 if (! delete_mod_from_section($mod->id
, $mod->section
)) {
1607 echo $OUTPUT->notification("Could not delete module from existing section");
1610 // Add the module into the new section.
1611 course_add_cm_to_section($section->course
, $mod->id
, $section->section
, $beforemod);
1613 // If moving to a hidden section then hide module.
1614 if ($mod->section
!= $section->id
) {
1615 if (!$section->visible
&& $mod->visible
) {
1616 // Module was visible but must become hidden after moving to hidden section.
1618 set_coursemodule_visible($mod->id
, 0);
1619 // Set visibleold to 1 so module will be visible when section is made visible.
1620 $DB->set_field('course_modules', 'visibleold', 1, array('id' => $mod->id
));
1622 if ($section->visible
&& !$mod->visible
) {
1623 // Hidden module was moved to the visible section, restore the module visibility from visibleold.
1624 set_coursemodule_visible($mod->id
, $mod->visibleold
);
1625 $modvisible = $mod->visibleold
;
1633 * Returns the list of all editing actions that current user can perform on the module
1635 * @param cm_info $mod The module to produce editing buttons for
1636 * @param int $indent The current indenting (default -1 means no move left-right actions)
1637 * @param int $sr The section to link back to (used for creating the links)
1638 * @return array array of action_link or pix_icon objects
1640 function course_get_cm_edit_actions(cm_info
$mod, $indent = -1, $sr = null) {
1641 global $COURSE, $SITE, $CFG;
1645 $coursecontext = context_course
::instance($mod->course
);
1646 $modcontext = context_module
::instance($mod->id
);
1647 $courseformat = course_get_format($mod->get_course());
1648 $usecomponents = $courseformat->supports_components();
1649 $sectioninfo = $mod->get_section_info();
1651 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
1652 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
1654 // No permission to edit anything.
1655 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
1659 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
1664 'delete', 'move', 'moveright', 'moveleft', 'editsettings',
1665 'duplicate', 'availability'
1669 $str->assign
= get_string('assignroles', 'role');
1670 $str->groupmode
= get_string('groupmode', 'group');
1673 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
1676 $baseurl->param('sr', $sr);
1681 if ($hasmanageactivities) {
1682 $actions['update'] = new action_menu_link_secondary(
1683 new moodle_url($baseurl, array('update' => $mod->id
)),
1684 new pix_icon('t/edit', '', 'moodle', array('class' => 'iconsmall')),
1686 array('class' => 'editing_update', 'data-action' => 'update')
1690 // Move (only for component compatible formats).
1691 if ($usecomponents) {
1692 $actions['move'] = new action_menu_link_secondary(
1693 new moodle_url($baseurl, [
1694 'sesskey' => sesskey(),
1697 new pix_icon('i/dragdrop', '', 'moodle', ['class' => 'iconsmall']),
1700 'class' => 'editing_movecm',
1701 'data-action' => 'moveCm',
1702 'data-id' => $mod->id
,
1708 if ($hasmanageactivities && $indent >= 0) {
1709 $indentlimits = new stdClass();
1710 $indentlimits->min
= 0;
1711 // Legacy indentation could continue using a limit of 16,
1712 // but components based formats will be forced to use one level indentation only.
1713 $indentlimits->max
= ($usecomponents) ?
1 : 16;
1714 if (right_to_left()) { // Exchange arrows on RTL
1715 $rightarrow = 't/left';
1716 $leftarrow = 't/right';
1718 $rightarrow = 't/right';
1719 $leftarrow = 't/left';
1722 if ($indent >= $indentlimits->max
) {
1723 $enabledclass = 'hidden';
1727 $actions['moveright'] = new action_menu_link_secondary(
1728 new moodle_url($baseurl, ['id' => $mod->id
, 'indent' => '1']),
1729 new pix_icon($rightarrow, '', 'moodle', ['class' => 'iconsmall']),
1732 'class' => 'editing_moveright ' . $enabledclass,
1733 'data-action' => ($usecomponents) ?
'cmMoveRight' : 'moveright',
1734 'data-keepopen' => true,
1735 'data-sectionreturn' => $sr,
1736 'data-id' => $mod->id
,
1740 if ($indent <= $indentlimits->min
) {
1741 $enabledclass = 'hidden';
1745 $actions['moveleft'] = new action_menu_link_secondary(
1746 new moodle_url($baseurl, ['id' => $mod->id
, 'indent' => '-1']),
1747 new pix_icon($leftarrow, '', 'moodle', ['class' => 'iconsmall']),
1750 'class' => 'editing_moveleft ' . $enabledclass,
1751 'data-action' => ($usecomponents) ?
'cmMoveLeft' : 'moveleft',
1752 'data-keepopen' => true,
1753 'data-sectionreturn' => $sr,
1754 'data-id' => $mod->id
,
1760 // Hide/Show/Available/Unavailable.
1761 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
1762 $availabilityclass = $courseformat->get_output_classname('content\\cm\\visibility');
1763 /** @var core_courseformat\output\local\content\cm\visibility */
1764 $availability = new $availabilityclass($courseformat, $sectioninfo, $mod);
1765 $availabilitychoice = $availability->get_choice_list();
1766 if ($availabilitychoice->count_options() > 1) {
1767 $actions['availability'] = new action_menu_subpanel(
1769 $availabilitychoice,
1770 ['class' => 'editing_availability'],
1771 new pix_icon('t/hide', '', 'moodle', array('class' => 'iconsmall'))
1776 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
1777 if (has_all_capabilities($dupecaps, $coursecontext) &&
1778 plugin_supports('mod', $mod->modname
, FEATURE_BACKUP_MOODLE2
) &&
1779 course_allowed_module($mod->get_course(), $mod->modname
)) {
1780 $actions['duplicate'] = new action_menu_link_secondary(
1781 new moodle_url($baseurl, ['duplicate' => $mod->id
]),
1782 new pix_icon('t/copy', '', 'moodle', array('class' => 'iconsmall')),
1785 'class' => 'editing_duplicate',
1786 'data-action' => ($courseformat->supports_components()) ?
'cmDuplicate' : 'duplicate',
1787 'data-sectionreturn' => $sr,
1788 'data-id' => $mod->id
,
1794 if (has_capability('moodle/role:assign', $modcontext)){
1795 $actions['assign'] = new action_menu_link_secondary(
1796 new moodle_url('/admin/roles/assign.php', array('contextid' => $modcontext->id
)),
1797 new pix_icon('t/assignroles', '', 'moodle', array('class' => 'iconsmall')),
1799 array('class' => 'editing_assign', 'data-action' => 'assignroles', 'data-sectionreturn' => $sr)
1804 if ($courseformat->show_groupmode($mod) && $usecomponents) {
1805 $groupmodeclass = $courseformat->get_output_classname('content\\cm\\groupmode');
1806 /** @var core_courseformat\output\local\content\cm\groupmode */
1807 $groupmode = new $groupmodeclass($courseformat, $sectioninfo, $mod);
1808 $actions['groupmode'] = new action_menu_subpanel(
1810 $groupmode->get_choice_list(),
1811 ['class' => 'editing_groupmode'],
1812 new pix_icon('i/groupv', '', 'moodle', ['class' => 'iconsmall'])
1817 if ($hasmanageactivities) {
1818 $actions['delete'] = new action_menu_link_secondary(
1819 new moodle_url($baseurl, ['delete' => $mod->id
]),
1820 new pix_icon('t/delete', '', 'moodle', ['class' => 'iconsmall']),
1823 'class' => 'editing_delete text-danger',
1824 'data-action' => ($usecomponents) ?
'cmDelete' : 'delete',
1825 'data-sectionreturn' => $sr,
1826 'data-id' => $mod->id
,
1835 * Returns the move action.
1837 * @param cm_info $mod The module to produce a move button for
1838 * @param int $sr The section to link back to (used for creating the links)
1839 * @return The markup for the move action, or an empty string if not available.
1841 function course_get_cm_move(cm_info
$mod, $sr = null) {
1847 $modcontext = context_module
::instance($mod->id
);
1848 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
1851 $str = get_strings(array('move'));
1854 if (!isset($baseurl)) {
1855 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
1858 $baseurl->param('sr', $sr);
1862 if ($hasmanageactivities) {
1863 $pixicon = 'i/dragdrop';
1865 if (!course_ajax_enabled($mod->get_course())) {
1866 // Override for course frontpage until we get drag/drop working there.
1867 $pixicon = 't/move';
1871 'class' => 'editing_move',
1872 'data-action' => 'move',
1873 'data-sectionreturn' => $sr,
1874 'title' => $str->move
,
1875 'aria-label' => $str->move
,
1877 return html_writer
::link(
1878 new moodle_url($baseurl, ['copy' => $mod->id
]),
1879 $OUTPUT->pix_icon($pixicon, '', 'moodle', ['class' => 'iconsmall']),
1887 * given a course object with shortname & fullname, this function will
1888 * truncate the the number of chars allowed and add ... if it was too long
1890 function course_format_name ($course,$max=100) {
1892 $context = context_course
::instance($course->id
);
1893 $shortname = format_string($course->shortname
, true, array('context' => $context));
1894 $fullname = format_string($course->fullname
, true, array('context' => context_course
::instance($course->id
)));
1895 $str = $shortname.': '. $fullname;
1896 if (core_text
::strlen($str) <= $max) {
1900 return core_text
::substr($str,0,$max-3).'...';
1905 * Is the user allowed to add this type of module to this course?
1906 * @param object $course the course settings. Only $course->id is used.
1907 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
1908 * @param \stdClass $user the user to check, defaults to the global user if not provided.
1909 * @return bool whether the current user is allowed to add this type of module to this course.
1911 function course_allowed_module($course, $modname, \stdClass
$user = null) {
1913 $user = $user ??
$USER;
1914 if (is_numeric($modname)) {
1915 throw new coding_exception('Function course_allowed_module no longer
1916 supports numeric module ids. Please update your code to pass the module name.');
1919 $capability = 'mod/' . $modname . ':addinstance';
1920 if (!get_capability_info($capability)) {
1921 // Debug warning that the capability does not exist, but no more than once per page.
1922 static $warned = array();
1923 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE
, MOD_ARCHETYPE_OTHER
);
1924 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM
) {
1925 debugging('The module ' . $modname . ' does not define the standard capability ' .
1926 $capability , DEBUG_DEVELOPER
);
1927 $warned[$modname] = 1;
1930 // If the capability does not exist, the module can always be added.
1934 $coursecontext = context_course
::instance($course->id
);
1935 return has_capability($capability, $coursecontext, $user);
1939 * Efficiently moves many courses around while maintaining
1940 * sortorder in order.
1942 * @param array $courseids is an array of course ids
1943 * @param int $categoryid
1944 * @return bool success
1946 function move_courses($courseids, $categoryid) {
1949 if (empty($courseids)) {
1954 if (!$category = $DB->get_record('course_categories', array('id' => $categoryid))) {
1958 $courseids = array_reverse($courseids);
1959 $newparent = context_coursecat
::instance($category->id
);
1962 list($where, $params) = $DB->get_in_or_equal($courseids);
1963 $dbcourses = $DB->get_records_select('course', 'id ' . $where, $params, '', 'id, category, shortname, fullname');
1964 foreach ($dbcourses as $dbcourse) {
1965 $course = new stdClass();
1966 $course->id
= $dbcourse->id
;
1967 $course->timemodified
= time();
1968 $course->category
= $category->id
;
1969 $course->sortorder
= $category->sortorder +
get_max_courses_in_category() - $i++
;
1970 if ($category->visible
== 0) {
1971 // Hide the course when moving into hidden category, do not update the visibleold flag - we want to get
1972 // to previous state if somebody unhides the category.
1973 $course->visible
= 0;
1976 $DB->update_record('course', $course);
1978 // Update context, so it can be passed to event.
1979 $context = context_course
::instance($course->id
);
1980 $context->update_moved($newparent);
1982 // Trigger a course updated event.
1983 $event = \core\event\course_updated
::create(array(
1984 'objectid' => $course->id
,
1985 'context' => context_course
::instance($course->id
),
1986 'other' => array('shortname' => $dbcourse->shortname
,
1987 'fullname' => $dbcourse->fullname
,
1988 'updatedfields' => array('category' => $category->id
))
1992 fix_course_sortorder();
1993 cache_helper
::purge_by_event('changesincourse');
1999 * Returns the display name of the given section that the course prefers
2001 * Implementation of this function is provided by course format
2002 * @see core_courseformat\base::get_section_name()
2004 * @param int|stdClass $courseorid The course to get the section name for (object or just course id)
2005 * @param int|stdClass $section Section object from database or just field course_sections.section
2006 * @return string Display name that the course format prefers, e.g. "Week 2"
2008 function get_section_name($courseorid, $section) {
2009 return course_get_format($courseorid)->get_section_name($section);
2013 * Tells if current course format uses sections
2015 * @param string $format Course format ID e.g. 'weeks' $course->format
2018 function course_format_uses_sections($format) {
2019 $course = new stdClass();
2020 $course->format
= $format;
2021 return course_get_format($course)->uses_sections();
2025 * Returns the information about the ajax support in the given source format
2027 * The returned object's property (boolean)capable indicates that
2028 * the course format supports Moodle course ajax features.
2030 * @param string $format
2033 function course_format_ajax_support($format) {
2034 $course = new stdClass();
2035 $course->format
= $format;
2036 return course_get_format($course)->supports_ajax();
2040 * Can the current user delete this course?
2041 * Course creators have exception,
2042 * 1 day after the creation they can sill delete the course.
2043 * @param int $courseid
2046 function can_delete_course($courseid) {
2049 $context = context_course
::instance($courseid);
2051 if (has_capability('moodle/course:delete', $context)) {
2055 // hack: now try to find out if creator created this course recently (1 day)
2056 if (!has_capability('moodle/course:create', $context)) {
2060 $since = time() - 60*60*24;
2061 $course = get_course($courseid);
2063 if ($course->timecreated
< $since) {
2064 return false; // Return if the course was not created in last 24 hours.
2067 $logmanger = get_log_manager();
2068 $readers = $logmanger->get_readers('\core\log\sql_reader');
2069 $reader = reset($readers);
2071 if (empty($reader)) {
2072 return false; // No log reader found.
2076 $select = "userid = :userid AND courseid = :courseid AND eventname = :eventname AND timecreated > :since";
2077 $params = array('userid' => $USER->id
, 'since' => $since, 'courseid' => $course->id
, 'eventname' => '\core\event\course_created');
2079 return (bool)$reader->get_events_select_count($select, $params);
2083 * Save the Your name for 'Some role' strings.
2085 * @param integer $courseid the id of this course.
2086 * @param array $data the data that came from the course settings form.
2088 function save_local_role_names($courseid, $data) {
2090 $context = context_course
::instance($courseid);
2092 foreach ($data as $fieldname => $value) {
2093 if (strpos($fieldname, 'role_') !== 0) {
2096 list($ignored, $roleid) = explode('_', $fieldname);
2098 // make up our mind whether we want to delete, update or insert
2100 $DB->delete_records('role_names', array('contextid' => $context->id
, 'roleid' => $roleid));
2102 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id
, 'roleid' => $roleid))) {
2103 $rolename->name
= $value;
2104 $DB->update_record('role_names', $rolename);
2107 $rolename = new stdClass
;
2108 $rolename->contextid
= $context->id
;
2109 $rolename->roleid
= $roleid;
2110 $rolename->name
= $value;
2111 $DB->insert_record('role_names', $rolename);
2113 // This will ensure the course contacts cache is purged..
2114 core_course_category
::role_assignment_changed($roleid, $context);
2119 * Returns options to use in course overviewfiles filemanager
2121 * @param null|stdClass|core_course_list_element|int $course either object that has 'id' property or just the course id;
2122 * may be empty if course does not exist yet (course create form)
2123 * @return array|null array of options such as maxfiles, maxbytes, accepted_types, etc.
2124 * or null if overviewfiles are disabled
2126 function course_overviewfiles_options($course) {
2128 if (empty($CFG->courseoverviewfileslimit
)) {
2132 // Create accepted file types based on config value, falling back to default all.
2133 $acceptedtypes = (new \core_form\filetypes_util
)->normalize_file_types($CFG->courseoverviewfilesext
);
2134 if (in_array('*', $acceptedtypes) ||
empty($acceptedtypes)) {
2135 $acceptedtypes = '*';
2139 'maxfiles' => $CFG->courseoverviewfileslimit
,
2140 'maxbytes' => $CFG->maxbytes
,
2142 'accepted_types' => $acceptedtypes
2144 if (!empty($course->id
)) {
2145 $options['context'] = context_course
::instance($course->id
);
2146 } else if (is_int($course) && $course > 0) {
2147 $options['context'] = context_course
::instance($course);
2153 * Create a course and either return a $course object
2155 * Please note this functions does not verify any access control,
2156 * the calling code is responsible for all validation (usually it is the form definition).
2158 * @param array $editoroptions course description editor options
2159 * @param object $data - all the data needed for an entry in the 'course' table
2160 * @return object new course instance
2162 function create_course($data, $editoroptions = NULL) {
2165 //check the categoryid - must be given for all new courses
2166 $category = $DB->get_record('course_categories', array('id'=>$data->category
), '*', MUST_EXIST
);
2168 // Check if the shortname already exists.
2169 if (!empty($data->shortname
)) {
2170 if ($DB->record_exists('course', array('shortname' => $data->shortname
))) {
2171 throw new moodle_exception('shortnametaken', '', '', $data->shortname
);
2175 // Check if the idnumber already exists.
2176 if (!empty($data->idnumber
)) {
2177 if ($DB->record_exists('course', array('idnumber' => $data->idnumber
))) {
2178 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber
);
2182 if (empty($CFG->enablecourserelativedates
)) {
2183 // Make sure we're not setting the relative dates mode when the setting is disabled.
2184 unset($data->relativedatesmode
);
2187 if ($errorcode = course_validate_dates((array)$data)) {
2188 throw new moodle_exception($errorcode);
2191 // Check if timecreated is given.
2192 $data->timecreated
= !empty($data->timecreated
) ?
$data->timecreated
: time();
2193 $data->timemodified
= $data->timecreated
;
2195 // place at beginning of any category
2196 $data->sortorder
= 0;
2198 if ($editoroptions) {
2199 // summary text is updated later, we need context to store the files first
2200 $data->summary
= '';
2201 $data->summary_format
= $data->summary_editor
['format'];
2204 // Get default completion settings as a fallback in case the enablecompletion field is not set.
2205 $courseconfig = get_config('moodlecourse');
2206 $defaultcompletion = !empty($CFG->enablecompletion
) ?
$courseconfig->enablecompletion
: COMPLETION_DISABLED
;
2207 $enablecompletion = $data->enablecompletion ??
$defaultcompletion;
2208 // Unset showcompletionconditions when completion tracking is not enabled for the course.
2209 if ($enablecompletion == COMPLETION_DISABLED
) {
2210 unset($data->showcompletionconditions
);
2211 } else if (!isset($data->showcompletionconditions
)) {
2212 // Show completion conditions should have a default value when completion is enabled. Set it to the site defaults.
2213 // This scenario can happen when a course is created through data generators or through a web service.
2214 $data->showcompletionconditions
= $courseconfig->showcompletionconditions
;
2217 if (!isset($data->visible
)) {
2218 // data not from form, add missing visibility info
2219 $data->visible
= $category->visible
;
2221 $data->visibleold
= $data->visible
;
2223 $newcourseid = $DB->insert_record('course', $data);
2224 $context = context_course
::instance($newcourseid, MUST_EXIST
);
2226 if ($editoroptions) {
2227 // Save the files used in the summary editor and store
2228 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2229 $DB->set_field('course', 'summary', $data->summary
, array('id'=>$newcourseid));
2230 $DB->set_field('course', 'summaryformat', $data->summary_format
, array('id'=>$newcourseid));
2232 if ($overviewfilesoptions = course_overviewfiles_options($newcourseid)) {
2233 // Save the course overviewfiles
2234 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2237 // update course format options
2238 course_get_format($newcourseid)->update_course_format_options($data);
2240 $course = course_get_format($newcourseid)->get_course();
2242 fix_course_sortorder();
2243 // purge appropriate caches in case fix_course_sortorder() did not change anything
2244 cache_helper
::purge_by_event('changesincourse');
2246 // Trigger a course created event.
2247 $event = \core\event\course_created
::create(array(
2248 'objectid' => $course->id
,
2249 'context' => context_course
::instance($course->id
),
2250 'other' => array('shortname' => $course->shortname
,
2251 'fullname' => $course->fullname
)
2257 blocks_add_default_course_blocks($course);
2259 // Create default section and initial sections if specified (unless they've already been created earlier).
2260 // We do not want to call course_create_sections_if_missing() because to avoid creating course cache.
2261 $numsections = isset($data->numsections
) ?
$data->numsections
: 0;
2262 $existingsections = $DB->get_fieldset_sql('SELECT section from {course_sections} WHERE course = ?', [$newcourseid]);
2263 $newsections = array_diff(range(0, $numsections), $existingsections);
2264 foreach ($newsections as $sectionnum) {
2265 course_create_section($newcourseid, $sectionnum, true);
2268 // Save any custom role names.
2269 save_local_role_names($course->id
, (array)$data);
2271 // set up enrolments
2272 enrol_course_updated(true, $course, $data);
2274 // Update course tags.
2275 if (isset($data->tags
)) {
2276 core_tag_tag
::set_item_tags('core', 'course', $course->id
, context_course
::instance($course->id
), $data->tags
);
2278 // Set up communication.
2279 if (core_communication\api
::is_available()) {
2280 // Check for default provider config setting.
2281 $defaultprovider = get_config('moodlecourse', 'coursecommunicationprovider');
2282 $provider = (isset($data->selectedcommunication
)) ?
$data->selectedcommunication
: $defaultprovider;
2284 if (!empty($provider)) {
2285 // Prepare the communication api data.
2286 $courseimage = course_get_courseimage($course);
2287 $communicationroomname = !empty($data->communicationroomname
) ?
$data->communicationroomname
: $data->fullname
;
2289 // Communication api call.
2290 $communication = \core_communication\api
::load_by_instance(
2292 'coursecommunication',
2295 $communication->create_and_configure_room(
2297 $communicationroomname,
2298 $courseimage ?
: null,
2304 // Save custom fields if there are any of them in the form.
2305 $handler = core_course\customfield\course_handler
::create();
2306 // Make sure to set the handler's parent context first.
2307 $coursecatcontext = context_coursecat
::instance($category->id
);
2308 $handler->set_parent_context($coursecatcontext);
2309 // Save the custom field data.
2310 $data->id
= $course->id
;
2311 $handler->instance_form_save($data, true);
2319 * Please note this functions does not verify any access control,
2320 * the calling code is responsible for all validation (usually it is the form definition).
2322 * @param object $data - all the data needed for an entry in the 'course' table
2323 * @param array $editoroptions course description editor options
2326 function update_course($data, $editoroptions = NULL) {
2329 // Prevent changes on front page course.
2330 if ($data->id
== SITEID
) {
2331 throw new moodle_exception('invalidcourse', 'error');
2334 $oldcourse = course_get_format($data->id
)->get_course();
2335 $context = context_course
::instance($oldcourse->id
);
2337 // Make sure we're not changing whatever the course's relativedatesmode setting is.
2338 unset($data->relativedatesmode
);
2340 // Capture the updated fields for the log data.
2341 $updatedfields = [];
2342 foreach (get_object_vars($oldcourse) as $field => $value) {
2343 if ($field == 'summary_editor') {
2344 if (($data->$field)['text'] !== $value['text']) {
2345 // The summary might be very long, we don't wan't to fill up the log record with the full text.
2346 $updatedfields[$field] = '(updated)';
2348 } else if ($field == 'tags' && isset($data->tags
)) {
2349 // Tags might not have the same array keys, just check the values.
2350 if (array_values($data->$field) !== array_values($value)) {
2351 $updatedfields[$field] = $data->$field;
2354 if (isset($data->$field) && $data->$field != $value) {
2355 $updatedfields[$field] = $data->$field;
2360 $data->timemodified
= time();
2362 if ($editoroptions) {
2363 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2365 if ($overviewfilesoptions = course_overviewfiles_options($data->id
)) {
2366 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2369 // Check we don't have a duplicate shortname.
2370 if (!empty($data->shortname
) && $oldcourse->shortname
!= $data->shortname
) {
2371 if ($DB->record_exists_sql('SELECT id from {course} WHERE shortname = ? AND id <> ?', array($data->shortname
, $data->id
))) {
2372 throw new moodle_exception('shortnametaken', '', '', $data->shortname
);
2376 // Check we don't have a duplicate idnumber.
2377 if (!empty($data->idnumber
) && $oldcourse->idnumber
!= $data->idnumber
) {
2378 if ($DB->record_exists_sql('SELECT id from {course} WHERE idnumber = ? AND id <> ?', array($data->idnumber
, $data->id
))) {
2379 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber
);
2383 if ($errorcode = course_validate_dates((array)$data)) {
2384 throw new moodle_exception($errorcode);
2387 if (!isset($data->category
) or empty($data->category
)) {
2388 // prevent nulls and 0 in category field
2389 unset($data->category
);
2391 $changesincoursecat = $movecat = (isset($data->category
) and $oldcourse->category
!= $data->category
);
2393 if (!isset($data->visible
)) {
2394 // data not from form, add missing visibility info
2395 $data->visible
= $oldcourse->visible
;
2398 if ($data->visible
!= $oldcourse->visible
) {
2399 // reset the visibleold flag when manually hiding/unhiding course
2400 $data->visibleold
= $data->visible
;
2401 $changesincoursecat = true;
2404 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category
));
2405 if (empty($newcategory->visible
)) {
2406 // make sure when moving into hidden category the course is hidden automatically
2412 // Set newsitems to 0 if format does not support announcements.
2413 if (isset($data->format
)) {
2414 $newcourseformat = course_get_format((object)['format' => $data->format
]);
2415 if (!$newcourseformat->supports_news()) {
2416 $data->newsitems
= 0;
2420 // Set showcompletionconditions to null when completion tracking has been disabled for the course.
2421 if (isset($data->enablecompletion
) && $data->enablecompletion
== COMPLETION_DISABLED
) {
2422 $data->showcompletionconditions
= null;
2425 // Check if provider is selected.
2426 $provider = $data->selectedcommunication ??
null;
2427 // If the course moved to hidden category, set provider to none.
2428 if ($changesincoursecat && empty($data->visible
)) {
2432 // Attempt to get the communication provider if it wasn't provided in the data.
2433 if (empty($provider) && core_communication\api
::is_available()) {
2434 $provider = \core_communication\api
::load_by_instance('core_course', 'coursecommunication', $data->id
)->get_provider();
2437 // Communication api call.
2438 if (!empty($provider) && core_communication\api
::is_available()) {
2439 // Prepare the communication api data.
2440 $courseimage = course_get_courseimage($data);
2442 // This nasty logic is here because of hide course doesn't pass anything in the data object.
2443 if (!empty($data->communicationroomname
)) {
2444 $communicationroomname = $data->communicationroomname
;
2446 $communicationroomname = $data->fullname ??
$oldcourse->fullname
;
2449 // Update communication room membership of enrolled users.
2450 require_once($CFG->libdir
. '/enrollib.php');
2451 $courseusers = enrol_get_course_users($data->id
);
2452 $enrolledusers = [];
2454 foreach ($courseusers as $user) {
2455 $enrolledusers[] = $user->id
;
2458 $communication = \core_communication\api
::load_by_instance(
2460 'coursecommunication',
2464 $addafterupdate = false;
2465 if ($provider !== $communication->get_provider()) {
2466 // If provider set to none, remove all the members.
2467 if ($provider === 'none') {
2468 $communication->remove_members_from_room($enrolledusers);
2470 // If previous provider was not none and current provider is not none, but a different provider, remove members.
2471 $communication->get_provider() !== '' &&
2472 $communication->get_provider() !== 'none' &&
2473 $provider !== $communication->get_provider()
2475 $communication->remove_members_from_room($enrolledusers);
2476 $addafterupdate = true;
2478 // If previous provider was none and current provider is not none, but a different provider, remove members.
2479 ($communication->get_provider() === '' ||
$communication->get_provider() === 'none') &&
2480 $provider !== $communication->get_provider()
2482 $addafterupdate = true;
2486 $communication->update_room($provider, $communicationroomname, $courseimage, $data);
2487 if ($addafterupdate) {
2488 $communication->add_members_to_room($enrolledusers, false);
2492 // Update custom fields if there are any of them in the form.
2493 $handler = core_course\customfield\course_handler
::create();
2494 $handler->instance_form_save($data);
2496 // Update with the new data
2497 $DB->update_record('course', $data);
2498 // make sure the modinfo cache is reset
2499 rebuild_course_cache($data->id
);
2501 // Purge course image cache in case if course image has been updated.
2502 \cache
::make('core', 'course_image')->delete($data->id
);
2504 // update course format options with full course data
2505 course_get_format($data->id
)->update_course_format_options($data, $oldcourse);
2507 $course = $DB->get_record('course', array('id'=>$data->id
));
2510 $newparent = context_coursecat
::instance($course->category
);
2511 $context->update_moved($newparent);
2513 $fixcoursesortorder = $movecat ||
(isset($data->sortorder
) && ($oldcourse->sortorder
!= $data->sortorder
));
2514 if ($fixcoursesortorder) {
2515 fix_course_sortorder();
2518 // purge appropriate caches in case fix_course_sortorder() did not change anything
2519 cache_helper
::purge_by_event('changesincourse');
2520 if ($changesincoursecat) {
2521 cache_helper
::purge_by_event('changesincoursecat');
2524 // Test for and remove blocks which aren't appropriate anymore
2525 blocks_remove_inappropriate($course);
2527 // Save any custom role names.
2528 save_local_role_names($course->id
, $data);
2530 // update enrol settings
2531 enrol_course_updated(false, $course, $data);
2533 // Update course tags.
2534 if (isset($data->tags
)) {
2535 core_tag_tag
::set_item_tags('core', 'course', $course->id
, context_course
::instance($course->id
), $data->tags
);
2538 // Trigger a course updated event.
2539 $event = \core\event\course_updated
::create(array(
2540 'objectid' => $course->id
,
2541 'context' => context_course
::instance($course->id
),
2542 'other' => array('shortname' => $course->shortname
,
2543 'fullname' => $course->fullname
,
2544 'updatedfields' => $updatedfields)
2549 if ($oldcourse->format
!== $course->format
) {
2550 // Remove all options stored for the previous format
2551 // We assume that new course format migrated everything it needed watching trigger
2552 // 'course_updated' and in method format_XXX::update_course_format_options()
2553 $DB->delete_records('course_format_options',
2554 array('courseid' => $course->id
, 'format' => $oldcourse->format
));
2559 * Calculate the average number of enrolled participants per course.
2561 * This is intended for statistics purposes during the site registration. Only visible courses are taken into account.
2562 * Front page enrolments are excluded.
2564 * @param bool $onlyactive Consider only active enrolments in enabled plugins and obey the enrolment time restrictions.
2565 * @param int $lastloginsince If specified, count only users who logged in after this timestamp.
2568 function average_number_of_participants(bool $onlyactive = false, int $lastloginsince = null): float {
2573 $sql = "SELECT DISTINCT ue.userid, e.courseid
2574 FROM {user_enrolments} ue
2575 JOIN {enrol} e ON e.id = ue.enrolid
2576 JOIN {course} c ON c.id = e.courseid ";
2578 if ($onlyactive ||
$lastloginsince) {
2579 $sql .= "JOIN {user} u ON u.id = ue.userid ";
2582 $sql .= "WHERE e.courseid <> " . SITEID
. " AND c.visible = 1 ";
2585 $sql .= "AND ue.status = :active
2586 AND e.status = :enabled
2587 AND ue.timestart < :now1
2588 AND (ue.timeend = 0 OR ue.timeend > :now2) ";
2590 // Same as in the enrollib - the rounding should help caching in the database.
2591 $now = round(time(), -2);
2594 'active' => ENROL_USER_ACTIVE
,
2595 'enabled' => ENROL_INSTANCE_ENABLED
,
2601 if ($lastloginsince) {
2602 $sql .= "AND u.lastlogin > :lastlogin ";
2603 $params['lastlogin'] = $lastloginsince;
2606 $sql = "SELECT COUNT(*)
2609 $enrolmenttotal = $DB->count_records_sql($sql, $params);
2611 // Get the number of visible courses (exclude the front page).
2612 $coursetotal = $DB->count_records('course', ['visible' => 1]);
2613 $coursetotal = $coursetotal - 1;
2615 if (empty($coursetotal)) {
2616 $participantaverage = 0;
2619 $participantaverage = $enrolmenttotal / $coursetotal;
2622 return $participantaverage;
2626 * Average number of course modules
2629 function average_number_of_courses_modules() {
2632 //count total of visible course module (except front page)
2633 $sql = 'SELECT COUNT(*) FROM (
2634 SELECT cm.course, cm.module
2635 FROM {course} c, {course_modules} cm
2636 WHERE c.id = cm.course
2639 AND c.visible = 1) total';
2640 $params = array('siteid' => $SITE->id
);
2641 $moduletotal = $DB->count_records_sql($sql, $params);
2644 //count total of visible courses (minus front page)
2645 $coursetotal = $DB->count_records('course', array('visible' => 1));
2646 $coursetotal = $coursetotal - 1 ;
2648 //average of course module
2649 if (empty($coursetotal)) {
2650 $coursemoduleaverage = 0;
2652 $coursemoduleaverage = $moduletotal / $coursetotal;
2655 return $coursemoduleaverage;
2659 * This class pertains to course requests and contains methods associated with
2660 * create, approving, and removing course requests.
2662 * Please note we do not allow embedded images here because there is no context
2663 * to store them with proper access control.
2665 * @copyright 2009 Sam Hemelryk
2666 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2669 * @property-read int $id
2670 * @property-read string $fullname
2671 * @property-read string $shortname
2672 * @property-read string $summary
2673 * @property-read int $summaryformat
2674 * @property-read int $summarytrust
2675 * @property-read string $reason
2676 * @property-read int $requester
2678 class course_request
{
2681 * This is the stdClass that stores the properties for the course request
2682 * and is externally accessed through the __get magic method
2685 protected $properties;
2688 * An array of options for the summary editor used by course request forms.
2689 * This is initially set by {@link summary_editor_options()}
2693 protected static $summaryeditoroptions;
2696 * Static function to prepare the summary editor for working with a course
2700 * @param null|stdClass $data Optional, an object containing the default values
2701 * for the form, these may be modified when preparing the
2702 * editor so this should be called before creating the form
2703 * @return stdClass An object that can be used to set the default values for
2706 public static function prepare($data=null) {
2707 if ($data === null) {
2708 $data = new stdClass
;
2710 $data = file_prepare_standard_editor($data, 'summary', self
::summary_editor_options());
2715 * Static function to create a new course request when passed an array of properties
2718 * This function also handles saving any files that may have been used in the editor
2721 * @param stdClass $data
2722 * @return course_request The newly created course request
2724 public static function create($data) {
2725 global $USER, $DB, $CFG;
2726 $data->requester
= $USER->id
;
2728 // Setting the default category if none set.
2729 if (empty($data->category
) ||
!empty($CFG->lockrequestcategory
)) {
2730 $data->category
= $CFG->defaultrequestcategory
;
2733 // Summary is a required field so copy the text over
2734 $data->summary
= $data->summary_editor
['text'];
2735 $data->summaryformat
= $data->summary_editor
['format'];
2737 $data->id
= $DB->insert_record('course_request', $data);
2739 // Create a new course_request object and return it
2740 $request = new course_request($data);
2742 // Notify the admin if required.
2743 if ($users = get_users_from_config($CFG->courserequestnotify
, 'moodle/site:approvecourse')) {
2746 $a->link
= "$CFG->wwwroot/course/pending.php";
2747 $a->user
= fullname($USER);
2748 $subject = get_string('courserequest');
2749 $message = get_string('courserequestnotifyemail', 'admin', $a);
2750 foreach ($users as $user) {
2751 $request->notify($user, $USER, 'courserequested', $subject, $message);
2759 * Returns an array of options to use with a summary editor
2761 * @uses course_request::$summaryeditoroptions
2762 * @return array An array of options to use with the editor
2764 public static function summary_editor_options() {
2766 if (self
::$summaryeditoroptions === null) {
2767 self
::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
2769 return self
::$summaryeditoroptions;
2773 * Loads the properties for this course request object. Id is required and if
2774 * only id is provided then we load the rest of the properties from the database
2776 * @param stdClass|int $properties Either an object containing properties
2777 * or the course_request id to load
2779 public function __construct($properties) {
2781 if (empty($properties->id
)) {
2782 if (empty($properties)) {
2783 throw new coding_exception('You must provide a course request id when creating a course_request object');
2786 $properties = new stdClass
;
2787 $properties->id
= (int)$id;
2790 if (empty($properties->requester
)) {
2791 if (!($this->properties
= $DB->get_record('course_request', array('id' => $properties->id
)))) {
2792 throw new \
moodle_exception('unknowncourserequest');
2795 $this->properties
= $properties;
2797 $this->properties
->collision
= null;
2801 * Returns the requested property
2803 * @param string $key
2806 public function __get($key) {
2807 return $this->properties
->$key;
2811 * Override this to ensure empty($request->blah) calls return a reliable answer...
2813 * This is required because we define the __get method
2816 * @return bool True is it not empty, false otherwise
2818 public function __isset($key) {
2819 return (!empty($this->properties
->$key));
2823 * Returns the user who requested this course
2825 * Uses a static var to cache the results and cut down the number of db queries
2827 * @staticvar array $requesters An array of cached users
2828 * @return stdClass The user who requested the course
2830 public function get_requester() {
2832 static $requesters= array();
2833 if (!array_key_exists($this->properties
->requester
, $requesters)) {
2834 $requesters[$this->properties
->requester
] = $DB->get_record('user', array('id'=>$this->properties
->requester
));
2836 return $requesters[$this->properties
->requester
];
2840 * Checks that the shortname used by the course does not conflict with any other
2841 * courses that exist
2843 * @param string|null $shortnamemark The string to append to the requests shortname
2844 * should a conflict be found
2845 * @return bool true is there is a conflict, false otherwise
2847 public function check_shortname_collision($shortnamemark = '[*]') {
2850 if ($this->properties
->collision
!== null) {
2851 return $this->properties
->collision
;
2854 if (empty($this->properties
->shortname
)) {
2855 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER
);
2856 $this->properties
->collision
= false;
2857 } else if ($DB->record_exists('course', array('shortname' => $this->properties
->shortname
))) {
2858 if (!empty($shortnamemark)) {
2859 $this->properties
->shortname
.= ' '.$shortnamemark;
2861 $this->properties
->collision
= true;
2863 $this->properties
->collision
= false;
2865 return $this->properties
->collision
;
2869 * Checks user capability to approve a requested course
2871 * If course was requested without category for some reason (might happen if $CFG->defaultrequestcategory is
2872 * misconfigured), we check capabilities 'moodle/site:approvecourse' and 'moodle/course:changecategory'.
2876 public function can_approve() {
2879 if ($this->properties
->category
) {
2880 $category = core_course_category
::get($this->properties
->category
, IGNORE_MISSING
);
2881 } else if ($CFG->defaultrequestcategory
) {
2882 $category = core_course_category
::get($CFG->defaultrequestcategory
, IGNORE_MISSING
);
2885 return has_capability('moodle/site:approvecourse', $category->get_context());
2888 // We can not determine the context where the course should be created. The approver should have
2889 // both capabilities to approve courses and change course category in the system context.
2890 return has_all_capabilities(['moodle/site:approvecourse', 'moodle/course:changecategory'], context_system
::instance());
2894 * Returns the category where this course request should be created
2896 * Note that we don't check here that user has a capability to view
2897 * hidden categories if he has capabilities 'moodle/site:approvecourse' and
2898 * 'moodle/course:changecategory'
2900 * @return core_course_category
2902 public function get_category() {
2904 if ($this->properties
->category
&& ($category = core_course_category
::get($this->properties
->category
, IGNORE_MISSING
))) {
2906 } else if ($CFG->defaultrequestcategory
&&
2907 ($category = core_course_category
::get($CFG->defaultrequestcategory
, IGNORE_MISSING
))) {
2910 return core_course_category
::get_default();
2915 * This function approves the request turning it into a course
2917 * This function converts the course request into a course, at the same time
2918 * transferring any files used in the summary to the new course and then removing
2919 * the course request and the files associated with it.
2921 * @return int The id of the course that was created from this request
2923 public function approve() {
2924 global $CFG, $DB, $USER;
2926 require_once($CFG->dirroot
. '/backup/util/includes/restore_includes.php');
2928 $user = $DB->get_record('user', array('id' => $this->properties
->requester
, 'deleted'=>0), '*', MUST_EXIST
);
2930 $courseconfig = get_config('moodlecourse');
2932 // Transfer appropriate settings
2933 $data = clone($this->properties
);
2935 unset($data->reason
);
2936 unset($data->requester
);
2939 $category = $this->get_category();
2940 $data->category
= $category->id
;
2941 // Set misc settings
2942 $data->requested
= 1;
2944 // Apply course default settings
2945 $data->format
= $courseconfig->format
;
2946 $data->newsitems
= $courseconfig->newsitems
;
2947 $data->showgrades
= $courseconfig->showgrades
;
2948 $data->showreports
= $courseconfig->showreports
;
2949 $data->maxbytes
= $courseconfig->maxbytes
;
2950 $data->groupmode
= $courseconfig->groupmode
;
2951 $data->groupmodeforce
= $courseconfig->groupmodeforce
;
2952 $data->visible
= $courseconfig->visible
;
2953 $data->visibleold
= $data->visible
;
2954 $data->lang
= $courseconfig->lang
;
2955 $data->enablecompletion
= $courseconfig->enablecompletion
;
2956 $data->numsections
= $courseconfig->numsections
;
2957 $data->startdate
= usergetmidnight(time());
2958 if ($courseconfig->courseenddateenabled
) {
2959 $data->enddate
= usergetmidnight(time()) +
$courseconfig->courseduration
;
2962 list($data->fullname
, $data->shortname
) = restore_dbops
::calculate_course_names(0, $data->fullname
, $data->shortname
);
2964 $course = create_course($data);
2965 $context = context_course
::instance($course->id
, MUST_EXIST
);
2967 // add enrol instances
2968 if (!$DB->record_exists('enrol', array('courseid'=>$course->id
, 'enrol'=>'manual'))) {
2969 if ($manual = enrol_get_plugin('manual')) {
2970 $manual->add_default_instance($course);
2974 // enrol the requester as teacher if necessary
2975 if (!empty($CFG->creatornewroleid
) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
2976 enrol_try_internal_enrol($course->id
, $user->id
, $CFG->creatornewroleid
);
2981 $a = new stdClass();
2982 $a->name
= format_string($course->fullname
, true, array('context' => context_course
::instance($course->id
)));
2983 $a->url
= $CFG->wwwroot
.'/course/view.php?id=' . $course->id
;
2984 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a), $course->id
);
2990 * Reject a course request
2992 * This function rejects a course request, emailing the requesting user the
2993 * provided notice and then removing the request from the database
2995 * @param string $notice The message to display to the user
2997 public function reject($notice) {
2999 $user = $DB->get_record('user', array('id' => $this->properties
->requester
), '*', MUST_EXIST
);
3000 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
3005 * Deletes the course request and any associated files
3007 public function delete() {
3009 $DB->delete_records('course_request', array('id' => $this->properties
->id
));
3013 * Send a message from one user to another using events_trigger
3015 * @param object $touser
3016 * @param object $fromuser
3017 * @param string $name
3018 * @param string $subject
3019 * @param string $message
3020 * @param int|null $courseid
3022 protected function notify($touser, $fromuser, $name, $subject, $message, $courseid = null) {
3023 $eventdata = new \core\message\
message();
3024 $eventdata->courseid
= empty($courseid) ? SITEID
: $courseid;
3025 $eventdata->component
= 'moodle';
3026 $eventdata->name
= $name;
3027 $eventdata->userfrom
= $fromuser;
3028 $eventdata->userto
= $touser;
3029 $eventdata->subject
= $subject;
3030 $eventdata->fullmessage
= $message;
3031 $eventdata->fullmessageformat
= FORMAT_PLAIN
;
3032 $eventdata->fullmessagehtml
= '';
3033 $eventdata->smallmessage
= '';
3034 $eventdata->notification
= 1;
3035 message_send($eventdata);
3039 * Checks if current user can request a course in this context
3041 * @param context $context
3044 public static function can_request(context
$context) {
3046 if (empty($CFG->enablecourserequests
)) {
3049 if (has_capability('moodle/course:create', $context)) {
3053 if ($context instanceof context_system
) {
3054 $defaultcontext = context_coursecat
::instance($CFG->defaultrequestcategory
, IGNORE_MISSING
);
3055 return $defaultcontext &&
3056 has_capability('moodle/course:request', $defaultcontext);
3057 } else if ($context instanceof context_coursecat
) {
3058 if (!$CFG->lockrequestcategory ||
$CFG->defaultrequestcategory
== $context->instanceid
) {
3059 return has_capability('moodle/course:request', $context);
3067 * Return a list of page types
3068 * @param string $pagetype current page type
3069 * @param context $parentcontext Block's parent context
3070 * @param context $currentcontext Current context of block
3071 * @return array array of page types
3073 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
3074 if ($pagetype === 'course-index' ||
$pagetype === 'course-index-category') {
3075 // For courses and categories browsing pages (/course/index.php) add option to show on ANY category page
3076 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
3077 'course-index-*' => get_string('page-course-index-x', 'pagetype'),
3079 } else if ($currentcontext && (!($coursecontext = $currentcontext->get_course_context(false)) ||
$coursecontext->instanceid
== SITEID
)) {
3080 // We know for sure that despite pagetype starts with 'course-' this is not a page in course context (i.e. /course/search.php, etc.)
3081 $pagetypes = array('*' => get_string('page-x', 'pagetype'));
3083 // Otherwise consider it a page inside a course even if $currentcontext is null
3084 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
3085 'course-*' => get_string('page-course-x', 'pagetype'),
3086 'course-view-*' => get_string('page-course-view-x', 'pagetype')
3093 * Determine whether course ajax should be enabled for the specified course
3095 * @param stdClass $course The course to test against
3096 * @return boolean Whether course ajax is enabled or note
3098 function course_ajax_enabled($course) {
3099 global $CFG, $PAGE, $SITE;
3101 // The user must be editing for AJAX to be included
3102 if (!$PAGE->user_is_editing()) {
3106 // Check that the theme suports
3107 if (!$PAGE->theme
->enablecourseajax
) {
3111 // Check that the course format supports ajax functionality
3112 // The site 'format' doesn't have information on course format support
3113 if ($SITE->id
!== $course->id
) {
3114 $courseformatajaxsupport = course_format_ajax_support($course->format
);
3115 if (!$courseformatajaxsupport->capable
) {
3120 // All conditions have been met so course ajax should be enabled
3125 * Include the relevant javascript and language strings for the resource
3126 * toolbox YUI module
3128 * @param integer $id The ID of the course being applied to
3129 * @param array $usedmodules An array containing the names of the modules in use on the page
3130 * @param array $enabledmodules An array containing the names of the enabled (visible) modules on this site
3131 * @param stdClass $config An object containing configuration parameters for ajax modules including:
3132 * * resourceurl The URL to post changes to for resource changes
3133 * * sectionurl The URL to post changes to for section changes
3134 * * pageparams Additional parameters to pass through in the post
3137 function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) {
3138 global $CFG, $PAGE, $SITE;
3140 // Init the course editor module to support UI components.
3141 $format = course_get_format($course);
3142 include_course_editor($format);
3144 // Ensure that ajax should be included
3145 if (!course_ajax_enabled($course)) {
3149 // Component based formats don't use YUI drag and drop anymore.
3150 if (!$format->supports_components() && course_format_uses_sections($course->format
)) {
3153 $config = new stdClass();
3156 // The URL to use for resource changes.
3157 if (!isset($config->resourceurl
)) {
3158 $config->resourceurl
= '/course/rest.php';
3161 // The URL to use for section changes.
3162 if (!isset($config->sectionurl
)) {
3163 $config->sectionurl
= '/course/rest.php';
3166 // Any additional parameters which need to be included on page submission.
3167 if (!isset($config->pageparams
)) {
3168 $config->pageparams
= array();
3171 $PAGE->requires
->yui_module('moodle-course-dragdrop', 'M.course.init_section_dragdrop',
3173 'courseid' => $course->id
,
3174 'ajaxurl' => $config->sectionurl
,
3175 'config' => $config,
3178 $PAGE->requires
->yui_module('moodle-course-dragdrop', 'M.course.init_resource_dragdrop',
3180 'courseid' => $course->id
,
3181 'ajaxurl' => $config->resourceurl
,
3182 'config' => $config,
3185 // Require various strings for the command toolbox.
3186 $PAGE->requires
->strings_for_js(array(
3189 'deletechecktypename',
3191 'edittitleinstructions',
3203 'movecoursesection',
3206 'emptydragdropregion',
3212 // Include section-specific strings for formats which support sections.
3213 if (course_format_uses_sections($course->format
)) {
3214 $PAGE->requires
->strings_for_js(array(
3217 ), 'format_' . $course->format
);
3220 // For confirming resource deletion we need the name of the module in question.
3221 foreach ($usedmodules as $module => $modname) {
3222 $PAGE->requires
->string_for_js('pluginname', $module);
3225 // Load drag and drop upload AJAX.
3226 require_once($CFG->dirroot
.'/course/dnduploadlib.php');
3227 dndupload_add_to_course($course, $enabledmodules);
3230 $PAGE->requires
->js_call_amd('core_course/actions', 'initCoursePage', array($course->format
));
3236 * Include and configure the course editor modules.
3238 * @param course_format $format the course format instance.
3240 function include_course_editor(course_format
$format) {
3241 global $PAGE, $SITE;
3243 $course = $format->get_course();
3245 if ($SITE->id
=== $course->id
) {
3249 $statekey = course_format
::session_cache($course);
3251 // Edition mode and some format specs must be passed to the init method.
3253 'editing' => $format->show_editor(),
3254 'supportscomponents' => $format->supports_components(),
3255 'statekey' => $statekey,
3256 'overriddenStrings' => $format->get_editor_custom_strings(),
3258 // All the new editor elements will be loaded after the course is presented and
3259 // the initial course state will be generated using core_course_get_state webservice.
3260 $PAGE->requires
->js_call_amd('core_courseformat/courseeditor', 'setViewFormat', [$course->id
, $setup]);
3264 * Returns the sorted list of available course formats, filtered by enabled if necessary
3266 * @param bool $enabledonly return only formats that are enabled
3267 * @return array array of sorted format names
3269 function get_sorted_course_formats($enabledonly = false) {
3271 $formats = core_component
::get_plugin_list('format');
3273 if (!empty($CFG->format_plugins_sortorder
)) {
3274 $order = explode(',', $CFG->format_plugins_sortorder
);
3275 $order = array_merge(array_intersect($order, array_keys($formats)),
3276 array_diff(array_keys($formats), $order));
3278 $order = array_keys($formats);
3280 if (!$enabledonly) {
3283 $sortedformats = array();
3284 foreach ($order as $formatname) {
3285 if (!get_config('format_'.$formatname, 'disabled')) {
3286 $sortedformats[] = $formatname;
3289 return $sortedformats;
3293 * The URL to use for the specified course (with section)
3295 * @param int|stdClass $courseorid The course to get the section name for (either object or just course id)
3296 * @param int|stdClass $section Section object from database or just field course_sections.section
3297 * if omitted the course view page is returned
3298 * @param array $options options for view URL. At the moment core uses:
3299 * 'navigation' (bool) if true and section has no separate page, the function returns null
3300 * 'sr' (int) used by multipage formats to specify to which section to return
3301 * @return moodle_url The url of course
3303 function course_get_url($courseorid, $section = null, $options = array()) {
3304 return course_get_format($courseorid)->get_view_url($section, $options);
3311 * - capability checks and other checks
3312 * - create the module from the module info
3314 * @param object $module
3315 * @return object the created module info
3316 * @throws moodle_exception if user is not allowed to perform the action or module is not allowed in this course
3318 function create_module($moduleinfo) {
3321 require_once($CFG->dirroot
. '/course/modlib.php');
3323 // Check manadatory attributs.
3324 $mandatoryfields = array('modulename', 'course', 'section', 'visible');
3325 if (plugin_supports('mod', $moduleinfo->modulename
, FEATURE_MOD_INTRO
, true)) {
3326 $mandatoryfields[] = 'introeditor';
3328 foreach($mandatoryfields as $mandatoryfield) {
3329 if (!isset($moduleinfo->{$mandatoryfield})) {
3330 throw new moodle_exception('createmodulemissingattribut', '', '', $mandatoryfield);
3334 // Some additional checks (capability / existing instances).
3335 $course = $DB->get_record('course', array('id'=>$moduleinfo->course
), '*', MUST_EXIST
);
3336 list($module, $context, $cw) = can_add_moduleinfo($course, $moduleinfo->modulename
, $moduleinfo->section
);
3339 $moduleinfo->module
= $module->id
;
3340 $moduleinfo = add_moduleinfo($moduleinfo, $course, null);
3349 * - capability and other checks
3350 * - update the module
3352 * @param object $module
3353 * @return object the updated module info
3354 * @throws moodle_exception if current user is not allowed to update the module
3356 function update_module($moduleinfo) {
3359 require_once($CFG->dirroot
. '/course/modlib.php');
3361 // Check the course module exists.
3362 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule
, 0, false, MUST_EXIST
);
3364 // Check the course exists.
3365 $course = $DB->get_record('course', array('id'=>$cm->course
), '*', MUST_EXIST
);
3367 // Some checks (capaibility / existing instances).
3368 list($cm, $context, $module, $data, $cw) = can_update_moduleinfo($cm);
3370 // Retrieve few information needed by update_moduleinfo.
3371 $moduleinfo->modulename
= $cm->modname
;
3372 if (!isset($moduleinfo->scale
)) {
3373 $moduleinfo->scale
= 0;
3375 $moduleinfo->type
= 'mod';
3377 // Update the module.
3378 list($cm, $moduleinfo) = update_moduleinfo($cm, $moduleinfo, $course, null);
3384 * Duplicate a module on the course for ajax.
3386 * @see mod_duplicate_module()
3387 * @param object $course The course
3388 * @param object $cm The course module to duplicate
3389 * @param int $sr The section to link back to (used for creating the links)
3390 * @throws moodle_exception if the plugin doesn't support duplication
3391 * @return Object containing:
3392 * - fullcontent: The HTML markup for the created CM
3393 * - cmid: The CMID of the newly created CM
3394 * - redirect: Whether to trigger a redirect following this change
3396 function mod_duplicate_activity($course, $cm, $sr = null) {
3399 $newcm = duplicate_module($course, $cm);
3401 $resp = new stdClass();
3404 $format = course_get_format($course);
3405 $renderer = $format->get_renderer($PAGE);
3406 $modinfo = $format->get_modinfo();
3407 $section = $modinfo->get_section_info($newcm->sectionnum
);
3409 // Get the new element html content.
3410 $resp->fullcontent
= $renderer->course_section_updated_cm_item($format, $section, $newcm);
3412 $resp->cmid
= $newcm->id
;
3414 // Trigger a redirect.
3415 $resp->redirect
= true;
3421 * Api to duplicate a module.
3423 * @param object $course course object.
3424 * @param object $cm course module object to be duplicated.
3425 * @param int $sectionid section ID new course module will be placed in.
3426 * @param bool $changename updates module name with text from duplicatedmodule lang string.
3430 * @throws coding_exception
3431 * @throws moodle_exception
3432 * @throws restore_controller_exception
3434 * @return cm_info|null cminfo object if we sucessfully duplicated the mod and found the new cm.
3436 function duplicate_module($course, $cm, int $sectionid = null, bool $changename = true): ?cm_info
{
3437 global $CFG, $DB, $USER;
3438 require_once($CFG->dirroot
. '/backup/util/includes/backup_includes.php');
3439 require_once($CFG->dirroot
. '/backup/util/includes/restore_includes.php');
3440 require_once($CFG->libdir
. '/filelib.php');
3442 $a = new stdClass();
3443 $a->modtype
= get_string('modulename', $cm->modname
);
3444 $a->modname
= format_string($cm->name
);
3446 if (!plugin_supports('mod', $cm->modname
, FEATURE_BACKUP_MOODLE2
)) {
3447 throw new moodle_exception('duplicatenosupport', 'error', '', $a);
3450 // Backup the activity.
3452 $bc = new backup_controller(backup
::TYPE_1ACTIVITY
, $cm->id
, backup
::FORMAT_MOODLE
,
3453 backup
::INTERACTIVE_NO
, backup
::MODE_IMPORT
, $USER->id
);
3455 $backupid = $bc->get_backupid();
3456 $backupbasepath = $bc->get_plan()->get_basepath();
3458 $bc->execute_plan();
3462 // Restore the backup immediately.
3464 $rc = new restore_controller($backupid, $course->id
,
3465 backup
::INTERACTIVE_NO
, backup
::MODE_IMPORT
, $USER->id
, backup
::TARGET_CURRENT_ADDING
);
3467 // Make sure that the restore_general_groups setting is always enabled when duplicating an activity.
3468 $plan = $rc->get_plan();
3469 $groupsetting = $plan->get_setting('groups');
3470 if (empty($groupsetting->get_value())) {
3471 $groupsetting->set_value(true);
3474 $cmcontext = context_module
::instance($cm->id
);
3475 if (!$rc->execute_precheck()) {
3476 $precheckresults = $rc->get_precheck_results();
3477 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
3478 if (empty($CFG->keeptempdirectoriesonbackup
)) {
3479 fulldelete($backupbasepath);
3484 $rc->execute_plan();
3486 // Now a bit hacky part follows - we try to get the cmid of the newly
3487 // restored copy of the module.
3489 $tasks = $rc->get_plan()->get_tasks();
3490 foreach ($tasks as $task) {
3491 if (is_subclass_of($task, 'restore_activity_task')) {
3492 if ($task->get_old_contextid() == $cmcontext->id
) {
3493 $newcmid = $task->get_moduleid();
3501 if (empty($CFG->keeptempdirectoriesonbackup
)) {
3502 fulldelete($backupbasepath);
3505 // If we know the cmid of the new course module, let us move it
3506 // right below the original one. otherwise it will stay at the
3507 // end of the section.
3509 // Proceed with activity renaming before everything else. We don't use APIs here to avoid
3510 // triggering a lot of create/update duplicated events.
3511 $newcm = get_coursemodule_from_id($cm->modname
, $newcmid, $cm->course
);
3513 // Add ' (copy)' language string postfix to duplicated module.
3514 $newname = get_string('duplicatedmodule', 'moodle', $newcm->name
);
3515 set_coursemodule_name($newcm->id
, $newname);
3518 $section = $DB->get_record('course_sections', ['id' => $sectionid ??
$cm->section
, 'course' => $cm->course
]);
3519 if (isset($sectionid)) {
3520 moveto_module($newcm, $section);
3522 $modarray = explode(",", trim($section->sequence
));
3523 $cmindex = array_search($cm->id
, $modarray);
3524 if ($cmindex !== false && $cmindex < count($modarray) - 1) {
3525 moveto_module($newcm, $section, $modarray[$cmindex +
1]);
3529 // Update calendar events with the duplicated module.
3530 // The following line is to be removed in MDL-58906.
3531 course_module_update_calendar_events($newcm->modname
, null, $newcm);
3533 // Trigger course module created event. We can trigger the event only if we know the newcmid.
3534 $newcm = get_fast_modinfo($cm->course
)->get_cm($newcmid);
3535 $event = \core\event\course_module_created
::create_from_cm($newcm);
3539 return isset($newcm) ?
$newcm : null;
3543 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3544 * Sorts by descending order of time.
3546 * @param stdClass $a First object
3547 * @param stdClass $b Second object
3548 * @return int 0,1,-1 representing the order
3550 function compare_activities_by_time_desc($a, $b) {
3551 // Make sure the activities actually have a timestamp property.
3552 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3555 // We treat instances without timestamp as if they have a timestamp of 0.
3556 if ((!property_exists($a, 'timestamp')) && (property_exists($b,'timestamp'))) {
3559 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3562 if ($a->timestamp
== $b->timestamp
) {
3565 return ($a->timestamp
> $b->timestamp
) ?
-1 : 1;
3569 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3570 * Sorts by ascending order of time.
3572 * @param stdClass $a First object
3573 * @param stdClass $b Second object
3574 * @return int 0,1,-1 representing the order
3576 function compare_activities_by_time_asc($a, $b) {
3577 // Make sure the activities actually have a timestamp property.
3578 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3581 // We treat instances without timestamp as if they have a timestamp of 0.
3582 if ((!property_exists($a, 'timestamp')) && (property_exists($b, 'timestamp'))) {
3585 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3588 if ($a->timestamp
== $b->timestamp
) {
3591 return ($a->timestamp
< $b->timestamp
) ?
-1 : 1;
3595 * Changes the visibility of a course.
3597 * @param int $courseid The course to change.
3598 * @param bool $show True to make it visible, false otherwise.
3601 function course_change_visibility($courseid, $show = true) {
3602 $course = new stdClass
;
3603 $course->id
= $courseid;
3604 $course->visible
= ($show) ?
'1' : '0';
3605 $course->visibleold
= $course->visible
;
3606 update_course($course);
3611 * Changes the course sortorder by one, moving it up or down one in respect to sort order.
3613 * @param stdClass|core_course_list_element $course
3614 * @param bool $up If set to true the course will be moved up one. Otherwise down one.
3617 function course_change_sortorder_by_one($course, $up) {
3619 $params = array($course->sortorder
, $course->category
);
3621 $select = 'sortorder < ? AND category = ?';
3622 $sort = 'sortorder DESC';
3624 $select = 'sortorder > ? AND category = ?';
3625 $sort = 'sortorder ASC';
3627 fix_course_sortorder();
3628 $swapcourse = $DB->get_records_select('course', $select, $params, $sort, '*', 0, 1);
3630 $swapcourse = reset($swapcourse);
3631 $DB->set_field('course', 'sortorder', $swapcourse->sortorder
, array('id' => $course->id
));
3632 $DB->set_field('course', 'sortorder', $course->sortorder
, array('id' => $swapcourse->id
));
3633 // Finally reorder courses.
3634 fix_course_sortorder();
3635 cache_helper
::purge_by_event('changesincourse');
3642 * Changes the sort order of courses in a category so that the first course appears after the second.
3644 * @param int|stdClass $courseorid The course to focus on.
3645 * @param int $moveaftercourseid The course to shifter after or 0 if you want it to be the first course in the category.
3648 function course_change_sortorder_after_course($courseorid, $moveaftercourseid) {
3651 if (!is_object($courseorid)) {
3652 $course = get_course($courseorid);
3654 $course = $courseorid;
3657 if ((int)$moveaftercourseid === 0) {
3658 // We've moving the course to the start of the queue.
3659 $sql = 'SELECT sortorder
3661 WHERE category = :categoryid
3662 ORDER BY sortorder';
3664 'categoryid' => $course->category
3666 $sortorder = $DB->get_field_sql($sql, $params, IGNORE_MULTIPLE
);
3668 $sql = 'UPDATE {course}
3669 SET sortorder = sortorder + 1
3670 WHERE category = :categoryid
3673 'categoryid' => $course->category
,
3674 'id' => $course->id
,
3676 $DB->execute($sql, $params);
3677 $DB->set_field('course', 'sortorder', $sortorder, array('id' => $course->id
));
3678 } else if ($course->id
=== $moveaftercourseid) {
3679 // They're the same - moronic.
3680 debugging("Invalid move after course given.", DEBUG_DEVELOPER
);
3683 // Moving this course after the given course. It could be before it could be after.
3684 $moveaftercourse = get_course($moveaftercourseid);
3685 if ($course->category
!== $moveaftercourse->category
) {
3686 debugging("Cannot re-order courses. The given courses do not belong to the same category.", DEBUG_DEVELOPER
);
3689 // Increment all courses in the same category that are ordered after the moveafter course.
3690 // This makes a space for the course we're moving.
3691 $sql = 'UPDATE {course}
3692 SET sortorder = sortorder + 1
3693 WHERE category = :categoryid
3694 AND sortorder > :sortorder';
3696 'categoryid' => $moveaftercourse->category
,
3697 'sortorder' => $moveaftercourse->sortorder
3699 $DB->execute($sql, $params);
3700 $DB->set_field('course', 'sortorder', $moveaftercourse->sortorder +
1, array('id' => $course->id
));
3702 fix_course_sortorder();
3703 cache_helper
::purge_by_event('changesincourse');
3708 * Trigger course viewed event. This API function is used when course view actions happens,
3709 * usually in course/view.php but also in external functions.
3711 * @param stdClass $context course context object
3712 * @param int $sectionnumber section number
3715 function course_view($context, $sectionnumber = 0) {
3717 $eventdata = array('context' => $context);
3719 if (!empty($sectionnumber)) {
3720 $eventdata['other']['coursesectionnumber'] = $sectionnumber;
3723 $event = \core\event\course_viewed
::create($eventdata);
3726 user_accesstime_log($context->instanceid
);
3730 * Returns courses tagged with a specified tag.
3732 * @param core_tag_tag $tag
3733 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
3734 * are displayed on the page and the per-page limit may be bigger
3735 * @param int $fromctx context id where the link was displayed, may be used by callbacks
3736 * to display items in the same context first
3737 * @param int $ctx context id where to search for records
3738 * @param bool $rec search in subcontexts as well
3739 * @param int $page 0-based number of page being displayed
3740 * @return \core_tag\output\tagindex
3742 function course_get_tagged_courses($tag, $exclusivemode = false, $fromctx = 0, $ctx = 0, $rec = 1, $page = 0) {
3745 $perpage = $exclusivemode ?
$CFG->coursesperpage
: 5;
3746 $displayoptions = array(
3747 'limit' => $perpage,
3748 'offset' => $page * $perpage,
3749 'viewmoreurl' => null,
3752 $courserenderer = $PAGE->get_renderer('core', 'course');
3753 $totalcount = core_course_category
::search_courses_count(array('tagid' => $tag->id
, 'ctx' => $ctx, 'rec' => $rec));
3754 $content = $courserenderer->tagged_courses($tag->id
, $exclusivemode, $ctx, $rec, $displayoptions);
3755 $totalpages = ceil($totalcount / $perpage);
3757 return new core_tag\output\tagindex
($tag, 'core', 'course', $content,
3758 $exclusivemode, $fromctx, $ctx, $rec, $page, $totalpages);
3762 * Implements callback inplace_editable() allowing to edit values in-place
3764 * @param string $itemtype
3765 * @param int $itemid
3766 * @param mixed $newvalue
3767 * @return \core\output\inplace_editable
3769 function core_course_inplace_editable($itemtype, $itemid, $newvalue) {
3770 if ($itemtype === 'activityname') {
3771 return \core_courseformat\output\local\content\cm\title
::update($itemid, $newvalue);
3776 * This function calculates the minimum and maximum cutoff values for the timestart of
3779 * It will return an array with two values, the first being the minimum cutoff value and
3780 * the second being the maximum cutoff value. Either or both values can be null, which
3781 * indicates there is no minimum or maximum, respectively.
3783 * If a cutoff is required then the function must return an array containing the cutoff
3784 * timestamp and error string to display to the user if the cutoff value is violated.
3786 * A minimum and maximum cutoff return value will look like:
3788 * [1505704373, 'The date must be after this date'],
3789 * [1506741172, 'The date must be before this date']
3792 * @param calendar_event $event The calendar event to get the time range for
3793 * @param stdClass $course The course object to get the range from
3794 * @return array Returns an array with min and max date.
3796 function core_course_core_calendar_get_valid_event_timestart_range(\calendar_event
$event, $course) {
3800 if ($course->startdate
) {
3803 get_string('errorbeforecoursestart', 'calendar')
3807 return [$mindate, $maxdate];
3811 * Render the message drawer to be included in the top of the body of each page.
3813 * @return string HTML
3815 function core_course_drawer(): string {
3818 // Only add course index on non-site course pages.
3819 if (!$PAGE->course ||
$PAGE->course
->id
== SITEID
) {
3823 // Show course index to users can access the course only.
3824 if (!can_access_course($PAGE->course
, null, '', true)) {
3828 $format = course_get_format($PAGE->course
);
3829 $renderer = $format->get_renderer($PAGE);
3830 if (method_exists($renderer, 'course_index_drawer')) {
3831 return $renderer->course_index_drawer($format);
3838 * Returns course modules tagged with a specified tag ready for output on tag/index.php page
3840 * This is a callback used by the tag area core/course_modules to search for course modules
3841 * tagged with a specific tag.
3843 * @param core_tag_tag $tag
3844 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
3845 * are displayed on the page and the per-page limit may be bigger
3846 * @param int $fromcontextid context id where the link was displayed, may be used by callbacks
3847 * to display items in the same context first
3848 * @param int $contextid context id where to search for records
3849 * @param bool $recursivecontext search in subcontexts as well
3850 * @param int $page 0-based number of page being displayed
3851 * @return \core_tag\output\tagindex
3853 function course_get_tagged_course_modules($tag, $exclusivemode = false, $fromcontextid = 0, $contextid = 0,
3854 $recursivecontext = 1, $page = 0) {
3856 $perpage = $exclusivemode ?
20 : 5;
3858 // Build select query.
3859 $ctxselect = context_helper
::get_preload_record_columns_sql('ctx');
3860 $query = "SELECT cm.id AS cmid, c.id AS courseid, $ctxselect
3861 FROM {course_modules} cm
3862 JOIN {tag_instance} tt ON cm.id = tt.itemid
3863 JOIN {course} c ON cm.course = c.id
3864 JOIN {context} ctx ON ctx.instanceid = cm.id AND ctx.contextlevel = :coursemodulecontextlevel
3865 WHERE tt.itemtype = :itemtype AND tt.tagid = :tagid AND tt.component = :component
3866 AND cm.deletioninprogress = 0
3867 AND c.id %COURSEFILTER% AND cm.id %ITEMFILTER%";
3869 $params = array('itemtype' => 'course_modules', 'tagid' => $tag->id
, 'component' => 'core',
3870 'coursemodulecontextlevel' => CONTEXT_MODULE
);
3872 $context = context
::instance_by_id($contextid);
3873 $query .= $recursivecontext ?
' AND (ctx.id = :contextid OR ctx.path LIKE :path)' : ' AND ctx.id = :contextid';
3874 $params['contextid'] = $context->id
;
3875 $params['path'] = $context->path
.'/%';
3878 $query .= ' ORDER BY';
3879 if ($fromcontextid) {
3880 // In order-clause specify that modules from inside "fromctx" context should be returned first.
3881 $fromcontext = context
::instance_by_id($fromcontextid);
3882 $query .= ' (CASE WHEN ctx.id = :fromcontextid OR ctx.path LIKE :frompath THEN 0 ELSE 1 END),';
3883 $params['fromcontextid'] = $fromcontext->id
;
3884 $params['frompath'] = $fromcontext->path
.'/%';
3886 $query .= ' c.sortorder, cm.id';
3887 $totalpages = $page +
1;
3889 // Use core_tag_index_builder to build and filter the list of items.
3890 // Request one item more than we need so we know if next page exists.
3891 $builder = new core_tag_index_builder('core', 'course_modules', $query, $params, $page * $perpage, $perpage +
1);
3892 while ($item = $builder->has_item_that_needs_access_check()) {
3893 context_helper
::preload_from_record($item);
3894 $courseid = $item->courseid
;
3895 if (!$builder->can_access_course($courseid)) {
3896 $builder->set_accessible($item, false);
3899 $modinfo = get_fast_modinfo($builder->get_course($courseid));
3900 // Set accessibility of this item and all other items in the same course.
3901 $builder->walk(function ($taggeditem) use ($courseid, $modinfo, $builder) {
3902 if ($taggeditem->courseid
== $courseid) {
3903 $cm = $modinfo->get_cm($taggeditem->cmid
);
3904 $builder->set_accessible($taggeditem, $cm->uservisible
);
3909 $items = $builder->get_items();
3910 if (count($items) > $perpage) {
3911 $totalpages = $page +
2; // We don't need exact page count, just indicate that the next page exists.
3915 // Build the display contents.
3917 $tagfeed = new core_tag\output\tagfeed
();
3918 foreach ($items as $item) {
3919 context_helper
::preload_from_record($item);
3920 $course = $builder->get_course($item->courseid
);
3921 $modinfo = get_fast_modinfo($course);
3922 $cm = $modinfo->get_cm($item->cmid
);
3923 $courseurl = course_get_url($item->courseid
, $cm->sectionnum
);
3924 $cmname = $cm->get_formatted_name();
3925 if (!$exclusivemode) {
3926 $cmname = shorten_text($cmname, 100);
3928 $cmname = html_writer
::link($cm->url?
:$courseurl, $cmname);
3929 $coursename = format_string($course->fullname
, true,
3930 array('context' => context_course
::instance($item->courseid
)));
3931 $coursename = html_writer
::link($courseurl, $coursename);
3932 $icon = html_writer
::empty_tag('img', array('src' => $cm->get_icon_url()));
3933 $tagfeed->add($icon, $cmname, $coursename);
3936 $content = $OUTPUT->render_from_template('core_tag/tagfeed',
3937 $tagfeed->export_for_template($OUTPUT));
3939 return new core_tag\output\tagindex
($tag, 'core', 'course_modules', $content,
3940 $exclusivemode, $fromcontextid, $contextid, $recursivecontext, $page, $totalpages);
3945 * Return an object with the list of navigation options in a course that are avaialable or not for the current user.
3946 * This function also handles the frontpage course.
3948 * @param stdClass $context context object (it can be a course context or the system context for frontpage settings)
3949 * @param stdClass $course the course where the settings are being rendered
3950 * @return stdClass the navigation options in a course and their availability status
3953 function course_get_user_navigation_options($context, $course = null) {
3956 $isloggedin = isloggedin();
3957 $isguestuser = isguestuser();
3958 $isfrontpage = $context->contextlevel
== CONTEXT_SYSTEM
;
3961 $sitecontext = $context;
3963 $sitecontext = context_system
::instance();
3966 // Sets defaults for all options.
3967 $options = (object) [
3970 'competencies' => false,
3973 'participants' => false,
3976 'communication' => false,
3979 $options->blogs
= !empty($CFG->enableblogs
) &&
3980 ($CFG->bloglevel
== BLOG_GLOBAL_LEVEL ||
3981 ($CFG->bloglevel
== BLOG_SITE_LEVEL
and ($isloggedin and !$isguestuser)))
3982 && has_capability('moodle/blog:view', $sitecontext);
3984 $options->notes
= !empty($CFG->enablenotes
) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $context);
3986 // Frontpage settings?
3988 // We are on the front page, so make sure we use the proper capability (site:viewparticipants).
3989 $options->participants
= course_can_view_participants($sitecontext);
3990 $options->badges
= !empty($CFG->enablebadges
) && has_capability('moodle/badges:viewbadges', $sitecontext);
3991 $options->tags
= !empty($CFG->usetags
) && $isloggedin;
3992 $options->search
= !empty($CFG->enableglobalsearch
) && has_capability('moodle/search:query', $sitecontext);
3994 // We are in a course, so make sure we use the proper capability (course:viewparticipants).
3995 $options->participants
= course_can_view_participants($context);
3997 // Only display badges if they are enabled and the current user can manage them or if they can view them and have,
3998 // at least, one available badge.
3999 if (!empty($CFG->enablebadges
) && !empty($CFG->badges_allowcoursebadges
)) {
4000 $canmanage = has_any_capability([
4001 'moodle/badges:createbadge',
4002 'moodle/badges:awardbadge',
4003 'moodle/badges:configurecriteria',
4004 'moodle/badges:configuremessages',
4005 'moodle/badges:configuredetails',
4006 'moodle/badges:deletebadge',
4013 // This only needs to be calculated if the user can't manage badges (to improve performance).
4014 $canview = has_capability('moodle/badges:viewbadges', $context);
4016 require_once($CFG->dirroot
.'/lib/badgeslib.php');
4017 if (is_null($course)) {
4018 $totalbadges = count(badges_get_badges(BADGE_TYPE_SITE
, 0, '', '', 0, 0, $USER->id
));
4020 $totalbadges = count(badges_get_badges(BADGE_TYPE_COURSE
, $course->id
, '', '', 0, 0, $USER->id
));
4025 $options->badges
= ($canmanage ||
($canview && $totalbadges > 0));
4027 // Add view grade report is permitted.
4030 if (has_capability('moodle/grade:viewall', $context)) {
4032 } else if (!empty($course->showgrades
)) {
4033 $reports = core_component
::get_plugin_list('gradereport');
4034 if (is_array($reports) && count($reports) > 0) { // Get all installed reports.
4035 arsort($reports); // User is last, we want to test it first.
4036 foreach ($reports as $plugin => $plugindir) {
4037 if (has_capability('gradereport/'.$plugin.':view', $context)) {
4038 // Stop when the first visible plugin is found.
4045 $options->grades
= $grades;
4048 if (\core_communication\api
::is_available()) {
4049 $options->communication
= has_capability('moodle/course:configurecoursecommunication', $context);
4052 if (\core_competency\api
::is_enabled()) {
4053 $capabilities = array('moodle/competency:coursecompetencyview', 'moodle/competency:coursecompetencymanage');
4054 $options->competencies
= has_any_capability($capabilities, $context);
4060 * Return an object with the list of administration options in a course that are available or not for the current user.
4061 * This function also handles the frontpage settings.
4063 * @param stdClass $course course object (for frontpage it should be a clone of $SITE)
4064 * @param stdClass $context context object (course context)
4065 * @return stdClass the administration options in a course and their availability status
4068 function course_get_user_administration_options($course, $context) {
4070 $isfrontpage = $course->id
== SITEID
;
4071 $completionenabled = $CFG->enablecompletion
&& $course->enablecompletion
;
4072 $hascompletionoptions = count(core_completion\manager
::get_available_completion_options($course->id
)) > 0;
4073 $options = new stdClass
;
4074 $options->update
= has_capability('moodle/course:update', $context);
4075 $options->editcompletion
= $CFG->enablecompletion
&& $course->enablecompletion
&&
4076 ($options->update ||
$hascompletionoptions);
4077 $options->filters
= has_capability('moodle/filter:manage', $context) &&
4078 count(filter_get_available_in_context($context)) > 0;
4079 $options->reports
= has_capability('moodle/site:viewreports', $context);
4080 $options->backup
= has_capability('moodle/backup:backupcourse', $context);
4081 $options->restore
= has_capability('moodle/restore:restorecourse', $context);
4082 $options->copy
= \core_course\management\helper
::can_copy_course($course->id
);
4083 $options->files
= ($course->legacyfiles
== 2 && has_capability('moodle/course:managefiles', $context));
4085 if (!$isfrontpage) {
4086 $options->tags
= has_capability('moodle/course:tag', $context);
4087 $options->gradebook
= has_capability('moodle/grade:manage', $context);
4088 $options->outcomes
= !empty($CFG->enableoutcomes
) && has_capability('moodle/course:update', $context);
4089 $options->badges
= !empty($CFG->enablebadges
);
4090 $options->import
= has_capability('moodle/restore:restoretargetimport', $context);
4091 $options->reset
= has_capability('moodle/course:reset', $context);
4092 $options->roles
= has_capability('moodle/role:switchroles', $context);
4094 // Set default options to false.
4095 $listofoptions = array('tags', 'gradebook', 'outcomes', 'badges', 'import', 'publish', 'reset', 'roles', 'grades');
4097 foreach ($listofoptions as $option) {
4098 $options->$option = false;
4106 * Validates course start and end dates.
4108 * Checks that the end course date is not greater than the start course date.
4110 * $coursedata['startdate'] or $coursedata['enddate'] may not be set, it depends on the form and user input.
4112 * @param array $coursedata May contain startdate and enddate timestamps, depends on the user input.
4113 * @return mixed False if everything alright, error codes otherwise.
4115 function course_validate_dates($coursedata) {
4117 // If both start and end dates are set end date should be later than the start date.
4118 if (!empty($coursedata['startdate']) && !empty($coursedata['enddate']) &&
4119 ($coursedata['enddate'] < $coursedata['startdate'])) {
4120 return 'enddatebeforestartdate';
4123 // If start date is not set end date can not be set.
4124 if (empty($coursedata['startdate']) && !empty($coursedata['enddate'])) {
4125 return 'nostartdatenoenddate';
4132 * Check for course updates in the given context level instances (only modules supported right Now)
4134 * @param stdClass $course course object
4135 * @param array $tocheck instances to check for updates
4136 * @param array $filter check only for updates in these areas
4137 * @return array list of warnings and instances with updates information
4140 function course_check_updates($course, $tocheck, $filter = array()) {
4143 $instances = array();
4144 $warnings = array();
4145 $modulescallbacksupport = array();
4146 $modinfo = get_fast_modinfo($course);
4148 $supportedplugins = get_plugin_list_with_function('mod', 'check_updates_since');
4151 foreach ($tocheck as $instance) {
4152 if ($instance['contextlevel'] == 'module') {
4153 // Check module visibility.
4155 $cm = $modinfo->get_cm($instance['id']);
4156 } catch (Exception
$e) {
4157 $warnings[] = array(
4159 'itemid' => $instance['id'],
4160 'warningcode' => 'cmidnotincourse',
4161 'message' => 'This module id does not belong to this course.'
4166 if (!$cm->uservisible
) {
4167 $warnings[] = array(
4169 'itemid' => $instance['id'],
4170 'warningcode' => 'nonuservisible',
4171 'message' => 'You don\'t have access to this module.'
4175 if (empty($supportedplugins['mod_' . $cm->modname
])) {
4176 $warnings[] = array(
4178 'itemid' => $instance['id'],
4179 'warningcode' => 'missingcallback',
4180 'message' => 'This module does not implement the check_updates_since callback: ' . $instance['contextlevel'],
4184 // Retrieve the module instance.
4185 $instances[] = array(
4186 'contextlevel' => $instance['contextlevel'],
4187 'id' => $instance['id'],
4188 'updates' => call_user_func($cm->modname
. '_check_updates_since', $cm, $instance['since'], $filter)
4192 $warnings[] = array(
4193 'item' => 'contextlevel',
4194 'itemid' => $instance['id'],
4195 'warningcode' => 'contextlevelnotsupported',
4196 'message' => 'Context level not yet supported ' . $instance['contextlevel'],
4200 return array($instances, $warnings);
4204 * This function classifies a course as past, in progress or future.
4206 * This function may incur a DB hit to calculate course completion.
4207 * @param stdClass $course Course record
4208 * @param stdClass $user User record (optional - defaults to $USER).
4209 * @param completion_info $completioninfo Completion record for the user (optional - will be fetched if required).
4210 * @return string (one of COURSE_TIMELINE_FUTURE, COURSE_TIMELINE_INPROGRESS or COURSE_TIMELINE_PAST)
4212 function course_classify_for_timeline($course, $user = null, $completioninfo = null) {
4215 if ($user == null) {
4219 if ($completioninfo == null) {
4220 $completioninfo = new completion_info($course);
4223 // Let plugins override data for timeline classification.
4224 $pluginsfunction = get_plugins_with_function('extend_course_classify_for_timeline', 'lib.php');
4225 foreach ($pluginsfunction as $plugintype => $plugins) {
4226 foreach ($plugins as $pluginfunction) {
4227 $pluginfunction($course, $user, $completioninfo);
4233 if (!empty($course->enddate
) && (course_classify_end_date($course) < $today)) {
4234 return COURSE_TIMELINE_PAST
;
4237 // Course was completed.
4238 if ($completioninfo->is_enabled() && $completioninfo->is_course_complete($user->id
)) {
4239 return COURSE_TIMELINE_PAST
;
4242 // Start date not reached.
4243 if (!empty($course->startdate
) && (course_classify_start_date($course) > $today)) {
4244 return COURSE_TIMELINE_FUTURE
;
4247 // Everything else is in progress.
4248 return COURSE_TIMELINE_INPROGRESS
;
4252 * This function calculates the end date to use for display classification purposes,
4253 * incorporating the grace period, if any.
4255 * @param stdClass $course The course record.
4256 * @return int The new enddate.
4258 function course_classify_end_date($course) {
4260 $coursegraceperiodafter = (empty($CFG->coursegraceperiodafter
)) ?
0 : $CFG->coursegraceperiodafter
;
4261 $enddate = (new \
DateTimeImmutable())->setTimestamp($course->enddate
)->modify("+{$coursegraceperiodafter} days");
4262 return $enddate->getTimestamp();
4266 * This function calculates the start date to use for display classification purposes,
4267 * incorporating the grace period, if any.
4269 * @param stdClass $course The course record.
4270 * @return int The new startdate.
4272 function course_classify_start_date($course) {
4274 $coursegraceperiodbefore = (empty($CFG->coursegraceperiodbefore
)) ?
0 : $CFG->coursegraceperiodbefore
;
4275 $startdate = (new \
DateTimeImmutable())->setTimestamp($course->startdate
)->modify("-{$coursegraceperiodbefore} days");
4276 return $startdate->getTimestamp();
4280 * Group a list of courses into either past, future, or in progress.
4282 * The return value will be an array indexed by the COURSE_TIMELINE_* constants
4283 * with each value being an array of courses in that group.
4286 * COURSE_TIMELINE_PAST => [... list of past courses ...],
4287 * COURSE_TIMELINE_FUTURE => [],
4288 * COURSE_TIMELINE_INPROGRESS => []
4291 * @param array $courses List of courses to be grouped.
4294 function course_classify_courses_for_timeline(array $courses) {
4295 return array_reduce($courses, function($carry, $course) {
4296 $classification = course_classify_for_timeline($course);
4297 array_push($carry[$classification], $course);
4301 COURSE_TIMELINE_PAST
=> [],
4302 COURSE_TIMELINE_FUTURE
=> [],
4303 COURSE_TIMELINE_INPROGRESS
=> []
4308 * Get the list of enrolled courses for the current user.
4310 * This function returns a Generator. The courses will be loaded from the database
4311 * in chunks rather than a single query.
4313 * @param int $limit Restrict result set to this amount
4314 * @param int $offset Skip this number of records from the start of the result set
4315 * @param string|null $sort SQL string for sorting
4316 * @param string|null $fields SQL string for fields to be returned
4317 * @param int $dbquerylimit The number of records to load per DB request
4318 * @param array $includecourses courses ids to be restricted
4319 * @param array $hiddencourses courses ids to be excluded
4322 function course_get_enrolled_courses_for_logged_in_user(
4325 string $sort = null,
4326 string $fields = null,
4327 int $dbquerylimit = COURSE_DB_QUERY_LIMIT
,
4328 array $includecourses = [],
4329 array $hiddencourses = []
4332 $haslimit = !empty($limit);
4334 $querylimit = (!$haslimit ||
$limit > $dbquerylimit) ?
$dbquerylimit : $limit;
4336 while ($courses = enrol_get_my_courses($fields, $sort, $querylimit, $includecourses, false, $offset, $hiddencourses)) {
4337 yield from
$courses;
4339 $recordsloaded +
= $querylimit;
4341 if (count($courses) < $querylimit) {
4344 if ($haslimit && $recordsloaded >= $limit) {
4348 $offset +
= $querylimit;
4353 * Get the list of enrolled courses the current user searched for.
4355 * This function returns a Generator. The courses will be loaded from the database
4356 * in chunks rather than a single query.
4358 * @param int $limit Restrict result set to this amount
4359 * @param int $offset Skip this number of records from the start of the result set
4360 * @param string|null $sort SQL string for sorting
4361 * @param string|null $fields SQL string for fields to be returned
4362 * @param int $dbquerylimit The number of records to load per DB request
4363 * @param array $searchcriteria contains search criteria
4364 * @param array $options display options, same as in get_courses() except 'recursive' is ignored -
4365 * search is always category-independent
4368 function course_get_enrolled_courses_for_logged_in_user_from_search(
4371 string $sort = null,
4372 string $fields = null,
4373 int $dbquerylimit = COURSE_DB_QUERY_LIMIT
,
4374 array $searchcriteria = [],
4378 $haslimit = !empty($limit);
4380 $querylimit = (!$haslimit ||
$limit > $dbquerylimit) ?
$dbquerylimit : $limit;
4381 $ids = core_course_category
::search_courses($searchcriteria, $options);
4383 // If no courses were found matching the criteria return back.
4388 while ($courses = enrol_get_my_courses($fields, $sort, $querylimit, $ids, false, $offset)) {
4389 yield from
$courses;
4391 $recordsloaded +
= $querylimit;
4393 if (count($courses) < $querylimit) {
4396 if ($haslimit && $recordsloaded >= $limit) {
4400 $offset +
= $querylimit;
4405 * Search the given $courses for any that match the given $classification up to the specified
4408 * This function will return the subset of courses that match the classification as well as the
4409 * number of courses it had to process to build that subset.
4411 * It is recommended that for larger sets of courses this function is given a Generator that loads
4412 * the courses from the database in chunks.
4414 * @param array|Traversable $courses List of courses to process
4415 * @param string $classification One of the COURSE_TIMELINE_* constants
4416 * @param int $limit Limit the number of results to this amount
4417 * @return array First value is the filtered courses, second value is the number of courses processed
4419 function course_filter_courses_by_timeline_classification(
4421 string $classification,
4425 if (!in_array($classification,
4426 [COURSE_TIMELINE_ALLINCLUDINGHIDDEN
, COURSE_TIMELINE_ALL
, COURSE_TIMELINE_PAST
, COURSE_TIMELINE_INPROGRESS
,
4427 COURSE_TIMELINE_FUTURE
, COURSE_TIMELINE_HIDDEN
, COURSE_TIMELINE_SEARCH
])) {
4428 $message = 'Classification must be one of COURSE_TIMELINE_ALLINCLUDINGHIDDEN, COURSE_TIMELINE_ALL, COURSE_TIMELINE_PAST, '
4429 . 'COURSE_TIMELINE_INPROGRESS, COURSE_TIMELINE_SEARCH or COURSE_TIMELINE_FUTURE';
4430 throw new moodle_exception($message);
4433 $filteredcourses = [];
4434 $numberofcoursesprocessed = 0;
4437 foreach ($courses as $course) {
4438 $numberofcoursesprocessed++
;
4439 $pref = get_user_preferences('block_myoverview_hidden_course_' . $course->id
, 0);
4441 // Added as of MDL-63457 toggle viewability for each user.
4442 if ($classification == COURSE_TIMELINE_ALLINCLUDINGHIDDEN ||
($classification == COURSE_TIMELINE_HIDDEN
&& $pref) ||
4443 $classification == COURSE_TIMELINE_SEARCH||
4444 (($classification == COURSE_TIMELINE_ALL ||
$classification == course_classify_for_timeline($course)) && !$pref)) {
4445 $filteredcourses[] = $course;
4449 if ($limit && $filtermatches >= $limit) {
4450 // We've found the number of requested courses. No need to continue searching.
4455 // Return the number of filtered courses as well as the number of courses that were searched
4456 // in order to find the matching courses. This allows the calling code to do some kind of
4458 return [$filteredcourses, $numberofcoursesprocessed];
4462 * Search the given $courses for any that match the given $classification up to the specified
4465 * This function will return the subset of courses that are favourites as well as the
4466 * number of courses it had to process to build that subset.
4468 * It is recommended that for larger sets of courses this function is given a Generator that loads
4469 * the courses from the database in chunks.
4471 * @param array|Traversable $courses List of courses to process
4472 * @param array $favouritecourseids Array of favourite courses.
4473 * @param int $limit Limit the number of results to this amount
4474 * @return array First value is the filtered courses, second value is the number of courses processed
4476 function course_filter_courses_by_favourites(
4478 $favouritecourseids,
4482 $filteredcourses = [];
4483 $numberofcoursesprocessed = 0;
4486 foreach ($courses as $course) {
4487 $numberofcoursesprocessed++
;
4489 if (in_array($course->id
, $favouritecourseids)) {
4490 $filteredcourses[] = $course;
4494 if ($limit && $filtermatches >= $limit) {
4495 // We've found the number of requested courses. No need to continue searching.
4500 // Return the number of filtered courses as well as the number of courses that were searched
4501 // in order to find the matching courses. This allows the calling code to do some kind of
4503 return [$filteredcourses, $numberofcoursesprocessed];
4507 * Search the given $courses for any that have a $customfieldname value that matches the given
4508 * $customfieldvalue, up to the specified $limit.
4510 * This function will return the subset of courses that matches the value as well as the
4511 * number of courses it had to process to build that subset.
4513 * It is recommended that for larger sets of courses this function is given a Generator that loads
4514 * the courses from the database in chunks.
4516 * @param array|Traversable $courses List of courses to process
4517 * @param string $customfieldname the shortname of the custom field to match against
4518 * @param string $customfieldvalue the value this custom field needs to match
4519 * @param int $limit Limit the number of results to this amount
4520 * @return array First value is the filtered courses, second value is the number of courses processed
4522 function course_filter_courses_by_customfield(
4534 // Prepare the list of courses to search through.
4536 foreach ($courses as $course) {
4537 $coursesbyid[$course->id
] = $course;
4539 if (!$coursesbyid) {
4542 list($csql, $params) = $DB->get_in_or_equal(array_keys($coursesbyid), SQL_PARAMS_NAMED
);
4544 // Get the id of the custom field.
4547 FROM {customfield_field} f
4548 JOIN {customfield_category} cat ON cat.id = f.categoryid
4549 WHERE f.shortname = ?
4550 AND cat.component = 'core_course'
4551 AND cat.area = 'course'
4553 $fieldid = $DB->get_field_sql($sql, [$customfieldname]);
4558 // Get a list of courseids that match that custom field value.
4559 if ($customfieldvalue == COURSE_CUSTOMFIELD_EMPTY
) {
4560 $comparevalue = $DB->sql_compare_text('cd.value');
4564 LEFT JOIN {customfield_data} cd ON cd.instanceid = c.id AND cd.fieldid = :fieldid
4566 AND (cd.value IS NULL OR $comparevalue = '' OR $comparevalue = '0')
4568 $params['fieldid'] = $fieldid;
4569 $matchcourseids = $DB->get_fieldset_sql($sql, $params);
4571 $comparevalue = $DB->sql_compare_text('value');
4572 $select = "fieldid = :fieldid AND $comparevalue = :customfieldvalue AND instanceid $csql";
4573 $params['fieldid'] = $fieldid;
4574 $params['customfieldvalue'] = $customfieldvalue;
4575 $matchcourseids = $DB->get_fieldset_select('customfield_data', 'instanceid', $select, $params);
4578 // Prepare the list of courses to return.
4579 $filteredcourses = [];
4580 $numberofcoursesprocessed = 0;
4583 foreach ($coursesbyid as $course) {
4584 $numberofcoursesprocessed++
;
4586 if (in_array($course->id
, $matchcourseids)) {
4587 $filteredcourses[] = $course;
4591 if ($limit && $filtermatches >= $limit) {
4592 // We've found the number of requested courses. No need to continue searching.
4597 // Return the number of filtered courses as well as the number of courses that were searched
4598 // in order to find the matching courses. This allows the calling code to do some kind of
4600 return [$filteredcourses, $numberofcoursesprocessed];
4604 * Check module updates since a given time.
4605 * This function checks for updates in the module config, file areas, completion, grades, comments and ratings.
4607 * @param cm_info $cm course module data
4608 * @param int $from the time to check
4609 * @param array $fileareas additional file ares to check
4610 * @param array $filter if we need to filter and return only selected updates
4611 * @return stdClass object with the different updates
4614 function course_check_module_updates_since($cm, $from, $fileareas = array(), $filter = array()) {
4615 global $DB, $CFG, $USER;
4617 $context = $cm->context
;
4618 $mod = $DB->get_record($cm->modname
, array('id' => $cm->instance
), '*', MUST_EXIST
);
4620 $updates = new stdClass();
4621 $course = get_course($cm->course
);
4622 $component = 'mod_' . $cm->modname
;
4624 // Check changes in the module configuration.
4625 if (isset($mod->timemodified
) and (empty($filter) or in_array('configuration', $filter))) {
4626 $updates->configuration
= (object) array('updated' => false);
4627 if ($updates->configuration
->updated
= $mod->timemodified
> $from) {
4628 $updates->configuration
->timeupdated
= $mod->timemodified
;
4632 // Check for updates in files.
4633 if (plugin_supports('mod', $cm->modname
, FEATURE_MOD_INTRO
)) {
4634 $fileareas[] = 'intro';
4636 if (!empty($fileareas) and (empty($filter) or in_array('fileareas', $filter))) {
4637 $fs = get_file_storage();
4638 $files = $fs->get_area_files($context->id
, $component, $fileareas, false, "filearea, timemodified DESC", false, $from);
4639 foreach ($fileareas as $filearea) {
4640 $updates->{$filearea . 'files'} = (object) array('updated' => false);
4642 foreach ($files as $file) {
4643 $updates->{$file->get_filearea() . 'files'}->updated
= true;
4644 $updates->{$file->get_filearea() . 'files'}->itemids
[] = $file->get_id();
4648 // Check completion.
4649 $supportcompletion = plugin_supports('mod', $cm->modname
, FEATURE_COMPLETION_HAS_RULES
);
4650 $supportcompletion = $supportcompletion or plugin_supports('mod', $cm->modname
, FEATURE_COMPLETION_TRACKS_VIEWS
);
4651 if ($supportcompletion and (empty($filter) or in_array('completion', $filter))) {
4652 $updates->completion
= (object) array('updated' => false);
4653 $completion = new completion_info($course);
4654 // Use wholecourse to cache all the modules the first time.
4655 $completiondata = $completion->get_data($cm, true);
4656 if ($updates->completion
->updated
= !empty($completiondata->timemodified
) && $completiondata->timemodified
> $from) {
4657 $updates->completion
->timemodified
= $completiondata->timemodified
;
4662 $supportgrades = plugin_supports('mod', $cm->modname
, FEATURE_GRADE_HAS_GRADE
);
4663 $supportgrades = $supportgrades or plugin_supports('mod', $cm->modname
, FEATURE_GRADE_OUTCOMES
);
4664 if ($supportgrades and (empty($filter) or (in_array('gradeitems', $filter) or in_array('outcomes', $filter)))) {
4665 require_once($CFG->libdir
. '/gradelib.php');
4666 $grades = grade_get_grades($course->id
, 'mod', $cm->modname
, $mod->id
, $USER->id
);
4668 if (empty($filter) or in_array('gradeitems', $filter)) {
4669 $updates->gradeitems
= (object) array('updated' => false);
4670 foreach ($grades->items
as $gradeitem) {
4671 foreach ($gradeitem->grades
as $grade) {
4672 if ($grade->datesubmitted
> $from or $grade->dategraded
> $from) {
4673 $updates->gradeitems
->updated
= true;
4674 $updates->gradeitems
->itemids
[] = $gradeitem->id
;
4680 if (empty($filter) or in_array('outcomes', $filter)) {
4681 $updates->outcomes
= (object) array('updated' => false);
4682 foreach ($grades->outcomes
as $outcome) {
4683 foreach ($outcome->grades
as $grade) {
4684 if ($grade->datesubmitted
> $from or $grade->dategraded
> $from) {
4685 $updates->outcomes
->updated
= true;
4686 $updates->outcomes
->itemids
[] = $outcome->id
;
4694 if (plugin_supports('mod', $cm->modname
, FEATURE_COMMENT
) and (empty($filter) or in_array('comments', $filter))) {
4695 $updates->comments
= (object) array('updated' => false);
4696 require_once($CFG->dirroot
. '/comment/lib.php');
4697 require_once($CFG->dirroot
. '/comment/locallib.php');
4698 $manager = new comment_manager();
4699 $comments = $manager->get_component_comments_since($course, $context, $component, $from, $cm);
4700 if (!empty($comments)) {
4701 $updates->comments
->updated
= true;
4702 $updates->comments
->itemids
= array_keys($comments);
4707 if (plugin_supports('mod', $cm->modname
, FEATURE_RATE
) and (empty($filter) or in_array('ratings', $filter))) {
4708 $updates->ratings
= (object) array('updated' => false);
4709 require_once($CFG->dirroot
. '/rating/lib.php');
4710 $manager = new rating_manager();
4711 $ratings = $manager->get_component_ratings_since($context, $component, $from);
4712 if (!empty($ratings)) {
4713 $updates->ratings
->updated
= true;
4714 $updates->ratings
->itemids
= array_keys($ratings);
4722 * Returns true if the user can view the participant page, false otherwise,
4724 * @param context $context The context we are checking.
4727 function course_can_view_participants($context) {
4728 $viewparticipantscap = 'moodle/course:viewparticipants';
4729 if ($context->contextlevel
== CONTEXT_SYSTEM
) {
4730 $viewparticipantscap = 'moodle/site:viewparticipants';
4733 return has_any_capability([$viewparticipantscap, 'moodle/course:enrolreview'], $context);
4737 * Checks if a user can view the participant page, if not throws an exception.
4739 * @param context $context The context we are checking.
4740 * @throws required_capability_exception
4742 function course_require_view_participants($context) {
4743 if (!course_can_view_participants($context)) {
4744 $viewparticipantscap = 'moodle/course:viewparticipants';
4745 if ($context->contextlevel
== CONTEXT_SYSTEM
) {
4746 $viewparticipantscap = 'moodle/site:viewparticipants';
4748 throw new required_capability_exception($context, $viewparticipantscap, 'nopermissions', '');
4753 * Return whether the user can download from the specified backup file area in the given context.
4755 * @param string $filearea the backup file area. E.g. 'course', 'backup' or 'automated'.
4756 * @param \context $context
4757 * @param stdClass $user the user object. If not provided, the current user will be checked.
4758 * @return bool true if the user is allowed to download in the context, false otherwise.
4760 function can_download_from_backup_filearea($filearea, \context
$context, stdClass
$user = null) {
4761 $candownload = false;
4762 switch ($filearea) {
4765 $candownload = has_capability('moodle/backup:downloadfile', $context, $user);
4768 // Given the automated backups may contain userinfo, we restrict access such that only users who are able to
4769 // restore with userinfo are able to download the file. Users can't create these backups, so checking 'backup:userinfo'
4770 // doesn't make sense here.
4771 $candownload = has_capability('moodle/backup:downloadfile', $context, $user) &&
4772 has_capability('moodle/restore:userinfo', $context, $user);
4778 return $candownload;
4782 * Get a list of hidden courses
4784 * @param int|object|null $user User override to get the filter from. Defaults to current user
4785 * @return array $ids List of hidden courses
4786 * @throws coding_exception
4788 function get_hidden_courses_on_timeline($user = null) {
4795 $preferences = get_user_preferences(null, null, $user);
4797 foreach ($preferences as $key => $value) {
4798 if (preg_match('/block_myoverview_hidden_course_(\d)+/', $key)) {
4799 $id = preg_split('/block_myoverview_hidden_course_/', $key);
4808 * Returns a list of the most recently courses accessed by a user
4810 * @param int $userid User id from which the courses will be obtained
4811 * @param int $limit Restrict result set to this amount
4812 * @param int $offset Skip this number of records from the start of the result set
4813 * @param string|null $sort SQL string for sorting
4816 function course_get_recent_courses(int $userid = null, int $limit = 0, int $offset = 0, string $sort = null) {
4818 global $CFG, $USER, $DB;
4820 if (empty($userid)) {
4821 $userid = $USER->id
;
4825 'id', 'idnumber', 'summary', 'summaryformat', 'startdate', 'enddate', 'category',
4826 'shortname', 'fullname', 'timeaccess', 'component', 'visible',
4827 'showactivitydates', 'showcompletionconditions', 'pdfexportfont'
4831 $sort = 'timeaccess DESC';
4833 // The SQL string for sorting can define sorting by multiple columns.
4834 $rawsorts = explode(',', $sort);
4836 // Validate and trim the sort parameters in the SQL string for sorting.
4837 foreach ($rawsorts as $rawsort) {
4838 $sort = trim($rawsort);
4839 $sortparams = explode(' ', $sort);
4840 // A valid sort statement can not have more than 2 params (ex. 'summary desc' or 'timeaccess').
4841 if (count($sortparams) > 2) {
4842 throw new invalid_parameter_exception(
4843 'Invalid structure of the sort parameter, allowed structure: fieldname [ASC|DESC].');
4845 $sortfield = trim($sortparams[0]);
4846 // Validate the value which defines the field to sort by.
4847 if (!in_array($sortfield, $basefields)) {
4848 throw new invalid_parameter_exception('Invalid field in the sort parameter, allowed fields: ' .
4849 implode(', ', $basefields) . '.');
4851 $sortdirection = isset($sortparams[1]) ?
trim($sortparams[1]) : '';
4852 // Validate the value which defines the sort direction (if present).
4853 $allowedsortdirections = ['asc', 'desc'];
4854 if (!empty($sortdirection) && !in_array(strtolower($sortdirection), $allowedsortdirections)) {
4855 throw new invalid_parameter_exception('Invalid sort direction in the sort parameter, allowed values: ' .
4856 implode(', ', $allowedsortdirections) . '.');
4860 $sort = implode(',', $sorts);
4863 $ctxfields = context_helper
::get_preload_record_columns_sql('ctx');
4865 $coursefields = 'c.' . join(',', $basefields);
4867 // Ask the favourites service to give us the join SQL for favourited courses,
4868 // so we can include favourite information in the query.
4869 $usercontext = \context_user
::instance($userid);
4870 $favservice = \core_favourites\service_factory
::get_service_for_user_context($usercontext);
4871 list($favsql, $favparams) = $favservice->get_join_sql_by_type('core_course', 'courses', 'fav', 'ul.courseid');
4873 $sql = "SELECT $coursefields, $ctxfields
4876 ON ctx.contextlevel = :contextlevel
4877 AND ctx.instanceid = c.id
4878 JOIN {user_lastaccess} ul
4879 ON ul.courseid = c.id
4881 LEFT JOIN {enrol} eg ON eg.courseid = c.id AND eg.status = :statusenrolg AND eg.enrol = :guestenrol
4882 WHERE ul.userid = :userid
4883 AND c.visible = :visible
4884 AND (eg.id IS NOT NULL
4885 OR EXISTS (SELECT e.id
4887 JOIN {user_enrolments} ue ON ue.enrolid = e.id
4888 WHERE e.courseid = c.id
4889 AND e.status = :statusenrol
4890 AND ue.status = :status
4891 AND ue.userid = :userid2
4892 AND ue.timestart < :now1
4893 AND (ue.timeend = 0 OR ue.timeend > :now2)
4897 $now = round(time(), -2); // Improves db caching.
4898 $params = ['userid' => $userid, 'contextlevel' => CONTEXT_COURSE
, 'visible' => 1, 'status' => ENROL_USER_ACTIVE
,
4899 'statusenrol' => ENROL_INSTANCE_ENABLED
, 'guestenrol' => 'guest', 'now1' => $now, 'now2' => $now,
4900 'userid2' => $userid, 'statusenrolg' => ENROL_INSTANCE_ENABLED
] +
$favparams;
4902 $recentcourses = $DB->get_records_sql($sql, $params, $offset, $limit);
4904 // Filter courses if last access field is hidden.
4905 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields
));
4907 if ($userid != $USER->id
&& isset($hiddenfields['lastaccess'])) {
4908 $recentcourses = array_filter($recentcourses, function($course) {
4909 context_helper
::preload_from_record($course);
4910 $context = context_course
::instance($course->id
, IGNORE_MISSING
);
4911 // If last access was a hidden field, a user requesting info about another user would need permission to view hidden
4913 return has_capability('moodle/course:viewhiddenuserfields', $context);
4917 return $recentcourses;
4921 * Calculate the course start date and offset for the given user ids.
4923 * If the course is a fixed date course then the course start date will be returned.
4924 * If the course is a relative date course then the course date will be calculated and
4925 * and offset provided.
4927 * The dates are returned as an array with the index being the user id. The array
4928 * contains the start date and start offset values for the user.
4930 * If the user is not enrolled in the course then the course start date will be returned.
4932 * If we have a course which starts on 1563244000 and 2 users, id 123 and 456, where the
4933 * former is enrolled in the course at 1563244693 and the latter is not enrolled then the
4934 * return value would look like:
4937 * 'start' => 1563244693,
4938 * 'startoffset' => 693
4941 * 'start' => 1563244000,
4942 * 'startoffset' => 0
4946 * @param stdClass $course The course to fetch dates for.
4947 * @param array $userids The list of user ids to get dates for.
4950 function course_get_course_dates_for_user_ids(stdClass
$course, array $userids): array {
4951 if (empty($course->relativedatesmode
)) {
4952 // This course isn't set to relative dates so we can early return with the course
4954 return array_reduce($userids, function($carry, $userid) use ($course) {
4956 'start' => $course->startdate
,
4963 // We're dealing with a relative dates course now so we need to calculate some dates.
4964 $cache = cache
::make('core', 'course_user_dates');
4966 $uncacheduserids = [];
4968 // Try fetching the values from the cache so that we don't need to do a DB request.
4969 foreach ($userids as $userid) {
4970 $cachekey = "{$course->id}_{$userid}";
4971 $cachedvalue = $cache->get($cachekey);
4973 if ($cachedvalue === false) {
4974 // Looks like we haven't seen this user for this course before so we'll have
4976 $uncacheduserids[] = $userid;
4978 [$start, $startoffset] = $cachedvalue;
4981 'startoffset' => $startoffset
4986 if (!empty($uncacheduserids)) {
4987 // Load the enrolments for any users we haven't seen yet. Set the "onlyactive" param
4988 // to false because it filters out users with enrolment start times in the future which
4990 $enrolments = enrol_get_course_users($course->id
, false, $uncacheduserids);
4992 foreach ($uncacheduserids as $userid) {
4993 // Find the user enrolment that has the earliest start date.
4994 $enrolment = array_reduce(array_values($enrolments), function($carry, $enrolment) use ($userid) {
4995 // Only consider enrolments for this user if the user enrolment is active and the
4996 // enrolment method is enabled.
4998 $enrolment->uestatus
== ENROL_USER_ACTIVE
&&
4999 $enrolment->estatus
== ENROL_INSTANCE_ENABLED
&&
5000 $enrolment->id
== $userid
5002 if (is_null($carry)) {
5003 // Haven't found an enrolment yet for this user so use the one we just found.
5004 $carry = $enrolment;
5006 // We've already found an enrolment for this user so let's use which ever one
5007 // has the earliest start time.
5008 $carry = $carry->uetimestart
< $enrolment->uetimestart ?
$carry : $enrolment;
5016 // The course is in relative dates mode so we calculate the student's start
5017 // date based on their enrolment start date.
5018 $start = $course->startdate
> $enrolment->uetimestart ?
$course->startdate
: $enrolment->uetimestart
;
5019 $startoffset = $start - $course->startdate
;
5021 // The user is not enrolled in the course so default back to the course start date.
5022 $start = $course->startdate
;
5028 'startoffset' => $startoffset
5031 $cachekey = "{$course->id}_{$userid}";
5032 $cache->set($cachekey, [$start, $startoffset]);
5040 * Calculate the course start date and offset for the given user id.
5042 * If the course is a fixed date course then the course start date will be returned.
5043 * If the course is a relative date course then the course date will be calculated and
5044 * and offset provided.
5046 * The return array contains the start date and start offset values for the user.
5048 * If the user is not enrolled in the course then the course start date will be returned.
5050 * If we have a course which starts on 1563244000. If a user's enrolment starts on 1563244693
5051 * then the return would be:
5053 * 'start' => 1563244693,
5054 * 'startoffset' => 693
5057 * If the use was not enrolled then the return would be:
5059 * 'start' => 1563244000,
5060 * 'startoffset' => 0
5063 * @param stdClass $course The course to fetch dates for.
5064 * @param int $userid The user id to get dates for.
5067 function course_get_course_dates_for_user_id(stdClass
$course, int $userid): array {
5068 return (course_get_course_dates_for_user_ids($course, [$userid]))[$userid];
5072 * Renders the course copy form for the modal on the course management screen.
5074 * @param array $args
5075 * @return string $o Form HTML.
5077 function course_output_fragment_new_base_form($args) {
5079 $serialiseddata = json_decode($args['jsonformdata'], true);
5081 if (!empty($serialiseddata)) {
5082 parse_str($serialiseddata, $formdata);
5085 $context = context_course
::instance($args['courseid']);
5086 $copycaps = \core_course\management\helper
::get_course_copy_capabilities();
5087 require_all_capabilities($copycaps, $context);
5089 $course = get_course($args['courseid']);
5090 $mform = new \core_backup\output\
copy_form(
5092 array('course' => $course, 'returnto' => '', 'returnurl' => ''),
5093 'post', '', ['class' => 'ignoredirty'], true, $formdata);
5095 if (!empty($serialiseddata)) {
5096 // If we were passed non-empty form data we want the mform to call validation functions and show errors.
5097 $mform->is_validated();
5102 $o = ob_get_contents();
5109 * Get the current course image for the given course.
5111 * @param \stdClass $course
5112 * @return null|stored_file
5114 function course_get_courseimage(\stdClass
$course): ?stored_file
{
5115 $courseinlist = new core_course_list_element($course);
5116 foreach ($courseinlist->get_course_overviewfiles() as $file) {
5117 if ($file->is_valid_image()) {
5125 * Get course specific data for configuring a communication instance.
5127 * @param integer $courseid The course id.
5128 * @return array Returns course data, context and heading.
5130 function course_get_communication_instance_data(int $courseid): array {
5131 // Do some checks and prepare instance specific data.
5132 $course = get_course($courseid);
5133 require_login($course);
5134 $context = context_course
::instance($course->id
);
5135 require_capability('moodle/course:configurecoursecommunication', $context);
5137 $heading = $course->fullname
;
5138 $returnurl = new moodle_url('/course/view.php', ['id' => $courseid]);
5140 return [$course, $context, $heading, $returnurl];
5144 * Update a course using communication configuration data.
5146 * @param stdClass $data The data to update the course with.
5148 function course_update_communication_instance_data(stdClass
$data): void
{
5149 $data->id
= $data->instanceid
; // For correct use in update_course.
5150 update_course($data);