Merge branch 'MDL-81082' of https://github.com/paulholden/moodle
[moodle.git] / course / lib.php
bloba809df14c61c89658600b6949d2d9acb30c8eb17
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
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/>.
17 /**
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_courseformat\formatactions;
30 use core\output\local\action_menu\subpanel as action_menu_subpanel;
32 require_once($CFG->libdir.'/completionlib.php');
33 require_once($CFG->libdir.'/filelib.php');
34 require_once($CFG->libdir.'/datalib.php');
35 require_once($CFG->dirroot.'/course/format/lib.php');
37 define('COURSE_MAX_LOGS_PER_PAGE', 1000); // Records.
38 define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds.
40 /**
41 * Number of courses to display when summaries are included.
42 * @var int
43 * @deprecated since 2.4, use $CFG->courseswithsummarieslimit instead.
45 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10);
47 // Max courses in log dropdown before switching to optional.
48 define('COURSE_MAX_COURSES_PER_DROPDOWN', 1000);
49 // Max users in log dropdown before switching to optional.
50 define('COURSE_MAX_USERS_PER_DROPDOWN', 1000);
51 define('FRONTPAGENEWS', '0');
52 define('FRONTPAGECATEGORYNAMES', '2');
53 define('FRONTPAGECATEGORYCOMBO', '4');
54 define('FRONTPAGEENROLLEDCOURSELIST', '5');
55 define('FRONTPAGEALLCOURSELIST', '6');
56 define('FRONTPAGECOURSESEARCH', '7');
57 // Important! Replaced with $CFG->frontpagecourselimit - maximum number of courses displayed on the frontpage.
58 define('EXCELROWS', 65535);
59 define('FIRSTUSEDEXCELROW', 3);
61 define('MOD_CLASS_ACTIVITY', 0);
62 define('MOD_CLASS_RESOURCE', 1);
64 define('COURSE_TIMELINE_ALLINCLUDINGHIDDEN', 'allincludinghidden');
65 define('COURSE_TIMELINE_ALL', 'all');
66 define('COURSE_TIMELINE_PAST', 'past');
67 define('COURSE_TIMELINE_INPROGRESS', 'inprogress');
68 define('COURSE_TIMELINE_FUTURE', 'future');
69 define('COURSE_TIMELINE_SEARCH', 'search');
70 define('COURSE_FAVOURITES', 'favourites');
71 define('COURSE_TIMELINE_HIDDEN', 'hidden');
72 define('COURSE_CUSTOMFIELD', 'customfield');
73 define('COURSE_DB_QUERY_LIMIT', 1000);
74 /** Searching for all courses that have no value for the specified custom field. */
75 define('COURSE_CUSTOMFIELD_EMPTY', -1);
77 // Course activity chooser footer default display option.
78 define('COURSE_CHOOSER_FOOTER_NONE', 'hidden');
80 // Download course content options.
81 define('DOWNLOAD_COURSE_CONTENT_DISABLED', 0);
82 define('DOWNLOAD_COURSE_CONTENT_ENABLED', 1);
83 define('DOWNLOAD_COURSE_CONTENT_SITE_DEFAULT', 2);
85 function make_log_url($module, $url) {
86 switch ($module) {
87 case 'course':
88 if (strpos($url, 'report/') === 0) {
89 // there is only one report type, course reports are deprecated
90 $url = "/$url";
91 break;
93 case 'file':
94 case 'login':
95 case 'lib':
96 case 'admin':
97 case 'category':
98 case 'mnet course':
99 if (strpos($url, '../') === 0) {
100 $url = ltrim($url, '.');
101 } else {
102 $url = "/course/$url";
104 break;
105 case 'calendar':
106 $url = "/calendar/$url";
107 break;
108 case 'user':
109 case 'blog':
110 $url = "/$module/$url";
111 break;
112 case 'upload':
113 $url = $url;
114 break;
115 case 'coursetags':
116 $url = '/'.$url;
117 break;
118 case 'library':
119 case '':
120 $url = '/';
121 break;
122 case 'message':
123 $url = "/message/$url";
124 break;
125 case 'notes':
126 $url = "/notes/$url";
127 break;
128 case 'tag':
129 $url = "/tag/$url";
130 break;
131 case 'role':
132 $url = '/'.$url;
133 break;
134 case 'grade':
135 $url = "/grade/$url";
136 break;
137 default:
138 $url = "/mod/$module/$url";
139 break;
142 //now let's sanitise urls - there might be some ugly nasties:-(
143 $parts = explode('?', $url);
144 $script = array_shift($parts);
145 if (strpos($script, 'http') === 0) {
146 $script = clean_param($script, PARAM_URL);
147 } else {
148 $script = clean_param($script, PARAM_PATH);
151 $query = '';
152 if ($parts) {
153 $query = implode('', $parts);
154 $query = str_replace('&amp;', '&', $query); // both & and &amp; are stored in db :-|
155 $parts = explode('&', $query);
156 $eq = urlencode('=');
157 foreach ($parts as $key=>$part) {
158 $part = urlencode(urldecode($part));
159 $part = str_replace($eq, '=', $part);
160 $parts[$key] = $part;
162 $query = '?'.implode('&amp;', $parts);
165 return $script.$query;
169 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
170 $modname="", $modid=0, $modaction="", $groupid=0) {
171 global $CFG, $DB;
173 // It is assumed that $date is the GMT time of midnight for that day,
174 // and so the next 86400 seconds worth of logs are printed.
176 /// Setup for group handling.
178 // TODO: I don't understand group/context/etc. enough to be able to do
179 // something interesting with it here
180 // What is the context of a remote course?
182 /// If the group mode is separate, and this user does not have editing privileges,
183 /// then only the user's group can be viewed.
184 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
185 // $groupid = get_current_group($course->id);
187 /// If this course doesn't have groups, no groupid can be specified.
188 //else if (!$course->groupmode) {
189 // $groupid = 0;
192 $groupid = 0;
194 $joins = array();
195 $where = '';
197 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
198 FROM {mnet_log} l
199 LEFT JOIN {user} u ON l.userid = u.id
200 WHERE ";
201 $params = array();
203 $where .= "l.hostid = :hostid";
204 $params['hostid'] = $hostid;
206 // TODO: Is 1 really a magic number referring to the sitename?
207 if ($course != SITEID || $modid != 0) {
208 $where .= " AND l.course=:courseid";
209 $params['courseid'] = $course;
212 if ($modname) {
213 $where .= " AND l.module = :modname";
214 $params['modname'] = $modname;
217 if ('site_errors' === $modid) {
218 $where .= " AND ( l.action='error' OR l.action='infected' )";
219 } else if ($modid) {
220 //TODO: This assumes that modids are the same across sites... probably
221 //not true
222 $where .= " AND l.cmid = :modid";
223 $params['modid'] = $modid;
226 if ($modaction) {
227 $firstletter = substr($modaction, 0, 1);
228 if ($firstletter == '-') {
229 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
230 $params['modaction'] = '%'.substr($modaction, 1).'%';
231 } else {
232 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
233 $params['modaction'] = '%'.$modaction.'%';
237 if ($user) {
238 $where .= " AND l.userid = :user";
239 $params['user'] = $user;
242 if ($date) {
243 $enddate = $date + 86400;
244 $where .= " AND l.time > :date AND l.time < :enddate";
245 $params['date'] = $date;
246 $params['enddate'] = $enddate;
249 $result = array();
250 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
251 if(!empty($result['totalcount'])) {
252 $where .= " ORDER BY $order";
253 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
254 } else {
255 $result['logs'] = array();
257 return $result;
261 * Checks the integrity of the course data.
263 * In summary - compares course_sections.sequence and course_modules.section.
265 * More detailed, checks that:
266 * - course_sections.sequence contains each module id not more than once in the course
267 * - for each moduleid from course_sections.sequence the field course_modules.section
268 * refers to the same section id (this means course_sections.sequence is more
269 * important if they are different)
270 * - ($fullcheck only) each module in the course is present in one of
271 * course_sections.sequence
272 * - ($fullcheck only) removes non-existing course modules from section sequences
274 * If there are any mismatches, the changes are made and records are updated in DB.
276 * Course cache is NOT rebuilt if there are any errors!
278 * This function is used each time when course cache is being rebuilt with $fullcheck = false
279 * and in CLI script admin/cli/fix_course_sequence.php with $fullcheck = true
281 * @param int $courseid id of the course
282 * @param array $rawmods result of funciton {@link get_course_mods()} - containst
283 * the list of enabled course modules in the course. Retrieved from DB if not specified.
284 * Argument ignored in cashe of $fullcheck, the list is retrieved form DB anyway.
285 * @param array $sections records from course_sections table for this course.
286 * Retrieved from DB if not specified
287 * @param bool $fullcheck Will add orphaned modules to their sections and remove non-existing
288 * course modules from sequences. Only to be used in site maintenance mode when we are
289 * sure that another user is not in the middle of the process of moving/removing a module.
290 * @param bool $checkonly Only performs the check without updating DB, outputs all errors as debug messages.
291 * @return array array of messages with found problems. Empty output means everything is ok
293 function course_integrity_check($courseid, $rawmods = null, $sections = null, $fullcheck = false, $checkonly = false) {
294 global $DB;
295 $messages = array();
296 if ($sections === null) {
297 $sections = $DB->get_records('course_sections', array('course' => $courseid), 'section', 'id,section,sequence');
299 if ($fullcheck) {
300 // Retrieve all records from course_modules regardless of module type visibility.
301 $rawmods = $DB->get_records('course_modules', array('course' => $courseid), 'id', 'id,section');
303 if ($rawmods === null) {
304 $rawmods = get_course_mods($courseid);
306 if (!$fullcheck && (empty($sections) || empty($rawmods))) {
307 // If either of the arrays is empty, no modules are displayed anyway.
308 return true;
310 $debuggingprefix = 'Failed integrity check for course ['.$courseid.']. ';
312 // First make sure that each module id appears in section sequences only once.
313 // If it appears in several section sequences the last section wins.
314 // If it appears twice in one section sequence, the first occurence wins.
315 $modsection = array();
316 foreach ($sections as $sectionid => $section) {
317 $sections[$sectionid]->newsequence = $section->sequence;
318 if (!empty($section->sequence)) {
319 $sequence = explode(",", $section->sequence);
320 $sequenceunique = array_unique($sequence);
321 if (count($sequenceunique) != count($sequence)) {
322 // Some course module id appears in this section sequence more than once.
323 ksort($sequenceunique); // Preserve initial order of modules.
324 $sequence = array_values($sequenceunique);
325 $sections[$sectionid]->newsequence = join(',', $sequence);
326 $messages[] = $debuggingprefix.'Sequence for course section ['.
327 $sectionid.'] is "'.$sections[$sectionid]->sequence.'", must be "'.$sections[$sectionid]->newsequence.'"';
329 foreach ($sequence as $cmid) {
330 if (array_key_exists($cmid, $modsection) && isset($rawmods[$cmid])) {
331 // Some course module id appears to be in more than one section's sequences.
332 $wrongsectionid = $modsection[$cmid];
333 $sections[$wrongsectionid]->newsequence = trim(preg_replace("/,$cmid,/", ',', ','.$sections[$wrongsectionid]->newsequence. ','), ',');
334 $messages[] = $debuggingprefix.'Course module ['.$cmid.'] must be removed from sequence of section ['.
335 $wrongsectionid.'] because it is also present in sequence of section ['.$sectionid.']';
337 $modsection[$cmid] = $sectionid;
342 // Add orphaned modules to their sections if they exist or to section 0 otherwise.
343 if ($fullcheck) {
344 foreach ($rawmods as $cmid => $mod) {
345 if (!isset($modsection[$cmid])) {
346 // This is a module that is not mentioned in course_section.sequence at all.
347 // Add it to the section $mod->section or to the last available section.
348 if ($mod->section && isset($sections[$mod->section])) {
349 $modsection[$cmid] = $mod->section;
350 } else {
351 $firstsection = reset($sections);
352 $modsection[$cmid] = $firstsection->id;
354 $sections[$modsection[$cmid]]->newsequence = trim($sections[$modsection[$cmid]]->newsequence.','.$cmid, ',');
355 $messages[] = $debuggingprefix.'Course module ['.$cmid.'] is missing from sequence of section ['.
356 $modsection[$cmid].']';
359 foreach ($modsection as $cmid => $sectionid) {
360 if (!isset($rawmods[$cmid])) {
361 // Section $sectionid refers to module id that does not exist.
362 $sections[$sectionid]->newsequence = trim(preg_replace("/,$cmid,/", ',', ','.$sections[$sectionid]->newsequence.','), ',');
363 $messages[] = $debuggingprefix.'Course module ['.$cmid.
364 '] does not exist but is present in the sequence of section ['.$sectionid.']';
369 // Update changed sections.
370 if (!$checkonly && !empty($messages)) {
371 foreach ($sections as $sectionid => $section) {
372 if ($section->newsequence !== $section->sequence) {
373 $DB->update_record('course_sections', array('id' => $sectionid, 'sequence' => $section->newsequence));
378 // Now make sure that all modules point to the correct sections.
379 foreach ($rawmods as $cmid => $mod) {
380 if (isset($modsection[$cmid]) && $modsection[$cmid] != $mod->section) {
381 if (!$checkonly) {
382 $DB->update_record('course_modules', array('id' => $cmid, 'section' => $modsection[$cmid]));
384 $messages[] = $debuggingprefix.'Course module ['.$cmid.
385 '] points to section ['.$mod->section.'] instead of ['.$modsection[$cmid].']';
389 return $messages;
393 * Returns an array where the key is the module name (component name without 'mod_')
394 * and the value is a lang_string object with a human-readable string.
396 * @param bool $plural If true, the function returns the plural forms of the names.
397 * @param bool $resetcache If true, the static cache will be reset
398 * @return lang_string[] Localised human-readable names of all used modules.
400 function get_module_types_names($plural = false, $resetcache = false) {
401 static $modnames = null;
402 global $DB, $CFG;
403 if ($modnames === null || empty($modnames[0]) || $resetcache) {
404 $modnames = array(0 => array(), 1 => array());
405 if ($allmods = $DB->get_records("modules")) {
406 foreach ($allmods as $mod) {
407 if (file_exists("$CFG->dirroot/mod/$mod->name/lib.php") && $mod->visible) {
408 $modnames[0][$mod->name] = get_string("modulename", "$mod->name", null, true);
409 $modnames[1][$mod->name] = get_string("modulenameplural", "$mod->name", null, true);
414 return $modnames[(int)$plural];
418 * Set highlighted section. Only one section can be highlighted at the time.
420 * @param int $courseid course id
421 * @param int $marker highlight section with this number, 0 means remove higlightin
422 * @return void
424 function course_set_marker($courseid, $marker) {
425 global $DB, $COURSE;
426 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
427 if ($COURSE && $COURSE->id == $courseid) {
428 $COURSE->marker = $marker;
430 core_courseformat\base::reset_course_cache($courseid);
431 course_modinfo::clear_instance_cache($courseid);
435 * For a given course section, marks it visible or hidden,
436 * and does the same for every activity in that section
438 * @param int $courseid course id
439 * @param int $sectionnumber The section number to adjust
440 * @param int $visibility The new visibility
441 * @return array A list of resources which were hidden in the section
443 function set_section_visible($courseid, $sectionnumber, $visibility) {
444 global $DB;
446 $resourcestotoggle = array();
447 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
448 course_update_section($courseid, $section, array('visible' => $visibility));
450 // Determine which modules are visible for AJAX update
451 $modules = !empty($section->sequence) ? explode(',', $section->sequence) : array();
452 if (!empty($modules)) {
453 list($insql, $params) = $DB->get_in_or_equal($modules);
454 $select = 'id ' . $insql . ' AND visible = ?';
455 array_push($params, $visibility);
456 if (!$visibility) {
457 $select .= ' AND visibleold = 1';
459 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
462 return $resourcestotoggle;
466 * Return the course category context for the category with id $categoryid, except
467 * that if $categoryid is 0, return the system context.
469 * @param integer $categoryid a category id or 0.
470 * @return context the corresponding context
472 function get_category_or_system_context($categoryid) {
473 if ($categoryid) {
474 return context_coursecat::instance($categoryid, IGNORE_MISSING);
475 } else {
476 return context_system::instance();
481 * Print the buttons relating to course requests.
483 * @param context $context current page context.
484 * @deprecated since Moodle 4.0
485 * @todo Final deprecation MDL-73976
487 function print_course_request_buttons($context) {
488 global $CFG, $DB, $OUTPUT;
489 debugging("print_course_request_buttons() is deprecated. " .
490 "This is replaced with the category_action_bar tertiary navigation.", DEBUG_DEVELOPER);
491 if (empty($CFG->enablecourserequests)) {
492 return;
494 if (course_request::can_request($context)) {
495 // Print a button to request a new course.
496 $params = [];
497 if ($context instanceof context_coursecat) {
498 $params['category'] = $context->instanceid;
500 echo $OUTPUT->single_button(new moodle_url('/course/request.php', $params),
501 get_string('requestcourse'), 'get');
503 /// Print a button to manage pending requests
504 if (has_capability('moodle/site:approvecourse', $context)) {
505 $disabled = !$DB->record_exists('course_request', array());
506 echo $OUTPUT->single_button(new moodle_url('/course/pending.php'), get_string('coursespending'), 'get', array('disabled' => $disabled));
511 * Does the user have permission to edit things in this category?
513 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
514 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
516 function can_edit_in_category($categoryid = 0) {
517 $context = get_category_or_system_context($categoryid);
518 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
521 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
523 function add_course_module($mod) {
524 global $DB;
526 $mod->added = time();
527 unset($mod->id);
529 $cmid = $DB->insert_record("course_modules", $mod);
530 rebuild_course_cache($mod->course, true);
531 return $cmid;
535 * Creates a course section and adds it to the specified position
537 * @param int|stdClass $courseorid course id or course object
538 * @param int $position position to add to, 0 means to the end. If position is greater than
539 * number of existing secitons, the section is added to the end. This will become sectionnum of the
540 * new section. All existing sections at this or bigger position will be shifted down.
541 * @param bool $skipcheck the check has already been made and we know that the section with this position does not exist
542 * @return stdClass created section object
544 function course_create_section($courseorid, $position = 0, $skipcheck = false) {
545 return formatactions::section($courseorid)->create($position, $skipcheck);
549 * Creates missing course section(s) and rebuilds course cache
551 * @param int|stdClass $courseorid course id or course object
552 * @param int|array $sections list of relative section numbers to create
553 * @return bool if there were any sections created
555 function course_create_sections_if_missing($courseorid, $sections) {
556 if (!is_array($sections)) {
557 $sections = array($sections);
559 return formatactions::section($courseorid)->create_if_missing($sections);
563 * Adds an existing module to the section
565 * Updates both tables {course_sections} and {course_modules}
567 * Note: This function does not use modinfo PROVIDED that the section you are
568 * adding the module to already exists. If the section does not exist, it will
569 * build modinfo if necessary and create the section.
571 * @param int|stdClass $courseorid course id or course object
572 * @param int $cmid id of the module already existing in course_modules table
573 * @param int $sectionnum relative number of the section (field course_sections.section)
574 * If section does not exist it will be created
575 * @param int|stdClass $beforemod id or object with field id corresponding to the module
576 * before which the module needs to be included. Null for inserting in the
577 * end of the section
578 * @return int The course_sections ID where the module is inserted
580 function course_add_cm_to_section($courseorid, $cmid, $sectionnum, $beforemod = null) {
581 global $DB, $COURSE;
582 if (is_object($beforemod)) {
583 $beforemod = $beforemod->id;
585 if (is_object($courseorid)) {
586 $courseid = $courseorid->id;
587 } else {
588 $courseid = $courseorid;
590 // Do not try to use modinfo here, there is no guarantee it is valid!
591 $section = $DB->get_record('course_sections',
592 array('course' => $courseid, 'section' => $sectionnum), '*', IGNORE_MISSING);
593 if (!$section) {
594 // This function call requires modinfo.
595 course_create_sections_if_missing($courseorid, $sectionnum);
596 $section = $DB->get_record('course_sections',
597 array('course' => $courseid, 'section' => $sectionnum), '*', MUST_EXIST);
600 $modarray = explode(",", trim($section->sequence));
601 if (empty($section->sequence)) {
602 $newsequence = "$cmid";
603 } else if ($beforemod && ($key = moodle_array_keys_filter($modarray, $beforemod))) {
604 $insertarray = array($cmid, $beforemod);
605 array_splice($modarray, $key[0], 1, $insertarray);
606 $newsequence = implode(",", $modarray);
607 } else {
608 $newsequence = "$section->sequence,$cmid";
610 $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id));
611 $DB->set_field('course_modules', 'section', $section->id, array('id' => $cmid));
612 rebuild_course_cache($courseid, true);
613 return $section->id; // Return course_sections ID that was used.
617 * Change the group mode of a course module.
619 * Note: Do not forget to trigger the event \core\event\course_module_updated as it needs
620 * to be triggered manually, refer to {@link \core\event\course_module_updated::create_from_cm()}.
622 * @param int $id course module ID.
623 * @param int $groupmode the new groupmode value.
624 * @return bool True if the $groupmode was updated.
626 function set_coursemodule_groupmode($id, $groupmode) {
627 global $DB;
628 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST);
629 if ($cm->groupmode != $groupmode) {
630 $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id));
631 \course_modinfo::purge_course_module_cache($cm->course, $cm->id);
632 rebuild_course_cache($cm->course, false, true);
634 return ($cm->groupmode != $groupmode);
637 function set_coursemodule_idnumber($id, $idnumber) {
638 global $DB;
639 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST);
640 if ($cm->idnumber != $idnumber) {
641 $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id));
642 \course_modinfo::purge_course_module_cache($cm->course, $cm->id);
643 rebuild_course_cache($cm->course, false, true);
645 return ($cm->idnumber != $idnumber);
649 * Set downloadcontent value to course module.
651 * @param int $id The id of the module.
652 * @param bool $downloadcontent Whether the module can be downloaded when download course content is enabled.
653 * @return bool True if downloadcontent has been updated, false otherwise.
655 function set_downloadcontent(int $id, bool $downloadcontent): bool {
656 global $DB;
657 $cm = $DB->get_record('course_modules', ['id' => $id], 'id, course, downloadcontent', MUST_EXIST);
658 if ($cm->downloadcontent != $downloadcontent) {
659 $DB->set_field('course_modules', 'downloadcontent', $downloadcontent, ['id' => $cm->id]);
660 rebuild_course_cache($cm->course, true);
662 return ($cm->downloadcontent != $downloadcontent);
666 * Set the visibility of a module and inherent properties.
668 * Note: Do not forget to trigger the event \core\event\course_module_updated as it needs
669 * to be triggered manually, refer to {@link \core\event\course_module_updated::create_from_cm()}.
671 * From 2.4 the parameter $prevstateoverrides has been removed, the logic it triggered
672 * has been moved to {@link set_section_visible()} which was the only place from which
673 * the parameter was used.
675 * If $rebuildcache is set to false, the calling code is responsible for ensuring the cache is purged
676 * and rebuilt as appropriate. Consider using this if set_coursemodule_visible is called multiple times
677 * (e.g. in a loop).
679 * @param int $id of the module
680 * @param int $visible state of the module
681 * @param int $visibleoncoursepage state of the module on the course page
682 * @param bool $rebuildcache If true (default), perform a partial cache purge and rebuild.
683 * @return bool false when the module was not found, true otherwise
685 function set_coursemodule_visible($id, $visible, $visibleoncoursepage = 1, bool $rebuildcache = true) {
686 global $DB, $CFG;
687 require_once($CFG->libdir.'/gradelib.php');
688 require_once($CFG->dirroot.'/calendar/lib.php');
690 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
691 return false;
694 // Create events and propagate visibility to associated grade items if the value has changed.
695 // Only do this if it's changed to avoid accidently overwriting manual showing/hiding of student grades.
696 if ($cm->visible == $visible && $cm->visibleoncoursepage == $visibleoncoursepage) {
697 return true;
700 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
701 return false;
703 if (($cm->visible != $visible) &&
704 ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename)))) {
705 foreach($events as $event) {
706 if ($visible) {
707 $event = new calendar_event($event);
708 $event->toggle_visibility(true);
709 } else {
710 $event = new calendar_event($event);
711 $event->toggle_visibility(false);
716 // Updating visible and visibleold to keep them in sync. Only changing a section visibility will
717 // affect visibleold to allow for an original visibility restore. See set_section_visible().
718 $cminfo = new stdClass();
719 $cminfo->id = $id;
720 $cminfo->visible = $visible;
721 $cminfo->visibleoncoursepage = $visibleoncoursepage;
722 $cminfo->visibleold = $visible;
723 $DB->update_record('course_modules', $cminfo);
725 // Hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there.
726 // Note that this must be done after updating the row in course_modules, in case
727 // the modules grade_item_update function needs to access $cm->visible.
728 if ($cm->visible != $visible &&
729 plugin_supports('mod', $modulename, FEATURE_CONTROLS_GRADE_VISIBILITY) &&
730 component_callback_exists('mod_' . $modulename, 'grade_item_update')) {
731 $instance = $DB->get_record($modulename, array('id' => $cm->instance), '*', MUST_EXIST);
732 component_callback('mod_' . $modulename, 'grade_item_update', array($instance));
733 } else if ($cm->visible != $visible) {
734 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
735 if ($grade_items) {
736 foreach ($grade_items as $grade_item) {
737 $grade_item->set_hidden(!$visible);
742 if ($rebuildcache) {
743 \course_modinfo::purge_course_module_cache($cm->course, $cm->id);
744 rebuild_course_cache($cm->course, false, true);
746 return true;
750 * Changes the course module name
752 * @param int $id course module id
753 * @param string $name new value for a name
754 * @return bool whether a change was made
756 function set_coursemodule_name($id, $name) {
757 global $CFG, $DB;
758 require_once($CFG->libdir . '/gradelib.php');
760 $cm = get_coursemodule_from_id('', $id, 0, false, MUST_EXIST);
762 $module = new \stdClass();
763 $module->id = $cm->instance;
765 // Escape strings as they would be by mform.
766 if (!empty($CFG->formatstringstriptags)) {
767 $module->name = clean_param($name, PARAM_TEXT);
768 } else {
769 $module->name = clean_param($name, PARAM_CLEANHTML);
771 if ($module->name === $cm->name || strval($module->name) === '') {
772 return false;
774 if (\core_text::strlen($module->name) > 255) {
775 throw new \moodle_exception('maximumchars', 'moodle', '', 255);
778 $module->timemodified = time();
779 $DB->update_record($cm->modname, $module);
780 $cm->name = $module->name;
781 \core\event\course_module_updated::create_from_cm($cm)->trigger();
782 \course_modinfo::purge_course_module_cache($cm->course, $cm->id);
783 rebuild_course_cache($cm->course, false, true);
785 // Attempt to update the grade item if relevant.
786 $grademodule = $DB->get_record($cm->modname, array('id' => $cm->instance));
787 $grademodule->cmidnumber = $cm->idnumber;
788 $grademodule->modname = $cm->modname;
789 grade_update_mod_grades($grademodule);
791 // Update calendar events with the new name.
792 course_module_update_calendar_events($cm->modname, $grademodule, $cm);
794 return true;
798 * This function will handle the whole deletion process of a module. This includes calling
799 * the modules delete_instance function, deleting files, events, grades, conditional data,
800 * the data in the course_module and course_sections table and adding a module deletion
801 * event to the DB.
803 * @param int $cmid the course module id
804 * @param bool $async whether or not to try to delete the module using an adhoc task. Async also depends on a plugin hook.
805 * @throws moodle_exception
806 * @since Moodle 2.5
808 function course_delete_module($cmid, $async = false) {
809 // Check the 'course_module_background_deletion_recommended' hook first.
810 // Only use asynchronous deletion if at least one plugin returns true and if async deletion has been requested.
811 // Both are checked because plugins should not be allowed to dictate the deletion behaviour, only support/decline it.
812 // It's up to plugins to handle things like whether or not they are enabled.
813 if ($async && $pluginsfunction = get_plugins_with_function('course_module_background_deletion_recommended')) {
814 foreach ($pluginsfunction as $plugintype => $plugins) {
815 foreach ($plugins as $pluginfunction) {
816 if ($pluginfunction()) {
817 return course_module_flag_for_async_deletion($cmid);
823 global $CFG, $DB;
825 require_once($CFG->libdir.'/gradelib.php');
826 require_once($CFG->libdir.'/questionlib.php');
827 require_once($CFG->dirroot.'/blog/lib.php');
828 require_once($CFG->dirroot.'/calendar/lib.php');
830 // Get the course module.
831 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
832 return true;
835 // Get the module context.
836 $modcontext = context_module::instance($cm->id);
838 // Get the course module name.
839 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
841 // Get the file location of the delete_instance function for this module.
842 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
844 // Include the file required to call the delete_instance function for this module.
845 if (file_exists($modlib)) {
846 require_once($modlib);
847 } else {
848 throw new moodle_exception('cannotdeletemodulemissinglib', '', '', null,
849 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
852 $deleteinstancefunction = $modulename . '_delete_instance';
854 // Ensure the delete_instance function exists for this module.
855 if (!function_exists($deleteinstancefunction)) {
856 throw new moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
857 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
860 // Allow plugins to use this course module before we completely delete it.
861 if ($pluginsfunction = get_plugins_with_function('pre_course_module_delete')) {
862 foreach ($pluginsfunction as $plugintype => $plugins) {
863 foreach ($plugins as $pluginfunction) {
864 $pluginfunction($cm);
869 // Call the delete_instance function, if it returns false throw an exception.
870 if (!$deleteinstancefunction($cm->instance)) {
871 throw new moodle_exception('cannotdeletemoduleinstance', '', '', null,
872 "Cannot delete the module $modulename (instance).");
875 question_delete_activity($cm);
877 // Remove all module files in case modules forget to do that.
878 $fs = get_file_storage();
879 $fs->delete_area_files($modcontext->id);
881 // Delete events from calendar.
882 if ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename))) {
883 $coursecontext = context_course::instance($cm->course);
884 foreach($events as $event) {
885 $event->context = $coursecontext;
886 $calendarevent = calendar_event::load($event);
887 $calendarevent->delete();
891 // Delete grade items, outcome items and grades attached to modules.
892 if ($grade_items = grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $modulename,
893 'iteminstance' => $cm->instance, 'courseid' => $cm->course))) {
894 foreach ($grade_items as $grade_item) {
895 $grade_item->delete('moddelete');
899 // Delete associated blogs and blog tag instances.
900 blog_remove_associations_for_module($modcontext->id);
902 // Delete completion and availability data; it is better to do this even if the
903 // features are not turned on, in case they were turned on previously (these will be
904 // very quick on an empty table).
905 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
906 $DB->delete_records('course_modules_viewed', ['coursemoduleid' => $cm->id]);
907 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
908 'course' => $cm->course,
909 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
911 // Delete all tag instances associated with the instance of this module.
912 core_tag_tag::delete_instances('mod_' . $modulename, null, $modcontext->id);
913 core_tag_tag::remove_all_item_tags('core', 'course_modules', $cm->id);
915 // Notify the competency subsystem.
916 \core_competency\api::hook_course_module_deleted($cm);
918 // Delete the context.
919 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
921 // Delete the module from the course_modules table.
922 $DB->delete_records('course_modules', array('id' => $cm->id));
924 // Delete module from that section.
925 if (!delete_mod_from_section($cm->id, $cm->section)) {
926 throw new moodle_exception('cannotdeletemodulefromsection', '', '', null,
927 "Cannot delete the module $modulename (instance) from section.");
930 // Trigger event for course module delete action.
931 $event = \core\event\course_module_deleted::create(array(
932 'courseid' => $cm->course,
933 'context' => $modcontext,
934 'objectid' => $cm->id,
935 'other' => array(
936 'modulename' => $modulename,
937 'instanceid' => $cm->instance,
940 $event->add_record_snapshot('course_modules', $cm);
941 $event->trigger();
942 \course_modinfo::purge_course_module_cache($cm->course, $cm->id);
943 rebuild_course_cache($cm->course, false, true);
947 * Schedule a course module for deletion in the background using an adhoc task.
949 * This method should not be called directly. Instead, please use course_delete_module($cmid, true), to denote async deletion.
950 * The real deletion of the module is handled by the task, which calls 'course_delete_module($cmid)'.
952 * @param int $cmid the course module id.
953 * @return bool whether the module was successfully scheduled for deletion.
954 * @throws \moodle_exception
956 function course_module_flag_for_async_deletion($cmid) {
957 global $CFG, $DB, $USER;
958 require_once($CFG->libdir.'/gradelib.php');
959 require_once($CFG->libdir.'/questionlib.php');
960 require_once($CFG->dirroot.'/blog/lib.php');
961 require_once($CFG->dirroot.'/calendar/lib.php');
963 // Get the course module.
964 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
965 return true;
968 // We need to be reasonably certain the deletion is going to succeed before we background the process.
969 // Make the necessary delete_instance checks, etc. before proceeding further. Throw exceptions if required.
971 // Get the course module name.
972 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
974 // Get the file location of the delete_instance function for this module.
975 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
977 // Include the file required to call the delete_instance function for this module.
978 if (file_exists($modlib)) {
979 require_once($modlib);
980 } else {
981 throw new \moodle_exception('cannotdeletemodulemissinglib', '', '', null,
982 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
985 $deleteinstancefunction = $modulename . '_delete_instance';
987 // Ensure the delete_instance function exists for this module.
988 if (!function_exists($deleteinstancefunction)) {
989 throw new \moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
990 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
993 // We are going to defer the deletion as we can't be sure how long the module's pre_delete code will run for.
994 $cm->deletioninprogress = '1';
995 $DB->update_record('course_modules', $cm);
997 // Create an adhoc task for the deletion of the course module. The task takes an array of course modules for removal.
998 $removaltask = new \core_course\task\course_delete_modules();
999 $removaltask->set_custom_data(array(
1000 'cms' => array($cm),
1001 'userid' => $USER->id,
1002 'realuserid' => \core\session\manager::get_realuser()->id
1005 // Queue the task for the next run.
1006 \core\task\manager::queue_adhoc_task($removaltask);
1008 // Reset the course cache to hide the module.
1009 rebuild_course_cache($cm->course, true);
1013 * Checks whether the given course has any course modules scheduled for adhoc deletion.
1015 * @param int $courseid the id of the course.
1016 * @param bool $onlygradable whether to check only gradable modules or all modules.
1017 * @return bool true if the course contains any modules pending deletion, false otherwise.
1019 function course_modules_pending_deletion(int $courseid, bool $onlygradable = false): bool {
1020 if (empty($courseid)) {
1021 return false;
1024 if ($onlygradable) {
1025 // Fetch modules with grade items.
1026 if (!$coursegradeitems = grade_item::fetch_all(['itemtype' => 'mod', 'courseid' => $courseid])) {
1027 // Return early when there is none.
1028 return false;
1032 $modinfo = get_fast_modinfo($courseid);
1033 foreach ($modinfo->get_cms() as $module) {
1034 if ($module->deletioninprogress == '1') {
1035 if ($onlygradable) {
1036 // Check if the module being deleted is in the list of course modules with grade items.
1037 foreach ($coursegradeitems as $coursegradeitem) {
1038 if ($coursegradeitem->itemmodule == $module->modname && $coursegradeitem->iteminstance == $module->instance) {
1039 // The module being deleted is within the gradable modules.
1040 return true;
1043 } else {
1044 return true;
1048 return false;
1052 * Checks whether the course module, as defined by modulename and instanceid, is scheduled for deletion within the given course.
1054 * @param int $courseid the course id.
1055 * @param string $modulename the module name. E.g. 'assign', 'book', etc.
1056 * @param int $instanceid the module instance id.
1057 * @return bool true if the course module is pending deletion, false otherwise.
1059 function course_module_instance_pending_deletion($courseid, $modulename, $instanceid) {
1060 if (empty($courseid) || empty($modulename) || empty($instanceid)) {
1061 return false;
1063 $modinfo = get_fast_modinfo($courseid);
1064 $instances = $modinfo->get_instances_of($modulename);
1065 return isset($instances[$instanceid]) && $instances[$instanceid]->deletioninprogress;
1068 function delete_mod_from_section($modid, $sectionid) {
1069 global $DB;
1071 if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
1073 $modarray = explode(",", $section->sequence);
1075 if ($key = moodle_array_keys_filter($modarray, $modid)) {
1076 array_splice($modarray, $key[0], 1);
1077 $newsequence = implode(",", $modarray);
1078 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
1079 rebuild_course_cache($section->course, true);
1080 return true;
1081 } else {
1082 return false;
1086 return false;
1090 * This function updates the calendar events from the information stored in the module table and the course
1091 * module table.
1093 * @param string $modulename Module name
1094 * @param stdClass $instance Module object. Either the $instance or the $cm must be supplied.
1095 * @param stdClass $cm Course module object. Either the $instance or the $cm must be supplied.
1096 * @return bool Returns true if calendar events are updated.
1097 * @since Moodle 3.3.4
1099 function course_module_update_calendar_events($modulename, $instance = null, $cm = null) {
1100 global $DB;
1102 if (isset($instance) || isset($cm)) {
1104 if (!isset($instance)) {
1105 $instance = $DB->get_record($modulename, array('id' => $cm->instance), '*', MUST_EXIST);
1107 if (!isset($cm)) {
1108 $cm = get_coursemodule_from_instance($modulename, $instance->id, $instance->course);
1110 if (!empty($cm)) {
1111 course_module_calendar_event_update_process($instance, $cm);
1113 return true;
1115 return false;
1119 * Update all instances through out the site or in a course.
1121 * @param string $modulename Module type to update.
1122 * @param integer $courseid Course id to update events. 0 for the whole site.
1123 * @return bool Returns True if the update was successful.
1124 * @since Moodle 3.3.4
1126 function course_module_bulk_update_calendar_events($modulename, $courseid = 0) {
1127 global $DB;
1129 $instances = null;
1130 if ($courseid) {
1131 if (!$instances = $DB->get_records($modulename, array('course' => $courseid))) {
1132 return false;
1134 } else {
1135 if (!$instances = $DB->get_records($modulename)) {
1136 return false;
1140 foreach ($instances as $instance) {
1141 if ($cm = get_coursemodule_from_instance($modulename, $instance->id, $instance->course)) {
1142 course_module_calendar_event_update_process($instance, $cm);
1145 return true;
1149 * Calendar events for a module instance are updated.
1151 * @param stdClass $instance Module instance object.
1152 * @param stdClass $cm Course Module object.
1153 * @since Moodle 3.3.4
1155 function course_module_calendar_event_update_process($instance, $cm) {
1156 // We need to call *_refresh_events() first because some modules delete 'old' events at the end of the code which
1157 // will remove the completion events.
1158 $refresheventsfunction = $cm->modname . '_refresh_events';
1159 if (function_exists($refresheventsfunction)) {
1160 call_user_func($refresheventsfunction, $cm->course, $instance, $cm);
1162 $completionexpected = (!empty($cm->completionexpected)) ? $cm->completionexpected : null;
1163 \core_completion\api::update_completion_date_event($cm->id, $cm->modname, $instance, $completionexpected);
1167 * Moves a section within a course, from a position to another.
1168 * Be very careful: $section and $destination refer to section number,
1169 * not id!.
1171 * @param object $course
1172 * @param int $section Section number (not id!!!)
1173 * @param int $destination
1174 * @param bool $ignorenumsections
1175 * @return boolean Result
1177 function move_section_to($course, $section, $destination, $ignorenumsections = false) {
1178 /// Moves a whole course section up and down within the course
1179 global $USER, $DB;
1181 if (!$destination && $destination != 0) {
1182 return true;
1185 // compartibility with course formats using field 'numsections'
1186 $courseformatoptions = course_get_format($course)->get_format_options();
1187 if ((!$ignorenumsections && array_key_exists('numsections', $courseformatoptions) &&
1188 ($destination > $courseformatoptions['numsections'])) || ($destination < 1)) {
1189 return false;
1192 // Get all sections for this course and re-order them (2 of them should now share the same section number)
1193 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
1194 'section ASC, id ASC', 'id, section')) {
1195 return false;
1198 $movedsections = reorder_sections($sections, $section, $destination);
1200 // Update all sections. Do this in 2 steps to avoid breaking database
1201 // uniqueness constraint
1202 $transaction = $DB->start_delegated_transaction();
1203 foreach ($movedsections as $id => $position) {
1204 if ((int) $sections[$id] !== $position) {
1205 $DB->set_field('course_sections', 'section', -$position, ['id' => $id]);
1206 // Invalidate the section cache by given section id.
1207 course_modinfo::purge_course_section_cache_by_id($course->id, $id);
1210 foreach ($movedsections as $id => $position) {
1211 if ((int) $sections[$id] !== $position) {
1212 $DB->set_field('course_sections', 'section', $position, ['id' => $id]);
1213 // Invalidate the section cache by given section id.
1214 course_modinfo::purge_course_section_cache_by_id($course->id, $id);
1218 // If we move the highlighted section itself, then just highlight the destination.
1219 // Adjust the higlighted section location if we move something over it either direction.
1220 if ($section == $course->marker) {
1221 course_set_marker($course->id, $destination);
1222 } else if ($section > $course->marker && $course->marker >= $destination) {
1223 course_set_marker($course->id, $course->marker+1);
1224 } else if ($section < $course->marker && $course->marker <= $destination) {
1225 course_set_marker($course->id, $course->marker-1);
1228 $transaction->allow_commit();
1229 rebuild_course_cache($course->id, true, true);
1230 return true;
1234 * This method will delete a course section and may delete all modules inside it.
1236 * No permissions are checked here, use {@link course_can_delete_section()} to
1237 * check if section can actually be deleted.
1239 * @param int|stdClass $course
1240 * @param int|stdClass|section_info $sectionornum
1241 * @param bool $forcedeleteifnotempty if set to false section will not be deleted if it has modules in it.
1242 * @param bool $async whether or not to try to delete the section using an adhoc task. Async also depends on a plugin hook.
1243 * @return bool whether section was deleted
1245 function course_delete_section($course, $sectionornum, $forcedeleteifnotempty = true, $async = false) {
1246 $sectionnum = (is_object($sectionornum)) ? $sectionornum->section : (int)$sectionornum;
1247 $sectioninfo = get_fast_modinfo($course)->get_section_info($sectionnum);
1248 if (!$sectioninfo) {
1249 return false;
1251 return formatactions::section($course)->delete($sectioninfo, $forcedeleteifnotempty, $async);
1255 * Course section deletion, using an adhoc task for deletion of the modules it contains.
1256 * 1. Schedule all modules within the section for adhoc removal.
1257 * 2. Move all modules to course section 0.
1258 * 3. Delete the resulting empty section.
1260 * @param \stdClass $section the section to schedule for deletion.
1261 * @param bool $forcedeleteifnotempty whether to force section deletion if it contains modules.
1262 * @return bool true if the section was scheduled for deletion, false otherwise.
1264 function course_delete_section_async($section, $forcedeleteifnotempty = true) {
1265 if (!is_object($section) || empty($section->id) || empty($section->course)) {
1266 return false;
1268 $sectioninfo = get_fast_modinfo($section->course)->get_section_info_by_id($section->id);
1269 if (!$sectioninfo) {
1270 return false;
1272 return formatactions::section($section->course)->delete_async($sectioninfo, $forcedeleteifnotempty);
1276 * Updates the course section
1278 * This function does not check permissions or clean values - this has to be done prior to calling it.
1280 * @param int|stdClass $course
1281 * @param stdClass $section record from course_sections table - it will be updated with the new values
1282 * @param array|stdClass $data
1284 function course_update_section($course, $section, $data) {
1285 global $DB;
1287 $courseid = (is_object($course)) ? $course->id : (int)$course;
1289 // Some fields can not be updated using this method.
1290 $data = array_diff_key((array)$data, array('id', 'course', 'section', 'sequence'));
1291 $changevisibility = (array_key_exists('visible', $data) && (bool)$data['visible'] != (bool)$section->visible);
1292 if (array_key_exists('name', $data) && \core_text::strlen($data['name']) > 255) {
1293 throw new moodle_exception('maximumchars', 'moodle', '', 255);
1296 // Update record in the DB and course format options.
1297 $data['id'] = $section->id;
1298 $data['timemodified'] = time();
1299 $DB->update_record('course_sections', $data);
1300 // Invalidate the section cache by given section id.
1301 course_modinfo::purge_course_section_cache_by_id($courseid, $section->id);
1302 rebuild_course_cache($courseid, false, true);
1303 course_get_format($courseid)->update_section_format_options($data);
1305 // Update fields of the $section object.
1306 foreach ($data as $key => $value) {
1307 if (property_exists($section, $key)) {
1308 $section->$key = $value;
1312 // Trigger an event for course section update.
1313 $event = \core\event\course_section_updated::create(
1314 array(
1315 'objectid' => $section->id,
1316 'courseid' => $courseid,
1317 'context' => context_course::instance($courseid),
1318 'other' => array('sectionnum' => $section->section)
1321 $event->trigger();
1323 // If section visibility was changed, hide the modules in this section too.
1324 if ($changevisibility && !empty($section->sequence)) {
1325 $modules = explode(',', $section->sequence);
1326 $cmids = [];
1327 foreach ($modules as $moduleid) {
1328 if ($cm = get_coursemodule_from_id(null, $moduleid, $courseid)) {
1329 $cmids[] = $cm->id;
1330 if ($data['visible']) {
1331 // As we unhide the section, we use the previously saved visibility stored in visibleold.
1332 set_coursemodule_visible($moduleid, $cm->visibleold, $cm->visibleoncoursepage, false);
1333 } else {
1334 // We hide the section, so we hide the module but we store the original state in visibleold.
1335 set_coursemodule_visible($moduleid, 0, $cm->visibleoncoursepage, false);
1336 $DB->set_field('course_modules', 'visibleold', $cm->visible, ['id' => $moduleid]);
1338 \core\event\course_module_updated::create_from_cm($cm)->trigger();
1341 \course_modinfo::purge_course_modules_cache($courseid, $cmids);
1342 rebuild_course_cache($courseid, false, true);
1347 * Checks if the current user can delete a section (if course format allows it and user has proper permissions).
1349 * @param int|stdClass $course
1350 * @param int|stdClass|section_info $section
1351 * @return bool
1353 function course_can_delete_section($course, $section) {
1354 if (is_object($section)) {
1355 $section = $section->section;
1357 if (!$section) {
1358 // Not possible to delete 0-section.
1359 return false;
1361 // Course format should allow to delete sections.
1362 if (!course_get_format($course)->can_delete_section($section)) {
1363 return false;
1365 // Make sure user has capability to update course and move sections.
1366 $context = context_course::instance(is_object($course) ? $course->id : $course);
1367 if (!has_all_capabilities(array('moodle/course:movesections', 'moodle/course:update'), $context)) {
1368 return false;
1370 // Make sure user has capability to delete each activity in this section.
1371 $modinfo = get_fast_modinfo($course);
1372 if (!empty($modinfo->sections[$section])) {
1373 foreach ($modinfo->sections[$section] as $cmid) {
1374 if (!has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
1375 return false;
1379 return true;
1383 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
1384 * an original position number and a target position number, rebuilds the array so that the
1385 * move is made without any duplication of section positions.
1386 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
1387 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
1389 * @param array $sections
1390 * @param int $origin_position
1391 * @param int $target_position
1392 * @return array
1394 function reorder_sections($sections, $origin_position, $target_position) {
1395 if (!is_array($sections)) {
1396 return false;
1399 // We can't move section position 0
1400 if ($origin_position < 1) {
1401 echo "We can't move section position 0";
1402 return false;
1405 // Locate origin section in sections array
1406 if (!$origin_key = array_search($origin_position, $sections)) {
1407 echo "searched position not in sections array";
1408 return false; // searched position not in sections array
1411 // Extract origin section
1412 $origin_section = $sections[$origin_key];
1413 unset($sections[$origin_key]);
1415 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
1416 $found = false;
1417 $append_array = array();
1418 foreach ($sections as $id => $position) {
1419 if ($found) {
1420 $append_array[$id] = $position;
1421 unset($sections[$id]);
1423 if ($position == $target_position) {
1424 if ($target_position < $origin_position) {
1425 $append_array[$id] = $position;
1426 unset($sections[$id]);
1428 $found = true;
1432 // Append moved section
1433 $sections[$origin_key] = $origin_section;
1435 // Append rest of array (if applicable)
1436 if (!empty($append_array)) {
1437 foreach ($append_array as $id => $position) {
1438 $sections[$id] = $position;
1442 // Renumber positions
1443 $position = 0;
1444 foreach ($sections as $id => $p) {
1445 $sections[$id] = $position;
1446 $position++;
1449 return $sections;
1454 * Move the module object $mod to the specified $section
1455 * If $beforemod exists then that is the module
1456 * before which $modid should be inserted
1458 * @param stdClass|cm_info $mod
1459 * @param stdClass|section_info $section
1460 * @param int|stdClass $beforemod id or object with field id corresponding to the module
1461 * before which the module needs to be included. Null for inserting in the
1462 * end of the section
1463 * @return int new value for module visibility (0 or 1)
1465 function moveto_module($mod, $section, $beforemod=NULL) {
1466 global $OUTPUT, $DB;
1468 // Current module visibility state - return value of this function.
1469 $modvisible = $mod->visible;
1471 // Remove original module from original section.
1472 if (! delete_mod_from_section($mod->id, $mod->section)) {
1473 echo $OUTPUT->notification("Could not delete module from existing section");
1476 // Add the module into the new section.
1477 course_add_cm_to_section($section->course, $mod->id, $section->section, $beforemod);
1479 // If moving to a hidden section then hide module.
1480 if ($mod->section != $section->id) {
1481 if (!$section->visible && $mod->visible) {
1482 // Module was visible but must become hidden after moving to hidden section.
1483 $modvisible = 0;
1484 set_coursemodule_visible($mod->id, 0);
1485 // Set visibleold to 1 so module will be visible when section is made visible.
1486 $DB->set_field('course_modules', 'visibleold', 1, array('id' => $mod->id));
1488 if ($section->visible && !$mod->visible) {
1489 // Hidden module was moved to the visible section, restore the module visibility from visibleold.
1490 set_coursemodule_visible($mod->id, $mod->visibleold);
1491 $modvisible = $mod->visibleold;
1495 return $modvisible;
1499 * Returns the list of all editing actions that current user can perform on the module
1501 * @param cm_info $mod The module to produce editing buttons for
1502 * @param int $indent The current indenting (default -1 means no move left-right actions)
1503 * @param int $sr The section to link back to (used for creating the links)
1504 * @return array array of action_link or pix_icon objects
1506 function course_get_cm_edit_actions(cm_info $mod, $indent = -1, $sr = null) {
1507 global $COURSE, $SITE, $CFG;
1509 static $str;
1511 $coursecontext = context_course::instance($mod->course);
1512 $modcontext = context_module::instance($mod->id);
1513 $courseformat = course_get_format($mod->get_course());
1514 $usecomponents = $courseformat->supports_components();
1515 $sectioninfo = $mod->get_section_info();
1517 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
1518 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
1520 // No permission to edit anything.
1521 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
1522 return array();
1525 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
1527 if (!isset($str)) {
1528 $str = get_strings(
1530 'delete', 'move', 'moveright', 'moveleft', 'editsettings',
1531 'duplicate', 'availability'
1533 'moodle'
1535 $str->assign = get_string('assignroles', 'role');
1536 $str->groupmode = get_string('groupmode', 'group');
1539 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
1541 if ($sr !== null) {
1542 $baseurl->param('sr', $sr);
1544 $actions = array();
1546 // Update.
1547 if ($hasmanageactivities) {
1548 $actions['update'] = new action_menu_link_secondary(
1549 new moodle_url($baseurl, array('update' => $mod->id)),
1550 new pix_icon('t/edit', '', 'moodle', array('class' => 'iconsmall')),
1551 $str->editsettings,
1552 array('class' => 'editing_update', 'data-action' => 'update')
1556 // Move (only for component compatible formats).
1557 if ($hasmanageactivities && $usecomponents) {
1558 $actions['move'] = new action_menu_link_secondary(
1559 new moodle_url($baseurl, [
1560 'sesskey' => sesskey(),
1561 'copy' => $mod->id,
1563 new pix_icon('i/dragdrop', '', 'moodle', ['class' => 'iconsmall']),
1564 $str->move,
1566 'class' => 'editing_movecm',
1567 'data-action' => 'moveCm',
1568 'data-id' => $mod->id,
1573 // Indent.
1574 if ($hasmanageactivities && $indent >= 0) {
1575 $indentlimits = new stdClass();
1576 $indentlimits->min = 0;
1577 // Legacy indentation could continue using a limit of 16,
1578 // but components based formats will be forced to use one level indentation only.
1579 $indentlimits->max = ($usecomponents) ? 1 : 16;
1580 if (right_to_left()) { // Exchange arrows on RTL
1581 $rightarrow = 't/left';
1582 $leftarrow = 't/right';
1583 } else {
1584 $rightarrow = 't/right';
1585 $leftarrow = 't/left';
1588 if ($indent >= $indentlimits->max) {
1589 $enabledclass = 'hidden';
1590 } else {
1591 $enabledclass = '';
1593 $actions['moveright'] = new action_menu_link_secondary(
1594 new moodle_url($baseurl, ['id' => $mod->id, 'indent' => '1']),
1595 new pix_icon($rightarrow, '', 'moodle', ['class' => 'iconsmall']),
1596 $str->moveright,
1598 'class' => 'editing_moveright ' . $enabledclass,
1599 'data-action' => ($usecomponents) ? 'cmMoveRight' : 'moveright',
1600 'data-keepopen' => true,
1601 'data-sectionreturn' => $sr,
1602 'data-id' => $mod->id,
1606 if ($indent <= $indentlimits->min) {
1607 $enabledclass = 'hidden';
1608 } else {
1609 $enabledclass = '';
1611 $actions['moveleft'] = new action_menu_link_secondary(
1612 new moodle_url($baseurl, ['id' => $mod->id, 'indent' => '-1']),
1613 new pix_icon($leftarrow, '', 'moodle', ['class' => 'iconsmall']),
1614 $str->moveleft,
1616 'class' => 'editing_moveleft ' . $enabledclass,
1617 'data-action' => ($usecomponents) ? 'cmMoveLeft' : 'moveleft',
1618 'data-keepopen' => true,
1619 'data-sectionreturn' => $sr,
1620 'data-id' => $mod->id,
1626 // Hide/Show/Available/Unavailable.
1627 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
1628 $availabilityclass = $courseformat->get_output_classname('content\\cm\\visibility');
1629 /** @var core_courseformat\output\local\content\cm\visibility */
1630 $availability = new $availabilityclass($courseformat, $sectioninfo, $mod);
1631 $availabilitychoice = $availability->get_choice_list();
1632 if ($availabilitychoice->count_options() > 1) {
1633 $actions['availability'] = new action_menu_subpanel(
1634 $str->availability,
1635 $availabilitychoice,
1636 ['class' => 'editing_availability'],
1637 new pix_icon('t/hide', '', 'moodle', array('class' => 'iconsmall'))
1642 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
1643 if (has_all_capabilities($dupecaps, $coursecontext) &&
1644 plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2) &&
1645 course_allowed_module($mod->get_course(), $mod->modname)) {
1646 $actions['duplicate'] = new action_menu_link_secondary(
1647 new moodle_url($baseurl, ['duplicate' => $mod->id]),
1648 new pix_icon('t/copy', '', 'moodle', array('class' => 'iconsmall')),
1649 $str->duplicate,
1651 'class' => 'editing_duplicate',
1652 'data-action' => ($courseformat->supports_components()) ? 'cmDuplicate' : 'duplicate',
1653 'data-sectionreturn' => $sr,
1654 'data-id' => $mod->id,
1659 // Assign.
1660 if (has_capability('moodle/role:assign', $modcontext)){
1661 $actions['assign'] = new action_menu_link_secondary(
1662 new moodle_url('/admin/roles/assign.php', array('contextid' => $modcontext->id)),
1663 new pix_icon('t/assignroles', '', 'moodle', array('class' => 'iconsmall')),
1664 $str->assign,
1665 array('class' => 'editing_assign', 'data-action' => 'assignroles', 'data-sectionreturn' => $sr)
1669 // Groupmode.
1670 if ($courseformat->show_groupmode($mod) && $usecomponents && !$mod->coursegroupmodeforce) {
1671 $groupmodeclass = $courseformat->get_output_classname('content\\cm\\groupmode');
1672 /** @var core_courseformat\output\local\content\cm\groupmode */
1673 $groupmode = new $groupmodeclass($courseformat, $sectioninfo, $mod);
1674 $actions['groupmode'] = new action_menu_subpanel(
1675 $str->groupmode,
1676 $groupmode->get_choice_list(),
1677 ['class' => 'editing_groupmode'],
1678 new pix_icon('i/groupv', '', 'moodle', ['class' => 'iconsmall'])
1682 // Delete.
1683 if ($hasmanageactivities) {
1684 $actions['delete'] = new action_menu_link_secondary(
1685 new moodle_url($baseurl, ['delete' => $mod->id]),
1686 new pix_icon('t/delete', '', 'moodle', ['class' => 'iconsmall']),
1687 $str->delete,
1689 'class' => 'editing_delete text-danger',
1690 'data-action' => ($usecomponents) ? 'cmDelete' : 'delete',
1691 'data-sectionreturn' => $sr,
1692 'data-id' => $mod->id,
1697 return $actions;
1701 * Returns the move action.
1703 * @param cm_info $mod The module to produce a move button for
1704 * @param int $sr The section to link back to (used for creating the links)
1705 * @return The markup for the move action, or an empty string if not available.
1707 function course_get_cm_move(cm_info $mod, $sr = null) {
1708 global $OUTPUT;
1710 static $str;
1711 static $baseurl;
1713 $modcontext = context_module::instance($mod->id);
1714 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
1716 if (!isset($str)) {
1717 $str = get_strings(array('move'));
1720 if (!isset($baseurl)) {
1721 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
1723 if ($sr !== null) {
1724 $baseurl->param('sr', $sr);
1728 if ($hasmanageactivities) {
1729 $pixicon = 'i/dragdrop';
1731 if (!course_ajax_enabled($mod->get_course())) {
1732 // Override for course frontpage until we get drag/drop working there.
1733 $pixicon = 't/move';
1736 $attributes = [
1737 'class' => 'editing_move',
1738 'data-action' => 'move',
1739 'data-sectionreturn' => $sr,
1740 'title' => $str->move,
1741 'aria-label' => $str->move,
1743 return html_writer::link(
1744 new moodle_url($baseurl, ['copy' => $mod->id]),
1745 $OUTPUT->pix_icon($pixicon, '', 'moodle', ['class' => 'iconsmall']),
1746 $attributes
1749 return '';
1753 * given a course object with shortname & fullname, this function will
1754 * truncate the the number of chars allowed and add ... if it was too long
1756 function course_format_name ($course,$max=100) {
1758 $context = context_course::instance($course->id);
1759 $shortname = format_string($course->shortname, true, array('context' => $context));
1760 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
1761 $str = $shortname.': '. $fullname;
1762 if (core_text::strlen($str) <= $max) {
1763 return $str;
1765 else {
1766 return core_text::substr($str,0,$max-3).'...';
1771 * Is the user allowed to add this type of module to this course?
1772 * @param object $course the course settings. Only $course->id is used.
1773 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
1774 * @param \stdClass $user the user to check, defaults to the global user if not provided.
1775 * @return bool whether the current user is allowed to add this type of module to this course.
1777 function course_allowed_module($course, $modname, \stdClass $user = null) {
1778 global $USER;
1779 $user = $user ?? $USER;
1780 if (is_numeric($modname)) {
1781 throw new coding_exception('Function course_allowed_module no longer
1782 supports numeric module ids. Please update your code to pass the module name.');
1785 $capability = 'mod/' . $modname . ':addinstance';
1786 if (!get_capability_info($capability)) {
1787 // Debug warning that the capability does not exist, but no more than once per page.
1788 static $warned = array();
1789 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1790 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
1791 debugging('The module ' . $modname . ' does not define the standard capability ' .
1792 $capability , DEBUG_DEVELOPER);
1793 $warned[$modname] = 1;
1796 // If the capability does not exist, the module can always be added.
1797 return true;
1800 $coursecontext = context_course::instance($course->id);
1801 return has_capability($capability, $coursecontext, $user);
1805 * Efficiently moves many courses around while maintaining
1806 * sortorder in order.
1808 * @param array $courseids is an array of course ids
1809 * @param int $categoryid
1810 * @return bool success
1812 function move_courses($courseids, $categoryid) {
1813 global $DB;
1815 if (empty($courseids)) {
1816 // Nothing to do.
1817 return false;
1820 if (!$category = $DB->get_record('course_categories', array('id' => $categoryid))) {
1821 return false;
1824 $courseids = array_reverse($courseids);
1825 $newparent = context_coursecat::instance($category->id);
1826 $i = 1;
1828 list($where, $params) = $DB->get_in_or_equal($courseids);
1829 $dbcourses = $DB->get_records_select('course', 'id ' . $where, $params, '', 'id, category, shortname, fullname');
1830 foreach ($dbcourses as $dbcourse) {
1831 $course = new stdClass();
1832 $course->id = $dbcourse->id;
1833 $course->timemodified = time();
1834 $course->category = $category->id;
1835 $course->sortorder = $category->sortorder + get_max_courses_in_category() - $i++;
1836 if ($category->visible == 0) {
1837 // Hide the course when moving into hidden category, do not update the visibleold flag - we want to get
1838 // to previous state if somebody unhides the category.
1839 $course->visible = 0;
1842 $DB->update_record('course', $course);
1844 // Update context, so it can be passed to event.
1845 $context = context_course::instance($course->id);
1846 $context->update_moved($newparent);
1848 // Trigger a course updated event.
1849 $event = \core\event\course_updated::create(array(
1850 'objectid' => $course->id,
1851 'context' => context_course::instance($course->id),
1852 'other' => array('shortname' => $dbcourse->shortname,
1853 'fullname' => $dbcourse->fullname,
1854 'updatedfields' => array('category' => $category->id))
1856 $event->trigger();
1858 fix_course_sortorder();
1859 cache_helper::purge_by_event('changesincourse');
1861 return true;
1865 * Returns the display name of the given section that the course prefers
1867 * Implementation of this function is provided by course format
1868 * @see core_courseformat\base::get_section_name()
1870 * @param int|stdClass $courseorid The course to get the section name for (object or just course id)
1871 * @param int|stdClass $section Section object from database or just field course_sections.section
1872 * @return string Display name that the course format prefers, e.g. "Week 2"
1874 function get_section_name($courseorid, $section) {
1875 return course_get_format($courseorid)->get_section_name($section);
1879 * Tells if current course format uses sections
1881 * @param string $format Course format ID e.g. 'weeks' $course->format
1882 * @return bool
1884 function course_format_uses_sections($format) {
1885 $course = new stdClass();
1886 $course->format = $format;
1887 return course_get_format($course)->uses_sections();
1891 * Returns the information about the ajax support in the given source format
1893 * The returned object's property (boolean)capable indicates that
1894 * the course format supports Moodle course ajax features.
1896 * @param string $format
1897 * @return stdClass
1899 function course_format_ajax_support($format) {
1900 $course = new stdClass();
1901 $course->format = $format;
1902 return course_get_format($course)->supports_ajax();
1906 * Can the current user delete this course?
1907 * Course creators have exception,
1908 * 1 day after the creation they can sill delete the course.
1909 * @param int $courseid
1910 * @return boolean
1912 function can_delete_course($courseid) {
1913 global $USER;
1915 $context = context_course::instance($courseid);
1917 if (has_capability('moodle/course:delete', $context)) {
1918 return true;
1921 // hack: now try to find out if creator created this course recently (1 day)
1922 if (!has_capability('moodle/course:create', $context)) {
1923 return false;
1926 $since = time() - 60*60*24;
1927 $course = get_course($courseid);
1929 if ($course->timecreated < $since) {
1930 return false; // Return if the course was not created in last 24 hours.
1933 $logmanger = get_log_manager();
1934 $readers = $logmanger->get_readers('\core\log\sql_reader');
1935 $reader = reset($readers);
1937 if (empty($reader)) {
1938 return false; // No log reader found.
1941 // A proper reader.
1942 $select = "userid = :userid AND courseid = :courseid AND eventname = :eventname AND timecreated > :since";
1943 $params = array('userid' => $USER->id, 'since' => $since, 'courseid' => $course->id, 'eventname' => '\core\event\course_created');
1945 return (bool)$reader->get_events_select_count($select, $params);
1949 * Save the Your name for 'Some role' strings.
1951 * @param integer $courseid the id of this course.
1952 * @param array $data the data that came from the course settings form.
1954 function save_local_role_names($courseid, $data) {
1955 global $DB;
1956 $context = context_course::instance($courseid);
1958 foreach ($data as $fieldname => $value) {
1959 if (strpos($fieldname, 'role_') !== 0) {
1960 continue;
1962 list($ignored, $roleid) = explode('_', $fieldname);
1964 // make up our mind whether we want to delete, update or insert
1965 if (!$value) {
1966 $DB->delete_records('role_names', array('contextid' => $context->id, 'roleid' => $roleid));
1968 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id, 'roleid' => $roleid))) {
1969 $rolename->name = $value;
1970 $DB->update_record('role_names', $rolename);
1972 } else {
1973 $rolename = new stdClass;
1974 $rolename->contextid = $context->id;
1975 $rolename->roleid = $roleid;
1976 $rolename->name = $value;
1977 $DB->insert_record('role_names', $rolename);
1979 // This will ensure the course contacts cache is purged..
1980 core_course_category::role_assignment_changed($roleid, $context);
1985 * Returns options to use in course overviewfiles filemanager
1987 * @param null|stdClass|core_course_list_element|int $course either object that has 'id' property or just the course id;
1988 * may be empty if course does not exist yet (course create form)
1989 * @return array|null array of options such as maxfiles, maxbytes, accepted_types, etc.
1990 * or null if overviewfiles are disabled
1992 function course_overviewfiles_options($course) {
1993 global $CFG;
1994 if (empty($CFG->courseoverviewfileslimit)) {
1995 return null;
1998 // Create accepted file types based on config value, falling back to default all.
1999 $acceptedtypes = (new \core_form\filetypes_util)->normalize_file_types($CFG->courseoverviewfilesext);
2000 if (in_array('*', $acceptedtypes) || empty($acceptedtypes)) {
2001 $acceptedtypes = '*';
2004 $options = array(
2005 'maxfiles' => $CFG->courseoverviewfileslimit,
2006 'maxbytes' => $CFG->maxbytes,
2007 'subdirs' => 0,
2008 'accepted_types' => $acceptedtypes
2010 if (!empty($course->id)) {
2011 $options['context'] = context_course::instance($course->id);
2012 } else if (is_int($course) && $course > 0) {
2013 $options['context'] = context_course::instance($course);
2015 return $options;
2019 * Create a course and either return a $course object
2021 * Please note this functions does not verify any access control,
2022 * the calling code is responsible for all validation (usually it is the form definition).
2024 * @param array $editoroptions course description editor options
2025 * @param object $data - all the data needed for an entry in the 'course' table
2026 * @return object new course instance
2028 function create_course($data, $editoroptions = NULL) {
2029 global $DB, $CFG;
2031 //check the categoryid - must be given for all new courses
2032 $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
2034 // Check if the shortname already exists.
2035 if (!empty($data->shortname)) {
2036 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
2037 throw new moodle_exception('shortnametaken', '', '', $data->shortname);
2041 // Check if the idnumber already exists.
2042 if (!empty($data->idnumber)) {
2043 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
2044 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber);
2048 if (empty($CFG->enablecourserelativedates)) {
2049 // Make sure we're not setting the relative dates mode when the setting is disabled.
2050 unset($data->relativedatesmode);
2053 if ($errorcode = course_validate_dates((array)$data)) {
2054 throw new moodle_exception($errorcode);
2057 // Check if timecreated is given.
2058 $data->timecreated = !empty($data->timecreated) ? $data->timecreated : time();
2059 $data->timemodified = $data->timecreated;
2061 // place at beginning of any category
2062 $data->sortorder = 0;
2064 if ($editoroptions) {
2065 // summary text is updated later, we need context to store the files first
2066 $data->summary = '';
2067 $data->summary_format = $data->summary_editor['format'];
2070 // Get default completion settings as a fallback in case the enablecompletion field is not set.
2071 $courseconfig = get_config('moodlecourse');
2072 $defaultcompletion = !empty($CFG->enablecompletion) ? $courseconfig->enablecompletion : COMPLETION_DISABLED;
2073 $enablecompletion = $data->enablecompletion ?? $defaultcompletion;
2074 // Unset showcompletionconditions when completion tracking is not enabled for the course.
2075 if ($enablecompletion == COMPLETION_DISABLED) {
2076 unset($data->showcompletionconditions);
2077 } else if (!isset($data->showcompletionconditions)) {
2078 // Show completion conditions should have a default value when completion is enabled. Set it to the site defaults.
2079 // This scenario can happen when a course is created through data generators or through a web service.
2080 $data->showcompletionconditions = $courseconfig->showcompletionconditions;
2083 if (!isset($data->visible)) {
2084 // data not from form, add missing visibility info
2085 $data->visible = $category->visible;
2087 $data->visibleold = $data->visible;
2089 $newcourseid = $DB->insert_record('course', $data);
2090 $context = context_course::instance($newcourseid, MUST_EXIST);
2092 if ($editoroptions) {
2093 // Save the files used in the summary editor and store
2094 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2095 $DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid));
2096 $DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid));
2098 if ($overviewfilesoptions = course_overviewfiles_options($newcourseid)) {
2099 // Save the course overviewfiles
2100 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2103 // update course format options
2104 course_get_format($newcourseid)->update_course_format_options($data);
2106 $course = course_get_format($newcourseid)->get_course();
2108 fix_course_sortorder();
2109 // purge appropriate caches in case fix_course_sortorder() did not change anything
2110 cache_helper::purge_by_event('changesincourse');
2112 // Trigger a course created event.
2113 $event = \core\event\course_created::create(array(
2114 'objectid' => $course->id,
2115 'context' => $context,
2116 'other' => array('shortname' => $course->shortname,
2117 'fullname' => $course->fullname)
2120 $event->trigger();
2122 // Setup the blocks
2123 blocks_add_default_course_blocks($course);
2125 // Create default section and initial sections if specified (unless they've already been created earlier).
2126 // We do not want to call course_create_sections_if_missing() because to avoid creating course cache.
2127 $numsections = isset($data->numsections) ? $data->numsections : 0;
2128 $existingsections = $DB->get_fieldset_sql('SELECT section from {course_sections} WHERE course = ?', [$newcourseid]);
2129 $newsections = array_diff(range(0, $numsections), $existingsections);
2130 foreach ($newsections as $sectionnum) {
2131 course_create_section($newcourseid, $sectionnum, true);
2134 // Save any custom role names.
2135 save_local_role_names($course->id, (array)$data);
2137 // set up enrolments
2138 enrol_course_updated(true, $course, $data);
2140 // Update course tags.
2141 if (isset($data->tags)) {
2142 core_tag_tag::set_item_tags('core', 'course', $course->id, $context, $data->tags);
2144 // Set up communication.
2145 if (core_communication\api::is_available()) {
2146 // Check for default provider config setting.
2147 $defaultprovider = get_config('moodlecourse', 'coursecommunicationprovider');
2148 $provider = (isset($data->selectedcommunication)) ? $data->selectedcommunication : $defaultprovider;
2150 if (!empty($provider)) {
2151 // Prepare the communication api data.
2152 $courseimage = course_get_courseimage($course);
2153 $communicationroomname = !empty($data->communicationroomname) ? $data->communicationroomname : $data->fullname;
2155 // Communication api call.
2156 $communication = \core_communication\api::load_by_instance(
2157 context: $context,
2158 component: 'core_course',
2159 instancetype: 'coursecommunication',
2160 instanceid: $course->id,
2161 provider: $provider,
2163 $communication->create_and_configure_room(
2164 $communicationroomname,
2165 $courseimage ?: null,
2166 $data,
2171 // Save custom fields if there are any of them in the form.
2172 $handler = core_course\customfield\course_handler::create();
2173 // Make sure to set the handler's parent context first.
2174 $coursecatcontext = context_coursecat::instance($category->id);
2175 $handler->set_parent_context($coursecatcontext);
2176 // Save the custom field data.
2177 $data->id = $course->id;
2178 $handler->instance_form_save($data, true);
2180 $hook = new \core_course\hook\after_form_submission($data, true);
2181 \core\hook\manager::get_instance()->dispatch($hook);
2183 return $course;
2187 * Update a course.
2189 * Please note this functions does not verify any access control,
2190 * the calling code is responsible for all validation (usually it is the form definition).
2192 * @param object $data - all the data needed for an entry in the 'course' table
2193 * @param array $editoroptions course description editor options
2194 * @return void
2196 function update_course($data, $editoroptions = NULL) {
2197 global $DB, $CFG;
2199 // Prevent changes on front page course.
2200 if ($data->id == SITEID) {
2201 throw new moodle_exception('invalidcourse', 'error');
2204 $oldcourse = course_get_format($data->id)->get_course();
2205 $context = context_course::instance($oldcourse->id);
2207 // Make sure we're not changing whatever the course's relativedatesmode setting is.
2208 unset($data->relativedatesmode);
2210 // Capture the updated fields for the log data.
2211 $updatedfields = [];
2212 foreach (get_object_vars($oldcourse) as $field => $value) {
2213 if ($field == 'summary_editor') {
2214 if (($data->$field)['text'] !== $value['text']) {
2215 // The summary might be very long, we don't wan't to fill up the log record with the full text.
2216 $updatedfields[$field] = '(updated)';
2218 } else if ($field == 'tags' && isset($data->tags)) {
2219 // Tags might not have the same array keys, just check the values.
2220 if (array_values($data->$field) !== array_values($value)) {
2221 $updatedfields[$field] = $data->$field;
2223 } else {
2224 if (isset($data->$field) && $data->$field != $value) {
2225 $updatedfields[$field] = $data->$field;
2230 $data->timemodified = time();
2232 if ($editoroptions) {
2233 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2235 if ($overviewfilesoptions = course_overviewfiles_options($data->id)) {
2236 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2239 // Check we don't have a duplicate shortname.
2240 if (!empty($data->shortname) && $oldcourse->shortname != $data->shortname) {
2241 if ($DB->record_exists_sql('SELECT id from {course} WHERE shortname = ? AND id <> ?', array($data->shortname, $data->id))) {
2242 throw new moodle_exception('shortnametaken', '', '', $data->shortname);
2246 // Check we don't have a duplicate idnumber.
2247 if (!empty($data->idnumber) && $oldcourse->idnumber != $data->idnumber) {
2248 if ($DB->record_exists_sql('SELECT id from {course} WHERE idnumber = ? AND id <> ?', array($data->idnumber, $data->id))) {
2249 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber);
2253 if ($errorcode = course_validate_dates((array)$data)) {
2254 throw new moodle_exception($errorcode);
2257 if (!isset($data->category) or empty($data->category)) {
2258 // prevent nulls and 0 in category field
2259 unset($data->category);
2261 $changesincoursecat = $movecat = (isset($data->category) and $oldcourse->category != $data->category);
2263 if (!isset($data->visible)) {
2264 // data not from form, add missing visibility info
2265 $data->visible = $oldcourse->visible;
2268 if ($data->visible != $oldcourse->visible) {
2269 // reset the visibleold flag when manually hiding/unhiding course
2270 $data->visibleold = $data->visible;
2271 $changesincoursecat = true;
2272 } else {
2273 if ($movecat) {
2274 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category));
2275 if (empty($newcategory->visible)) {
2276 // make sure when moving into hidden category the course is hidden automatically
2277 $data->visible = 0;
2282 // Set newsitems to 0 if format does not support announcements.
2283 if (isset($data->format)) {
2284 $newcourseformat = course_get_format((object)['format' => $data->format]);
2285 if (!$newcourseformat->supports_news()) {
2286 $data->newsitems = 0;
2290 // Set showcompletionconditions to null when completion tracking has been disabled for the course.
2291 if (isset($data->enablecompletion) && $data->enablecompletion == COMPLETION_DISABLED) {
2292 $data->showcompletionconditions = null;
2295 // Check if provider is selected.
2296 $provider = $data->selectedcommunication ?? null;
2297 // If the course moved to hidden category, set provider to none.
2298 if ($changesincoursecat && empty($data->visible)) {
2299 $provider = 'none';
2302 // Attempt to get the communication provider if it wasn't provided in the data.
2303 if (empty($provider) && core_communication\api::is_available()) {
2304 $provider = \core_communication\api::load_by_instance(
2305 context: $context,
2306 component: 'core_course',
2307 instancetype: 'coursecommunication',
2308 instanceid: $data->id,
2309 )->get_provider();
2312 // Communication api call.
2313 if (!empty($provider) && core_communication\api::is_available()) {
2314 // Prepare the communication api data.
2315 $courseimage = course_get_courseimage($data);
2317 // This nasty logic is here because of hide course doesn't pass anything in the data object.
2318 if (!empty($data->communicationroomname)) {
2319 $communicationroomname = $data->communicationroomname;
2320 } else {
2321 $communicationroomname = $data->fullname ?? $oldcourse->fullname;
2324 // Update communication room membership of enrolled users.
2325 require_once($CFG->libdir . '/enrollib.php');
2326 $courseusers = enrol_get_course_users($data->id);
2327 $enrolledusers = [];
2329 foreach ($courseusers as $user) {
2330 $enrolledusers[] = $user->id;
2333 // Existing communication provider.
2334 $communication = \core_communication\api::load_by_instance(
2335 context: $context,
2336 component: 'core_course',
2337 instancetype: 'coursecommunication',
2338 instanceid: $data->id,
2340 $existingprovider = $communication->get_provider();
2341 $addusersrequired = false;
2342 $enablenewprovider = false;
2343 $instanceexists = true;
2345 // Action required changes if provider has changed.
2346 if ($provider !== $existingprovider) {
2347 // Provider changed, flag new one to be enabled.
2348 $enablenewprovider = true;
2350 // If provider set to none, remove all the members from previous provider.
2351 if ($provider === 'none' && $existingprovider !== '') {
2352 $communication->remove_members_from_room($enrolledusers);
2353 } else if (
2354 // If previous provider was not none and current provider is not none,
2355 // remove members from previous provider.
2356 $existingprovider !== '' &&
2357 $existingprovider !== 'none'
2359 $communication->remove_members_from_room($enrolledusers);
2360 $addusersrequired = true;
2361 } else if (
2362 // If previous provider was none and current provider is not none,
2363 // remove members from previous provider.
2364 ($existingprovider === '' || $existingprovider === 'none')
2366 $addusersrequired = true;
2369 // Disable previous provider, if one was enabled.
2370 if ($existingprovider !== '' && $existingprovider !== 'none') {
2371 $communication->update_room(
2372 active: \core_communication\processor::PROVIDER_INACTIVE,
2376 // Switch to the newly selected provider so it can be updated.
2377 if ($provider !== 'none') {
2378 $communication = \core_communication\api::load_by_instance(
2379 context: $context,
2380 component: 'core_course',
2381 instancetype: 'coursecommunication',
2382 instanceid: $data->id,
2383 provider: $provider,
2386 // Create it if it does not exist.
2387 if ($communication->get_provider() === '') {
2388 $communication->create_and_configure_room(
2389 communicationroomname: $communicationroomname,
2390 avatar: $courseimage,
2391 instance: $data
2394 $communication = \core_communication\api::load_by_instance(
2395 context: $context,
2396 component: 'core_course',
2397 instancetype: 'coursecommunication',
2398 instanceid: $data->id,
2399 provider: $provider,
2402 $addusersrequired = true;
2403 $instanceexists = false;
2408 if ($provider !== 'none' && $instanceexists) {
2409 // Update the currently enabled provider's room data.
2410 // Newly created providers do not need to run this, the create process handles it.
2411 $communication->update_room(
2412 active: $enablenewprovider ? \core_communication\processor::PROVIDER_ACTIVE : null,
2413 communicationroomname: $communicationroomname,
2414 avatar: $courseimage,
2415 instance: $data,
2419 // Complete room membership tasks if required.
2420 // Newly created providers complete the user mapping but do not queue the task
2421 // (it will be handled by the room creation task).
2422 if ($addusersrequired) {
2423 $communication->add_members_to_room($enrolledusers, $instanceexists);
2427 // Update custom fields if there are any of them in the form.
2428 $handler = core_course\customfield\course_handler::create();
2429 $handler->instance_form_save($data);
2431 $hook = new \core_course\hook\after_form_submission($data);
2432 \core\hook\manager::get_instance()->dispatch($hook);
2434 // Update with the new data
2435 $DB->update_record('course', $data);
2436 // make sure the modinfo cache is reset
2437 rebuild_course_cache($data->id);
2439 // Purge course image cache in case if course image has been updated.
2440 \cache::make('core', 'course_image')->delete($data->id);
2442 // update course format options with full course data
2443 course_get_format($data->id)->update_course_format_options($data, $oldcourse);
2445 $course = $DB->get_record('course', array('id'=>$data->id));
2447 if ($movecat) {
2448 $newparent = context_coursecat::instance($course->category);
2449 $context->update_moved($newparent);
2451 $fixcoursesortorder = $movecat || (isset($data->sortorder) && ($oldcourse->sortorder != $data->sortorder));
2452 if ($fixcoursesortorder) {
2453 fix_course_sortorder();
2456 // purge appropriate caches in case fix_course_sortorder() did not change anything
2457 cache_helper::purge_by_event('changesincourse');
2458 if ($changesincoursecat) {
2459 cache_helper::purge_by_event('changesincoursecat');
2462 // Test for and remove blocks which aren't appropriate anymore
2463 blocks_remove_inappropriate($course);
2465 // Save any custom role names.
2466 save_local_role_names($course->id, $data);
2468 // update enrol settings
2469 enrol_course_updated(false, $course, $data);
2471 // Update course tags.
2472 if (isset($data->tags)) {
2473 core_tag_tag::set_item_tags('core', 'course', $course->id, context_course::instance($course->id), $data->tags);
2476 // Trigger a course updated event.
2477 $event = \core\event\course_updated::create(array(
2478 'objectid' => $course->id,
2479 'context' => context_course::instance($course->id),
2480 'other' => array('shortname' => $course->shortname,
2481 'fullname' => $course->fullname,
2482 'updatedfields' => $updatedfields)
2485 $event->trigger();
2487 if ($oldcourse->format !== $course->format) {
2488 // Remove all options stored for the previous format
2489 // We assume that new course format migrated everything it needed watching trigger
2490 // 'course_updated' and in method format_XXX::update_course_format_options()
2491 $DB->delete_records('course_format_options',
2492 array('courseid' => $course->id, 'format' => $oldcourse->format));
2495 // Delete theme usage cache if the theme has been changed.
2496 if (isset($data->theme) && ($data->theme != $oldcourse->theme)) {
2497 theme_delete_used_in_context_cache($data->theme, $oldcourse->theme);
2502 * Calculate the average number of enrolled participants per course.
2504 * This is intended for statistics purposes during the site registration. Only visible courses are taken into account.
2505 * Front page enrolments are excluded.
2507 * @param bool $onlyactive Consider only active enrolments in enabled plugins and obey the enrolment time restrictions.
2508 * @param int $lastloginsince If specified, count only users who logged in after this timestamp.
2509 * @return float
2511 function average_number_of_participants(bool $onlyactive = false, int $lastloginsince = null): float {
2512 global $DB;
2514 $params = [];
2516 $sql = "SELECT DISTINCT ue.userid, e.courseid
2517 FROM {user_enrolments} ue
2518 JOIN {enrol} e ON e.id = ue.enrolid
2519 JOIN {course} c ON c.id = e.courseid ";
2521 if ($onlyactive || $lastloginsince) {
2522 $sql .= "JOIN {user} u ON u.id = ue.userid ";
2525 $sql .= "WHERE e.courseid <> " . SITEID . " AND c.visible = 1 ";
2527 if ($onlyactive) {
2528 $sql .= "AND ue.status = :active
2529 AND e.status = :enabled
2530 AND ue.timestart < :now1
2531 AND (ue.timeend = 0 OR ue.timeend > :now2) ";
2533 // Same as in the enrollib - the rounding should help caching in the database.
2534 $now = round(time(), -2);
2536 $params += [
2537 'active' => ENROL_USER_ACTIVE,
2538 'enabled' => ENROL_INSTANCE_ENABLED,
2539 'now1' => $now,
2540 'now2' => $now,
2544 if ($lastloginsince) {
2545 $sql .= "AND u.lastlogin > :lastlogin ";
2546 $params['lastlogin'] = $lastloginsince;
2549 $sql = "SELECT COUNT(*)
2550 FROM ($sql) total";
2552 $enrolmenttotal = $DB->count_records_sql($sql, $params);
2554 // Get the number of visible courses (exclude the front page).
2555 $coursetotal = $DB->count_records('course', ['visible' => 1]);
2556 $coursetotal = $coursetotal - 1;
2558 if (empty($coursetotal)) {
2559 $participantaverage = 0;
2561 } else {
2562 $participantaverage = $enrolmenttotal / $coursetotal;
2565 return $participantaverage;
2569 * Average number of course modules
2570 * @return integer
2572 function average_number_of_courses_modules() {
2573 global $DB, $SITE;
2575 //count total of visible course module (except front page)
2576 $sql = 'SELECT COUNT(*) FROM (
2577 SELECT cm.course, cm.module
2578 FROM {course} c, {course_modules} cm
2579 WHERE c.id = cm.course
2580 AND c.id <> :siteid
2581 AND cm.visible = 1
2582 AND c.visible = 1) total';
2583 $params = array('siteid' => $SITE->id);
2584 $moduletotal = $DB->count_records_sql($sql, $params);
2587 //count total of visible courses (minus front page)
2588 $coursetotal = $DB->count_records('course', array('visible' => 1));
2589 $coursetotal = $coursetotal - 1 ;
2591 //average of course module
2592 if (empty($coursetotal)) {
2593 $coursemoduleaverage = 0;
2594 } else {
2595 $coursemoduleaverage = $moduletotal / $coursetotal;
2598 return $coursemoduleaverage;
2602 * This class pertains to course requests and contains methods associated with
2603 * create, approving, and removing course requests.
2605 * Please note we do not allow embedded images here because there is no context
2606 * to store them with proper access control.
2608 * @copyright 2009 Sam Hemelryk
2609 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2610 * @since Moodle 2.0
2612 * @property-read int $id
2613 * @property-read string $fullname
2614 * @property-read string $shortname
2615 * @property-read string $summary
2616 * @property-read int $summaryformat
2617 * @property-read int $summarytrust
2618 * @property-read string $reason
2619 * @property-read int $requester
2621 class course_request {
2624 * This is the stdClass that stores the properties for the course request
2625 * and is externally accessed through the __get magic method
2626 * @var stdClass
2628 protected $properties;
2631 * An array of options for the summary editor used by course request forms.
2632 * This is initially set by {@link summary_editor_options()}
2633 * @var array
2634 * @static
2636 protected static $summaryeditoroptions;
2639 * Static function to prepare the summary editor for working with a course
2640 * request.
2642 * @static
2643 * @param null|stdClass $data Optional, an object containing the default values
2644 * for the form, these may be modified when preparing the
2645 * editor so this should be called before creating the form
2646 * @return stdClass An object that can be used to set the default values for
2647 * an mforms form
2649 public static function prepare($data=null) {
2650 if ($data === null) {
2651 $data = new stdClass;
2653 $data = file_prepare_standard_editor($data, 'summary', self::summary_editor_options());
2654 return $data;
2658 * Static function to create a new course request when passed an array of properties
2659 * for it.
2661 * This function also handles saving any files that may have been used in the editor
2663 * @static
2664 * @param stdClass $data
2665 * @return course_request The newly created course request
2667 public static function create($data) {
2668 global $USER, $DB, $CFG;
2669 $data->requester = $USER->id;
2671 // Setting the default category if none set.
2672 if (empty($data->category) || !empty($CFG->lockrequestcategory)) {
2673 $data->category = $CFG->defaultrequestcategory;
2676 // Summary is a required field so copy the text over
2677 $data->summary = $data->summary_editor['text'];
2678 $data->summaryformat = $data->summary_editor['format'];
2680 $data->id = $DB->insert_record('course_request', $data);
2682 // Create a new course_request object and return it
2683 $request = new course_request($data);
2685 // Notify the admin if required.
2686 if ($users = get_users_from_config($CFG->courserequestnotify, 'moodle/site:approvecourse')) {
2688 $a = new stdClass;
2689 $a->link = "$CFG->wwwroot/course/pending.php";
2690 $a->user = fullname($USER);
2691 $subject = get_string('courserequest');
2692 $message = get_string('courserequestnotifyemail', 'admin', $a);
2693 foreach ($users as $user) {
2694 $request->notify($user, $USER, 'courserequested', $subject, $message);
2698 return $request;
2702 * Returns an array of options to use with a summary editor
2704 * @uses course_request::$summaryeditoroptions
2705 * @return array An array of options to use with the editor
2707 public static function summary_editor_options() {
2708 global $CFG;
2709 if (self::$summaryeditoroptions === null) {
2710 self::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
2712 return self::$summaryeditoroptions;
2716 * Loads the properties for this course request object. Id is required and if
2717 * only id is provided then we load the rest of the properties from the database
2719 * @param stdClass|int $properties Either an object containing properties
2720 * or the course_request id to load
2722 public function __construct($properties) {
2723 global $DB;
2724 if (empty($properties->id)) {
2725 if (empty($properties)) {
2726 throw new coding_exception('You must provide a course request id when creating a course_request object');
2728 $id = $properties;
2729 $properties = new stdClass;
2730 $properties->id = (int)$id;
2731 unset($id);
2733 if (empty($properties->requester)) {
2734 if (!($this->properties = $DB->get_record('course_request', array('id' => $properties->id)))) {
2735 throw new \moodle_exception('unknowncourserequest');
2737 } else {
2738 $this->properties = $properties;
2740 $this->properties->collision = null;
2744 * Returns the requested property
2746 * @param string $key
2747 * @return mixed
2749 public function __get($key) {
2750 return $this->properties->$key;
2754 * Override this to ensure empty($request->blah) calls return a reliable answer...
2756 * This is required because we define the __get method
2758 * @param mixed $key
2759 * @return bool True is it not empty, false otherwise
2761 public function __isset($key) {
2762 return (!empty($this->properties->$key));
2766 * Returns the user who requested this course
2768 * Uses a static var to cache the results and cut down the number of db queries
2770 * @staticvar array $requesters An array of cached users
2771 * @return stdClass The user who requested the course
2773 public function get_requester() {
2774 global $DB;
2775 static $requesters= array();
2776 if (!array_key_exists($this->properties->requester, $requesters)) {
2777 $requesters[$this->properties->requester] = $DB->get_record('user', array('id'=>$this->properties->requester));
2779 return $requesters[$this->properties->requester];
2783 * Checks that the shortname used by the course does not conflict with any other
2784 * courses that exist
2786 * @param string|null $shortnamemark The string to append to the requests shortname
2787 * should a conflict be found
2788 * @return bool true is there is a conflict, false otherwise
2790 public function check_shortname_collision($shortnamemark = '[*]') {
2791 global $DB;
2793 if ($this->properties->collision !== null) {
2794 return $this->properties->collision;
2797 if (empty($this->properties->shortname)) {
2798 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER);
2799 $this->properties->collision = false;
2800 } else if ($DB->record_exists('course', array('shortname' => $this->properties->shortname))) {
2801 if (!empty($shortnamemark)) {
2802 $this->properties->shortname .= ' '.$shortnamemark;
2804 $this->properties->collision = true;
2805 } else {
2806 $this->properties->collision = false;
2808 return $this->properties->collision;
2812 * Checks user capability to approve a requested course
2814 * If course was requested without category for some reason (might happen if $CFG->defaultrequestcategory is
2815 * misconfigured), we check capabilities 'moodle/site:approvecourse' and 'moodle/course:changecategory'.
2817 * @return bool
2819 public function can_approve() {
2820 global $CFG;
2821 $category = null;
2822 if ($this->properties->category) {
2823 $category = core_course_category::get($this->properties->category, IGNORE_MISSING);
2824 } else if ($CFG->defaultrequestcategory) {
2825 $category = core_course_category::get($CFG->defaultrequestcategory, IGNORE_MISSING);
2827 if ($category) {
2828 return has_capability('moodle/site:approvecourse', $category->get_context());
2831 // We can not determine the context where the course should be created. The approver should have
2832 // both capabilities to approve courses and change course category in the system context.
2833 return has_all_capabilities(['moodle/site:approvecourse', 'moodle/course:changecategory'], context_system::instance());
2837 * Returns the category where this course request should be created
2839 * Note that we don't check here that user has a capability to view
2840 * hidden categories if he has capabilities 'moodle/site:approvecourse' and
2841 * 'moodle/course:changecategory'
2843 * @return core_course_category
2845 public function get_category() {
2846 global $CFG;
2847 if ($this->properties->category && ($category = core_course_category::get($this->properties->category, IGNORE_MISSING))) {
2848 return $category;
2849 } else if ($CFG->defaultrequestcategory &&
2850 ($category = core_course_category::get($CFG->defaultrequestcategory, IGNORE_MISSING))) {
2851 return $category;
2852 } else {
2853 return core_course_category::get_default();
2858 * This function approves the request turning it into a course
2860 * This function converts the course request into a course, at the same time
2861 * transferring any files used in the summary to the new course and then removing
2862 * the course request and the files associated with it.
2864 * @return int The id of the course that was created from this request
2866 public function approve() {
2867 global $CFG, $DB, $USER;
2869 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
2871 $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted'=>0), '*', MUST_EXIST);
2873 $courseconfig = get_config('moodlecourse');
2875 // Transfer appropriate settings
2876 $data = clone($this->properties);
2877 unset($data->id);
2878 unset($data->reason);
2879 unset($data->requester);
2881 // Set category
2882 $category = $this->get_category();
2883 $data->category = $category->id;
2884 // Set misc settings
2885 $data->requested = 1;
2887 // Apply course default settings
2888 $data->format = $courseconfig->format;
2889 $data->newsitems = $courseconfig->newsitems;
2890 $data->showgrades = $courseconfig->showgrades;
2891 $data->showreports = $courseconfig->showreports;
2892 $data->maxbytes = $courseconfig->maxbytes;
2893 $data->groupmode = $courseconfig->groupmode;
2894 $data->groupmodeforce = $courseconfig->groupmodeforce;
2895 $data->visible = $courseconfig->visible;
2896 $data->visibleold = $data->visible;
2897 $data->lang = $courseconfig->lang;
2898 $data->enablecompletion = $courseconfig->enablecompletion;
2899 $data->numsections = $courseconfig->numsections;
2900 $data->startdate = usergetmidnight(time());
2901 if ($courseconfig->courseenddateenabled) {
2902 $data->enddate = usergetmidnight(time()) + $courseconfig->courseduration;
2905 list($data->fullname, $data->shortname) = restore_dbops::calculate_course_names(0, $data->fullname, $data->shortname);
2907 $course = create_course($data);
2908 $context = context_course::instance($course->id, MUST_EXIST);
2910 // add enrol instances
2911 if (!$DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
2912 if ($manual = enrol_get_plugin('manual')) {
2913 $manual->add_default_instance($course);
2917 // enrol the requester as teacher if necessary
2918 if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
2919 enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid);
2922 $this->delete();
2924 $a = new stdClass();
2925 $a->name = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
2926 $a->url = $CFG->wwwroot.'/course/view.php?id=' . $course->id;
2927 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a), $course->id);
2929 return $course->id;
2933 * Reject a course request
2935 * This function rejects a course request, emailing the requesting user the
2936 * provided notice and then removing the request from the database
2938 * @param string $notice The message to display to the user
2940 public function reject($notice) {
2941 global $USER, $DB;
2942 $user = $DB->get_record('user', array('id' => $this->properties->requester), '*', MUST_EXIST);
2943 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
2944 $this->delete();
2948 * Deletes the course request and any associated files
2950 public function delete() {
2951 global $DB;
2952 $DB->delete_records('course_request', array('id' => $this->properties->id));
2956 * Send a message from one user to another using events_trigger
2958 * @param object $touser
2959 * @param object $fromuser
2960 * @param string $name
2961 * @param string $subject
2962 * @param string $message
2963 * @param int|null $courseid
2965 protected function notify($touser, $fromuser, $name, $subject, $message, $courseid = null) {
2966 $eventdata = new \core\message\message();
2967 $eventdata->courseid = empty($courseid) ? SITEID : $courseid;
2968 $eventdata->component = 'moodle';
2969 $eventdata->name = $name;
2970 $eventdata->userfrom = $fromuser;
2971 $eventdata->userto = $touser;
2972 $eventdata->subject = $subject;
2973 $eventdata->fullmessage = $message;
2974 $eventdata->fullmessageformat = FORMAT_PLAIN;
2975 $eventdata->fullmessagehtml = '';
2976 $eventdata->smallmessage = '';
2977 $eventdata->notification = 1;
2978 message_send($eventdata);
2982 * Checks if current user can request a course in this context
2984 * @param context $context
2985 * @return bool
2987 public static function can_request(context $context) {
2988 global $CFG;
2989 if (empty($CFG->enablecourserequests)) {
2990 return false;
2992 if (has_capability('moodle/course:create', $context)) {
2993 return false;
2996 if ($context instanceof context_system) {
2997 $defaultcontext = context_coursecat::instance($CFG->defaultrequestcategory, IGNORE_MISSING);
2998 return $defaultcontext &&
2999 has_capability('moodle/course:request', $defaultcontext);
3000 } else if ($context instanceof context_coursecat) {
3001 if (!$CFG->lockrequestcategory || $CFG->defaultrequestcategory == $context->instanceid) {
3002 return has_capability('moodle/course:request', $context);
3005 return false;
3010 * Return a list of page types
3011 * @param string $pagetype current page type
3012 * @param context $parentcontext Block's parent context
3013 * @param context $currentcontext Current context of block
3014 * @return array array of page types
3016 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
3017 if ($pagetype === 'course-index' || $pagetype === 'course-index-category') {
3018 // For courses and categories browsing pages (/course/index.php) add option to show on ANY category page
3019 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
3020 'course-index-*' => get_string('page-course-index-x', 'pagetype'),
3022 } else if ($currentcontext && (!($coursecontext = $currentcontext->get_course_context(false)) || $coursecontext->instanceid == SITEID)) {
3023 // We know for sure that despite pagetype starts with 'course-' this is not a page in course context (i.e. /course/search.php, etc.)
3024 $pagetypes = array('*' => get_string('page-x', 'pagetype'));
3025 } else {
3026 // Otherwise consider it a page inside a course even if $currentcontext is null
3027 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
3028 'course-*' => get_string('page-course-x', 'pagetype'),
3029 'course-view-*' => get_string('page-course-view-x', 'pagetype')
3032 return $pagetypes;
3036 * Determine whether course ajax should be enabled for the specified course
3038 * @param stdClass $course The course to test against
3039 * @return boolean Whether course ajax is enabled or note
3041 function course_ajax_enabled($course) {
3042 global $CFG, $PAGE, $SITE;
3044 // The user must be editing for AJAX to be included
3045 if (!$PAGE->user_is_editing()) {
3046 return false;
3049 // Check that the theme suports
3050 if (!$PAGE->theme->enablecourseajax) {
3051 return false;
3054 // Check that the course format supports ajax functionality
3055 // The site 'format' doesn't have information on course format support
3056 if ($SITE->id !== $course->id) {
3057 $courseformatajaxsupport = course_format_ajax_support($course->format);
3058 if (!$courseformatajaxsupport->capable) {
3059 return false;
3063 // All conditions have been met so course ajax should be enabled
3064 return true;
3068 * Include the relevant javascript and language strings for the resource
3069 * toolbox YUI module
3071 * @param integer $id The ID of the course being applied to
3072 * @param array $usedmodules An array containing the names of the modules in use on the page
3073 * @param array $enabledmodules An array containing the names of the enabled (visible) modules on this site
3074 * @param stdClass $config An object containing configuration parameters for ajax modules including:
3075 * * resourceurl The URL to post changes to for resource changes
3076 * * sectionurl The URL to post changes to for section changes
3077 * * pageparams Additional parameters to pass through in the post
3078 * @return bool
3080 function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) {
3081 global $CFG, $PAGE, $SITE;
3083 // Init the course editor module to support UI components.
3084 $format = course_get_format($course);
3085 include_course_editor($format);
3087 // Ensure that ajax should be included
3088 if (!course_ajax_enabled($course)) {
3089 return false;
3092 // Component based formats don't use YUI drag and drop anymore.
3093 if (!$format->supports_components() && course_format_uses_sections($course->format)) {
3095 if (!$config) {
3096 $config = new stdClass();
3099 // The URL to use for resource changes.
3100 if (!isset($config->resourceurl)) {
3101 $config->resourceurl = '/course/rest.php';
3104 // The URL to use for section changes.
3105 if (!isset($config->sectionurl)) {
3106 $config->sectionurl = '/course/rest.php';
3109 // Any additional parameters which need to be included on page submission.
3110 if (!isset($config->pageparams)) {
3111 $config->pageparams = array();
3114 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_section_dragdrop',
3115 array(array(
3116 'courseid' => $course->id,
3117 'ajaxurl' => $config->sectionurl,
3118 'config' => $config,
3119 )), null, true);
3121 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_resource_dragdrop',
3122 array(array(
3123 'courseid' => $course->id,
3124 'ajaxurl' => $config->resourceurl,
3125 'config' => $config,
3126 )), null, true);
3128 // Require various strings for the command toolbox.
3129 $PAGE->requires->strings_for_js(array(
3130 'moveleft',
3131 'deletechecktype',
3132 'deletechecktypename',
3133 'edittitle',
3134 'edittitleinstructions',
3135 'show',
3136 'hide',
3137 'highlight',
3138 'highlightoff',
3139 'groupsnone',
3140 'groupsvisible',
3141 'groupsseparate',
3142 'movesection',
3143 'movecoursemodule',
3144 'movecoursesection',
3145 'movecontent',
3146 'tocontent',
3147 'emptydragdropregion',
3148 'afterresource',
3149 'aftersection',
3150 'totopofsection',
3151 ), 'moodle');
3153 // Include section-specific strings for formats which support sections.
3154 if (course_format_uses_sections($course->format)) {
3155 $PAGE->requires->strings_for_js(array(
3156 'showfromothers',
3157 'hidefromothers',
3158 ), 'format_' . $course->format);
3161 // For confirming resource deletion we need the name of the module in question.
3162 foreach ($usedmodules as $module => $modname) {
3163 $PAGE->requires->string_for_js('pluginname', $module);
3166 // Load drag and drop upload AJAX.
3167 require_once($CFG->dirroot.'/course/dnduploadlib.php');
3168 dndupload_add_to_course($course, $enabledmodules);
3171 $PAGE->requires->js_call_amd('core_course/actions', 'initCoursePage', array($course->format));
3173 return true;
3177 * Include and configure the course editor modules.
3179 * @param course_format $format the course format instance.
3181 function include_course_editor(course_format $format) {
3182 global $PAGE, $SITE;
3184 $course = $format->get_course();
3186 if ($SITE->id === $course->id) {
3187 return;
3190 $statekey = course_format::session_cache($course);
3192 // Edition mode and some format specs must be passed to the init method.
3193 $setup = (object)[
3194 'editing' => $format->show_editor(),
3195 'supportscomponents' => $format->supports_components(),
3196 'statekey' => $statekey,
3197 'overriddenStrings' => $format->get_editor_custom_strings(),
3199 // All the new editor elements will be loaded after the course is presented and
3200 // the initial course state will be generated using core_course_get_state webservice.
3201 $PAGE->requires->js_call_amd('core_courseformat/courseeditor', 'setViewFormat', [$course->id, $setup]);
3205 * Returns the sorted list of available course formats, filtered by enabled if necessary
3207 * @param bool $enabledonly return only formats that are enabled
3208 * @return array array of sorted format names
3210 function get_sorted_course_formats($enabledonly = false) {
3211 global $CFG;
3212 $formats = core_component::get_plugin_list('format');
3214 if (!empty($CFG->format_plugins_sortorder)) {
3215 $order = explode(',', $CFG->format_plugins_sortorder);
3216 $order = array_merge(array_intersect($order, array_keys($formats)),
3217 array_diff(array_keys($formats), $order));
3218 } else {
3219 $order = array_keys($formats);
3221 if (!$enabledonly) {
3222 return $order;
3224 $sortedformats = array();
3225 foreach ($order as $formatname) {
3226 if (!get_config('format_'.$formatname, 'disabled')) {
3227 $sortedformats[] = $formatname;
3230 return $sortedformats;
3234 * The URL to use for the specified course (with section)
3236 * @param int|stdClass $courseorid The course to get the section name for (either object or just course id)
3237 * @param int|stdClass $section Section object from database or just field course_sections.section
3238 * if omitted the course view page is returned
3239 * @param array $options options for view URL. At the moment core uses:
3240 * 'navigation' (bool) if true and section has no separate page, the function returns null
3241 * 'sr' (int) used by multipage formats to specify to which section to return
3242 * @return moodle_url The url of course
3244 function course_get_url($courseorid, $section = null, $options = array()) {
3245 return course_get_format($courseorid)->get_view_url($section, $options);
3249 * Create a module.
3251 * It includes:
3252 * - capability checks and other checks
3253 * - create the module from the module info
3255 * @param object $module
3256 * @return object the created module info
3257 * @throws moodle_exception if user is not allowed to perform the action or module is not allowed in this course
3259 function create_module($moduleinfo) {
3260 global $DB, $CFG;
3262 require_once($CFG->dirroot . '/course/modlib.php');
3264 // Check manadatory attributs.
3265 $mandatoryfields = array('modulename', 'course', 'section', 'visible');
3266 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
3267 $mandatoryfields[] = 'introeditor';
3269 foreach($mandatoryfields as $mandatoryfield) {
3270 if (!isset($moduleinfo->{$mandatoryfield})) {
3271 throw new moodle_exception('createmodulemissingattribut', '', '', $mandatoryfield);
3275 // Some additional checks (capability / existing instances).
3276 $course = $DB->get_record('course', array('id'=>$moduleinfo->course), '*', MUST_EXIST);
3277 list($module, $context, $cw) = can_add_moduleinfo($course, $moduleinfo->modulename, $moduleinfo->section);
3279 // Add the module.
3280 $moduleinfo->module = $module->id;
3281 $moduleinfo = add_moduleinfo($moduleinfo, $course, null);
3283 return $moduleinfo;
3287 * Update a module.
3289 * It includes:
3290 * - capability and other checks
3291 * - update the module
3293 * @param object $module
3294 * @return object the updated module info
3295 * @throws moodle_exception if current user is not allowed to update the module
3297 function update_module($moduleinfo) {
3298 global $DB, $CFG;
3300 require_once($CFG->dirroot . '/course/modlib.php');
3302 // Check the course module exists.
3303 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule, 0, false, MUST_EXIST);
3305 // Check the course exists.
3306 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
3308 // Some checks (capaibility / existing instances).
3309 list($cm, $context, $module, $data, $cw) = can_update_moduleinfo($cm);
3311 // Retrieve few information needed by update_moduleinfo.
3312 $moduleinfo->modulename = $cm->modname;
3313 if (!isset($moduleinfo->scale)) {
3314 $moduleinfo->scale = 0;
3316 $moduleinfo->type = 'mod';
3318 // Update the module.
3319 list($cm, $moduleinfo) = update_moduleinfo($cm, $moduleinfo, $course, null);
3321 return $moduleinfo;
3325 * Duplicate a module on the course for ajax.
3327 * @see mod_duplicate_module()
3328 * @param object $course The course
3329 * @param object $cm The course module to duplicate
3330 * @param int $sr The section to link back to (used for creating the links)
3331 * @throws moodle_exception if the plugin doesn't support duplication
3332 * @return Object containing:
3333 * - fullcontent: The HTML markup for the created CM
3334 * - cmid: The CMID of the newly created CM
3335 * - redirect: Whether to trigger a redirect following this change
3337 function mod_duplicate_activity($course, $cm, $sr = null) {
3338 global $PAGE;
3340 $newcm = duplicate_module($course, $cm);
3342 $resp = new stdClass();
3343 if ($newcm) {
3345 $format = course_get_format($course);
3346 $renderer = $format->get_renderer($PAGE);
3347 $modinfo = $format->get_modinfo();
3348 $section = $modinfo->get_section_info($newcm->sectionnum);
3350 // Get the new element html content.
3351 $resp->fullcontent = $renderer->course_section_updated_cm_item($format, $section, $newcm);
3353 $resp->cmid = $newcm->id;
3354 } else {
3355 // Trigger a redirect.
3356 $resp->redirect = true;
3358 return $resp;
3362 * Api to duplicate a module.
3364 * @param object $course course object.
3365 * @param object $cm course module object to be duplicated.
3366 * @param int $sectionid section ID new course module will be placed in.
3367 * @param bool $changename updates module name with text from duplicatedmodule lang string.
3368 * @since Moodle 2.8
3370 * @throws Exception
3371 * @throws coding_exception
3372 * @throws moodle_exception
3373 * @throws restore_controller_exception
3375 * @return cm_info|null cminfo object if we sucessfully duplicated the mod and found the new cm.
3377 function duplicate_module($course, $cm, int $sectionid = null, bool $changename = true): ?cm_info {
3378 global $CFG, $DB, $USER;
3379 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
3380 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
3381 require_once($CFG->libdir . '/filelib.php');
3383 $a = new stdClass();
3384 $a->modtype = get_string('modulename', $cm->modname);
3385 $a->modname = format_string($cm->name);
3387 if (!plugin_supports('mod', $cm->modname, FEATURE_BACKUP_MOODLE2)) {
3388 throw new moodle_exception('duplicatenosupport', 'error', '', $a);
3391 // Backup the activity.
3393 $bc = new backup_controller(backup::TYPE_1ACTIVITY, $cm->id, backup::FORMAT_MOODLE,
3394 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
3396 $backupid = $bc->get_backupid();
3397 $backupbasepath = $bc->get_plan()->get_basepath();
3399 $bc->execute_plan();
3401 $bc->destroy();
3403 // Restore the backup immediately.
3405 $rc = new restore_controller($backupid, $course->id,
3406 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, backup::TARGET_CURRENT_ADDING);
3408 // Make sure that the restore_general_groups setting is always enabled when duplicating an activity.
3409 $plan = $rc->get_plan();
3410 $groupsetting = $plan->get_setting('groups');
3411 if (empty($groupsetting->get_value())) {
3412 $groupsetting->set_value(true);
3415 $cmcontext = context_module::instance($cm->id);
3416 if (!$rc->execute_precheck()) {
3417 $precheckresults = $rc->get_precheck_results();
3418 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
3419 if (empty($CFG->keeptempdirectoriesonbackup)) {
3420 fulldelete($backupbasepath);
3425 $rc->execute_plan();
3427 // Now a bit hacky part follows - we try to get the cmid of the newly
3428 // restored copy of the module.
3429 $newcmid = null;
3430 $tasks = $rc->get_plan()->get_tasks();
3431 foreach ($tasks as $task) {
3432 if (is_subclass_of($task, 'restore_activity_task')) {
3433 if ($task->get_old_contextid() == $cmcontext->id) {
3434 $newcmid = $task->get_moduleid();
3435 break;
3440 $rc->destroy();
3442 if (empty($CFG->keeptempdirectoriesonbackup)) {
3443 fulldelete($backupbasepath);
3446 // If we know the cmid of the new course module, let us move it
3447 // right below the original one. otherwise it will stay at the
3448 // end of the section.
3449 if ($newcmid) {
3450 // Proceed with activity renaming before everything else. We don't use APIs here to avoid
3451 // triggering a lot of create/update duplicated events.
3452 $newcm = get_coursemodule_from_id($cm->modname, $newcmid, $cm->course);
3453 if ($changename) {
3454 // Add ' (copy)' language string postfix to duplicated module.
3455 $newname = get_string('duplicatedmodule', 'moodle', $newcm->name);
3456 set_coursemodule_name($newcm->id, $newname);
3459 $section = $DB->get_record('course_sections', ['id' => $sectionid ?? $cm->section, 'course' => $cm->course]);
3460 if (isset($sectionid)) {
3461 moveto_module($newcm, $section);
3462 } else {
3463 $modarray = explode(",", trim($section->sequence));
3464 $cmindex = array_search($cm->id, $modarray);
3465 if ($cmindex !== false && $cmindex < count($modarray) - 1) {
3466 moveto_module($newcm, $section, $modarray[$cmindex + 1]);
3470 // Update calendar events with the duplicated module.
3471 // The following line is to be removed in MDL-58906.
3472 course_module_update_calendar_events($newcm->modname, null, $newcm);
3474 // Trigger course module created event. We can trigger the event only if we know the newcmid.
3475 $newcm = get_fast_modinfo($cm->course)->get_cm($newcmid);
3476 $event = \core\event\course_module_created::create_from_cm($newcm);
3477 $event->trigger();
3480 return isset($newcm) ? $newcm : null;
3484 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3485 * Sorts by descending order of time.
3487 * @param stdClass $a First object
3488 * @param stdClass $b Second object
3489 * @return int 0,1,-1 representing the order
3491 function compare_activities_by_time_desc($a, $b) {
3492 // Make sure the activities actually have a timestamp property.
3493 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3494 return 0;
3496 // We treat instances without timestamp as if they have a timestamp of 0.
3497 if ((!property_exists($a, 'timestamp')) && (property_exists($b,'timestamp'))) {
3498 return 1;
3500 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3501 return -1;
3503 if ($a->timestamp == $b->timestamp) {
3504 return 0;
3506 return ($a->timestamp > $b->timestamp) ? -1 : 1;
3510 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3511 * Sorts by ascending order of time.
3513 * @param stdClass $a First object
3514 * @param stdClass $b Second object
3515 * @return int 0,1,-1 representing the order
3517 function compare_activities_by_time_asc($a, $b) {
3518 // Make sure the activities actually have a timestamp property.
3519 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3520 return 0;
3522 // We treat instances without timestamp as if they have a timestamp of 0.
3523 if ((!property_exists($a, 'timestamp')) && (property_exists($b, 'timestamp'))) {
3524 return -1;
3526 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3527 return 1;
3529 if ($a->timestamp == $b->timestamp) {
3530 return 0;
3532 return ($a->timestamp < $b->timestamp) ? -1 : 1;
3536 * Changes the visibility of a course.
3538 * @param int $courseid The course to change.
3539 * @param bool $show True to make it visible, false otherwise.
3540 * @return bool
3542 function course_change_visibility($courseid, $show = true) {
3543 $course = new stdClass;
3544 $course->id = $courseid;
3545 $course->visible = ($show) ? '1' : '0';
3546 $course->visibleold = $course->visible;
3547 update_course($course);
3548 return true;
3552 * Changes the course sortorder by one, moving it up or down one in respect to sort order.
3554 * @param stdClass|core_course_list_element $course
3555 * @param bool $up If set to true the course will be moved up one. Otherwise down one.
3556 * @return bool
3558 function course_change_sortorder_by_one($course, $up) {
3559 global $DB;
3560 $params = array($course->sortorder, $course->category);
3561 if ($up) {
3562 $select = 'sortorder < ? AND category = ?';
3563 $sort = 'sortorder DESC';
3564 } else {
3565 $select = 'sortorder > ? AND category = ?';
3566 $sort = 'sortorder ASC';
3568 fix_course_sortorder();
3569 $swapcourse = $DB->get_records_select('course', $select, $params, $sort, '*', 0, 1);
3570 if ($swapcourse) {
3571 $swapcourse = reset($swapcourse);
3572 $DB->set_field('course', 'sortorder', $swapcourse->sortorder, array('id' => $course->id));
3573 $DB->set_field('course', 'sortorder', $course->sortorder, array('id' => $swapcourse->id));
3574 // Finally reorder courses.
3575 fix_course_sortorder();
3576 cache_helper::purge_by_event('changesincourse');
3577 return true;
3579 return false;
3583 * Changes the sort order of courses in a category so that the first course appears after the second.
3585 * @param int|stdClass $courseorid The course to focus on.
3586 * @param int $moveaftercourseid The course to shifter after or 0 if you want it to be the first course in the category.
3587 * @return bool
3589 function course_change_sortorder_after_course($courseorid, $moveaftercourseid) {
3590 global $DB;
3592 if (!is_object($courseorid)) {
3593 $course = get_course($courseorid);
3594 } else {
3595 $course = $courseorid;
3598 if ((int)$moveaftercourseid === 0) {
3599 // We've moving the course to the start of the queue.
3600 $sql = 'SELECT sortorder
3601 FROM {course}
3602 WHERE category = :categoryid
3603 ORDER BY sortorder';
3604 $params = array(
3605 'categoryid' => $course->category
3607 $sortorder = $DB->get_field_sql($sql, $params, IGNORE_MULTIPLE);
3609 $sql = 'UPDATE {course}
3610 SET sortorder = sortorder + 1
3611 WHERE category = :categoryid
3612 AND id <> :id';
3613 $params = array(
3614 'categoryid' => $course->category,
3615 'id' => $course->id,
3617 $DB->execute($sql, $params);
3618 $DB->set_field('course', 'sortorder', $sortorder, array('id' => $course->id));
3619 } else if ($course->id === $moveaftercourseid) {
3620 // They're the same - moronic.
3621 debugging("Invalid move after course given.", DEBUG_DEVELOPER);
3622 return false;
3623 } else {
3624 // Moving this course after the given course. It could be before it could be after.
3625 $moveaftercourse = get_course($moveaftercourseid);
3626 if ($course->category !== $moveaftercourse->category) {
3627 debugging("Cannot re-order courses. The given courses do not belong to the same category.", DEBUG_DEVELOPER);
3628 return false;
3630 // Increment all courses in the same category that are ordered after the moveafter course.
3631 // This makes a space for the course we're moving.
3632 $sql = 'UPDATE {course}
3633 SET sortorder = sortorder + 1
3634 WHERE category = :categoryid
3635 AND sortorder > :sortorder';
3636 $params = array(
3637 'categoryid' => $moveaftercourse->category,
3638 'sortorder' => $moveaftercourse->sortorder
3640 $DB->execute($sql, $params);
3641 $DB->set_field('course', 'sortorder', $moveaftercourse->sortorder + 1, array('id' => $course->id));
3643 fix_course_sortorder();
3644 cache_helper::purge_by_event('changesincourse');
3645 return true;
3649 * Trigger course viewed event. This API function is used when course view actions happens,
3650 * usually in course/view.php but also in external functions.
3652 * @param stdClass $context course context object
3653 * @param int $sectionnumber section number
3654 * @since Moodle 2.9
3656 function course_view($context, $sectionnumber = 0) {
3658 $eventdata = array('context' => $context);
3660 if (!empty($sectionnumber)) {
3661 $eventdata['other']['coursesectionnumber'] = $sectionnumber;
3664 $event = \core\event\course_viewed::create($eventdata);
3665 $event->trigger();
3667 user_accesstime_log($context->instanceid);
3671 * Returns courses tagged with a specified tag.
3673 * @param core_tag_tag $tag
3674 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
3675 * are displayed on the page and the per-page limit may be bigger
3676 * @param int $fromctx context id where the link was displayed, may be used by callbacks
3677 * to display items in the same context first
3678 * @param int $ctx context id where to search for records
3679 * @param bool $rec search in subcontexts as well
3680 * @param int $page 0-based number of page being displayed
3681 * @return \core_tag\output\tagindex
3683 function course_get_tagged_courses($tag, $exclusivemode = false, $fromctx = 0, $ctx = 0, $rec = 1, $page = 0) {
3684 global $CFG, $PAGE;
3686 $perpage = $exclusivemode ? $CFG->coursesperpage : 5;
3687 $displayoptions = array(
3688 'limit' => $perpage,
3689 'offset' => $page * $perpage,
3690 'viewmoreurl' => null,
3693 $courserenderer = $PAGE->get_renderer('core', 'course');
3694 $totalcount = core_course_category::search_courses_count(array('tagid' => $tag->id, 'ctx' => $ctx, 'rec' => $rec));
3695 $content = $courserenderer->tagged_courses($tag->id, $exclusivemode, $ctx, $rec, $displayoptions);
3696 $totalpages = ceil($totalcount / $perpage);
3698 return new core_tag\output\tagindex($tag, 'core', 'course', $content,
3699 $exclusivemode, $fromctx, $ctx, $rec, $page, $totalpages);
3703 * Implements callback inplace_editable() allowing to edit values in-place
3705 * @param string $itemtype
3706 * @param int $itemid
3707 * @param mixed $newvalue
3708 * @return \core\output\inplace_editable
3710 function core_course_inplace_editable($itemtype, $itemid, $newvalue) {
3711 if ($itemtype === 'activityname') {
3712 return \core_courseformat\output\local\content\cm\title::update($itemid, $newvalue);
3717 * This function calculates the minimum and maximum cutoff values for the timestart of
3718 * the given event.
3720 * It will return an array with two values, the first being the minimum cutoff value and
3721 * the second being the maximum cutoff value. Either or both values can be null, which
3722 * indicates there is no minimum or maximum, respectively.
3724 * If a cutoff is required then the function must return an array containing the cutoff
3725 * timestamp and error string to display to the user if the cutoff value is violated.
3727 * A minimum and maximum cutoff return value will look like:
3729 * [1505704373, 'The date must be after this date'],
3730 * [1506741172, 'The date must be before this date']
3733 * @param calendar_event $event The calendar event to get the time range for
3734 * @param stdClass $course The course object to get the range from
3735 * @return array Returns an array with min and max date.
3737 function core_course_core_calendar_get_valid_event_timestart_range(\calendar_event $event, $course) {
3738 $mindate = null;
3739 $maxdate = null;
3741 if ($course->startdate) {
3742 $mindate = [
3743 $course->startdate,
3744 get_string('errorbeforecoursestart', 'calendar')
3748 return [$mindate, $maxdate];
3752 * Render the message drawer to be included in the top of the body of each page.
3754 * @return string HTML
3756 function core_course_drawer(): string {
3757 global $PAGE;
3759 // If the course index is explicitly set and if it should be hidden.
3760 if ($PAGE->get_show_course_index() === false) {
3761 return '';
3764 // Only add course index on non-site course pages.
3765 if (!$PAGE->course || $PAGE->course->id == SITEID) {
3766 return '';
3769 // Show course index to users can access the course only.
3770 if (!can_access_course($PAGE->course, null, '', true)) {
3771 return '';
3774 $format = course_get_format($PAGE->course);
3775 $renderer = $format->get_renderer($PAGE);
3776 if (method_exists($renderer, 'course_index_drawer')) {
3777 return $renderer->course_index_drawer($format);
3780 return '';
3784 * Returns course modules tagged with a specified tag ready for output on tag/index.php page
3786 * This is a callback used by the tag area core/course_modules to search for course modules
3787 * tagged with a specific tag.
3789 * @param core_tag_tag $tag
3790 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
3791 * are displayed on the page and the per-page limit may be bigger
3792 * @param int $fromcontextid context id where the link was displayed, may be used by callbacks
3793 * to display items in the same context first
3794 * @param int $contextid context id where to search for records
3795 * @param bool $recursivecontext search in subcontexts as well
3796 * @param int $page 0-based number of page being displayed
3797 * @return \core_tag\output\tagindex
3799 function course_get_tagged_course_modules($tag, $exclusivemode = false, $fromcontextid = 0, $contextid = 0,
3800 $recursivecontext = 1, $page = 0) {
3801 global $OUTPUT;
3802 $perpage = $exclusivemode ? 20 : 5;
3804 // Build select query.
3805 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
3806 $query = "SELECT cm.id AS cmid, c.id AS courseid, $ctxselect
3807 FROM {course_modules} cm
3808 JOIN {tag_instance} tt ON cm.id = tt.itemid
3809 JOIN {course} c ON cm.course = c.id
3810 JOIN {context} ctx ON ctx.instanceid = cm.id AND ctx.contextlevel = :coursemodulecontextlevel
3811 WHERE tt.itemtype = :itemtype AND tt.tagid = :tagid AND tt.component = :component
3812 AND cm.deletioninprogress = 0
3813 AND c.id %COURSEFILTER% AND cm.id %ITEMFILTER%";
3815 $params = array('itemtype' => 'course_modules', 'tagid' => $tag->id, 'component' => 'core',
3816 'coursemodulecontextlevel' => CONTEXT_MODULE);
3817 if ($contextid) {
3818 $context = context::instance_by_id($contextid);
3819 $query .= $recursivecontext ? ' AND (ctx.id = :contextid OR ctx.path LIKE :path)' : ' AND ctx.id = :contextid';
3820 $params['contextid'] = $context->id;
3821 $params['path'] = $context->path.'/%';
3824 $query .= ' ORDER BY';
3825 if ($fromcontextid) {
3826 // In order-clause specify that modules from inside "fromctx" context should be returned first.
3827 $fromcontext = context::instance_by_id($fromcontextid);
3828 $query .= ' (CASE WHEN ctx.id = :fromcontextid OR ctx.path LIKE :frompath THEN 0 ELSE 1 END),';
3829 $params['fromcontextid'] = $fromcontext->id;
3830 $params['frompath'] = $fromcontext->path.'/%';
3832 $query .= ' c.sortorder, cm.id';
3833 $totalpages = $page + 1;
3835 // Use core_tag_index_builder to build and filter the list of items.
3836 // Request one item more than we need so we know if next page exists.
3837 $builder = new core_tag_index_builder('core', 'course_modules', $query, $params, $page * $perpage, $perpage + 1);
3838 while ($item = $builder->has_item_that_needs_access_check()) {
3839 context_helper::preload_from_record($item);
3840 $courseid = $item->courseid;
3841 if (!$builder->can_access_course($courseid)) {
3842 $builder->set_accessible($item, false);
3843 continue;
3845 $modinfo = get_fast_modinfo($builder->get_course($courseid));
3846 // Set accessibility of this item and all other items in the same course.
3847 $builder->walk(function ($taggeditem) use ($courseid, $modinfo, $builder) {
3848 if ($taggeditem->courseid == $courseid) {
3849 $cm = $modinfo->get_cm($taggeditem->cmid);
3850 $builder->set_accessible($taggeditem, $cm->uservisible);
3855 $items = $builder->get_items();
3856 if (count($items) > $perpage) {
3857 $totalpages = $page + 2; // We don't need exact page count, just indicate that the next page exists.
3858 array_pop($items);
3861 // Build the display contents.
3862 if ($items) {
3863 $tagfeed = new core_tag\output\tagfeed();
3864 foreach ($items as $item) {
3865 context_helper::preload_from_record($item);
3866 $course = $builder->get_course($item->courseid);
3867 $modinfo = get_fast_modinfo($course);
3868 $cm = $modinfo->get_cm($item->cmid);
3869 $courseurl = course_get_url($item->courseid, $cm->sectionnum);
3870 $cmname = $cm->get_formatted_name();
3871 if (!$exclusivemode) {
3872 $cmname = shorten_text($cmname, 100);
3874 $cmname = html_writer::link($cm->url?:$courseurl, $cmname);
3875 $coursename = format_string($course->fullname, true,
3876 array('context' => context_course::instance($item->courseid)));
3877 $coursename = html_writer::link($courseurl, $coursename);
3878 $icon = html_writer::empty_tag('img', array('src' => $cm->get_icon_url()));
3879 $tagfeed->add($icon, $cmname, $coursename);
3882 $content = $OUTPUT->render_from_template('core_tag/tagfeed',
3883 $tagfeed->export_for_template($OUTPUT));
3885 return new core_tag\output\tagindex($tag, 'core', 'course_modules', $content,
3886 $exclusivemode, $fromcontextid, $contextid, $recursivecontext, $page, $totalpages);
3891 * Return an object with the list of navigation options in a course that are avaialable or not for the current user.
3892 * This function also handles the frontpage course.
3894 * @param stdClass $context context object (it can be a course context or the system context for frontpage settings)
3895 * @param stdClass $course the course where the settings are being rendered
3896 * @return stdClass the navigation options in a course and their availability status
3897 * @since Moodle 3.2
3899 function course_get_user_navigation_options($context, $course = null) {
3900 global $CFG, $USER;
3902 $isloggedin = isloggedin();
3903 $isguestuser = isguestuser();
3904 $isfrontpage = $context->contextlevel == CONTEXT_SYSTEM;
3906 if ($isfrontpage) {
3907 $sitecontext = $context;
3908 } else {
3909 $sitecontext = context_system::instance();
3912 // Sets defaults for all options.
3913 $options = (object) [
3914 'badges' => false,
3915 'blogs' => false,
3916 'competencies' => false,
3917 'grades' => false,
3918 'notes' => false,
3919 'participants' => false,
3920 'search' => false,
3921 'tags' => false,
3922 'communication' => false,
3925 $options->blogs = !empty($CFG->enableblogs) &&
3926 ($CFG->bloglevel == BLOG_GLOBAL_LEVEL ||
3927 ($CFG->bloglevel == BLOG_SITE_LEVEL and ($isloggedin and !$isguestuser)))
3928 && has_capability('moodle/blog:view', $sitecontext);
3930 $options->notes = !empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $context);
3932 // Frontpage settings?
3933 if ($isfrontpage) {
3934 // We are on the front page, so make sure we use the proper capability (site:viewparticipants).
3935 $options->participants = course_can_view_participants($sitecontext);
3936 $options->badges = !empty($CFG->enablebadges) && has_capability('moodle/badges:viewbadges', $sitecontext);
3937 $options->tags = !empty($CFG->usetags) && $isloggedin;
3938 $options->search = !empty($CFG->enableglobalsearch) && has_capability('moodle/search:query', $sitecontext);
3939 } else {
3940 // We are in a course, so make sure we use the proper capability (course:viewparticipants).
3941 $options->participants = course_can_view_participants($context);
3943 // Only display badges if they are enabled and the current user can manage them or if they can view them and have,
3944 // at least, one available badge.
3945 if (!empty($CFG->enablebadges) && !empty($CFG->badges_allowcoursebadges)) {
3946 $canmanage = has_any_capability([
3947 'moodle/badges:createbadge',
3948 'moodle/badges:awardbadge',
3949 'moodle/badges:configurecriteria',
3950 'moodle/badges:configuremessages',
3951 'moodle/badges:configuredetails',
3952 'moodle/badges:deletebadge',
3954 $context
3956 $totalbadges = [];
3957 $canview = false;
3958 if (!$canmanage) {
3959 // This only needs to be calculated if the user can't manage badges (to improve performance).
3960 $canview = has_capability('moodle/badges:viewbadges', $context);
3961 if ($canview) {
3962 require_once($CFG->dirroot.'/lib/badgeslib.php');
3963 if (is_null($course)) {
3964 $totalbadges = count(badges_get_badges(BADGE_TYPE_SITE, 0, '', '', 0, 0, $USER->id));
3965 } else {
3966 $totalbadges = count(badges_get_badges(BADGE_TYPE_COURSE, $course->id, '', '', 0, 0, $USER->id));
3971 $options->badges = ($canmanage || ($canview && $totalbadges > 0));
3973 // Add view grade report is permitted.
3974 $grades = false;
3976 if (has_capability('moodle/grade:viewall', $context)) {
3977 $grades = true;
3978 } else if (!empty($course->showgrades)) {
3979 $reports = core_component::get_plugin_list('gradereport');
3980 if (is_array($reports) && count($reports) > 0) { // Get all installed reports.
3981 arsort($reports); // User is last, we want to test it first.
3982 foreach ($reports as $plugin => $plugindir) {
3983 if (has_capability('gradereport/'.$plugin.':view', $context)) {
3984 // Stop when the first visible plugin is found.
3985 $grades = true;
3986 break;
3991 $options->grades = $grades;
3994 if (\core_communication\api::is_available()) {
3995 $options->communication = has_capability('moodle/course:configurecoursecommunication', $context);
3998 if (\core_competency\api::is_enabled()) {
3999 $capabilities = array('moodle/competency:coursecompetencyview', 'moodle/competency:coursecompetencymanage');
4000 $options->competencies = has_any_capability($capabilities, $context);
4002 return $options;
4006 * Return an object with the list of administration options in a course that are available or not for the current user.
4007 * This function also handles the frontpage settings.
4009 * @param stdClass $course course object (for frontpage it should be a clone of $SITE)
4010 * @param stdClass $context context object (course context)
4011 * @return stdClass the administration options in a course and their availability status
4012 * @since Moodle 3.2
4014 function course_get_user_administration_options($course, $context) {
4015 global $CFG;
4016 $isfrontpage = $course->id == SITEID;
4017 $completionenabled = $CFG->enablecompletion && $course->enablecompletion;
4018 $hascompletionoptions = count(core_completion\manager::get_available_completion_options($course->id)) > 0;
4019 $options = new stdClass;
4020 $options->update = has_capability('moodle/course:update', $context);
4021 $options->editcompletion = $CFG->enablecompletion && $course->enablecompletion &&
4022 ($options->update || $hascompletionoptions);
4023 $options->filters = has_capability('moodle/filter:manage', $context) &&
4024 count(filter_get_available_in_context($context)) > 0;
4025 $options->reports = has_capability('moodle/site:viewreports', $context);
4026 $options->backup = has_capability('moodle/backup:backupcourse', $context);
4027 $options->restore = has_capability('moodle/restore:restorecourse', $context);
4028 $options->copy = \core_course\management\helper::can_copy_course($course->id);
4029 $options->files = ($course->legacyfiles == 2 && has_capability('moodle/course:managefiles', $context));
4031 if (!$isfrontpage) {
4032 $options->tags = has_capability('moodle/course:tag', $context);
4033 $options->gradebook = has_capability('moodle/grade:manage', $context);
4034 $options->outcomes = !empty($CFG->enableoutcomes) && has_capability('moodle/course:update', $context);
4035 $options->badges = !empty($CFG->enablebadges);
4036 $options->import = has_capability('moodle/restore:restoretargetimport', $context);
4037 $options->reset = has_capability('moodle/course:reset', $context);
4038 $options->roles = has_capability('moodle/role:switchroles', $context);
4039 } else {
4040 // Set default options to false.
4041 $listofoptions = array('tags', 'gradebook', 'outcomes', 'badges', 'import', 'publish', 'reset', 'roles', 'grades');
4043 foreach ($listofoptions as $option) {
4044 $options->$option = false;
4048 return $options;
4052 * Validates course start and end dates.
4054 * Checks that the end course date is not greater than the start course date.
4056 * $coursedata['startdate'] or $coursedata['enddate'] may not be set, it depends on the form and user input.
4058 * @param array $coursedata May contain startdate and enddate timestamps, depends on the user input.
4059 * @return mixed False if everything alright, error codes otherwise.
4061 function course_validate_dates($coursedata) {
4063 // If both start and end dates are set end date should be later than the start date.
4064 if (!empty($coursedata['startdate']) && !empty($coursedata['enddate']) &&
4065 ($coursedata['enddate'] < $coursedata['startdate'])) {
4066 return 'enddatebeforestartdate';
4069 // If start date is not set end date can not be set.
4070 if (empty($coursedata['startdate']) && !empty($coursedata['enddate'])) {
4071 return 'nostartdatenoenddate';
4074 return false;
4078 * Check for course updates in the given context level instances (only modules supported right Now)
4080 * @param stdClass $course course object
4081 * @param array $tocheck instances to check for updates
4082 * @param array $filter check only for updates in these areas
4083 * @return array list of warnings and instances with updates information
4084 * @since Moodle 3.2
4086 function course_check_updates($course, $tocheck, $filter = array()) {
4087 global $CFG, $DB;
4089 $instances = array();
4090 $warnings = array();
4091 $modulescallbacksupport = array();
4092 $modinfo = get_fast_modinfo($course);
4094 $supportedplugins = get_plugin_list_with_function('mod', 'check_updates_since');
4096 // Check instances.
4097 foreach ($tocheck as $instance) {
4098 if ($instance['contextlevel'] == 'module') {
4099 // Check module visibility.
4100 try {
4101 $cm = $modinfo->get_cm($instance['id']);
4102 } catch (Exception $e) {
4103 $warnings[] = array(
4104 'item' => 'module',
4105 'itemid' => $instance['id'],
4106 'warningcode' => 'cmidnotincourse',
4107 'message' => 'This module id does not belong to this course.'
4109 continue;
4112 if (!$cm->uservisible) {
4113 $warnings[] = array(
4114 'item' => 'module',
4115 'itemid' => $instance['id'],
4116 'warningcode' => 'nonuservisible',
4117 'message' => 'You don\'t have access to this module.'
4119 continue;
4121 if (empty($supportedplugins['mod_' . $cm->modname])) {
4122 $warnings[] = array(
4123 'item' => 'module',
4124 'itemid' => $instance['id'],
4125 'warningcode' => 'missingcallback',
4126 'message' => 'This module does not implement the check_updates_since callback: ' . $instance['contextlevel'],
4128 continue;
4130 // Retrieve the module instance.
4131 $instances[] = array(
4132 'contextlevel' => $instance['contextlevel'],
4133 'id' => $instance['id'],
4134 'updates' => call_user_func($cm->modname . '_check_updates_since', $cm, $instance['since'], $filter)
4137 } else {
4138 $warnings[] = array(
4139 'item' => 'contextlevel',
4140 'itemid' => $instance['id'],
4141 'warningcode' => 'contextlevelnotsupported',
4142 'message' => 'Context level not yet supported ' . $instance['contextlevel'],
4146 return array($instances, $warnings);
4150 * This function classifies a course as past, in progress or future.
4152 * This function may incur a DB hit to calculate course completion.
4153 * @param stdClass $course Course record
4154 * @param stdClass $user User record (optional - defaults to $USER).
4155 * @param completion_info $completioninfo Completion record for the user (optional - will be fetched if required).
4156 * @return string (one of COURSE_TIMELINE_FUTURE, COURSE_TIMELINE_INPROGRESS or COURSE_TIMELINE_PAST)
4158 function course_classify_for_timeline($course, $user = null, $completioninfo = null) {
4159 global $USER;
4161 if ($user == null) {
4162 $user = $USER;
4165 if ($completioninfo == null) {
4166 $completioninfo = new completion_info($course);
4169 // Let plugins override data for timeline classification.
4170 $pluginsfunction = get_plugins_with_function('extend_course_classify_for_timeline', 'lib.php');
4171 foreach ($pluginsfunction as $plugintype => $plugins) {
4172 foreach ($plugins as $pluginfunction) {
4173 $pluginfunction($course, $user, $completioninfo);
4177 $today = time();
4178 // End date past.
4179 if (!empty($course->enddate) && (course_classify_end_date($course) < $today)) {
4180 return COURSE_TIMELINE_PAST;
4183 // Course was completed.
4184 if ($completioninfo->is_enabled() && $completioninfo->is_course_complete($user->id)) {
4185 return COURSE_TIMELINE_PAST;
4188 // Start date not reached.
4189 if (!empty($course->startdate) && (course_classify_start_date($course) > $today)) {
4190 return COURSE_TIMELINE_FUTURE;
4193 // Everything else is in progress.
4194 return COURSE_TIMELINE_INPROGRESS;
4198 * This function calculates the end date to use for display classification purposes,
4199 * incorporating the grace period, if any.
4201 * @param stdClass $course The course record.
4202 * @return int The new enddate.
4204 function course_classify_end_date($course) {
4205 global $CFG;
4206 $coursegraceperiodafter = (empty($CFG->coursegraceperiodafter)) ? 0 : $CFG->coursegraceperiodafter;
4207 $enddate = (new \DateTimeImmutable())->setTimestamp($course->enddate)->modify("+{$coursegraceperiodafter} days");
4208 return $enddate->getTimestamp();
4212 * This function calculates the start date to use for display classification purposes,
4213 * incorporating the grace period, if any.
4215 * @param stdClass $course The course record.
4216 * @return int The new startdate.
4218 function course_classify_start_date($course) {
4219 global $CFG;
4220 $coursegraceperiodbefore = (empty($CFG->coursegraceperiodbefore)) ? 0 : $CFG->coursegraceperiodbefore;
4221 $startdate = (new \DateTimeImmutable())->setTimestamp($course->startdate)->modify("-{$coursegraceperiodbefore} days");
4222 return $startdate->getTimestamp();
4226 * Group a list of courses into either past, future, or in progress.
4228 * The return value will be an array indexed by the COURSE_TIMELINE_* constants
4229 * with each value being an array of courses in that group.
4230 * E.g.
4232 * COURSE_TIMELINE_PAST => [... list of past courses ...],
4233 * COURSE_TIMELINE_FUTURE => [],
4234 * COURSE_TIMELINE_INPROGRESS => []
4237 * @param array $courses List of courses to be grouped.
4238 * @return array
4240 function course_classify_courses_for_timeline(array $courses) {
4241 return array_reduce($courses, function($carry, $course) {
4242 $classification = course_classify_for_timeline($course);
4243 array_push($carry[$classification], $course);
4245 return $carry;
4246 }, [
4247 COURSE_TIMELINE_PAST => [],
4248 COURSE_TIMELINE_FUTURE => [],
4249 COURSE_TIMELINE_INPROGRESS => []
4254 * Get the list of enrolled courses for the current user.
4256 * This function returns a Generator. The courses will be loaded from the database
4257 * in chunks rather than a single query.
4259 * @param int $limit Restrict result set to this amount
4260 * @param int $offset Skip this number of records from the start of the result set
4261 * @param string|null $sort SQL string for sorting
4262 * @param string|null $fields SQL string for fields to be returned
4263 * @param int $dbquerylimit The number of records to load per DB request
4264 * @param array $includecourses courses ids to be restricted
4265 * @param array $hiddencourses courses ids to be excluded
4266 * @return Generator
4268 function course_get_enrolled_courses_for_logged_in_user(
4269 int $limit = 0,
4270 int $offset = 0,
4271 string $sort = null,
4272 string $fields = null,
4273 int $dbquerylimit = COURSE_DB_QUERY_LIMIT,
4274 array $includecourses = [],
4275 array $hiddencourses = []
4276 ): Generator {
4278 $haslimit = !empty($limit);
4279 $recordsloaded = 0;
4280 $querylimit = (!$haslimit || $limit > $dbquerylimit) ? $dbquerylimit : $limit;
4282 while ($courses = enrol_get_my_courses($fields, $sort, $querylimit, $includecourses, false, $offset, $hiddencourses)) {
4283 yield from $courses;
4285 $recordsloaded += $querylimit;
4287 if (count($courses) < $querylimit) {
4288 break;
4290 if ($haslimit && $recordsloaded >= $limit) {
4291 break;
4294 $offset += $querylimit;
4299 * Get the list of enrolled courses the current user searched for.
4301 * This function returns a Generator. The courses will be loaded from the database
4302 * in chunks rather than a single query.
4304 * @param int $limit Restrict result set to this amount
4305 * @param int $offset Skip this number of records from the start of the result set
4306 * @param string|null $sort SQL string for sorting
4307 * @param string|null $fields SQL string for fields to be returned
4308 * @param int $dbquerylimit The number of records to load per DB request
4309 * @param array $searchcriteria contains search criteria
4310 * @param array $options display options, same as in get_courses() except 'recursive' is ignored -
4311 * search is always category-independent
4312 * @return Generator
4314 function course_get_enrolled_courses_for_logged_in_user_from_search(
4315 int $limit = 0,
4316 int $offset = 0,
4317 string $sort = null,
4318 string $fields = null,
4319 int $dbquerylimit = COURSE_DB_QUERY_LIMIT,
4320 array $searchcriteria = [],
4321 array $options = []
4322 ): Generator {
4324 $haslimit = !empty($limit);
4325 $recordsloaded = 0;
4326 $querylimit = (!$haslimit || $limit > $dbquerylimit) ? $dbquerylimit : $limit;
4327 $ids = core_course_category::search_courses($searchcriteria, $options);
4329 // If no courses were found matching the criteria return back.
4330 if (empty($ids)) {
4331 return;
4334 while ($courses = enrol_get_my_courses($fields, $sort, $querylimit, $ids, false, $offset)) {
4335 yield from $courses;
4337 $recordsloaded += $querylimit;
4339 if (count($courses) < $querylimit) {
4340 break;
4342 if ($haslimit && $recordsloaded >= $limit) {
4343 break;
4346 $offset += $querylimit;
4351 * Search the given $courses for any that match the given $classification up to the specified
4352 * $limit.
4354 * This function will return the subset of courses that match the classification as well as the
4355 * number of courses it had to process to build that subset.
4357 * It is recommended that for larger sets of courses this function is given a Generator that loads
4358 * the courses from the database in chunks.
4360 * @param array|Traversable $courses List of courses to process
4361 * @param string $classification One of the COURSE_TIMELINE_* constants
4362 * @param int $limit Limit the number of results to this amount
4363 * @return array First value is the filtered courses, second value is the number of courses processed
4365 function course_filter_courses_by_timeline_classification(
4366 $courses,
4367 string $classification,
4368 int $limit = 0
4369 ): array {
4371 if (!in_array($classification,
4372 [COURSE_TIMELINE_ALLINCLUDINGHIDDEN, COURSE_TIMELINE_ALL, COURSE_TIMELINE_PAST, COURSE_TIMELINE_INPROGRESS,
4373 COURSE_TIMELINE_FUTURE, COURSE_TIMELINE_HIDDEN, COURSE_TIMELINE_SEARCH])) {
4374 $message = 'Classification must be one of COURSE_TIMELINE_ALLINCLUDINGHIDDEN, COURSE_TIMELINE_ALL, COURSE_TIMELINE_PAST, '
4375 . 'COURSE_TIMELINE_INPROGRESS, COURSE_TIMELINE_SEARCH or COURSE_TIMELINE_FUTURE';
4376 throw new moodle_exception($message);
4379 $filteredcourses = [];
4380 $numberofcoursesprocessed = 0;
4381 $filtermatches = 0;
4383 foreach ($courses as $course) {
4384 $numberofcoursesprocessed++;
4385 $pref = get_user_preferences('block_myoverview_hidden_course_' . $course->id, 0);
4387 // Added as of MDL-63457 toggle viewability for each user.
4388 if ($classification == COURSE_TIMELINE_ALLINCLUDINGHIDDEN || ($classification == COURSE_TIMELINE_HIDDEN && $pref) ||
4389 $classification == COURSE_TIMELINE_SEARCH||
4390 (($classification == COURSE_TIMELINE_ALL || $classification == course_classify_for_timeline($course)) && !$pref)) {
4391 $filteredcourses[] = $course;
4392 $filtermatches++;
4395 if ($limit && $filtermatches >= $limit) {
4396 // We've found the number of requested courses. No need to continue searching.
4397 break;
4401 // Return the number of filtered courses as well as the number of courses that were searched
4402 // in order to find the matching courses. This allows the calling code to do some kind of
4403 // pagination.
4404 return [$filteredcourses, $numberofcoursesprocessed];
4408 * Search the given $courses for any that match the given $classification up to the specified
4409 * $limit.
4411 * This function will return the subset of courses that are favourites as well as the
4412 * number of courses it had to process to build that subset.
4414 * It is recommended that for larger sets of courses this function is given a Generator that loads
4415 * the courses from the database in chunks.
4417 * @param array|Traversable $courses List of courses to process
4418 * @param array $favouritecourseids Array of favourite courses.
4419 * @param int $limit Limit the number of results to this amount
4420 * @return array First value is the filtered courses, second value is the number of courses processed
4422 function course_filter_courses_by_favourites(
4423 $courses,
4424 $favouritecourseids,
4425 int $limit = 0
4426 ): array {
4428 $filteredcourses = [];
4429 $numberofcoursesprocessed = 0;
4430 $filtermatches = 0;
4432 foreach ($courses as $course) {
4433 $numberofcoursesprocessed++;
4435 if (in_array($course->id, $favouritecourseids)) {
4436 $filteredcourses[] = $course;
4437 $filtermatches++;
4440 if ($limit && $filtermatches >= $limit) {
4441 // We've found the number of requested courses. No need to continue searching.
4442 break;
4446 // Return the number of filtered courses as well as the number of courses that were searched
4447 // in order to find the matching courses. This allows the calling code to do some kind of
4448 // pagination.
4449 return [$filteredcourses, $numberofcoursesprocessed];
4453 * Search the given $courses for any that have a $customfieldname value that matches the given
4454 * $customfieldvalue, up to the specified $limit.
4456 * This function will return the subset of courses that matches the value as well as the
4457 * number of courses it had to process to build that subset.
4459 * It is recommended that for larger sets of courses this function is given a Generator that loads
4460 * the courses from the database in chunks.
4462 * @param array|Traversable $courses List of courses to process
4463 * @param string $customfieldname the shortname of the custom field to match against
4464 * @param string $customfieldvalue the value this custom field needs to match
4465 * @param int $limit Limit the number of results to this amount
4466 * @return array First value is the filtered courses, second value is the number of courses processed
4468 function course_filter_courses_by_customfield(
4469 $courses,
4470 $customfieldname,
4471 $customfieldvalue,
4472 int $limit = 0
4473 ): array {
4474 global $DB;
4476 if (!$courses) {
4477 return [[], 0];
4480 // Prepare the list of courses to search through.
4481 $coursesbyid = [];
4482 foreach ($courses as $course) {
4483 $coursesbyid[$course->id] = $course;
4485 if (!$coursesbyid) {
4486 return [[], 0];
4488 list($csql, $params) = $DB->get_in_or_equal(array_keys($coursesbyid), SQL_PARAMS_NAMED);
4490 // Get the id of the custom field.
4491 $sql = "
4492 SELECT f.id
4493 FROM {customfield_field} f
4494 JOIN {customfield_category} cat ON cat.id = f.categoryid
4495 WHERE f.shortname = ?
4496 AND cat.component = 'core_course'
4497 AND cat.area = 'course'
4499 $fieldid = $DB->get_field_sql($sql, [$customfieldname]);
4500 if (!$fieldid) {
4501 return [[], 0];
4504 // Get a list of courseids that match that custom field value.
4505 if ($customfieldvalue == COURSE_CUSTOMFIELD_EMPTY) {
4506 $comparevalue = $DB->sql_compare_text('cd.value');
4507 $sql = "
4508 SELECT c.id
4509 FROM {course} c
4510 LEFT JOIN {customfield_data} cd ON cd.instanceid = c.id AND cd.fieldid = :fieldid
4511 WHERE c.id $csql
4512 AND (cd.value IS NULL OR $comparevalue = '' OR $comparevalue = '0')
4514 $params['fieldid'] = $fieldid;
4515 $matchcourseids = $DB->get_fieldset_sql($sql, $params);
4516 } else {
4517 $comparevalue = $DB->sql_compare_text('value');
4518 $select = "fieldid = :fieldid AND $comparevalue = :customfieldvalue AND instanceid $csql";
4519 $params['fieldid'] = $fieldid;
4520 $params['customfieldvalue'] = $customfieldvalue;
4521 $matchcourseids = $DB->get_fieldset_select('customfield_data', 'instanceid', $select, $params);
4524 // Prepare the list of courses to return.
4525 $filteredcourses = [];
4526 $numberofcoursesprocessed = 0;
4527 $filtermatches = 0;
4529 foreach ($coursesbyid as $course) {
4530 $numberofcoursesprocessed++;
4532 if (in_array($course->id, $matchcourseids)) {
4533 $filteredcourses[] = $course;
4534 $filtermatches++;
4537 if ($limit && $filtermatches >= $limit) {
4538 // We've found the number of requested courses. No need to continue searching.
4539 break;
4543 // Return the number of filtered courses as well as the number of courses that were searched
4544 // in order to find the matching courses. This allows the calling code to do some kind of
4545 // pagination.
4546 return [$filteredcourses, $numberofcoursesprocessed];
4550 * Check module updates since a given time.
4551 * This function checks for updates in the module config, file areas, completion, grades, comments and ratings.
4553 * @param cm_info $cm course module data
4554 * @param int $from the time to check
4555 * @param array $fileareas additional file ares to check
4556 * @param array $filter if we need to filter and return only selected updates
4557 * @return stdClass object with the different updates
4558 * @since Moodle 3.2
4560 function course_check_module_updates_since($cm, $from, $fileareas = array(), $filter = array()) {
4561 global $DB, $CFG, $USER;
4563 $context = $cm->context;
4564 $mod = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
4566 $updates = new stdClass();
4567 $course = get_course($cm->course);
4568 $component = 'mod_' . $cm->modname;
4570 // Check changes in the module configuration.
4571 if (isset($mod->timemodified) and (empty($filter) or in_array('configuration', $filter))) {
4572 $updates->configuration = (object) array('updated' => false);
4573 if ($updates->configuration->updated = $mod->timemodified > $from) {
4574 $updates->configuration->timeupdated = $mod->timemodified;
4578 // Check for updates in files.
4579 if (plugin_supports('mod', $cm->modname, FEATURE_MOD_INTRO)) {
4580 $fileareas[] = 'intro';
4582 if (!empty($fileareas) and (empty($filter) or in_array('fileareas', $filter))) {
4583 $fs = get_file_storage();
4584 $files = $fs->get_area_files($context->id, $component, $fileareas, false, "filearea, timemodified DESC", false, $from);
4585 foreach ($fileareas as $filearea) {
4586 $updates->{$filearea . 'files'} = (object) array('updated' => false);
4588 foreach ($files as $file) {
4589 $updates->{$file->get_filearea() . 'files'}->updated = true;
4590 $updates->{$file->get_filearea() . 'files'}->itemids[] = $file->get_id();
4594 // Check completion.
4595 $supportcompletion = plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_HAS_RULES);
4596 $supportcompletion = $supportcompletion or plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_TRACKS_VIEWS);
4597 if ($supportcompletion and (empty($filter) or in_array('completion', $filter))) {
4598 $updates->completion = (object) array('updated' => false);
4599 $completion = new completion_info($course);
4600 // Use wholecourse to cache all the modules the first time.
4601 $completiondata = $completion->get_data($cm, true);
4602 if ($updates->completion->updated = !empty($completiondata->timemodified) && $completiondata->timemodified > $from) {
4603 $updates->completion->timemodified = $completiondata->timemodified;
4607 // Check grades.
4608 $supportgrades = plugin_supports('mod', $cm->modname, FEATURE_GRADE_HAS_GRADE);
4609 $supportgrades = $supportgrades or plugin_supports('mod', $cm->modname, FEATURE_GRADE_OUTCOMES);
4610 if ($supportgrades and (empty($filter) or (in_array('gradeitems', $filter) or in_array('outcomes', $filter)))) {
4611 require_once($CFG->libdir . '/gradelib.php');
4612 $grades = grade_get_grades($course->id, 'mod', $cm->modname, $mod->id, $USER->id);
4614 if (empty($filter) or in_array('gradeitems', $filter)) {
4615 $updates->gradeitems = (object) array('updated' => false);
4616 foreach ($grades->items as $gradeitem) {
4617 foreach ($gradeitem->grades as $grade) {
4618 if ($grade->datesubmitted > $from or $grade->dategraded > $from) {
4619 $updates->gradeitems->updated = true;
4620 $updates->gradeitems->itemids[] = $gradeitem->id;
4626 if (empty($filter) or in_array('outcomes', $filter)) {
4627 $updates->outcomes = (object) array('updated' => false);
4628 foreach ($grades->outcomes as $outcome) {
4629 foreach ($outcome->grades as $grade) {
4630 if ($grade->datesubmitted > $from or $grade->dategraded > $from) {
4631 $updates->outcomes->updated = true;
4632 $updates->outcomes->itemids[] = $outcome->id;
4639 // Check comments.
4640 if (plugin_supports('mod', $cm->modname, FEATURE_COMMENT) and (empty($filter) or in_array('comments', $filter))) {
4641 $updates->comments = (object) array('updated' => false);
4642 require_once($CFG->dirroot . '/comment/lib.php');
4643 require_once($CFG->dirroot . '/comment/locallib.php');
4644 $manager = new comment_manager();
4645 $comments = $manager->get_component_comments_since($course, $context, $component, $from, $cm);
4646 if (!empty($comments)) {
4647 $updates->comments->updated = true;
4648 $updates->comments->itemids = array_keys($comments);
4652 // Check ratings.
4653 if (plugin_supports('mod', $cm->modname, FEATURE_RATE) and (empty($filter) or in_array('ratings', $filter))) {
4654 $updates->ratings = (object) array('updated' => false);
4655 require_once($CFG->dirroot . '/rating/lib.php');
4656 $manager = new rating_manager();
4657 $ratings = $manager->get_component_ratings_since($context, $component, $from);
4658 if (!empty($ratings)) {
4659 $updates->ratings->updated = true;
4660 $updates->ratings->itemids = array_keys($ratings);
4664 return $updates;
4668 * Returns true if the user can view the participant page, false otherwise,
4670 * @param context $context The context we are checking.
4671 * @return bool
4673 function course_can_view_participants($context) {
4674 $viewparticipantscap = 'moodle/course:viewparticipants';
4675 if ($context->contextlevel == CONTEXT_SYSTEM) {
4676 $viewparticipantscap = 'moodle/site:viewparticipants';
4679 return has_any_capability([$viewparticipantscap, 'moodle/course:enrolreview'], $context);
4683 * Checks if a user can view the participant page, if not throws an exception.
4685 * @param context $context The context we are checking.
4686 * @throws required_capability_exception
4688 function course_require_view_participants($context) {
4689 if (!course_can_view_participants($context)) {
4690 $viewparticipantscap = 'moodle/course:viewparticipants';
4691 if ($context->contextlevel == CONTEXT_SYSTEM) {
4692 $viewparticipantscap = 'moodle/site:viewparticipants';
4694 throw new required_capability_exception($context, $viewparticipantscap, 'nopermissions', '');
4699 * Return whether the user can download from the specified backup file area in the given context.
4701 * @param string $filearea the backup file area. E.g. 'course', 'backup' or 'automated'.
4702 * @param \context $context
4703 * @param stdClass $user the user object. If not provided, the current user will be checked.
4704 * @return bool true if the user is allowed to download in the context, false otherwise.
4706 function can_download_from_backup_filearea($filearea, \context $context, stdClass $user = null) {
4707 $candownload = false;
4708 switch ($filearea) {
4709 case 'course':
4710 case 'backup':
4711 $candownload = has_capability('moodle/backup:downloadfile', $context, $user);
4712 break;
4713 case 'automated':
4714 // Given the automated backups may contain userinfo, we restrict access such that only users who are able to
4715 // restore with userinfo are able to download the file. Users can't create these backups, so checking 'backup:userinfo'
4716 // doesn't make sense here.
4717 $candownload = has_capability('moodle/backup:downloadfile', $context, $user) &&
4718 has_capability('moodle/restore:userinfo', $context, $user);
4719 break;
4720 default:
4721 break;
4724 return $candownload;
4728 * Get a list of hidden courses
4730 * @param int|object|null $user User override to get the filter from. Defaults to current user
4731 * @return array $ids List of hidden courses
4732 * @throws coding_exception
4734 function get_hidden_courses_on_timeline($user = null) {
4735 global $USER;
4737 if (empty($user)) {
4738 $user = $USER->id;
4741 $preferences = get_user_preferences(null, null, $user);
4742 $ids = [];
4743 foreach ($preferences as $key => $value) {
4744 if (preg_match('/block_myoverview_hidden_course_(\d)+/', $key)) {
4745 $id = preg_split('/block_myoverview_hidden_course_/', $key);
4746 $ids[] = $id[1];
4750 return $ids;
4754 * Returns a list of the most recently courses accessed by a user
4756 * @param int $userid User id from which the courses will be obtained
4757 * @param int $limit Restrict result set to this amount
4758 * @param int $offset Skip this number of records from the start of the result set
4759 * @param string|null $sort SQL string for sorting
4760 * @return array
4762 function course_get_recent_courses(int $userid = null, int $limit = 0, int $offset = 0, string $sort = null) {
4764 global $CFG, $USER, $DB;
4766 if (empty($userid)) {
4767 $userid = $USER->id;
4770 $basefields = [
4771 'id', 'idnumber', 'summary', 'summaryformat', 'startdate', 'enddate', 'category',
4772 'shortname', 'fullname', 'timeaccess', 'component', 'visible',
4773 'showactivitydates', 'showcompletionconditions', 'pdfexportfont'
4776 if (empty($sort)) {
4777 $sort = 'timeaccess DESC';
4778 } else {
4779 // The SQL string for sorting can define sorting by multiple columns.
4780 $rawsorts = explode(',', $sort);
4781 $sorts = array();
4782 // Validate and trim the sort parameters in the SQL string for sorting.
4783 foreach ($rawsorts as $rawsort) {
4784 $sort = trim($rawsort);
4785 $sortparams = explode(' ', $sort);
4786 // A valid sort statement can not have more than 2 params (ex. 'summary desc' or 'timeaccess').
4787 if (count($sortparams) > 2) {
4788 throw new invalid_parameter_exception(
4789 'Invalid structure of the sort parameter, allowed structure: fieldname [ASC|DESC].');
4791 $sortfield = trim($sortparams[0]);
4792 // Validate the value which defines the field to sort by.
4793 if (!in_array($sortfield, $basefields)) {
4794 throw new invalid_parameter_exception('Invalid field in the sort parameter, allowed fields: ' .
4795 implode(', ', $basefields) . '.');
4797 $sortdirection = isset($sortparams[1]) ? trim($sortparams[1]) : '';
4798 // Validate the value which defines the sort direction (if present).
4799 $allowedsortdirections = ['asc', 'desc'];
4800 if (!empty($sortdirection) && !in_array(strtolower($sortdirection), $allowedsortdirections)) {
4801 throw new invalid_parameter_exception('Invalid sort direction in the sort parameter, allowed values: ' .
4802 implode(', ', $allowedsortdirections) . '.');
4804 $sorts[] = $sort;
4806 $sort = implode(',', $sorts);
4809 $ctxfields = context_helper::get_preload_record_columns_sql('ctx');
4811 $coursefields = 'c.' . join(',', $basefields);
4813 // Ask the favourites service to give us the join SQL for favourited courses,
4814 // so we can include favourite information in the query.
4815 $usercontext = \context_user::instance($userid);
4816 $favservice = \core_favourites\service_factory::get_service_for_user_context($usercontext);
4817 list($favsql, $favparams) = $favservice->get_join_sql_by_type('core_course', 'courses', 'fav', 'ul.courseid');
4819 $sql = "SELECT $coursefields, $ctxfields
4820 FROM {course} c
4821 JOIN {context} ctx
4822 ON ctx.contextlevel = :contextlevel
4823 AND ctx.instanceid = c.id
4824 JOIN {user_lastaccess} ul
4825 ON ul.courseid = c.id
4826 $favsql
4827 LEFT JOIN {enrol} eg ON eg.courseid = c.id AND eg.status = :statusenrolg AND eg.enrol = :guestenrol
4828 WHERE ul.userid = :userid
4829 AND c.visible = :visible
4830 AND (eg.id IS NOT NULL
4831 OR EXISTS (SELECT e.id
4832 FROM {enrol} e
4833 JOIN {user_enrolments} ue ON ue.enrolid = e.id
4834 WHERE e.courseid = c.id
4835 AND e.status = :statusenrol
4836 AND ue.status = :status
4837 AND ue.userid = :userid2
4838 AND ue.timestart < :now1
4839 AND (ue.timeend = 0 OR ue.timeend > :now2)
4841 ORDER BY $sort";
4843 $now = round(time(), -2); // Improves db caching.
4844 $params = ['userid' => $userid, 'contextlevel' => CONTEXT_COURSE, 'visible' => 1, 'status' => ENROL_USER_ACTIVE,
4845 'statusenrol' => ENROL_INSTANCE_ENABLED, 'guestenrol' => 'guest', 'now1' => $now, 'now2' => $now,
4846 'userid2' => $userid, 'statusenrolg' => ENROL_INSTANCE_ENABLED] + $favparams;
4848 $recentcourses = $DB->get_records_sql($sql, $params, $offset, $limit);
4850 // Filter courses if last access field is hidden.
4851 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
4853 if ($userid != $USER->id && isset($hiddenfields['lastaccess'])) {
4854 $recentcourses = array_filter($recentcourses, function($course) {
4855 context_helper::preload_from_record($course);
4856 $context = context_course::instance($course->id, IGNORE_MISSING);
4857 // If last access was a hidden field, a user requesting info about another user would need permission to view hidden
4858 // fields.
4859 return has_capability('moodle/course:viewhiddenuserfields', $context);
4863 return $recentcourses;
4867 * Calculate the course start date and offset for the given user ids.
4869 * If the course is a fixed date course then the course start date will be returned.
4870 * If the course is a relative date course then the course date will be calculated and
4871 * and offset provided.
4873 * The dates are returned as an array with the index being the user id. The array
4874 * contains the start date and start offset values for the user.
4876 * If the user is not enrolled in the course then the course start date will be returned.
4878 * If we have a course which starts on 1563244000 and 2 users, id 123 and 456, where the
4879 * former is enrolled in the course at 1563244693 and the latter is not enrolled then the
4880 * return value would look like:
4882 * '123' => [
4883 * 'start' => 1563244693,
4884 * 'startoffset' => 693
4885 * ],
4886 * '456' => [
4887 * 'start' => 1563244000,
4888 * 'startoffset' => 0
4892 * @param stdClass $course The course to fetch dates for.
4893 * @param array $userids The list of user ids to get dates for.
4894 * @return array
4896 function course_get_course_dates_for_user_ids(stdClass $course, array $userids): array {
4897 if (empty($course->relativedatesmode)) {
4898 // This course isn't set to relative dates so we can early return with the course
4899 // start date.
4900 return array_reduce($userids, function($carry, $userid) use ($course) {
4901 $carry[$userid] = [
4902 'start' => $course->startdate,
4903 'startoffset' => 0
4905 return $carry;
4906 }, []);
4909 // We're dealing with a relative dates course now so we need to calculate some dates.
4910 $cache = cache::make('core', 'course_user_dates');
4911 $dates = [];
4912 $uncacheduserids = [];
4914 // Try fetching the values from the cache so that we don't need to do a DB request.
4915 foreach ($userids as $userid) {
4916 $cachekey = "{$course->id}_{$userid}";
4917 $cachedvalue = $cache->get($cachekey);
4919 if ($cachedvalue === false) {
4920 // Looks like we haven't seen this user for this course before so we'll have
4921 // to fetch it.
4922 $uncacheduserids[] = $userid;
4923 } else {
4924 [$start, $startoffset] = $cachedvalue;
4925 $dates[$userid] = [
4926 'start' => $start,
4927 'startoffset' => $startoffset
4932 if (!empty($uncacheduserids)) {
4933 // Load the enrolments for any users we haven't seen yet. Set the "onlyactive" param
4934 // to false because it filters out users with enrolment start times in the future which
4935 // we don't want.
4936 $enrolments = enrol_get_course_users($course->id, false, $uncacheduserids);
4938 foreach ($uncacheduserids as $userid) {
4939 // Find the user enrolment that has the earliest start date.
4940 $enrolment = array_reduce(array_values($enrolments), function($carry, $enrolment) use ($userid) {
4941 // Only consider enrolments for this user if the user enrolment is active and the
4942 // enrolment method is enabled.
4943 if (
4944 $enrolment->uestatus == ENROL_USER_ACTIVE &&
4945 $enrolment->estatus == ENROL_INSTANCE_ENABLED &&
4946 $enrolment->id == $userid
4948 if (is_null($carry)) {
4949 // Haven't found an enrolment yet for this user so use the one we just found.
4950 $carry = $enrolment;
4951 } else {
4952 // We've already found an enrolment for this user so let's use which ever one
4953 // has the earliest start time.
4954 $carry = $carry->uetimestart < $enrolment->uetimestart ? $carry : $enrolment;
4958 return $carry;
4959 }, null);
4961 if ($enrolment) {
4962 // The course is in relative dates mode so we calculate the student's start
4963 // date based on their enrolment start date.
4964 $start = $course->startdate > $enrolment->uetimestart ? $course->startdate : $enrolment->uetimestart;
4965 $startoffset = $start - $course->startdate;
4966 } else {
4967 // The user is not enrolled in the course so default back to the course start date.
4968 $start = $course->startdate;
4969 $startoffset = 0;
4972 $dates[$userid] = [
4973 'start' => $start,
4974 'startoffset' => $startoffset
4977 $cachekey = "{$course->id}_{$userid}";
4978 $cache->set($cachekey, [$start, $startoffset]);
4982 return $dates;
4986 * Calculate the course start date and offset for the given user id.
4988 * If the course is a fixed date course then the course start date will be returned.
4989 * If the course is a relative date course then the course date will be calculated and
4990 * and offset provided.
4992 * The return array contains the start date and start offset values for the user.
4994 * If the user is not enrolled in the course then the course start date will be returned.
4996 * If we have a course which starts on 1563244000. If a user's enrolment starts on 1563244693
4997 * then the return would be:
4999 * 'start' => 1563244693,
5000 * 'startoffset' => 693
5003 * If the use was not enrolled then the return would be:
5005 * 'start' => 1563244000,
5006 * 'startoffset' => 0
5009 * @param stdClass $course The course to fetch dates for.
5010 * @param int $userid The user id to get dates for.
5011 * @return array
5013 function course_get_course_dates_for_user_id(stdClass $course, int $userid): array {
5014 return (course_get_course_dates_for_user_ids($course, [$userid]))[$userid];
5018 * Renders the course copy form for the modal on the course management screen.
5020 * @param array $args
5021 * @return string $o Form HTML.
5023 function course_output_fragment_new_base_form($args) {
5025 $serialiseddata = json_decode($args['jsonformdata'], true);
5026 $formdata = [];
5027 if (!empty($serialiseddata)) {
5028 parse_str($serialiseddata, $formdata);
5031 $context = context_course::instance($args['courseid']);
5032 $copycaps = \core_course\management\helper::get_course_copy_capabilities();
5033 require_all_capabilities($copycaps, $context);
5035 $course = get_course($args['courseid']);
5036 $mform = new \core_backup\output\copy_form(
5037 null,
5038 array('course' => $course, 'returnto' => '', 'returnurl' => ''),
5039 'post', '', ['class' => 'ignoredirty'], true, $formdata);
5041 if (!empty($serialiseddata)) {
5042 // If we were passed non-empty form data we want the mform to call validation functions and show errors.
5043 $mform->is_validated();
5046 ob_start();
5047 $mform->display();
5048 $o = ob_get_contents();
5049 ob_end_clean();
5051 return $o;
5055 * Get the current course image for the given course.
5057 * @param \stdClass $course
5058 * @return null|stored_file
5060 function course_get_courseimage(\stdClass $course): ?stored_file {
5061 $courseinlist = new core_course_list_element($course);
5062 foreach ($courseinlist->get_course_overviewfiles() as $file) {
5063 if ($file->is_valid_image()) {
5064 return $file;
5067 return null;
5071 * Get course specific data for configuring a communication instance.
5073 * @param integer $courseid The course id.
5074 * @return array Returns course data, context and heading.
5076 function course_get_communication_instance_data(int $courseid): array {
5077 // Do some checks and prepare instance specific data.
5078 $course = get_course($courseid);
5079 require_login($course);
5080 $context = context_course::instance($course->id);
5081 require_capability('moodle/course:configurecoursecommunication', $context);
5083 $heading = $course->fullname;
5084 $returnurl = new moodle_url('/course/view.php', ['id' => $courseid]);
5086 return [$course, $context, $heading, $returnurl];
5090 * Update a course using communication configuration data.
5092 * @param stdClass $data The data to update the course with.
5094 function course_update_communication_instance_data(stdClass $data): void {
5095 $data->id = $data->instanceid; // For correct use in update_course.
5096 update_course($data);
5100 * Trigger course section viewed event.
5102 * @param context_course $context course context object
5103 * @param int $sectionid section number
5104 * @since Moodle 4.4.
5106 function course_section_view(context_course $context, int $sectionid) {
5108 $eventdata = [
5109 'objectid' => $sectionid,
5110 'context' => $context,
5112 $event = \core\event\section_viewed::create($eventdata);
5113 $event->trigger();
5115 user_accesstime_log($context->instanceid);