MDL-68404 gradingform_rubric: Style "Add level" button.
[moodle.git] / course / lib.php
blob7268824761a4dd059a8f29e825ab6a3ace841a9b
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 require_once($CFG->libdir.'/completionlib.php');
28 require_once($CFG->libdir.'/filelib.php');
29 require_once($CFG->libdir.'/datalib.php');
30 require_once($CFG->dirroot.'/course/format/lib.php');
32 define('COURSE_MAX_LOGS_PER_PAGE', 1000); // Records.
33 define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds.
35 /**
36 * Number of courses to display when summaries are included.
37 * @var int
38 * @deprecated since 2.4, use $CFG->courseswithsummarieslimit instead.
40 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10);
42 // Max courses in log dropdown before switching to optional.
43 define('COURSE_MAX_COURSES_PER_DROPDOWN', 1000);
44 // Max users in log dropdown before switching to optional.
45 define('COURSE_MAX_USERS_PER_DROPDOWN', 1000);
46 define('FRONTPAGENEWS', '0');
47 define('FRONTPAGECATEGORYNAMES', '2');
48 define('FRONTPAGECATEGORYCOMBO', '4');
49 define('FRONTPAGEENROLLEDCOURSELIST', '5');
50 define('FRONTPAGEALLCOURSELIST', '6');
51 define('FRONTPAGECOURSESEARCH', '7');
52 // Important! Replaced with $CFG->frontpagecourselimit - maximum number of courses displayed on the frontpage.
53 define('EXCELROWS', 65535);
54 define('FIRSTUSEDEXCELROW', 3);
56 define('MOD_CLASS_ACTIVITY', 0);
57 define('MOD_CLASS_RESOURCE', 1);
59 define('COURSE_TIMELINE_ALLINCLUDINGHIDDEN', 'allincludinghidden');
60 define('COURSE_TIMELINE_ALL', 'all');
61 define('COURSE_TIMELINE_PAST', 'past');
62 define('COURSE_TIMELINE_INPROGRESS', 'inprogress');
63 define('COURSE_TIMELINE_FUTURE', 'future');
64 define('COURSE_FAVOURITES', 'favourites');
65 define('COURSE_TIMELINE_HIDDEN', 'hidden');
66 define('COURSE_CUSTOMFIELD', 'customfield');
67 define('COURSE_DB_QUERY_LIMIT', 1000);
68 /** Searching for all courses that have no value for the specified custom field. */
69 define('COURSE_CUSTOMFIELD_EMPTY', -1);
71 function make_log_url($module, $url) {
72 switch ($module) {
73 case 'course':
74 if (strpos($url, 'report/') === 0) {
75 // there is only one report type, course reports are deprecated
76 $url = "/$url";
77 break;
79 case 'file':
80 case 'login':
81 case 'lib':
82 case 'admin':
83 case 'category':
84 case 'mnet course':
85 if (strpos($url, '../') === 0) {
86 $url = ltrim($url, '.');
87 } else {
88 $url = "/course/$url";
90 break;
91 case 'calendar':
92 $url = "/calendar/$url";
93 break;
94 case 'user':
95 case 'blog':
96 $url = "/$module/$url";
97 break;
98 case 'upload':
99 $url = $url;
100 break;
101 case 'coursetags':
102 $url = '/'.$url;
103 break;
104 case 'library':
105 case '':
106 $url = '/';
107 break;
108 case 'message':
109 $url = "/message/$url";
110 break;
111 case 'notes':
112 $url = "/notes/$url";
113 break;
114 case 'tag':
115 $url = "/tag/$url";
116 break;
117 case 'role':
118 $url = '/'.$url;
119 break;
120 case 'grade':
121 $url = "/grade/$url";
122 break;
123 default:
124 $url = "/mod/$module/$url";
125 break;
128 //now let's sanitise urls - there might be some ugly nasties:-(
129 $parts = explode('?', $url);
130 $script = array_shift($parts);
131 if (strpos($script, 'http') === 0) {
132 $script = clean_param($script, PARAM_URL);
133 } else {
134 $script = clean_param($script, PARAM_PATH);
137 $query = '';
138 if ($parts) {
139 $query = implode('', $parts);
140 $query = str_replace('&amp;', '&', $query); // both & and &amp; are stored in db :-|
141 $parts = explode('&', $query);
142 $eq = urlencode('=');
143 foreach ($parts as $key=>$part) {
144 $part = urlencode(urldecode($part));
145 $part = str_replace($eq, '=', $part);
146 $parts[$key] = $part;
148 $query = '?'.implode('&amp;', $parts);
151 return $script.$query;
155 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
156 $modname="", $modid=0, $modaction="", $groupid=0) {
157 global $CFG, $DB;
159 // It is assumed that $date is the GMT time of midnight for that day,
160 // and so the next 86400 seconds worth of logs are printed.
162 /// Setup for group handling.
164 // TODO: I don't understand group/context/etc. enough to be able to do
165 // something interesting with it here
166 // What is the context of a remote course?
168 /// If the group mode is separate, and this user does not have editing privileges,
169 /// then only the user's group can be viewed.
170 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
171 // $groupid = get_current_group($course->id);
173 /// If this course doesn't have groups, no groupid can be specified.
174 //else if (!$course->groupmode) {
175 // $groupid = 0;
178 $groupid = 0;
180 $joins = array();
181 $where = '';
183 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
184 FROM {mnet_log} l
185 LEFT JOIN {user} u ON l.userid = u.id
186 WHERE ";
187 $params = array();
189 $where .= "l.hostid = :hostid";
190 $params['hostid'] = $hostid;
192 // TODO: Is 1 really a magic number referring to the sitename?
193 if ($course != SITEID || $modid != 0) {
194 $where .= " AND l.course=:courseid";
195 $params['courseid'] = $course;
198 if ($modname) {
199 $where .= " AND l.module = :modname";
200 $params['modname'] = $modname;
203 if ('site_errors' === $modid) {
204 $where .= " AND ( l.action='error' OR l.action='infected' )";
205 } else if ($modid) {
206 //TODO: This assumes that modids are the same across sites... probably
207 //not true
208 $where .= " AND l.cmid = :modid";
209 $params['modid'] = $modid;
212 if ($modaction) {
213 $firstletter = substr($modaction, 0, 1);
214 if ($firstletter == '-') {
215 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
216 $params['modaction'] = '%'.substr($modaction, 1).'%';
217 } else {
218 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
219 $params['modaction'] = '%'.$modaction.'%';
223 if ($user) {
224 $where .= " AND l.userid = :user";
225 $params['user'] = $user;
228 if ($date) {
229 $enddate = $date + 86400;
230 $where .= " AND l.time > :date AND l.time < :enddate";
231 $params['date'] = $date;
232 $params['enddate'] = $enddate;
235 $result = array();
236 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
237 if(!empty($result['totalcount'])) {
238 $where .= " ORDER BY $order";
239 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
240 } else {
241 $result['logs'] = array();
243 return $result;
247 * Checks the integrity of the course data.
249 * In summary - compares course_sections.sequence and course_modules.section.
251 * More detailed, checks that:
252 * - course_sections.sequence contains each module id not more than once in the course
253 * - for each moduleid from course_sections.sequence the field course_modules.section
254 * refers to the same section id (this means course_sections.sequence is more
255 * important if they are different)
256 * - ($fullcheck only) each module in the course is present in one of
257 * course_sections.sequence
258 * - ($fullcheck only) removes non-existing course modules from section sequences
260 * If there are any mismatches, the changes are made and records are updated in DB.
262 * Course cache is NOT rebuilt if there are any errors!
264 * This function is used each time when course cache is being rebuilt with $fullcheck = false
265 * and in CLI script admin/cli/fix_course_sequence.php with $fullcheck = true
267 * @param int $courseid id of the course
268 * @param array $rawmods result of funciton {@link get_course_mods()} - containst
269 * the list of enabled course modules in the course. Retrieved from DB if not specified.
270 * Argument ignored in cashe of $fullcheck, the list is retrieved form DB anyway.
271 * @param array $sections records from course_sections table for this course.
272 * Retrieved from DB if not specified
273 * @param bool $fullcheck Will add orphaned modules to their sections and remove non-existing
274 * course modules from sequences. Only to be used in site maintenance mode when we are
275 * sure that another user is not in the middle of the process of moving/removing a module.
276 * @param bool $checkonly Only performs the check without updating DB, outputs all errors as debug messages.
277 * @return array array of messages with found problems. Empty output means everything is ok
279 function course_integrity_check($courseid, $rawmods = null, $sections = null, $fullcheck = false, $checkonly = false) {
280 global $DB;
281 $messages = array();
282 if ($sections === null) {
283 $sections = $DB->get_records('course_sections', array('course' => $courseid), 'section', 'id,section,sequence');
285 if ($fullcheck) {
286 // Retrieve all records from course_modules regardless of module type visibility.
287 $rawmods = $DB->get_records('course_modules', array('course' => $courseid), 'id', 'id,section');
289 if ($rawmods === null) {
290 $rawmods = get_course_mods($courseid);
292 if (!$fullcheck && (empty($sections) || empty($rawmods))) {
293 // If either of the arrays is empty, no modules are displayed anyway.
294 return true;
296 $debuggingprefix = 'Failed integrity check for course ['.$courseid.']. ';
298 // First make sure that each module id appears in section sequences only once.
299 // If it appears in several section sequences the last section wins.
300 // If it appears twice in one section sequence, the first occurence wins.
301 $modsection = array();
302 foreach ($sections as $sectionid => $section) {
303 $sections[$sectionid]->newsequence = $section->sequence;
304 if (!empty($section->sequence)) {
305 $sequence = explode(",", $section->sequence);
306 $sequenceunique = array_unique($sequence);
307 if (count($sequenceunique) != count($sequence)) {
308 // Some course module id appears in this section sequence more than once.
309 ksort($sequenceunique); // Preserve initial order of modules.
310 $sequence = array_values($sequenceunique);
311 $sections[$sectionid]->newsequence = join(',', $sequence);
312 $messages[] = $debuggingprefix.'Sequence for course section ['.
313 $sectionid.'] is "'.$sections[$sectionid]->sequence.'", must be "'.$sections[$sectionid]->newsequence.'"';
315 foreach ($sequence as $cmid) {
316 if (array_key_exists($cmid, $modsection) && isset($rawmods[$cmid])) {
317 // Some course module id appears to be in more than one section's sequences.
318 $wrongsectionid = $modsection[$cmid];
319 $sections[$wrongsectionid]->newsequence = trim(preg_replace("/,$cmid,/", ',', ','.$sections[$wrongsectionid]->newsequence. ','), ',');
320 $messages[] = $debuggingprefix.'Course module ['.$cmid.'] must be removed from sequence of section ['.
321 $wrongsectionid.'] because it is also present in sequence of section ['.$sectionid.']';
323 $modsection[$cmid] = $sectionid;
328 // Add orphaned modules to their sections if they exist or to section 0 otherwise.
329 if ($fullcheck) {
330 foreach ($rawmods as $cmid => $mod) {
331 if (!isset($modsection[$cmid])) {
332 // This is a module that is not mentioned in course_section.sequence at all.
333 // Add it to the section $mod->section or to the last available section.
334 if ($mod->section && isset($sections[$mod->section])) {
335 $modsection[$cmid] = $mod->section;
336 } else {
337 $firstsection = reset($sections);
338 $modsection[$cmid] = $firstsection->id;
340 $sections[$modsection[$cmid]]->newsequence = trim($sections[$modsection[$cmid]]->newsequence.','.$cmid, ',');
341 $messages[] = $debuggingprefix.'Course module ['.$cmid.'] is missing from sequence of section ['.
342 $modsection[$cmid].']';
345 foreach ($modsection as $cmid => $sectionid) {
346 if (!isset($rawmods[$cmid])) {
347 // Section $sectionid refers to module id that does not exist.
348 $sections[$sectionid]->newsequence = trim(preg_replace("/,$cmid,/", ',', ','.$sections[$sectionid]->newsequence.','), ',');
349 $messages[] = $debuggingprefix.'Course module ['.$cmid.
350 '] does not exist but is present in the sequence of section ['.$sectionid.']';
355 // Update changed sections.
356 if (!$checkonly && !empty($messages)) {
357 foreach ($sections as $sectionid => $section) {
358 if ($section->newsequence !== $section->sequence) {
359 $DB->update_record('course_sections', array('id' => $sectionid, 'sequence' => $section->newsequence));
364 // Now make sure that all modules point to the correct sections.
365 foreach ($rawmods as $cmid => $mod) {
366 if (isset($modsection[$cmid]) && $modsection[$cmid] != $mod->section) {
367 if (!$checkonly) {
368 $DB->update_record('course_modules', array('id' => $cmid, 'section' => $modsection[$cmid]));
370 $messages[] = $debuggingprefix.'Course module ['.$cmid.
371 '] points to section ['.$mod->section.'] instead of ['.$modsection[$cmid].']';
375 return $messages;
379 * For a given course, returns an array of course activity objects
380 * Each item in the array contains he following properties:
382 function get_array_of_activities($courseid) {
383 // cm - course module id
384 // mod - name of the module (eg forum)
385 // section - the number of the section (eg week or topic)
386 // name - the name of the instance
387 // visible - is the instance visible or not
388 // groupingid - grouping id
389 // extra - contains extra string to include in any link
390 global $CFG, $DB;
392 $course = $DB->get_record('course', array('id'=>$courseid));
394 if (empty($course)) {
395 throw new moodle_exception('courseidnotfound');
398 $mod = array();
400 $rawmods = get_course_mods($courseid);
401 if (empty($rawmods)) {
402 return $mod; // always return array
404 $courseformat = course_get_format($course);
406 if ($sections = $DB->get_records('course_sections', array('course' => $courseid),
407 'section ASC', 'id,section,sequence,visible')) {
408 // First check and correct obvious mismatches between course_sections.sequence and course_modules.section.
409 if ($errormessages = course_integrity_check($courseid, $rawmods, $sections)) {
410 debugging(join('<br>', $errormessages));
411 $rawmods = get_course_mods($courseid);
412 $sections = $DB->get_records('course_sections', array('course' => $courseid),
413 'section ASC', 'id,section,sequence,visible');
415 // Build array of activities.
416 foreach ($sections as $section) {
417 if (!empty($section->sequence)) {
418 $sequence = explode(",", $section->sequence);
419 foreach ($sequence as $seq) {
420 if (empty($rawmods[$seq])) {
421 continue;
423 // Adjust visibleoncoursepage, value in DB may not respect format availability.
424 $rawmods[$seq]->visibleoncoursepage = (!$rawmods[$seq]->visible
425 || $rawmods[$seq]->visibleoncoursepage
426 || empty($CFG->allowstealth)
427 || !$courseformat->allow_stealth_module_visibility($rawmods[$seq], $section)) ? 1 : 0;
429 // Create an object that will be cached.
430 $mod[$seq] = new stdClass();
431 $mod[$seq]->id = $rawmods[$seq]->instance;
432 $mod[$seq]->cm = $rawmods[$seq]->id;
433 $mod[$seq]->mod = $rawmods[$seq]->modname;
435 // Oh dear. Inconsistent names left here for backward compatibility.
436 $mod[$seq]->section = $section->section;
437 $mod[$seq]->sectionid = $rawmods[$seq]->section;
439 $mod[$seq]->module = $rawmods[$seq]->module;
440 $mod[$seq]->added = $rawmods[$seq]->added;
441 $mod[$seq]->score = $rawmods[$seq]->score;
442 $mod[$seq]->idnumber = $rawmods[$seq]->idnumber;
443 $mod[$seq]->visible = $rawmods[$seq]->visible;
444 $mod[$seq]->visibleoncoursepage = $rawmods[$seq]->visibleoncoursepage;
445 $mod[$seq]->visibleold = $rawmods[$seq]->visibleold;
446 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
447 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
448 $mod[$seq]->indent = $rawmods[$seq]->indent;
449 $mod[$seq]->completion = $rawmods[$seq]->completion;
450 $mod[$seq]->extra = "";
451 $mod[$seq]->completiongradeitemnumber =
452 $rawmods[$seq]->completiongradeitemnumber;
453 $mod[$seq]->completionview = $rawmods[$seq]->completionview;
454 $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected;
455 $mod[$seq]->showdescription = $rawmods[$seq]->showdescription;
456 $mod[$seq]->availability = $rawmods[$seq]->availability;
457 $mod[$seq]->deletioninprogress = $rawmods[$seq]->deletioninprogress;
459 $modname = $mod[$seq]->mod;
460 $functionname = $modname."_get_coursemodule_info";
462 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
463 continue;
466 include_once("$CFG->dirroot/mod/$modname/lib.php");
468 if ($hasfunction = function_exists($functionname)) {
469 if ($info = $functionname($rawmods[$seq])) {
470 if (!empty($info->icon)) {
471 $mod[$seq]->icon = $info->icon;
473 if (!empty($info->iconcomponent)) {
474 $mod[$seq]->iconcomponent = $info->iconcomponent;
476 if (!empty($info->name)) {
477 $mod[$seq]->name = $info->name;
479 if ($info instanceof cached_cm_info) {
480 // When using cached_cm_info you can include three new fields
481 // that aren't available for legacy code
482 if (!empty($info->content)) {
483 $mod[$seq]->content = $info->content;
485 if (!empty($info->extraclasses)) {
486 $mod[$seq]->extraclasses = $info->extraclasses;
488 if (!empty($info->iconurl)) {
489 // Convert URL to string as it's easier to store. Also serialized object contains \0 byte and can not be written to Postgres DB.
490 $url = new moodle_url($info->iconurl);
491 $mod[$seq]->iconurl = $url->out(false);
493 if (!empty($info->onclick)) {
494 $mod[$seq]->onclick = $info->onclick;
496 if (!empty($info->customdata)) {
497 $mod[$seq]->customdata = $info->customdata;
499 } else {
500 // When using a stdclass, the (horrible) deprecated ->extra field
501 // is available for BC
502 if (!empty($info->extra)) {
503 $mod[$seq]->extra = $info->extra;
508 // When there is no modname_get_coursemodule_info function,
509 // but showdescriptions is enabled, then we use the 'intro'
510 // and 'introformat' fields in the module table
511 if (!$hasfunction && $rawmods[$seq]->showdescription) {
512 if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
513 array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
514 // Set content from intro and introformat. Filters are disabled
515 // because we filter it with format_text at display time
516 $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
517 $modvalues, $rawmods[$seq]->id, false);
519 // To save making another query just below, put name in here
520 $mod[$seq]->name = $modvalues->name;
523 if (!isset($mod[$seq]->name)) {
524 $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
527 // Minimise the database size by unsetting default options when they are
528 // 'empty'. This list corresponds to code in the cm_info constructor.
529 foreach (array('idnumber', 'groupmode', 'groupingid',
530 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
531 'icon', 'iconcomponent', 'customdata', 'availability', 'completionview',
532 'completionexpected', 'score', 'showdescription', 'deletioninprogress') as $property) {
533 if (property_exists($mod[$seq], $property) &&
534 empty($mod[$seq]->{$property})) {
535 unset($mod[$seq]->{$property});
538 // Special case: this value is usually set to null, but may be 0
539 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
540 is_null($mod[$seq]->completiongradeitemnumber)) {
541 unset($mod[$seq]->completiongradeitemnumber);
547 return $mod;
551 * Returns the localised human-readable names of all used modules
553 * @param bool $plural if true returns the plural forms of the names
554 * @return array where key is the module name (component name without 'mod_') and
555 * the value is the human-readable string. Array sorted alphabetically by value
557 function get_module_types_names($plural = false) {
558 static $modnames = null;
559 global $DB, $CFG;
560 if ($modnames === null) {
561 $modnames = array(0 => array(), 1 => array());
562 if ($allmods = $DB->get_records("modules")) {
563 foreach ($allmods as $mod) {
564 if (file_exists("$CFG->dirroot/mod/$mod->name/lib.php") && $mod->visible) {
565 $modnames[0][$mod->name] = get_string("modulename", "$mod->name", null, true);
566 $modnames[1][$mod->name] = get_string("modulenameplural", "$mod->name", null, true);
571 return $modnames[(int)$plural];
575 * Set highlighted section. Only one section can be highlighted at the time.
577 * @param int $courseid course id
578 * @param int $marker highlight section with this number, 0 means remove higlightin
579 * @return void
581 function course_set_marker($courseid, $marker) {
582 global $DB, $COURSE;
583 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
584 if ($COURSE && $COURSE->id == $courseid) {
585 $COURSE->marker = $marker;
587 if (class_exists('format_base')) {
588 format_base::reset_course_cache($courseid);
590 course_modinfo::clear_instance_cache($courseid);
594 * For a given course section, marks it visible or hidden,
595 * and does the same for every activity in that section
597 * @param int $courseid course id
598 * @param int $sectionnumber The section number to adjust
599 * @param int $visibility The new visibility
600 * @return array A list of resources which were hidden in the section
602 function set_section_visible($courseid, $sectionnumber, $visibility) {
603 global $DB;
605 $resourcestotoggle = array();
606 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
607 course_update_section($courseid, $section, array('visible' => $visibility));
609 // Determine which modules are visible for AJAX update
610 $modules = !empty($section->sequence) ? explode(',', $section->sequence) : array();
611 if (!empty($modules)) {
612 list($insql, $params) = $DB->get_in_or_equal($modules);
613 $select = 'id ' . $insql . ' AND visible = ?';
614 array_push($params, $visibility);
615 if (!$visibility) {
616 $select .= ' AND visibleold = 1';
618 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
621 return $resourcestotoggle;
625 * Return the course category context for the category with id $categoryid, except
626 * that if $categoryid is 0, return the system context.
628 * @param integer $categoryid a category id or 0.
629 * @return context the corresponding context
631 function get_category_or_system_context($categoryid) {
632 if ($categoryid) {
633 return context_coursecat::instance($categoryid, IGNORE_MISSING);
634 } else {
635 return context_system::instance();
640 * Returns full course categories trees to be used in html_writer::select()
642 * Calls {@link core_course_category::make_categories_list()} to build the tree and
643 * adds whitespace to denote nesting
645 * @return array array mapping course category id to the display name
647 function make_categories_options() {
648 $cats = core_course_category::make_categories_list('', 0, ' / ');
649 foreach ($cats as $key => $value) {
650 // Prefix the value with the number of spaces equal to category depth (number of separators in the value).
651 $cats[$key] = str_repeat('&nbsp;', substr_count($value, ' / ')). $value;
653 return $cats;
657 * Print the buttons relating to course requests.
659 * @param context $context current page context.
661 function print_course_request_buttons($context) {
662 global $CFG, $DB, $OUTPUT;
663 if (empty($CFG->enablecourserequests)) {
664 return;
666 if (course_request::can_request($context)) {
667 // Print a button to request a new course.
668 $params = [];
669 if ($context instanceof context_coursecat) {
670 $params['category'] = $context->instanceid;
672 echo $OUTPUT->single_button(new moodle_url('/course/request.php', $params),
673 get_string('requestcourse'), 'get');
675 /// Print a button to manage pending requests
676 if (has_capability('moodle/site:approvecourse', $context)) {
677 $disabled = !$DB->record_exists('course_request', array());
678 echo $OUTPUT->single_button(new moodle_url('/course/pending.php'), get_string('coursespending'), 'get', array('disabled' => $disabled));
683 * Does the user have permission to edit things in this category?
685 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
686 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
688 function can_edit_in_category($categoryid = 0) {
689 $context = get_category_or_system_context($categoryid);
690 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
693 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
695 function add_course_module($mod) {
696 global $DB;
698 $mod->added = time();
699 unset($mod->id);
701 $cmid = $DB->insert_record("course_modules", $mod);
702 rebuild_course_cache($mod->course, true);
703 return $cmid;
707 * Creates a course section and adds it to the specified position
709 * @param int|stdClass $courseorid course id or course object
710 * @param int $position position to add to, 0 means to the end. If position is greater than
711 * number of existing secitons, the section is added to the end. This will become sectionnum of the
712 * new section. All existing sections at this or bigger position will be shifted down.
713 * @param bool $skipcheck the check has already been made and we know that the section with this position does not exist
714 * @return stdClass created section object
716 function course_create_section($courseorid, $position = 0, $skipcheck = false) {
717 global $DB;
718 $courseid = is_object($courseorid) ? $courseorid->id : $courseorid;
720 // Find the last sectionnum among existing sections.
721 if ($skipcheck) {
722 $lastsection = $position - 1;
723 } else {
724 $lastsection = (int)$DB->get_field_sql('SELECT max(section) from {course_sections} WHERE course = ?', [$courseid]);
727 // First add section to the end.
728 $cw = new stdClass();
729 $cw->course = $courseid;
730 $cw->section = $lastsection + 1;
731 $cw->summary = '';
732 $cw->summaryformat = FORMAT_HTML;
733 $cw->sequence = '';
734 $cw->name = null;
735 $cw->visible = 1;
736 $cw->availability = null;
737 $cw->timemodified = time();
738 $cw->id = $DB->insert_record("course_sections", $cw);
740 // Now move it to the specified position.
741 if ($position > 0 && $position <= $lastsection) {
742 $course = is_object($courseorid) ? $courseorid : get_course($courseorid);
743 move_section_to($course, $cw->section, $position, true);
744 $cw->section = $position;
747 core\event\course_section_created::create_from_section($cw)->trigger();
749 rebuild_course_cache($courseid, true);
750 return $cw;
754 * Creates missing course section(s) and rebuilds course cache
756 * @param int|stdClass $courseorid course id or course object
757 * @param int|array $sections list of relative section numbers to create
758 * @return bool if there were any sections created
760 function course_create_sections_if_missing($courseorid, $sections) {
761 if (!is_array($sections)) {
762 $sections = array($sections);
764 $existing = array_keys(get_fast_modinfo($courseorid)->get_section_info_all());
765 if ($newsections = array_diff($sections, $existing)) {
766 foreach ($newsections as $sectionnum) {
767 course_create_section($courseorid, $sectionnum, true);
769 return true;
771 return false;
775 * Adds an existing module to the section
777 * Updates both tables {course_sections} and {course_modules}
779 * Note: This function does not use modinfo PROVIDED that the section you are
780 * adding the module to already exists. If the section does not exist, it will
781 * build modinfo if necessary and create the section.
783 * @param int|stdClass $courseorid course id or course object
784 * @param int $cmid id of the module already existing in course_modules table
785 * @param int $sectionnum relative number of the section (field course_sections.section)
786 * If section does not exist it will be created
787 * @param int|stdClass $beforemod id or object with field id corresponding to the module
788 * before which the module needs to be included. Null for inserting in the
789 * end of the section
790 * @return int The course_sections ID where the module is inserted
792 function course_add_cm_to_section($courseorid, $cmid, $sectionnum, $beforemod = null) {
793 global $DB, $COURSE;
794 if (is_object($beforemod)) {
795 $beforemod = $beforemod->id;
797 if (is_object($courseorid)) {
798 $courseid = $courseorid->id;
799 } else {
800 $courseid = $courseorid;
802 // Do not try to use modinfo here, there is no guarantee it is valid!
803 $section = $DB->get_record('course_sections',
804 array('course' => $courseid, 'section' => $sectionnum), '*', IGNORE_MISSING);
805 if (!$section) {
806 // This function call requires modinfo.
807 course_create_sections_if_missing($courseorid, $sectionnum);
808 $section = $DB->get_record('course_sections',
809 array('course' => $courseid, 'section' => $sectionnum), '*', MUST_EXIST);
812 $modarray = explode(",", trim($section->sequence));
813 if (empty($section->sequence)) {
814 $newsequence = "$cmid";
815 } else if ($beforemod && ($key = array_keys($modarray, $beforemod))) {
816 $insertarray = array($cmid, $beforemod);
817 array_splice($modarray, $key[0], 1, $insertarray);
818 $newsequence = implode(",", $modarray);
819 } else {
820 $newsequence = "$section->sequence,$cmid";
822 $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id));
823 $DB->set_field('course_modules', 'section', $section->id, array('id' => $cmid));
824 if (is_object($courseorid)) {
825 rebuild_course_cache($courseorid->id, true);
826 } else {
827 rebuild_course_cache($courseorid, true);
829 return $section->id; // Return course_sections ID that was used.
833 * Change the group mode of a course module.
835 * Note: Do not forget to trigger the event \core\event\course_module_updated as it needs
836 * to be triggered manually, refer to {@link \core\event\course_module_updated::create_from_cm()}.
838 * @param int $id course module ID.
839 * @param int $groupmode the new groupmode value.
840 * @return bool True if the $groupmode was updated.
842 function set_coursemodule_groupmode($id, $groupmode) {
843 global $DB;
844 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST);
845 if ($cm->groupmode != $groupmode) {
846 $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id));
847 rebuild_course_cache($cm->course, true);
849 return ($cm->groupmode != $groupmode);
852 function set_coursemodule_idnumber($id, $idnumber) {
853 global $DB;
854 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST);
855 if ($cm->idnumber != $idnumber) {
856 $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id));
857 rebuild_course_cache($cm->course, true);
859 return ($cm->idnumber != $idnumber);
863 * Set the visibility of a module and inherent properties.
865 * Note: Do not forget to trigger the event \core\event\course_module_updated as it needs
866 * to be triggered manually, refer to {@link \core\event\course_module_updated::create_from_cm()}.
868 * From 2.4 the parameter $prevstateoverrides has been removed, the logic it triggered
869 * has been moved to {@link set_section_visible()} which was the only place from which
870 * the parameter was used.
872 * @param int $id of the module
873 * @param int $visible state of the module
874 * @param int $visibleoncoursepage state of the module on the course page
875 * @return bool false when the module was not found, true otherwise
877 function set_coursemodule_visible($id, $visible, $visibleoncoursepage = 1) {
878 global $DB, $CFG;
879 require_once($CFG->libdir.'/gradelib.php');
880 require_once($CFG->dirroot.'/calendar/lib.php');
882 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
883 return false;
886 // Create events and propagate visibility to associated grade items if the value has changed.
887 // Only do this if it's changed to avoid accidently overwriting manual showing/hiding of student grades.
888 if ($cm->visible == $visible && $cm->visibleoncoursepage == $visibleoncoursepage) {
889 return true;
892 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
893 return false;
895 if (($cm->visible != $visible) &&
896 ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename)))) {
897 foreach($events as $event) {
898 if ($visible) {
899 $event = new calendar_event($event);
900 $event->toggle_visibility(true);
901 } else {
902 $event = new calendar_event($event);
903 $event->toggle_visibility(false);
908 // Updating visible and visibleold to keep them in sync. Only changing a section visibility will
909 // affect visibleold to allow for an original visibility restore. See set_section_visible().
910 $cminfo = new stdClass();
911 $cminfo->id = $id;
912 $cminfo->visible = $visible;
913 $cminfo->visibleoncoursepage = $visibleoncoursepage;
914 $cminfo->visibleold = $visible;
915 $DB->update_record('course_modules', $cminfo);
917 // Hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there.
918 // Note that this must be done after updating the row in course_modules, in case
919 // the modules grade_item_update function needs to access $cm->visible.
920 if ($cm->visible != $visible &&
921 plugin_supports('mod', $modulename, FEATURE_CONTROLS_GRADE_VISIBILITY) &&
922 component_callback_exists('mod_' . $modulename, 'grade_item_update')) {
923 $instance = $DB->get_record($modulename, array('id' => $cm->instance), '*', MUST_EXIST);
924 component_callback('mod_' . $modulename, 'grade_item_update', array($instance));
925 } else if ($cm->visible != $visible) {
926 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
927 if ($grade_items) {
928 foreach ($grade_items as $grade_item) {
929 $grade_item->set_hidden(!$visible);
934 rebuild_course_cache($cm->course, true);
935 return true;
939 * Changes the course module name
941 * @param int $id course module id
942 * @param string $name new value for a name
943 * @return bool whether a change was made
945 function set_coursemodule_name($id, $name) {
946 global $CFG, $DB;
947 require_once($CFG->libdir . '/gradelib.php');
949 $cm = get_coursemodule_from_id('', $id, 0, false, MUST_EXIST);
951 $module = new \stdClass();
952 $module->id = $cm->instance;
954 // Escape strings as they would be by mform.
955 if (!empty($CFG->formatstringstriptags)) {
956 $module->name = clean_param($name, PARAM_TEXT);
957 } else {
958 $module->name = clean_param($name, PARAM_CLEANHTML);
960 if ($module->name === $cm->name || strval($module->name) === '') {
961 return false;
963 if (\core_text::strlen($module->name) > 255) {
964 throw new \moodle_exception('maximumchars', 'moodle', '', 255);
967 $module->timemodified = time();
968 $DB->update_record($cm->modname, $module);
969 $cm->name = $module->name;
970 \core\event\course_module_updated::create_from_cm($cm)->trigger();
971 rebuild_course_cache($cm->course, true);
973 // Attempt to update the grade item if relevant.
974 $grademodule = $DB->get_record($cm->modname, array('id' => $cm->instance));
975 $grademodule->cmidnumber = $cm->idnumber;
976 $grademodule->modname = $cm->modname;
977 grade_update_mod_grades($grademodule);
979 // Update calendar events with the new name.
980 course_module_update_calendar_events($cm->modname, $grademodule, $cm);
982 return true;
986 * This function will handle the whole deletion process of a module. This includes calling
987 * the modules delete_instance function, deleting files, events, grades, conditional data,
988 * the data in the course_module and course_sections table and adding a module deletion
989 * event to the DB.
991 * @param int $cmid the course module id
992 * @param bool $async whether or not to try to delete the module using an adhoc task. Async also depends on a plugin hook.
993 * @throws moodle_exception
994 * @since Moodle 2.5
996 function course_delete_module($cmid, $async = false) {
997 // Check the 'course_module_background_deletion_recommended' hook first.
998 // Only use asynchronous deletion if at least one plugin returns true and if async deletion has been requested.
999 // Both are checked because plugins should not be allowed to dictate the deletion behaviour, only support/decline it.
1000 // It's up to plugins to handle things like whether or not they are enabled.
1001 if ($async && $pluginsfunction = get_plugins_with_function('course_module_background_deletion_recommended')) {
1002 foreach ($pluginsfunction as $plugintype => $plugins) {
1003 foreach ($plugins as $pluginfunction) {
1004 if ($pluginfunction()) {
1005 return course_module_flag_for_async_deletion($cmid);
1011 global $CFG, $DB;
1013 require_once($CFG->libdir.'/gradelib.php');
1014 require_once($CFG->libdir.'/questionlib.php');
1015 require_once($CFG->dirroot.'/blog/lib.php');
1016 require_once($CFG->dirroot.'/calendar/lib.php');
1018 // Get the course module.
1019 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
1020 return true;
1023 // Get the module context.
1024 $modcontext = context_module::instance($cm->id);
1026 // Get the course module name.
1027 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
1029 // Get the file location of the delete_instance function for this module.
1030 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
1032 // Include the file required to call the delete_instance function for this module.
1033 if (file_exists($modlib)) {
1034 require_once($modlib);
1035 } else {
1036 throw new moodle_exception('cannotdeletemodulemissinglib', '', '', null,
1037 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
1040 $deleteinstancefunction = $modulename . '_delete_instance';
1042 // Ensure the delete_instance function exists for this module.
1043 if (!function_exists($deleteinstancefunction)) {
1044 throw new moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
1045 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
1048 // Allow plugins to use this course module before we completely delete it.
1049 if ($pluginsfunction = get_plugins_with_function('pre_course_module_delete')) {
1050 foreach ($pluginsfunction as $plugintype => $plugins) {
1051 foreach ($plugins as $pluginfunction) {
1052 $pluginfunction($cm);
1057 // Delete activity context questions and question categories.
1058 $showinfo = !defined('AJAX_SCRIPT') || AJAX_SCRIPT == '0';
1060 question_delete_activity($cm, $showinfo);
1062 // Call the delete_instance function, if it returns false throw an exception.
1063 if (!$deleteinstancefunction($cm->instance)) {
1064 throw new moodle_exception('cannotdeletemoduleinstance', '', '', null,
1065 "Cannot delete the module $modulename (instance).");
1068 // Remove all module files in case modules forget to do that.
1069 $fs = get_file_storage();
1070 $fs->delete_area_files($modcontext->id);
1072 // Delete events from calendar.
1073 if ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename))) {
1074 $coursecontext = context_course::instance($cm->course);
1075 foreach($events as $event) {
1076 $event->context = $coursecontext;
1077 $calendarevent = calendar_event::load($event);
1078 $calendarevent->delete();
1082 // Delete grade items, outcome items and grades attached to modules.
1083 if ($grade_items = grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $modulename,
1084 'iteminstance' => $cm->instance, 'courseid' => $cm->course))) {
1085 foreach ($grade_items as $grade_item) {
1086 $grade_item->delete('moddelete');
1090 // Delete associated blogs and blog tag instances.
1091 blog_remove_associations_for_module($modcontext->id);
1093 // Delete completion and availability data; it is better to do this even if the
1094 // features are not turned on, in case they were turned on previously (these will be
1095 // very quick on an empty table).
1096 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
1097 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
1098 'course' => $cm->course,
1099 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
1101 // Delete all tag instances associated with the instance of this module.
1102 core_tag_tag::delete_instances('mod_' . $modulename, null, $modcontext->id);
1103 core_tag_tag::remove_all_item_tags('core', 'course_modules', $cm->id);
1105 // Notify the competency subsystem.
1106 \core_competency\api::hook_course_module_deleted($cm);
1108 // Delete the context.
1109 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
1111 // Delete the module from the course_modules table.
1112 $DB->delete_records('course_modules', array('id' => $cm->id));
1114 // Delete module from that section.
1115 if (!delete_mod_from_section($cm->id, $cm->section)) {
1116 throw new moodle_exception('cannotdeletemodulefromsection', '', '', null,
1117 "Cannot delete the module $modulename (instance) from section.");
1120 // Trigger event for course module delete action.
1121 $event = \core\event\course_module_deleted::create(array(
1122 'courseid' => $cm->course,
1123 'context' => $modcontext,
1124 'objectid' => $cm->id,
1125 'other' => array(
1126 'modulename' => $modulename,
1127 'instanceid' => $cm->instance,
1130 $event->add_record_snapshot('course_modules', $cm);
1131 $event->trigger();
1132 rebuild_course_cache($cm->course, true);
1136 * Schedule a course module for deletion in the background using an adhoc task.
1138 * This method should not be called directly. Instead, please use course_delete_module($cmid, true), to denote async deletion.
1139 * The real deletion of the module is handled by the task, which calls 'course_delete_module($cmid)'.
1141 * @param int $cmid the course module id.
1142 * @return bool whether the module was successfully scheduled for deletion.
1143 * @throws \moodle_exception
1145 function course_module_flag_for_async_deletion($cmid) {
1146 global $CFG, $DB, $USER;
1147 require_once($CFG->libdir.'/gradelib.php');
1148 require_once($CFG->libdir.'/questionlib.php');
1149 require_once($CFG->dirroot.'/blog/lib.php');
1150 require_once($CFG->dirroot.'/calendar/lib.php');
1152 // Get the course module.
1153 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
1154 return true;
1157 // We need to be reasonably certain the deletion is going to succeed before we background the process.
1158 // Make the necessary delete_instance checks, etc. before proceeding further. Throw exceptions if required.
1160 // Get the course module name.
1161 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
1163 // Get the file location of the delete_instance function for this module.
1164 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
1166 // Include the file required to call the delete_instance function for this module.
1167 if (file_exists($modlib)) {
1168 require_once($modlib);
1169 } else {
1170 throw new \moodle_exception('cannotdeletemodulemissinglib', '', '', null,
1171 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
1174 $deleteinstancefunction = $modulename . '_delete_instance';
1176 // Ensure the delete_instance function exists for this module.
1177 if (!function_exists($deleteinstancefunction)) {
1178 throw new \moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
1179 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
1182 // We are going to defer the deletion as we can't be sure how long the module's pre_delete code will run for.
1183 $cm->deletioninprogress = '1';
1184 $DB->update_record('course_modules', $cm);
1186 // Create an adhoc task for the deletion of the course module. The task takes an array of course modules for removal.
1187 $removaltask = new \core_course\task\course_delete_modules();
1188 $removaltask->set_custom_data(array(
1189 'cms' => array($cm),
1190 'userid' => $USER->id,
1191 'realuserid' => \core\session\manager::get_realuser()->id
1194 // Queue the task for the next run.
1195 \core\task\manager::queue_adhoc_task($removaltask);
1197 // Reset the course cache to hide the module.
1198 rebuild_course_cache($cm->course, true);
1202 * Checks whether the given course has any course modules scheduled for adhoc deletion.
1204 * @param int $courseid the id of the course.
1205 * @param bool $onlygradable whether to check only gradable modules or all modules.
1206 * @return bool true if the course contains any modules pending deletion, false otherwise.
1208 function course_modules_pending_deletion(int $courseid, bool $onlygradable = false) : bool {
1209 if (empty($courseid)) {
1210 return false;
1213 if ($onlygradable) {
1214 // Fetch modules with grade items.
1215 if (!$coursegradeitems = grade_item::fetch_all(['itemtype' => 'mod', 'courseid' => $courseid])) {
1216 // Return early when there is none.
1217 return false;
1221 $modinfo = get_fast_modinfo($courseid);
1222 foreach ($modinfo->get_cms() as $module) {
1223 if ($module->deletioninprogress == '1') {
1224 if ($onlygradable) {
1225 // Check if the module being deleted is in the list of course modules with grade items.
1226 foreach ($coursegradeitems as $coursegradeitem) {
1227 if ($coursegradeitem->itemmodule == $module->modname && $coursegradeitem->iteminstance == $module->instance) {
1228 // The module being deleted is within the gradable modules.
1229 return true;
1232 } else {
1233 return true;
1237 return false;
1241 * Checks whether the course module, as defined by modulename and instanceid, is scheduled for deletion within the given course.
1243 * @param int $courseid the course id.
1244 * @param string $modulename the module name. E.g. 'assign', 'book', etc.
1245 * @param int $instanceid the module instance id.
1246 * @return bool true if the course module is pending deletion, false otherwise.
1248 function course_module_instance_pending_deletion($courseid, $modulename, $instanceid) {
1249 if (empty($courseid) || empty($modulename) || empty($instanceid)) {
1250 return false;
1252 $modinfo = get_fast_modinfo($courseid);
1253 $instances = $modinfo->get_instances_of($modulename);
1254 return isset($instances[$instanceid]) && $instances[$instanceid]->deletioninprogress;
1257 function delete_mod_from_section($modid, $sectionid) {
1258 global $DB;
1260 if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
1262 $modarray = explode(",", $section->sequence);
1264 if ($key = array_keys ($modarray, $modid)) {
1265 array_splice($modarray, $key[0], 1);
1266 $newsequence = implode(",", $modarray);
1267 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
1268 rebuild_course_cache($section->course, true);
1269 return true;
1270 } else {
1271 return false;
1275 return false;
1279 * This function updates the calendar events from the information stored in the module table and the course
1280 * module table.
1282 * @param string $modulename Module name
1283 * @param stdClass $instance Module object. Either the $instance or the $cm must be supplied.
1284 * @param stdClass $cm Course module object. Either the $instance or the $cm must be supplied.
1285 * @return bool Returns true if calendar events are updated.
1286 * @since Moodle 3.3.4
1288 function course_module_update_calendar_events($modulename, $instance = null, $cm = null) {
1289 global $DB;
1291 if (isset($instance) || isset($cm)) {
1293 if (!isset($instance)) {
1294 $instance = $DB->get_record($modulename, array('id' => $cm->instance), '*', MUST_EXIST);
1296 if (!isset($cm)) {
1297 $cm = get_coursemodule_from_instance($modulename, $instance->id, $instance->course);
1299 if (!empty($cm)) {
1300 course_module_calendar_event_update_process($instance, $cm);
1302 return true;
1304 return false;
1308 * Update all instances through out the site or in a course.
1310 * @param string $modulename Module type to update.
1311 * @param integer $courseid Course id to update events. 0 for the whole site.
1312 * @return bool Returns True if the update was successful.
1313 * @since Moodle 3.3.4
1315 function course_module_bulk_update_calendar_events($modulename, $courseid = 0) {
1316 global $DB;
1318 $instances = null;
1319 if ($courseid) {
1320 if (!$instances = $DB->get_records($modulename, array('course' => $courseid))) {
1321 return false;
1323 } else {
1324 if (!$instances = $DB->get_records($modulename)) {
1325 return false;
1329 foreach ($instances as $instance) {
1330 if ($cm = get_coursemodule_from_instance($modulename, $instance->id, $instance->course)) {
1331 course_module_calendar_event_update_process($instance, $cm);
1334 return true;
1338 * Calendar events for a module instance are updated.
1340 * @param stdClass $instance Module instance object.
1341 * @param stdClass $cm Course Module object.
1342 * @since Moodle 3.3.4
1344 function course_module_calendar_event_update_process($instance, $cm) {
1345 // We need to call *_refresh_events() first because some modules delete 'old' events at the end of the code which
1346 // will remove the completion events.
1347 $refresheventsfunction = $cm->modname . '_refresh_events';
1348 if (function_exists($refresheventsfunction)) {
1349 call_user_func($refresheventsfunction, $cm->course, $instance, $cm);
1351 $completionexpected = (!empty($cm->completionexpected)) ? $cm->completionexpected : null;
1352 \core_completion\api::update_completion_date_event($cm->id, $cm->modname, $instance, $completionexpected);
1356 * Moves a section within a course, from a position to another.
1357 * Be very careful: $section and $destination refer to section number,
1358 * not id!.
1360 * @param object $course
1361 * @param int $section Section number (not id!!!)
1362 * @param int $destination
1363 * @param bool $ignorenumsections
1364 * @return boolean Result
1366 function move_section_to($course, $section, $destination, $ignorenumsections = false) {
1367 /// Moves a whole course section up and down within the course
1368 global $USER, $DB;
1370 if (!$destination && $destination != 0) {
1371 return true;
1374 // compartibility with course formats using field 'numsections'
1375 $courseformatoptions = course_get_format($course)->get_format_options();
1376 if ((!$ignorenumsections && array_key_exists('numsections', $courseformatoptions) &&
1377 ($destination > $courseformatoptions['numsections'])) || ($destination < 1)) {
1378 return false;
1381 // Get all sections for this course and re-order them (2 of them should now share the same section number)
1382 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
1383 'section ASC, id ASC', 'id, section')) {
1384 return false;
1387 $movedsections = reorder_sections($sections, $section, $destination);
1389 // Update all sections. Do this in 2 steps to avoid breaking database
1390 // uniqueness constraint
1391 $transaction = $DB->start_delegated_transaction();
1392 foreach ($movedsections as $id => $position) {
1393 if ($sections[$id] !== $position) {
1394 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
1397 foreach ($movedsections as $id => $position) {
1398 if ($sections[$id] !== $position) {
1399 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
1403 // If we move the highlighted section itself, then just highlight the destination.
1404 // Adjust the higlighted section location if we move something over it either direction.
1405 if ($section == $course->marker) {
1406 course_set_marker($course->id, $destination);
1407 } elseif ($section > $course->marker && $course->marker >= $destination) {
1408 course_set_marker($course->id, $course->marker+1);
1409 } elseif ($section < $course->marker && $course->marker <= $destination) {
1410 course_set_marker($course->id, $course->marker-1);
1413 $transaction->allow_commit();
1414 rebuild_course_cache($course->id, true);
1415 return true;
1419 * This method will delete a course section and may delete all modules inside it.
1421 * No permissions are checked here, use {@link course_can_delete_section()} to
1422 * check if section can actually be deleted.
1424 * @param int|stdClass $course
1425 * @param int|stdClass|section_info $section
1426 * @param bool $forcedeleteifnotempty if set to false section will not be deleted if it has modules in it.
1427 * @param bool $async whether or not to try to delete the section using an adhoc task. Async also depends on a plugin hook.
1428 * @return bool whether section was deleted
1430 function course_delete_section($course, $section, $forcedeleteifnotempty = true, $async = false) {
1431 global $DB;
1433 // Prepare variables.
1434 $courseid = (is_object($course)) ? $course->id : (int)$course;
1435 $sectionnum = (is_object($section)) ? $section->section : (int)$section;
1436 $section = $DB->get_record('course_sections', array('course' => $courseid, 'section' => $sectionnum));
1437 if (!$section) {
1438 // No section exists, can't proceed.
1439 return false;
1442 // Check the 'course_module_background_deletion_recommended' hook first.
1443 // Only use asynchronous deletion if at least one plugin returns true and if async deletion has been requested.
1444 // Both are checked because plugins should not be allowed to dictate the deletion behaviour, only support/decline it.
1445 // It's up to plugins to handle things like whether or not they are enabled.
1446 if ($async && $pluginsfunction = get_plugins_with_function('course_module_background_deletion_recommended')) {
1447 foreach ($pluginsfunction as $plugintype => $plugins) {
1448 foreach ($plugins as $pluginfunction) {
1449 if ($pluginfunction()) {
1450 return course_delete_section_async($section, $forcedeleteifnotempty);
1456 $format = course_get_format($course);
1457 $sectionname = $format->get_section_name($section);
1459 // Delete section.
1460 $result = $format->delete_section($section, $forcedeleteifnotempty);
1462 // Trigger an event for course section deletion.
1463 if ($result) {
1464 $context = context_course::instance($courseid);
1465 $event = \core\event\course_section_deleted::create(
1466 array(
1467 'objectid' => $section->id,
1468 'courseid' => $courseid,
1469 'context' => $context,
1470 'other' => array(
1471 'sectionnum' => $section->section,
1472 'sectionname' => $sectionname,
1476 $event->add_record_snapshot('course_sections', $section);
1477 $event->trigger();
1479 return $result;
1483 * Course section deletion, using an adhoc task for deletion of the modules it contains.
1484 * 1. Schedule all modules within the section for adhoc removal.
1485 * 2. Move all modules to course section 0.
1486 * 3. Delete the resulting empty section.
1488 * @param \stdClass $section the section to schedule for deletion.
1489 * @param bool $forcedeleteifnotempty whether to force section deletion if it contains modules.
1490 * @return bool true if the section was scheduled for deletion, false otherwise.
1492 function course_delete_section_async($section, $forcedeleteifnotempty = true) {
1493 global $DB, $USER;
1495 // Objects only, and only valid ones.
1496 if (!is_object($section) || empty($section->id)) {
1497 return false;
1500 // Does the object currently exist in the DB for removal (check for stale objects).
1501 $section = $DB->get_record('course_sections', array('id' => $section->id));
1502 if (!$section || !$section->section) {
1503 // No section exists, or the section is 0. Can't proceed.
1504 return false;
1507 // Check whether the section can be removed.
1508 if (!$forcedeleteifnotempty && (!empty($section->sequence) || !empty($section->summary))) {
1509 return false;
1512 $format = course_get_format($section->course);
1513 $sectionname = $format->get_section_name($section);
1515 // Flag those modules having no existing deletion flag. Some modules may have been scheduled for deletion manually, and we don't
1516 // want to create additional adhoc deletion tasks for these. Moving them to section 0 will suffice.
1517 $affectedmods = $DB->get_records_select('course_modules', 'course = ? AND section = ? AND deletioninprogress <> ?',
1518 [$section->course, $section->id, 1], '', 'id');
1519 $DB->set_field('course_modules', 'deletioninprogress', '1', ['course' => $section->course, 'section' => $section->id]);
1521 // Move all modules to section 0.
1522 $modules = $DB->get_records('course_modules', ['section' => $section->id], '');
1523 $sectionzero = $DB->get_record('course_sections', ['course' => $section->course, 'section' => '0']);
1524 foreach ($modules as $mod) {
1525 moveto_module($mod, $sectionzero);
1528 // Create and queue an adhoc task for the deletion of the modules.
1529 $removaltask = new \core_course\task\course_delete_modules();
1530 $data = array(
1531 'cms' => $affectedmods,
1532 'userid' => $USER->id,
1533 'realuserid' => \core\session\manager::get_realuser()->id
1535 $removaltask->set_custom_data($data);
1536 \core\task\manager::queue_adhoc_task($removaltask);
1538 // Delete the now empty section, passing in only the section number, which forces the function to fetch a new object.
1539 // The refresh is needed because the section->sequence is now stale.
1540 $result = $format->delete_section($section->section, $forcedeleteifnotempty);
1542 // Trigger an event for course section deletion.
1543 if ($result) {
1544 $context = \context_course::instance($section->course);
1545 $event = \core\event\course_section_deleted::create(
1546 array(
1547 'objectid' => $section->id,
1548 'courseid' => $section->course,
1549 'context' => $context,
1550 'other' => array(
1551 'sectionnum' => $section->section,
1552 'sectionname' => $sectionname,
1556 $event->add_record_snapshot('course_sections', $section);
1557 $event->trigger();
1559 rebuild_course_cache($section->course, true);
1561 return $result;
1565 * Updates the course section
1567 * This function does not check permissions or clean values - this has to be done prior to calling it.
1569 * @param int|stdClass $course
1570 * @param stdClass $section record from course_sections table - it will be updated with the new values
1571 * @param array|stdClass $data
1573 function course_update_section($course, $section, $data) {
1574 global $DB;
1576 $courseid = (is_object($course)) ? $course->id : (int)$course;
1578 // Some fields can not be updated using this method.
1579 $data = array_diff_key((array)$data, array('id', 'course', 'section', 'sequence'));
1580 $changevisibility = (array_key_exists('visible', $data) && (bool)$data['visible'] != (bool)$section->visible);
1581 if (array_key_exists('name', $data) && \core_text::strlen($data['name']) > 255) {
1582 throw new moodle_exception('maximumchars', 'moodle', '', 255);
1585 // Update record in the DB and course format options.
1586 $data['id'] = $section->id;
1587 $data['timemodified'] = time();
1588 $DB->update_record('course_sections', $data);
1589 rebuild_course_cache($courseid, true);
1590 course_get_format($courseid)->update_section_format_options($data);
1592 // Update fields of the $section object.
1593 foreach ($data as $key => $value) {
1594 if (property_exists($section, $key)) {
1595 $section->$key = $value;
1599 // Trigger an event for course section update.
1600 $event = \core\event\course_section_updated::create(
1601 array(
1602 'objectid' => $section->id,
1603 'courseid' => $courseid,
1604 'context' => context_course::instance($courseid),
1605 'other' => array('sectionnum' => $section->section)
1608 $event->trigger();
1610 // If section visibility was changed, hide the modules in this section too.
1611 if ($changevisibility && !empty($section->sequence)) {
1612 $modules = explode(',', $section->sequence);
1613 foreach ($modules as $moduleid) {
1614 if ($cm = get_coursemodule_from_id(null, $moduleid, $courseid)) {
1615 if ($data['visible']) {
1616 // As we unhide the section, we use the previously saved visibility stored in visibleold.
1617 set_coursemodule_visible($moduleid, $cm->visibleold, $cm->visibleoncoursepage);
1618 } else {
1619 // We hide the section, so we hide the module but we store the original state in visibleold.
1620 set_coursemodule_visible($moduleid, 0, $cm->visibleoncoursepage);
1621 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id' => $moduleid));
1623 \core\event\course_module_updated::create_from_cm($cm)->trigger();
1630 * Checks if the current user can delete a section (if course format allows it and user has proper permissions).
1632 * @param int|stdClass $course
1633 * @param int|stdClass|section_info $section
1634 * @return bool
1636 function course_can_delete_section($course, $section) {
1637 if (is_object($section)) {
1638 $section = $section->section;
1640 if (!$section) {
1641 // Not possible to delete 0-section.
1642 return false;
1644 // Course format should allow to delete sections.
1645 if (!course_get_format($course)->can_delete_section($section)) {
1646 return false;
1648 // Make sure user has capability to update course and move sections.
1649 $context = context_course::instance(is_object($course) ? $course->id : $course);
1650 if (!has_all_capabilities(array('moodle/course:movesections', 'moodle/course:update'), $context)) {
1651 return false;
1653 // Make sure user has capability to delete each activity in this section.
1654 $modinfo = get_fast_modinfo($course);
1655 if (!empty($modinfo->sections[$section])) {
1656 foreach ($modinfo->sections[$section] as $cmid) {
1657 if (!has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
1658 return false;
1662 return true;
1666 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
1667 * an original position number and a target position number, rebuilds the array so that the
1668 * move is made without any duplication of section positions.
1669 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
1670 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
1672 * @param array $sections
1673 * @param int $origin_position
1674 * @param int $target_position
1675 * @return array
1677 function reorder_sections($sections, $origin_position, $target_position) {
1678 if (!is_array($sections)) {
1679 return false;
1682 // We can't move section position 0
1683 if ($origin_position < 1) {
1684 echo "We can't move section position 0";
1685 return false;
1688 // Locate origin section in sections array
1689 if (!$origin_key = array_search($origin_position, $sections)) {
1690 echo "searched position not in sections array";
1691 return false; // searched position not in sections array
1694 // Extract origin section
1695 $origin_section = $sections[$origin_key];
1696 unset($sections[$origin_key]);
1698 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
1699 $found = false;
1700 $append_array = array();
1701 foreach ($sections as $id => $position) {
1702 if ($found) {
1703 $append_array[$id] = $position;
1704 unset($sections[$id]);
1706 if ($position == $target_position) {
1707 if ($target_position < $origin_position) {
1708 $append_array[$id] = $position;
1709 unset($sections[$id]);
1711 $found = true;
1715 // Append moved section
1716 $sections[$origin_key] = $origin_section;
1718 // Append rest of array (if applicable)
1719 if (!empty($append_array)) {
1720 foreach ($append_array as $id => $position) {
1721 $sections[$id] = $position;
1725 // Renumber positions
1726 $position = 0;
1727 foreach ($sections as $id => $p) {
1728 $sections[$id] = $position;
1729 $position++;
1732 return $sections;
1737 * Move the module object $mod to the specified $section
1738 * If $beforemod exists then that is the module
1739 * before which $modid should be inserted
1741 * @param stdClass|cm_info $mod
1742 * @param stdClass|section_info $section
1743 * @param int|stdClass $beforemod id or object with field id corresponding to the module
1744 * before which the module needs to be included. Null for inserting in the
1745 * end of the section
1746 * @return int new value for module visibility (0 or 1)
1748 function moveto_module($mod, $section, $beforemod=NULL) {
1749 global $OUTPUT, $DB;
1751 // Current module visibility state - return value of this function.
1752 $modvisible = $mod->visible;
1754 // Remove original module from original section.
1755 if (! delete_mod_from_section($mod->id, $mod->section)) {
1756 echo $OUTPUT->notification("Could not delete module from existing section");
1759 // If moving to a hidden section then hide module.
1760 if ($mod->section != $section->id) {
1761 if (!$section->visible && $mod->visible) {
1762 // Module was visible but must become hidden after moving to hidden section.
1763 $modvisible = 0;
1764 set_coursemodule_visible($mod->id, 0);
1765 // Set visibleold to 1 so module will be visible when section is made visible.
1766 $DB->set_field('course_modules', 'visibleold', 1, array('id' => $mod->id));
1768 if ($section->visible && !$mod->visible) {
1769 // Hidden module was moved to the visible section, restore the module visibility from visibleold.
1770 set_coursemodule_visible($mod->id, $mod->visibleold);
1771 $modvisible = $mod->visibleold;
1775 // Add the module into the new section.
1776 course_add_cm_to_section($section->course, $mod->id, $section->section, $beforemod);
1777 return $modvisible;
1781 * Returns the list of all editing actions that current user can perform on the module
1783 * @param cm_info $mod The module to produce editing buttons for
1784 * @param int $indent The current indenting (default -1 means no move left-right actions)
1785 * @param int $sr The section to link back to (used for creating the links)
1786 * @return array array of action_link or pix_icon objects
1788 function course_get_cm_edit_actions(cm_info $mod, $indent = -1, $sr = null) {
1789 global $COURSE, $SITE, $CFG;
1791 static $str;
1793 $coursecontext = context_course::instance($mod->course);
1794 $modcontext = context_module::instance($mod->id);
1795 $courseformat = course_get_format($mod->get_course());
1797 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
1798 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
1800 // No permission to edit anything.
1801 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
1802 return array();
1805 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
1807 if (!isset($str)) {
1808 $str = get_strings(array('delete', 'move', 'moveright', 'moveleft',
1809 'editsettings', 'duplicate', 'modhide', 'makeavailable', 'makeunavailable', 'modshow'), 'moodle');
1810 $str->assign = get_string('assignroles', 'role');
1811 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
1812 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
1813 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
1816 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
1818 if ($sr !== null) {
1819 $baseurl->param('sr', $sr);
1821 $actions = array();
1823 // Update.
1824 if ($hasmanageactivities) {
1825 $actions['update'] = new action_menu_link_secondary(
1826 new moodle_url($baseurl, array('update' => $mod->id)),
1827 new pix_icon('t/edit', '', 'moodle', array('class' => 'iconsmall')),
1828 $str->editsettings,
1829 array('class' => 'editing_update', 'data-action' => 'update')
1833 // Indent.
1834 if ($hasmanageactivities && $indent >= 0) {
1835 $indentlimits = new stdClass();
1836 $indentlimits->min = 0;
1837 $indentlimits->max = 16;
1838 if (right_to_left()) { // Exchange arrows on RTL
1839 $rightarrow = 't/left';
1840 $leftarrow = 't/right';
1841 } else {
1842 $rightarrow = 't/right';
1843 $leftarrow = 't/left';
1846 if ($indent >= $indentlimits->max) {
1847 $enabledclass = 'hidden';
1848 } else {
1849 $enabledclass = '';
1851 $actions['moveright'] = new action_menu_link_secondary(
1852 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
1853 new pix_icon($rightarrow, '', 'moodle', array('class' => 'iconsmall')),
1854 $str->moveright,
1855 array('class' => 'editing_moveright ' . $enabledclass, 'data-action' => 'moveright',
1856 'data-keepopen' => true, 'data-sectionreturn' => $sr)
1859 if ($indent <= $indentlimits->min) {
1860 $enabledclass = 'hidden';
1861 } else {
1862 $enabledclass = '';
1864 $actions['moveleft'] = new action_menu_link_secondary(
1865 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
1866 new pix_icon($leftarrow, '', 'moodle', array('class' => 'iconsmall')),
1867 $str->moveleft,
1868 array('class' => 'editing_moveleft ' . $enabledclass, 'data-action' => 'moveleft',
1869 'data-keepopen' => true, 'data-sectionreturn' => $sr)
1874 // Hide/Show/Available/Unavailable.
1875 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
1876 $allowstealth = !empty($CFG->allowstealth) && $courseformat->allow_stealth_module_visibility($mod, $mod->get_section_info());
1878 $sectionvisible = $mod->get_section_info()->visible;
1879 // The module on the course page may be in one of the following states:
1880 // - Available and displayed on the course page ($displayedoncoursepage);
1881 // - Not available and not displayed on the course page ($unavailable);
1882 // - Available but not displayed on the course page ($stealth) - this can also be a visible activity in a hidden section.
1883 $displayedoncoursepage = $mod->visible && $mod->visibleoncoursepage && $sectionvisible;
1884 $unavailable = !$mod->visible;
1885 $stealth = $mod->visible && (!$mod->visibleoncoursepage || !$sectionvisible);
1886 if ($displayedoncoursepage) {
1887 $actions['hide'] = new action_menu_link_secondary(
1888 new moodle_url($baseurl, array('hide' => $mod->id)),
1889 new pix_icon('t/hide', '', 'moodle', array('class' => 'iconsmall')),
1890 $str->modhide,
1891 array('class' => 'editing_hide', 'data-action' => 'hide')
1893 } else if (!$displayedoncoursepage && $sectionvisible) {
1894 // Offer to "show" only if the section is visible.
1895 $actions['show'] = new action_menu_link_secondary(
1896 new moodle_url($baseurl, array('show' => $mod->id)),
1897 new pix_icon('t/show', '', 'moodle', array('class' => 'iconsmall')),
1898 $str->modshow,
1899 array('class' => 'editing_show', 'data-action' => 'show')
1903 if ($stealth) {
1904 // When making the "stealth" module unavailable we perform the same action as hiding the visible module.
1905 $actions['hide'] = new action_menu_link_secondary(
1906 new moodle_url($baseurl, array('hide' => $mod->id)),
1907 new pix_icon('t/unblock', '', 'moodle', array('class' => 'iconsmall')),
1908 $str->makeunavailable,
1909 array('class' => 'editing_makeunavailable', 'data-action' => 'hide', 'data-sectionreturn' => $sr)
1911 } else if ($unavailable && (!$sectionvisible || $allowstealth) && $mod->has_view()) {
1912 // Allow to make visually hidden module available in gradebook and other reports by making it a "stealth" module.
1913 // When the section is hidden it is an equivalent of "showing" the module.
1914 // Activities without the link (i.e. labels) can not be made available but hidden on course page.
1915 $action = $sectionvisible ? 'stealth' : 'show';
1916 $actions[$action] = new action_menu_link_secondary(
1917 new moodle_url($baseurl, array($action => $mod->id)),
1918 new pix_icon('t/block', '', 'moodle', array('class' => 'iconsmall')),
1919 $str->makeavailable,
1920 array('class' => 'editing_makeavailable', 'data-action' => $action, 'data-sectionreturn' => $sr)
1925 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
1926 if (has_all_capabilities($dupecaps, $coursecontext) &&
1927 plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2) &&
1928 course_allowed_module($mod->get_course(), $mod->modname)) {
1929 $actions['duplicate'] = new action_menu_link_secondary(
1930 new moodle_url($baseurl, array('duplicate' => $mod->id)),
1931 new pix_icon('t/copy', '', 'moodle', array('class' => 'iconsmall')),
1932 $str->duplicate,
1933 array('class' => 'editing_duplicate', 'data-action' => 'duplicate', 'data-sectionreturn' => $sr)
1937 // Groupmode.
1938 if ($hasmanageactivities && !$mod->coursegroupmodeforce) {
1939 if (plugin_supports('mod', $mod->modname, FEATURE_GROUPS, false)) {
1940 if ($mod->effectivegroupmode == SEPARATEGROUPS) {
1941 $nextgroupmode = VISIBLEGROUPS;
1942 $grouptitle = $str->groupsseparate;
1943 $actionname = 'groupsseparate';
1944 $nextactionname = 'groupsvisible';
1945 $groupimage = 'i/groups';
1946 } else if ($mod->effectivegroupmode == VISIBLEGROUPS) {
1947 $nextgroupmode = NOGROUPS;
1948 $grouptitle = $str->groupsvisible;
1949 $actionname = 'groupsvisible';
1950 $nextactionname = 'groupsnone';
1951 $groupimage = 'i/groupv';
1952 } else {
1953 $nextgroupmode = SEPARATEGROUPS;
1954 $grouptitle = $str->groupsnone;
1955 $actionname = 'groupsnone';
1956 $nextactionname = 'groupsseparate';
1957 $groupimage = 'i/groupn';
1960 $actions[$actionname] = new action_menu_link_primary(
1961 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $nextgroupmode)),
1962 new pix_icon($groupimage, '', 'moodle', array('class' => 'iconsmall')),
1963 $grouptitle,
1964 array('class' => 'editing_'. $actionname, 'data-action' => $nextactionname,
1965 'aria-live' => 'assertive', 'data-sectionreturn' => $sr)
1967 } else {
1968 $actions['nogroupsupport'] = new action_menu_filler();
1972 // Assign.
1973 if (has_capability('moodle/role:assign', $modcontext)){
1974 $actions['assign'] = new action_menu_link_secondary(
1975 new moodle_url('/admin/roles/assign.php', array('contextid' => $modcontext->id)),
1976 new pix_icon('t/assignroles', '', 'moodle', array('class' => 'iconsmall')),
1977 $str->assign,
1978 array('class' => 'editing_assign', 'data-action' => 'assignroles', 'data-sectionreturn' => $sr)
1982 // Delete.
1983 if ($hasmanageactivities) {
1984 $actions['delete'] = new action_menu_link_secondary(
1985 new moodle_url($baseurl, array('delete' => $mod->id)),
1986 new pix_icon('t/delete', '', 'moodle', array('class' => 'iconsmall')),
1987 $str->delete,
1988 array('class' => 'editing_delete', 'data-action' => 'delete', 'data-sectionreturn' => $sr)
1992 return $actions;
1996 * Returns the move action.
1998 * @param cm_info $mod The module to produce a move button for
1999 * @param int $sr The section to link back to (used for creating the links)
2000 * @return The markup for the move action, or an empty string if not available.
2002 function course_get_cm_move(cm_info $mod, $sr = null) {
2003 global $OUTPUT;
2005 static $str;
2006 static $baseurl;
2008 $modcontext = context_module::instance($mod->id);
2009 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
2011 if (!isset($str)) {
2012 $str = get_strings(array('move'));
2015 if (!isset($baseurl)) {
2016 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
2018 if ($sr !== null) {
2019 $baseurl->param('sr', $sr);
2023 if ($hasmanageactivities) {
2024 $pixicon = 'i/dragdrop';
2026 if (!course_ajax_enabled($mod->get_course())) {
2027 // Override for course frontpage until we get drag/drop working there.
2028 $pixicon = 't/move';
2031 return html_writer::link(
2032 new moodle_url($baseurl, array('copy' => $mod->id)),
2033 $OUTPUT->pix_icon($pixicon, $str->move, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2034 array('class' => 'editing_move', 'data-action' => 'move', 'data-sectionreturn' => $sr)
2037 return '';
2041 * given a course object with shortname & fullname, this function will
2042 * truncate the the number of chars allowed and add ... if it was too long
2044 function course_format_name ($course,$max=100) {
2046 $context = context_course::instance($course->id);
2047 $shortname = format_string($course->shortname, true, array('context' => $context));
2048 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
2049 $str = $shortname.': '. $fullname;
2050 if (core_text::strlen($str) <= $max) {
2051 return $str;
2053 else {
2054 return core_text::substr($str,0,$max-3).'...';
2059 * Is the user allowed to add this type of module to this course?
2060 * @param object $course the course settings. Only $course->id is used.
2061 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
2062 * @param \stdClass $user the user to check, defaults to the global user if not provided.
2063 * @return bool whether the current user is allowed to add this type of module to this course.
2065 function course_allowed_module($course, $modname, \stdClass $user = null) {
2066 global $USER;
2067 $user = $user ?? $USER;
2068 if (is_numeric($modname)) {
2069 throw new coding_exception('Function course_allowed_module no longer
2070 supports numeric module ids. Please update your code to pass the module name.');
2073 $capability = 'mod/' . $modname . ':addinstance';
2074 if (!get_capability_info($capability)) {
2075 // Debug warning that the capability does not exist, but no more than once per page.
2076 static $warned = array();
2077 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
2078 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
2079 debugging('The module ' . $modname . ' does not define the standard capability ' .
2080 $capability , DEBUG_DEVELOPER);
2081 $warned[$modname] = 1;
2084 // If the capability does not exist, the module can always be added.
2085 return true;
2088 $coursecontext = context_course::instance($course->id);
2089 return has_capability($capability, $coursecontext, $user);
2093 * Efficiently moves many courses around while maintaining
2094 * sortorder in order.
2096 * @param array $courseids is an array of course ids
2097 * @param int $categoryid
2098 * @return bool success
2100 function move_courses($courseids, $categoryid) {
2101 global $DB;
2103 if (empty($courseids)) {
2104 // Nothing to do.
2105 return false;
2108 if (!$category = $DB->get_record('course_categories', array('id' => $categoryid))) {
2109 return false;
2112 $courseids = array_reverse($courseids);
2113 $newparent = context_coursecat::instance($category->id);
2114 $i = 1;
2116 list($where, $params) = $DB->get_in_or_equal($courseids);
2117 $dbcourses = $DB->get_records_select('course', 'id ' . $where, $params, '', 'id, category, shortname, fullname');
2118 foreach ($dbcourses as $dbcourse) {
2119 $course = new stdClass();
2120 $course->id = $dbcourse->id;
2121 $course->timemodified = time();
2122 $course->category = $category->id;
2123 $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
2124 if ($category->visible == 0) {
2125 // Hide the course when moving into hidden category, do not update the visibleold flag - we want to get
2126 // to previous state if somebody unhides the category.
2127 $course->visible = 0;
2130 $DB->update_record('course', $course);
2132 // Update context, so it can be passed to event.
2133 $context = context_course::instance($course->id);
2134 $context->update_moved($newparent);
2136 // Trigger a course updated event.
2137 $event = \core\event\course_updated::create(array(
2138 'objectid' => $course->id,
2139 'context' => context_course::instance($course->id),
2140 'other' => array('shortname' => $dbcourse->shortname,
2141 'fullname' => $dbcourse->fullname,
2142 'updatedfields' => array('category' => $category->id))
2144 $event->set_legacy_logdata(array($course->id, 'course', 'move', 'edit.php?id=' . $course->id, $course->id));
2145 $event->trigger();
2147 fix_course_sortorder();
2148 cache_helper::purge_by_event('changesincourse');
2150 return true;
2154 * Returns the display name of the given section that the course prefers
2156 * Implementation of this function is provided by course format
2157 * @see format_base::get_section_name()
2159 * @param int|stdClass $courseorid The course to get the section name for (object or just course id)
2160 * @param int|stdClass $section Section object from database or just field course_sections.section
2161 * @return string Display name that the course format prefers, e.g. "Week 2"
2163 function get_section_name($courseorid, $section) {
2164 return course_get_format($courseorid)->get_section_name($section);
2168 * Tells if current course format uses sections
2170 * @param string $format Course format ID e.g. 'weeks' $course->format
2171 * @return bool
2173 function course_format_uses_sections($format) {
2174 $course = new stdClass();
2175 $course->format = $format;
2176 return course_get_format($course)->uses_sections();
2180 * Returns the information about the ajax support in the given source format
2182 * The returned object's property (boolean)capable indicates that
2183 * the course format supports Moodle course ajax features.
2185 * @param string $format
2186 * @return stdClass
2188 function course_format_ajax_support($format) {
2189 $course = new stdClass();
2190 $course->format = $format;
2191 return course_get_format($course)->supports_ajax();
2195 * Can the current user delete this course?
2196 * Course creators have exception,
2197 * 1 day after the creation they can sill delete the course.
2198 * @param int $courseid
2199 * @return boolean
2201 function can_delete_course($courseid) {
2202 global $USER;
2204 $context = context_course::instance($courseid);
2206 if (has_capability('moodle/course:delete', $context)) {
2207 return true;
2210 // hack: now try to find out if creator created this course recently (1 day)
2211 if (!has_capability('moodle/course:create', $context)) {
2212 return false;
2215 $since = time() - 60*60*24;
2216 $course = get_course($courseid);
2218 if ($course->timecreated < $since) {
2219 return false; // Return if the course was not created in last 24 hours.
2222 $logmanger = get_log_manager();
2223 $readers = $logmanger->get_readers('\core\log\sql_reader');
2224 $reader = reset($readers);
2226 if (empty($reader)) {
2227 return false; // No log reader found.
2230 // A proper reader.
2231 $select = "userid = :userid AND courseid = :courseid AND eventname = :eventname AND timecreated > :since";
2232 $params = array('userid' => $USER->id, 'since' => $since, 'courseid' => $course->id, 'eventname' => '\core\event\course_created');
2234 return (bool)$reader->get_events_select_count($select, $params);
2238 * Save the Your name for 'Some role' strings.
2240 * @param integer $courseid the id of this course.
2241 * @param array $data the data that came from the course settings form.
2243 function save_local_role_names($courseid, $data) {
2244 global $DB;
2245 $context = context_course::instance($courseid);
2247 foreach ($data as $fieldname => $value) {
2248 if (strpos($fieldname, 'role_') !== 0) {
2249 continue;
2251 list($ignored, $roleid) = explode('_', $fieldname);
2253 // make up our mind whether we want to delete, update or insert
2254 if (!$value) {
2255 $DB->delete_records('role_names', array('contextid' => $context->id, 'roleid' => $roleid));
2257 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id, 'roleid' => $roleid))) {
2258 $rolename->name = $value;
2259 $DB->update_record('role_names', $rolename);
2261 } else {
2262 $rolename = new stdClass;
2263 $rolename->contextid = $context->id;
2264 $rolename->roleid = $roleid;
2265 $rolename->name = $value;
2266 $DB->insert_record('role_names', $rolename);
2268 // This will ensure the course contacts cache is purged..
2269 core_course_category::role_assignment_changed($roleid, $context);
2274 * Returns options to use in course overviewfiles filemanager
2276 * @param null|stdClass|core_course_list_element|int $course either object that has 'id' property or just the course id;
2277 * may be empty if course does not exist yet (course create form)
2278 * @return array|null array of options such as maxfiles, maxbytes, accepted_types, etc.
2279 * or null if overviewfiles are disabled
2281 function course_overviewfiles_options($course) {
2282 global $CFG;
2283 if (empty($CFG->courseoverviewfileslimit)) {
2284 return null;
2286 $accepted_types = preg_split('/\s*,\s*/', trim($CFG->courseoverviewfilesext), -1, PREG_SPLIT_NO_EMPTY);
2287 if (in_array('*', $accepted_types) || empty($accepted_types)) {
2288 $accepted_types = '*';
2289 } else {
2290 // Since config for $CFG->courseoverviewfilesext is a text box, human factor must be considered.
2291 // Make sure extensions are prefixed with dot unless they are valid typegroups
2292 foreach ($accepted_types as $i => $type) {
2293 if (substr($type, 0, 1) !== '.') {
2294 require_once($CFG->libdir. '/filelib.php');
2295 if (!count(file_get_typegroup('extension', $type))) {
2296 // It does not start with dot and is not a valid typegroup, this is most likely extension.
2297 $accepted_types[$i] = '.'. $type;
2298 $corrected = true;
2302 if (!empty($corrected)) {
2303 set_config('courseoverviewfilesext', join(',', $accepted_types));
2306 $options = array(
2307 'maxfiles' => $CFG->courseoverviewfileslimit,
2308 'maxbytes' => $CFG->maxbytes,
2309 'subdirs' => 0,
2310 'accepted_types' => $accepted_types
2312 if (!empty($course->id)) {
2313 $options['context'] = context_course::instance($course->id);
2314 } else if (is_int($course) && $course > 0) {
2315 $options['context'] = context_course::instance($course);
2317 return $options;
2321 * Create a course and either return a $course object
2323 * Please note this functions does not verify any access control,
2324 * the calling code is responsible for all validation (usually it is the form definition).
2326 * @param array $editoroptions course description editor options
2327 * @param object $data - all the data needed for an entry in the 'course' table
2328 * @return object new course instance
2330 function create_course($data, $editoroptions = NULL) {
2331 global $DB, $CFG;
2333 //check the categoryid - must be given for all new courses
2334 $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
2336 // Check if the shortname already exists.
2337 if (!empty($data->shortname)) {
2338 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
2339 throw new moodle_exception('shortnametaken', '', '', $data->shortname);
2343 // Check if the idnumber already exists.
2344 if (!empty($data->idnumber)) {
2345 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
2346 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber);
2350 if (empty($CFG->enablecourserelativedates)) {
2351 // Make sure we're not setting the relative dates mode when the setting is disabled.
2352 unset($data->relativedatesmode);
2355 if ($errorcode = course_validate_dates((array)$data)) {
2356 throw new moodle_exception($errorcode);
2359 // Check if timecreated is given.
2360 $data->timecreated = !empty($data->timecreated) ? $data->timecreated : time();
2361 $data->timemodified = $data->timecreated;
2363 // place at beginning of any category
2364 $data->sortorder = 0;
2366 if ($editoroptions) {
2367 // summary text is updated later, we need context to store the files first
2368 $data->summary = '';
2369 $data->summary_format = FORMAT_HTML;
2372 if (!isset($data->visible)) {
2373 // data not from form, add missing visibility info
2374 $data->visible = $category->visible;
2376 $data->visibleold = $data->visible;
2378 $newcourseid = $DB->insert_record('course', $data);
2379 $context = context_course::instance($newcourseid, MUST_EXIST);
2381 if ($editoroptions) {
2382 // Save the files used in the summary editor and store
2383 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2384 $DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid));
2385 $DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid));
2387 if ($overviewfilesoptions = course_overviewfiles_options($newcourseid)) {
2388 // Save the course overviewfiles
2389 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2392 // update course format options
2393 course_get_format($newcourseid)->update_course_format_options($data);
2395 $course = course_get_format($newcourseid)->get_course();
2397 fix_course_sortorder();
2398 // purge appropriate caches in case fix_course_sortorder() did not change anything
2399 cache_helper::purge_by_event('changesincourse');
2401 // Trigger a course created event.
2402 $event = \core\event\course_created::create(array(
2403 'objectid' => $course->id,
2404 'context' => context_course::instance($course->id),
2405 'other' => array('shortname' => $course->shortname,
2406 'fullname' => $course->fullname)
2409 $event->trigger();
2411 // Setup the blocks
2412 blocks_add_default_course_blocks($course);
2414 // Create default section and initial sections if specified (unless they've already been created earlier).
2415 // We do not want to call course_create_sections_if_missing() because to avoid creating course cache.
2416 $numsections = isset($data->numsections) ? $data->numsections : 0;
2417 $existingsections = $DB->get_fieldset_sql('SELECT section from {course_sections} WHERE course = ?', [$newcourseid]);
2418 $newsections = array_diff(range(0, $numsections), $existingsections);
2419 foreach ($newsections as $sectionnum) {
2420 course_create_section($newcourseid, $sectionnum, true);
2423 // Save any custom role names.
2424 save_local_role_names($course->id, (array)$data);
2426 // set up enrolments
2427 enrol_course_updated(true, $course, $data);
2429 // Update course tags.
2430 if (isset($data->tags)) {
2431 core_tag_tag::set_item_tags('core', 'course', $course->id, context_course::instance($course->id), $data->tags);
2434 // Save custom fields if there are any of them in the form.
2435 $handler = core_course\customfield\course_handler::create();
2436 // Make sure to set the handler's parent context first.
2437 $coursecatcontext = context_coursecat::instance($category->id);
2438 $handler->set_parent_context($coursecatcontext);
2439 // Save the custom field data.
2440 $data->id = $course->id;
2441 $handler->instance_form_save($data, true);
2443 return $course;
2447 * Update a course.
2449 * Please note this functions does not verify any access control,
2450 * the calling code is responsible for all validation (usually it is the form definition).
2452 * @param object $data - all the data needed for an entry in the 'course' table
2453 * @param array $editoroptions course description editor options
2454 * @return void
2456 function update_course($data, $editoroptions = NULL) {
2457 global $DB, $CFG;
2459 // Prevent changes on front page course.
2460 if ($data->id == SITEID) {
2461 throw new moodle_exception('invalidcourse', 'error');
2464 $oldcourse = course_get_format($data->id)->get_course();
2465 $context = context_course::instance($oldcourse->id);
2467 // Make sure we're not changing whatever the course's relativedatesmode setting is.
2468 unset($data->relativedatesmode);
2470 // Capture the updated fields for the log data.
2471 $updatedfields = [];
2472 foreach (get_object_vars($oldcourse) as $field => $value) {
2473 if ($field == 'summary_editor') {
2474 if (($data->$field)['text'] !== $value['text']) {
2475 // The summary might be very long, we don't wan't to fill up the log record with the full text.
2476 $updatedfields[$field] = '(updated)';
2478 } else if ($field == 'tags' && !empty($CFG->usetags)) {
2479 // Tags might not have the same array keys, just check the values.
2480 if (array_values($data->$field) !== array_values($value)) {
2481 $updatedfields[$field] = $data->$field;
2483 } else {
2484 if (isset($data->$field) && $data->$field != $value) {
2485 $updatedfields[$field] = $data->$field;
2490 $data->timemodified = time();
2492 if ($editoroptions) {
2493 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2495 if ($overviewfilesoptions = course_overviewfiles_options($data->id)) {
2496 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2499 // Check we don't have a duplicate shortname.
2500 if (!empty($data->shortname) && $oldcourse->shortname != $data->shortname) {
2501 if ($DB->record_exists_sql('SELECT id from {course} WHERE shortname = ? AND id <> ?', array($data->shortname, $data->id))) {
2502 throw new moodle_exception('shortnametaken', '', '', $data->shortname);
2506 // Check we don't have a duplicate idnumber.
2507 if (!empty($data->idnumber) && $oldcourse->idnumber != $data->idnumber) {
2508 if ($DB->record_exists_sql('SELECT id from {course} WHERE idnumber = ? AND id <> ?', array($data->idnumber, $data->id))) {
2509 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber);
2513 if ($errorcode = course_validate_dates((array)$data)) {
2514 throw new moodle_exception($errorcode);
2517 if (!isset($data->category) or empty($data->category)) {
2518 // prevent nulls and 0 in category field
2519 unset($data->category);
2521 $changesincoursecat = $movecat = (isset($data->category) and $oldcourse->category != $data->category);
2523 if (!isset($data->visible)) {
2524 // data not from form, add missing visibility info
2525 $data->visible = $oldcourse->visible;
2528 if ($data->visible != $oldcourse->visible) {
2529 // reset the visibleold flag when manually hiding/unhiding course
2530 $data->visibleold = $data->visible;
2531 $changesincoursecat = true;
2532 } else {
2533 if ($movecat) {
2534 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category));
2535 if (empty($newcategory->visible)) {
2536 // make sure when moving into hidden category the course is hidden automatically
2537 $data->visible = 0;
2542 // Set newsitems to 0 if format does not support announcements.
2543 if (isset($data->format)) {
2544 $newcourseformat = course_get_format((object)['format' => $data->format]);
2545 if (!$newcourseformat->supports_news()) {
2546 $data->newsitems = 0;
2550 // Update custom fields if there are any of them in the form.
2551 $handler = core_course\customfield\course_handler::create();
2552 $handler->instance_form_save($data);
2554 // Update with the new data
2555 $DB->update_record('course', $data);
2556 // make sure the modinfo cache is reset
2557 rebuild_course_cache($data->id);
2559 // update course format options with full course data
2560 course_get_format($data->id)->update_course_format_options($data, $oldcourse);
2562 $course = $DB->get_record('course', array('id'=>$data->id));
2564 if ($movecat) {
2565 $newparent = context_coursecat::instance($course->category);
2566 $context->update_moved($newparent);
2568 $fixcoursesortorder = $movecat || (isset($data->sortorder) && ($oldcourse->sortorder != $data->sortorder));
2569 if ($fixcoursesortorder) {
2570 fix_course_sortorder();
2573 // purge appropriate caches in case fix_course_sortorder() did not change anything
2574 cache_helper::purge_by_event('changesincourse');
2575 if ($changesincoursecat) {
2576 cache_helper::purge_by_event('changesincoursecat');
2579 // Test for and remove blocks which aren't appropriate anymore
2580 blocks_remove_inappropriate($course);
2582 // Save any custom role names.
2583 save_local_role_names($course->id, $data);
2585 // update enrol settings
2586 enrol_course_updated(false, $course, $data);
2588 // Update course tags.
2589 if (isset($data->tags)) {
2590 core_tag_tag::set_item_tags('core', 'course', $course->id, context_course::instance($course->id), $data->tags);
2593 // Trigger a course updated event.
2594 $event = \core\event\course_updated::create(array(
2595 'objectid' => $course->id,
2596 'context' => context_course::instance($course->id),
2597 'other' => array('shortname' => $course->shortname,
2598 'fullname' => $course->fullname,
2599 'updatedfields' => $updatedfields)
2602 $event->set_legacy_logdata(array($course->id, 'course', 'update', 'edit.php?id=' . $course->id, $course->id));
2603 $event->trigger();
2605 if ($oldcourse->format !== $course->format) {
2606 // Remove all options stored for the previous format
2607 // We assume that new course format migrated everything it needed watching trigger
2608 // 'course_updated' and in method format_XXX::update_course_format_options()
2609 $DB->delete_records('course_format_options',
2610 array('courseid' => $course->id, 'format' => $oldcourse->format));
2615 * Calculate the average number of enrolled participants per course.
2617 * This is intended for statistics purposes during the site registration. Only visible courses are taken into account.
2618 * Front page enrolments are excluded.
2620 * @param bool $onlyactive Consider only active enrolments in enabled plugins and obey the enrolment time restrictions.
2621 * @param int $lastloginsince If specified, count only users who logged in after this timestamp.
2622 * @return float
2624 function average_number_of_participants(bool $onlyactive = false, int $lastloginsince = null): float {
2625 global $DB;
2627 $params = [
2628 'siteid' => SITEID,
2631 $sql = "SELECT DISTINCT ue.userid, e.courseid
2632 FROM {user_enrolments} ue
2633 JOIN {enrol} e ON e.id = ue.enrolid
2634 JOIN {course} c ON c.id = e.courseid ";
2636 if ($onlyactive || $lastloginsince) {
2637 $sql .= "JOIN {user} u ON u.id = ue.userid ";
2640 $sql .= "WHERE e.courseid <> :siteid
2641 AND c.visible = 1 ";
2643 if ($onlyactive) {
2644 $sql .= "AND ue.status = :active
2645 AND e.status = :enabled
2646 AND ue.timestart < :now1
2647 AND (ue.timeend = 0 OR ue.timeend > :now2) ";
2649 // Same as in the enrollib - the rounding should help caching in the database.
2650 $now = round(time(), -2);
2652 $params += [
2653 'active' => ENROL_USER_ACTIVE,
2654 'enabled' => ENROL_INSTANCE_ENABLED,
2655 'now1' => $now,
2656 'now2' => $now,
2660 if ($lastloginsince) {
2661 $sql .= "AND u.lastlogin > :lastlogin ";
2662 $params['lastlogin'] = $lastloginsince;
2665 $sql = "SELECT COUNT(*)
2666 FROM ($sql) total";
2668 $enrolmenttotal = $DB->count_records_sql($sql, $params);
2670 // Get the number of visible courses (exclude the front page).
2671 $coursetotal = $DB->count_records('course', ['visible' => 1]);
2672 $coursetotal = $coursetotal - 1;
2674 if (empty($coursetotal)) {
2675 $participantaverage = 0;
2677 } else {
2678 $participantaverage = $enrolmenttotal / $coursetotal;
2681 return $participantaverage;
2685 * Average number of course modules
2686 * @return integer
2688 function average_number_of_courses_modules() {
2689 global $DB, $SITE;
2691 //count total of visible course module (except front page)
2692 $sql = 'SELECT COUNT(*) FROM (
2693 SELECT cm.course, cm.module
2694 FROM {course} c, {course_modules} cm
2695 WHERE c.id = cm.course
2696 AND c.id <> :siteid
2697 AND cm.visible = 1
2698 AND c.visible = 1) total';
2699 $params = array('siteid' => $SITE->id);
2700 $moduletotal = $DB->count_records_sql($sql, $params);
2703 //count total of visible courses (minus front page)
2704 $coursetotal = $DB->count_records('course', array('visible' => 1));
2705 $coursetotal = $coursetotal - 1 ;
2707 //average of course module
2708 if (empty($coursetotal)) {
2709 $coursemoduleaverage = 0;
2710 } else {
2711 $coursemoduleaverage = $moduletotal / $coursetotal;
2714 return $coursemoduleaverage;
2718 * This class pertains to course requests and contains methods associated with
2719 * create, approving, and removing course requests.
2721 * Please note we do not allow embedded images here because there is no context
2722 * to store them with proper access control.
2724 * @copyright 2009 Sam Hemelryk
2725 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2726 * @since Moodle 2.0
2728 * @property-read int $id
2729 * @property-read string $fullname
2730 * @property-read string $shortname
2731 * @property-read string $summary
2732 * @property-read int $summaryformat
2733 * @property-read int $summarytrust
2734 * @property-read string $reason
2735 * @property-read int $requester
2737 class course_request {
2740 * This is the stdClass that stores the properties for the course request
2741 * and is externally accessed through the __get magic method
2742 * @var stdClass
2744 protected $properties;
2747 * An array of options for the summary editor used by course request forms.
2748 * This is initially set by {@link summary_editor_options()}
2749 * @var array
2750 * @static
2752 protected static $summaryeditoroptions;
2755 * Static function to prepare the summary editor for working with a course
2756 * request.
2758 * @static
2759 * @param null|stdClass $data Optional, an object containing the default values
2760 * for the form, these may be modified when preparing the
2761 * editor so this should be called before creating the form
2762 * @return stdClass An object that can be used to set the default values for
2763 * an mforms form
2765 public static function prepare($data=null) {
2766 if ($data === null) {
2767 $data = new stdClass;
2769 $data = file_prepare_standard_editor($data, 'summary', self::summary_editor_options());
2770 return $data;
2774 * Static function to create a new course request when passed an array of properties
2775 * for it.
2777 * This function also handles saving any files that may have been used in the editor
2779 * @static
2780 * @param stdClass $data
2781 * @return course_request The newly created course request
2783 public static function create($data) {
2784 global $USER, $DB, $CFG;
2785 $data->requester = $USER->id;
2787 // Setting the default category if none set.
2788 if (empty($data->category) || !empty($CFG->lockrequestcategory)) {
2789 $data->category = $CFG->defaultrequestcategory;
2792 // Summary is a required field so copy the text over
2793 $data->summary = $data->summary_editor['text'];
2794 $data->summaryformat = $data->summary_editor['format'];
2796 $data->id = $DB->insert_record('course_request', $data);
2798 // Create a new course_request object and return it
2799 $request = new course_request($data);
2801 // Notify the admin if required.
2802 if ($users = get_users_from_config($CFG->courserequestnotify, 'moodle/site:approvecourse')) {
2804 $a = new stdClass;
2805 $a->link = "$CFG->wwwroot/course/pending.php";
2806 $a->user = fullname($USER);
2807 $subject = get_string('courserequest');
2808 $message = get_string('courserequestnotifyemail', 'admin', $a);
2809 foreach ($users as $user) {
2810 $request->notify($user, $USER, 'courserequested', $subject, $message);
2814 return $request;
2818 * Returns an array of options to use with a summary editor
2820 * @uses course_request::$summaryeditoroptions
2821 * @return array An array of options to use with the editor
2823 public static function summary_editor_options() {
2824 global $CFG;
2825 if (self::$summaryeditoroptions === null) {
2826 self::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
2828 return self::$summaryeditoroptions;
2832 * Loads the properties for this course request object. Id is required and if
2833 * only id is provided then we load the rest of the properties from the database
2835 * @param stdClass|int $properties Either an object containing properties
2836 * or the course_request id to load
2838 public function __construct($properties) {
2839 global $DB;
2840 if (empty($properties->id)) {
2841 if (empty($properties)) {
2842 throw new coding_exception('You must provide a course request id when creating a course_request object');
2844 $id = $properties;
2845 $properties = new stdClass;
2846 $properties->id = (int)$id;
2847 unset($id);
2849 if (empty($properties->requester)) {
2850 if (!($this->properties = $DB->get_record('course_request', array('id' => $properties->id)))) {
2851 print_error('unknowncourserequest');
2853 } else {
2854 $this->properties = $properties;
2856 $this->properties->collision = null;
2860 * Returns the requested property
2862 * @param string $key
2863 * @return mixed
2865 public function __get($key) {
2866 return $this->properties->$key;
2870 * Override this to ensure empty($request->blah) calls return a reliable answer...
2872 * This is required because we define the __get method
2874 * @param mixed $key
2875 * @return bool True is it not empty, false otherwise
2877 public function __isset($key) {
2878 return (!empty($this->properties->$key));
2882 * Returns the user who requested this course
2884 * Uses a static var to cache the results and cut down the number of db queries
2886 * @staticvar array $requesters An array of cached users
2887 * @return stdClass The user who requested the course
2889 public function get_requester() {
2890 global $DB;
2891 static $requesters= array();
2892 if (!array_key_exists($this->properties->requester, $requesters)) {
2893 $requesters[$this->properties->requester] = $DB->get_record('user', array('id'=>$this->properties->requester));
2895 return $requesters[$this->properties->requester];
2899 * Checks that the shortname used by the course does not conflict with any other
2900 * courses that exist
2902 * @param string|null $shortnamemark The string to append to the requests shortname
2903 * should a conflict be found
2904 * @return bool true is there is a conflict, false otherwise
2906 public function check_shortname_collision($shortnamemark = '[*]') {
2907 global $DB;
2909 if ($this->properties->collision !== null) {
2910 return $this->properties->collision;
2913 if (empty($this->properties->shortname)) {
2914 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER);
2915 $this->properties->collision = false;
2916 } else if ($DB->record_exists('course', array('shortname' => $this->properties->shortname))) {
2917 if (!empty($shortnamemark)) {
2918 $this->properties->shortname .= ' '.$shortnamemark;
2920 $this->properties->collision = true;
2921 } else {
2922 $this->properties->collision = false;
2924 return $this->properties->collision;
2928 * Checks user capability to approve a requested course
2930 * If course was requested without category for some reason (might happen if $CFG->defaultrequestcategory is
2931 * misconfigured), we check capabilities 'moodle/site:approvecourse' and 'moodle/course:changecategory'.
2933 * @return bool
2935 public function can_approve() {
2936 global $CFG;
2937 $category = null;
2938 if ($this->properties->category) {
2939 $category = core_course_category::get($this->properties->category, IGNORE_MISSING);
2940 } else if ($CFG->defaultrequestcategory) {
2941 $category = core_course_category::get($CFG->defaultrequestcategory, IGNORE_MISSING);
2943 if ($category) {
2944 return has_capability('moodle/site:approvecourse', $category->get_context());
2947 // We can not determine the context where the course should be created. The approver should have
2948 // both capabilities to approve courses and change course category in the system context.
2949 return has_all_capabilities(['moodle/site:approvecourse', 'moodle/course:changecategory'], context_system::instance());
2953 * Returns the category where this course request should be created
2955 * Note that we don't check here that user has a capability to view
2956 * hidden categories if he has capabilities 'moodle/site:approvecourse' and
2957 * 'moodle/course:changecategory'
2959 * @return core_course_category
2961 public function get_category() {
2962 global $CFG;
2963 if ($this->properties->category && ($category = core_course_category::get($this->properties->category, IGNORE_MISSING))) {
2964 return $category;
2965 } else if ($CFG->defaultrequestcategory &&
2966 ($category = core_course_category::get($CFG->defaultrequestcategory, IGNORE_MISSING))) {
2967 return $category;
2968 } else {
2969 return core_course_category::get_default();
2974 * This function approves the request turning it into a course
2976 * This function converts the course request into a course, at the same time
2977 * transferring any files used in the summary to the new course and then removing
2978 * the course request and the files associated with it.
2980 * @return int The id of the course that was created from this request
2982 public function approve() {
2983 global $CFG, $DB, $USER;
2985 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
2987 $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted'=>0), '*', MUST_EXIST);
2989 $courseconfig = get_config('moodlecourse');
2991 // Transfer appropriate settings
2992 $data = clone($this->properties);
2993 unset($data->id);
2994 unset($data->reason);
2995 unset($data->requester);
2997 // Set category
2998 $category = $this->get_category();
2999 $data->category = $category->id;
3000 // Set misc settings
3001 $data->requested = 1;
3003 // Apply course default settings
3004 $data->format = $courseconfig->format;
3005 $data->newsitems = $courseconfig->newsitems;
3006 $data->showgrades = $courseconfig->showgrades;
3007 $data->showreports = $courseconfig->showreports;
3008 $data->maxbytes = $courseconfig->maxbytes;
3009 $data->groupmode = $courseconfig->groupmode;
3010 $data->groupmodeforce = $courseconfig->groupmodeforce;
3011 $data->visible = $courseconfig->visible;
3012 $data->visibleold = $data->visible;
3013 $data->lang = $courseconfig->lang;
3014 $data->enablecompletion = $courseconfig->enablecompletion;
3015 $data->numsections = $courseconfig->numsections;
3016 $data->startdate = usergetmidnight(time());
3017 if ($courseconfig->courseenddateenabled) {
3018 $data->enddate = usergetmidnight(time()) + $courseconfig->courseduration;
3021 list($data->fullname, $data->shortname) = restore_dbops::calculate_course_names(0, $data->fullname, $data->shortname);
3023 $course = create_course($data);
3024 $context = context_course::instance($course->id, MUST_EXIST);
3026 // add enrol instances
3027 if (!$DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
3028 if ($manual = enrol_get_plugin('manual')) {
3029 $manual->add_default_instance($course);
3033 // enrol the requester as teacher if necessary
3034 if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
3035 enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid);
3038 $this->delete();
3040 $a = new stdClass();
3041 $a->name = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
3042 $a->url = $CFG->wwwroot.'/course/view.php?id=' . $course->id;
3043 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a), $course->id);
3045 return $course->id;
3049 * Reject a course request
3051 * This function rejects a course request, emailing the requesting user the
3052 * provided notice and then removing the request from the database
3054 * @param string $notice The message to display to the user
3056 public function reject($notice) {
3057 global $USER, $DB;
3058 $user = $DB->get_record('user', array('id' => $this->properties->requester), '*', MUST_EXIST);
3059 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
3060 $this->delete();
3064 * Deletes the course request and any associated files
3066 public function delete() {
3067 global $DB;
3068 $DB->delete_records('course_request', array('id' => $this->properties->id));
3072 * Send a message from one user to another using events_trigger
3074 * @param object $touser
3075 * @param object $fromuser
3076 * @param string $name
3077 * @param string $subject
3078 * @param string $message
3079 * @param int|null $courseid
3081 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message, $courseid = null) {
3082 $eventdata = new \core\message\message();
3083 $eventdata->courseid = empty($courseid) ? SITEID : $courseid;
3084 $eventdata->component = 'moodle';
3085 $eventdata->name = $name;
3086 $eventdata->userfrom = $fromuser;
3087 $eventdata->userto = $touser;
3088 $eventdata->subject = $subject;
3089 $eventdata->fullmessage = $message;
3090 $eventdata->fullmessageformat = FORMAT_PLAIN;
3091 $eventdata->fullmessagehtml = '';
3092 $eventdata->smallmessage = '';
3093 $eventdata->notification = 1;
3094 message_send($eventdata);
3098 * Checks if current user can request a course in this context
3100 * @param context $context
3101 * @return bool
3103 public static function can_request(context $context) {
3104 global $CFG;
3105 if (empty($CFG->enablecourserequests)) {
3106 return false;
3108 if (has_capability('moodle/course:create', $context)) {
3109 return false;
3112 if ($context instanceof context_system) {
3113 $defaultcontext = context_coursecat::instance($CFG->defaultrequestcategory, IGNORE_MISSING);
3114 return $defaultcontext &&
3115 has_capability('moodle/course:request', $defaultcontext);
3116 } else if ($context instanceof context_coursecat) {
3117 if (!$CFG->lockrequestcategory || $CFG->defaultrequestcategory == $context->instanceid) {
3118 return has_capability('moodle/course:request', $context);
3121 return false;
3126 * Return a list of page types
3127 * @param string $pagetype current page type
3128 * @param context $parentcontext Block's parent context
3129 * @param context $currentcontext Current context of block
3130 * @return array array of page types
3132 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
3133 if ($pagetype === 'course-index' || $pagetype === 'course-index-category') {
3134 // For courses and categories browsing pages (/course/index.php) add option to show on ANY category page
3135 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
3136 'course-index-*' => get_string('page-course-index-x', 'pagetype'),
3138 } else if ($currentcontext && (!($coursecontext = $currentcontext->get_course_context(false)) || $coursecontext->instanceid == SITEID)) {
3139 // We know for sure that despite pagetype starts with 'course-' this is not a page in course context (i.e. /course/search.php, etc.)
3140 $pagetypes = array('*' => get_string('page-x', 'pagetype'));
3141 } else {
3142 // Otherwise consider it a page inside a course even if $currentcontext is null
3143 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
3144 'course-*' => get_string('page-course-x', 'pagetype'),
3145 'course-view-*' => get_string('page-course-view-x', 'pagetype')
3148 return $pagetypes;
3152 * Determine whether course ajax should be enabled for the specified course
3154 * @param stdClass $course The course to test against
3155 * @return boolean Whether course ajax is enabled or note
3157 function course_ajax_enabled($course) {
3158 global $CFG, $PAGE, $SITE;
3160 // The user must be editing for AJAX to be included
3161 if (!$PAGE->user_is_editing()) {
3162 return false;
3165 // Check that the theme suports
3166 if (!$PAGE->theme->enablecourseajax) {
3167 return false;
3170 // Check that the course format supports ajax functionality
3171 // The site 'format' doesn't have information on course format support
3172 if ($SITE->id !== $course->id) {
3173 $courseformatajaxsupport = course_format_ajax_support($course->format);
3174 if (!$courseformatajaxsupport->capable) {
3175 return false;
3179 // All conditions have been met so course ajax should be enabled
3180 return true;
3184 * Include the relevant javascript and language strings for the resource
3185 * toolbox YUI module
3187 * @param integer $id The ID of the course being applied to
3188 * @param array $usedmodules An array containing the names of the modules in use on the page
3189 * @param array $enabledmodules An array containing the names of the enabled (visible) modules on this site
3190 * @param stdClass $config An object containing configuration parameters for ajax modules including:
3191 * * resourceurl The URL to post changes to for resource changes
3192 * * sectionurl The URL to post changes to for section changes
3193 * * pageparams Additional parameters to pass through in the post
3194 * @return bool
3196 function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) {
3197 global $CFG, $PAGE, $SITE;
3199 // Ensure that ajax should be included
3200 if (!course_ajax_enabled($course)) {
3201 return false;
3204 if (!$config) {
3205 $config = new stdClass();
3208 // The URL to use for resource changes
3209 if (!isset($config->resourceurl)) {
3210 $config->resourceurl = '/course/rest.php';
3213 // The URL to use for section changes
3214 if (!isset($config->sectionurl)) {
3215 $config->sectionurl = '/course/rest.php';
3218 // Any additional parameters which need to be included on page submission
3219 if (!isset($config->pageparams)) {
3220 $config->pageparams = array();
3223 // Include course dragdrop
3224 if (course_format_uses_sections($course->format)) {
3225 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_section_dragdrop',
3226 array(array(
3227 'courseid' => $course->id,
3228 'ajaxurl' => $config->sectionurl,
3229 'config' => $config,
3230 )), null, true);
3232 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_resource_dragdrop',
3233 array(array(
3234 'courseid' => $course->id,
3235 'ajaxurl' => $config->resourceurl,
3236 'config' => $config,
3237 )), null, true);
3240 // Require various strings for the command toolbox
3241 $PAGE->requires->strings_for_js(array(
3242 'moveleft',
3243 'deletechecktype',
3244 'deletechecktypename',
3245 'edittitle',
3246 'edittitleinstructions',
3247 'show',
3248 'hide',
3249 'highlight',
3250 'highlightoff',
3251 'groupsnone',
3252 'groupsvisible',
3253 'groupsseparate',
3254 'clicktochangeinbrackets',
3255 'markthistopic',
3256 'markedthistopic',
3257 'movesection',
3258 'movecoursemodule',
3259 'movecoursesection',
3260 'movecontent',
3261 'tocontent',
3262 'emptydragdropregion',
3263 'afterresource',
3264 'aftersection',
3265 'totopofsection',
3266 ), 'moodle');
3268 // Include section-specific strings for formats which support sections.
3269 if (course_format_uses_sections($course->format)) {
3270 $PAGE->requires->strings_for_js(array(
3271 'showfromothers',
3272 'hidefromothers',
3273 ), 'format_' . $course->format);
3276 // For confirming resource deletion we need the name of the module in question
3277 foreach ($usedmodules as $module => $modname) {
3278 $PAGE->requires->string_for_js('pluginname', $module);
3281 // Load drag and drop upload AJAX.
3282 require_once($CFG->dirroot.'/course/dnduploadlib.php');
3283 dndupload_add_to_course($course, $enabledmodules);
3285 $PAGE->requires->js_call_amd('core_course/actions', 'initCoursePage', array($course->format));
3287 return true;
3291 * Returns the sorted list of available course formats, filtered by enabled if necessary
3293 * @param bool $enabledonly return only formats that are enabled
3294 * @return array array of sorted format names
3296 function get_sorted_course_formats($enabledonly = false) {
3297 global $CFG;
3298 $formats = core_component::get_plugin_list('format');
3300 if (!empty($CFG->format_plugins_sortorder)) {
3301 $order = explode(',', $CFG->format_plugins_sortorder);
3302 $order = array_merge(array_intersect($order, array_keys($formats)),
3303 array_diff(array_keys($formats), $order));
3304 } else {
3305 $order = array_keys($formats);
3307 if (!$enabledonly) {
3308 return $order;
3310 $sortedformats = array();
3311 foreach ($order as $formatname) {
3312 if (!get_config('format_'.$formatname, 'disabled')) {
3313 $sortedformats[] = $formatname;
3316 return $sortedformats;
3320 * The URL to use for the specified course (with section)
3322 * @param int|stdClass $courseorid The course to get the section name for (either object or just course id)
3323 * @param int|stdClass $section Section object from database or just field course_sections.section
3324 * if omitted the course view page is returned
3325 * @param array $options options for view URL. At the moment core uses:
3326 * 'navigation' (bool) if true and section has no separate page, the function returns null
3327 * 'sr' (int) used by multipage formats to specify to which section to return
3328 * @return moodle_url The url of course
3330 function course_get_url($courseorid, $section = null, $options = array()) {
3331 return course_get_format($courseorid)->get_view_url($section, $options);
3335 * Create a module.
3337 * It includes:
3338 * - capability checks and other checks
3339 * - create the module from the module info
3341 * @param object $module
3342 * @return object the created module info
3343 * @throws moodle_exception if user is not allowed to perform the action or module is not allowed in this course
3345 function create_module($moduleinfo) {
3346 global $DB, $CFG;
3348 require_once($CFG->dirroot . '/course/modlib.php');
3350 // Check manadatory attributs.
3351 $mandatoryfields = array('modulename', 'course', 'section', 'visible');
3352 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
3353 $mandatoryfields[] = 'introeditor';
3355 foreach($mandatoryfields as $mandatoryfield) {
3356 if (!isset($moduleinfo->{$mandatoryfield})) {
3357 throw new moodle_exception('createmodulemissingattribut', '', '', $mandatoryfield);
3361 // Some additional checks (capability / existing instances).
3362 $course = $DB->get_record('course', array('id'=>$moduleinfo->course), '*', MUST_EXIST);
3363 list($module, $context, $cw) = can_add_moduleinfo($course, $moduleinfo->modulename, $moduleinfo->section);
3365 // Add the module.
3366 $moduleinfo->module = $module->id;
3367 $moduleinfo = add_moduleinfo($moduleinfo, $course, null);
3369 return $moduleinfo;
3373 * Update a module.
3375 * It includes:
3376 * - capability and other checks
3377 * - update the module
3379 * @param object $module
3380 * @return object the updated module info
3381 * @throws moodle_exception if current user is not allowed to update the module
3383 function update_module($moduleinfo) {
3384 global $DB, $CFG;
3386 require_once($CFG->dirroot . '/course/modlib.php');
3388 // Check the course module exists.
3389 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule, 0, false, MUST_EXIST);
3391 // Check the course exists.
3392 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
3394 // Some checks (capaibility / existing instances).
3395 list($cm, $context, $module, $data, $cw) = can_update_moduleinfo($cm);
3397 // Retrieve few information needed by update_moduleinfo.
3398 $moduleinfo->modulename = $cm->modname;
3399 if (!isset($moduleinfo->scale)) {
3400 $moduleinfo->scale = 0;
3402 $moduleinfo->type = 'mod';
3404 // Update the module.
3405 list($cm, $moduleinfo) = update_moduleinfo($cm, $moduleinfo, $course, null);
3407 return $moduleinfo;
3411 * Duplicate a module on the course for ajax.
3413 * @see mod_duplicate_module()
3414 * @param object $course The course
3415 * @param object $cm The course module to duplicate
3416 * @param int $sr The section to link back to (used for creating the links)
3417 * @throws moodle_exception if the plugin doesn't support duplication
3418 * @return Object containing:
3419 * - fullcontent: The HTML markup for the created CM
3420 * - cmid: The CMID of the newly created CM
3421 * - redirect: Whether to trigger a redirect following this change
3423 function mod_duplicate_activity($course, $cm, $sr = null) {
3424 global $PAGE;
3426 $newcm = duplicate_module($course, $cm);
3428 $resp = new stdClass();
3429 if ($newcm) {
3430 $courserenderer = $PAGE->get_renderer('core', 'course');
3431 $completioninfo = new completion_info($course);
3432 $modulehtml = $courserenderer->course_section_cm($course, $completioninfo,
3433 $newcm, null, array());
3435 $resp->fullcontent = $courserenderer->course_section_cm_list_item($course, $completioninfo, $newcm, $sr);
3436 $resp->cmid = $newcm->id;
3437 } else {
3438 // Trigger a redirect.
3439 $resp->redirect = true;
3441 return $resp;
3445 * Api to duplicate a module.
3447 * @param object $course course object.
3448 * @param object $cm course module object to be duplicated.
3449 * @since Moodle 2.8
3451 * @throws Exception
3452 * @throws coding_exception
3453 * @throws moodle_exception
3454 * @throws restore_controller_exception
3456 * @return cm_info|null cminfo object if we sucessfully duplicated the mod and found the new cm.
3458 function duplicate_module($course, $cm) {
3459 global $CFG, $DB, $USER;
3460 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
3461 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
3462 require_once($CFG->libdir . '/filelib.php');
3464 $a = new stdClass();
3465 $a->modtype = get_string('modulename', $cm->modname);
3466 $a->modname = format_string($cm->name);
3468 if (!plugin_supports('mod', $cm->modname, FEATURE_BACKUP_MOODLE2)) {
3469 throw new moodle_exception('duplicatenosupport', 'error', '', $a);
3472 // Backup the activity.
3474 $bc = new backup_controller(backup::TYPE_1ACTIVITY, $cm->id, backup::FORMAT_MOODLE,
3475 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
3477 $backupid = $bc->get_backupid();
3478 $backupbasepath = $bc->get_plan()->get_basepath();
3480 $bc->execute_plan();
3482 $bc->destroy();
3484 // Restore the backup immediately.
3486 $rc = new restore_controller($backupid, $course->id,
3487 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, backup::TARGET_CURRENT_ADDING);
3489 // Make sure that the restore_general_groups setting is always enabled when duplicating an activity.
3490 $plan = $rc->get_plan();
3491 $groupsetting = $plan->get_setting('groups');
3492 if (empty($groupsetting->get_value())) {
3493 $groupsetting->set_value(true);
3496 $cmcontext = context_module::instance($cm->id);
3497 if (!$rc->execute_precheck()) {
3498 $precheckresults = $rc->get_precheck_results();
3499 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
3500 if (empty($CFG->keeptempdirectoriesonbackup)) {
3501 fulldelete($backupbasepath);
3506 $rc->execute_plan();
3508 // Now a bit hacky part follows - we try to get the cmid of the newly
3509 // restored copy of the module.
3510 $newcmid = null;
3511 $tasks = $rc->get_plan()->get_tasks();
3512 foreach ($tasks as $task) {
3513 if (is_subclass_of($task, 'restore_activity_task')) {
3514 if ($task->get_old_contextid() == $cmcontext->id) {
3515 $newcmid = $task->get_moduleid();
3516 break;
3521 $rc->destroy();
3523 if (empty($CFG->keeptempdirectoriesonbackup)) {
3524 fulldelete($backupbasepath);
3527 // If we know the cmid of the new course module, let us move it
3528 // right below the original one. otherwise it will stay at the
3529 // end of the section.
3530 if ($newcmid) {
3531 // Proceed with activity renaming before everything else. We don't use APIs here to avoid
3532 // triggering a lot of create/update duplicated events.
3533 $newcm = get_coursemodule_from_id($cm->modname, $newcmid, $cm->course);
3534 // Add ' (copy)' to duplicates. Note we don't cleanup or validate lengths here. It comes
3535 // from original name that was valid, so the copy should be too.
3536 $newname = get_string('duplicatedmodule', 'moodle', $newcm->name);
3537 $DB->set_field($cm->modname, 'name', $newname, ['id' => $newcm->instance]);
3539 $section = $DB->get_record('course_sections', array('id' => $cm->section, 'course' => $cm->course));
3540 $modarray = explode(",", trim($section->sequence));
3541 $cmindex = array_search($cm->id, $modarray);
3542 if ($cmindex !== false && $cmindex < count($modarray) - 1) {
3543 moveto_module($newcm, $section, $modarray[$cmindex + 1]);
3546 // Update calendar events with the duplicated module.
3547 // The following line is to be removed in MDL-58906.
3548 course_module_update_calendar_events($newcm->modname, null, $newcm);
3550 // Trigger course module created event. We can trigger the event only if we know the newcmid.
3551 $newcm = get_fast_modinfo($cm->course)->get_cm($newcmid);
3552 $event = \core\event\course_module_created::create_from_cm($newcm);
3553 $event->trigger();
3556 return isset($newcm) ? $newcm : null;
3560 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3561 * Sorts by descending order of time.
3563 * @param stdClass $a First object
3564 * @param stdClass $b Second object
3565 * @return int 0,1,-1 representing the order
3567 function compare_activities_by_time_desc($a, $b) {
3568 // Make sure the activities actually have a timestamp property.
3569 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3570 return 0;
3572 // We treat instances without timestamp as if they have a timestamp of 0.
3573 if ((!property_exists($a, 'timestamp')) && (property_exists($b,'timestamp'))) {
3574 return 1;
3576 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3577 return -1;
3579 if ($a->timestamp == $b->timestamp) {
3580 return 0;
3582 return ($a->timestamp > $b->timestamp) ? -1 : 1;
3586 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3587 * Sorts by ascending order of time.
3589 * @param stdClass $a First object
3590 * @param stdClass $b Second object
3591 * @return int 0,1,-1 representing the order
3593 function compare_activities_by_time_asc($a, $b) {
3594 // Make sure the activities actually have a timestamp property.
3595 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3596 return 0;
3598 // We treat instances without timestamp as if they have a timestamp of 0.
3599 if ((!property_exists($a, 'timestamp')) && (property_exists($b, 'timestamp'))) {
3600 return -1;
3602 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3603 return 1;
3605 if ($a->timestamp == $b->timestamp) {
3606 return 0;
3608 return ($a->timestamp < $b->timestamp) ? -1 : 1;
3612 * Changes the visibility of a course.
3614 * @param int $courseid The course to change.
3615 * @param bool $show True to make it visible, false otherwise.
3616 * @return bool
3618 function course_change_visibility($courseid, $show = true) {
3619 $course = new stdClass;
3620 $course->id = $courseid;
3621 $course->visible = ($show) ? '1' : '0';
3622 $course->visibleold = $course->visible;
3623 update_course($course);
3624 return true;
3628 * Changes the course sortorder by one, moving it up or down one in respect to sort order.
3630 * @param stdClass|core_course_list_element $course
3631 * @param bool $up If set to true the course will be moved up one. Otherwise down one.
3632 * @return bool
3634 function course_change_sortorder_by_one($course, $up) {
3635 global $DB;
3636 $params = array($course->sortorder, $course->category);
3637 if ($up) {
3638 $select = 'sortorder < ? AND category = ?';
3639 $sort = 'sortorder DESC';
3640 } else {
3641 $select = 'sortorder > ? AND category = ?';
3642 $sort = 'sortorder ASC';
3644 fix_course_sortorder();
3645 $swapcourse = $DB->get_records_select('course', $select, $params, $sort, '*', 0, 1);
3646 if ($swapcourse) {
3647 $swapcourse = reset($swapcourse);
3648 $DB->set_field('course', 'sortorder', $swapcourse->sortorder, array('id' => $course->id));
3649 $DB->set_field('course', 'sortorder', $course->sortorder, array('id' => $swapcourse->id));
3650 // Finally reorder courses.
3651 fix_course_sortorder();
3652 cache_helper::purge_by_event('changesincourse');
3653 return true;
3655 return false;
3659 * Changes the sort order of courses in a category so that the first course appears after the second.
3661 * @param int|stdClass $courseorid The course to focus on.
3662 * @param int $moveaftercourseid The course to shifter after or 0 if you want it to be the first course in the category.
3663 * @return bool
3665 function course_change_sortorder_after_course($courseorid, $moveaftercourseid) {
3666 global $DB;
3668 if (!is_object($courseorid)) {
3669 $course = get_course($courseorid);
3670 } else {
3671 $course = $courseorid;
3674 if ((int)$moveaftercourseid === 0) {
3675 // We've moving the course to the start of the queue.
3676 $sql = 'SELECT sortorder
3677 FROM {course}
3678 WHERE category = :categoryid
3679 ORDER BY sortorder';
3680 $params = array(
3681 'categoryid' => $course->category
3683 $sortorder = $DB->get_field_sql($sql, $params, IGNORE_MULTIPLE);
3685 $sql = 'UPDATE {course}
3686 SET sortorder = sortorder + 1
3687 WHERE category = :categoryid
3688 AND id <> :id';
3689 $params = array(
3690 'categoryid' => $course->category,
3691 'id' => $course->id,
3693 $DB->execute($sql, $params);
3694 $DB->set_field('course', 'sortorder', $sortorder, array('id' => $course->id));
3695 } else if ($course->id === $moveaftercourseid) {
3696 // They're the same - moronic.
3697 debugging("Invalid move after course given.", DEBUG_DEVELOPER);
3698 return false;
3699 } else {
3700 // Moving this course after the given course. It could be before it could be after.
3701 $moveaftercourse = get_course($moveaftercourseid);
3702 if ($course->category !== $moveaftercourse->category) {
3703 debugging("Cannot re-order courses. The given courses do not belong to the same category.", DEBUG_DEVELOPER);
3704 return false;
3706 // Increment all courses in the same category that are ordered after the moveafter course.
3707 // This makes a space for the course we're moving.
3708 $sql = 'UPDATE {course}
3709 SET sortorder = sortorder + 1
3710 WHERE category = :categoryid
3711 AND sortorder > :sortorder';
3712 $params = array(
3713 'categoryid' => $moveaftercourse->category,
3714 'sortorder' => $moveaftercourse->sortorder
3716 $DB->execute($sql, $params);
3717 $DB->set_field('course', 'sortorder', $moveaftercourse->sortorder + 1, array('id' => $course->id));
3719 fix_course_sortorder();
3720 cache_helper::purge_by_event('changesincourse');
3721 return true;
3725 * Trigger course viewed event. This API function is used when course view actions happens,
3726 * usually in course/view.php but also in external functions.
3728 * @param stdClass $context course context object
3729 * @param int $sectionnumber section number
3730 * @since Moodle 2.9
3732 function course_view($context, $sectionnumber = 0) {
3734 $eventdata = array('context' => $context);
3736 if (!empty($sectionnumber)) {
3737 $eventdata['other']['coursesectionnumber'] = $sectionnumber;
3740 $event = \core\event\course_viewed::create($eventdata);
3741 $event->trigger();
3743 user_accesstime_log($context->instanceid);
3747 * Returns courses tagged with a specified tag.
3749 * @param core_tag_tag $tag
3750 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
3751 * are displayed on the page and the per-page limit may be bigger
3752 * @param int $fromctx context id where the link was displayed, may be used by callbacks
3753 * to display items in the same context first
3754 * @param int $ctx context id where to search for records
3755 * @param bool $rec search in subcontexts as well
3756 * @param int $page 0-based number of page being displayed
3757 * @return \core_tag\output\tagindex
3759 function course_get_tagged_courses($tag, $exclusivemode = false, $fromctx = 0, $ctx = 0, $rec = 1, $page = 0) {
3760 global $CFG, $PAGE;
3762 $perpage = $exclusivemode ? $CFG->coursesperpage : 5;
3763 $displayoptions = array(
3764 'limit' => $perpage,
3765 'offset' => $page * $perpage,
3766 'viewmoreurl' => null,
3769 $courserenderer = $PAGE->get_renderer('core', 'course');
3770 $totalcount = core_course_category::search_courses_count(array('tagid' => $tag->id, 'ctx' => $ctx, 'rec' => $rec));
3771 $content = $courserenderer->tagged_courses($tag->id, $exclusivemode, $ctx, $rec, $displayoptions);
3772 $totalpages = ceil($totalcount / $perpage);
3774 return new core_tag\output\tagindex($tag, 'core', 'course', $content,
3775 $exclusivemode, $fromctx, $ctx, $rec, $page, $totalpages);
3779 * Implements callback inplace_editable() allowing to edit values in-place
3781 * @param string $itemtype
3782 * @param int $itemid
3783 * @param mixed $newvalue
3784 * @return \core\output\inplace_editable
3786 function core_course_inplace_editable($itemtype, $itemid, $newvalue) {
3787 if ($itemtype === 'activityname') {
3788 return \core_course\output\course_module_name::update($itemid, $newvalue);
3793 * This function calculates the minimum and maximum cutoff values for the timestart of
3794 * the given event.
3796 * It will return an array with two values, the first being the minimum cutoff value and
3797 * the second being the maximum cutoff value. Either or both values can be null, which
3798 * indicates there is no minimum or maximum, respectively.
3800 * If a cutoff is required then the function must return an array containing the cutoff
3801 * timestamp and error string to display to the user if the cutoff value is violated.
3803 * A minimum and maximum cutoff return value will look like:
3805 * [1505704373, 'The date must be after this date'],
3806 * [1506741172, 'The date must be before this date']
3809 * @param calendar_event $event The calendar event to get the time range for
3810 * @param stdClass $course The course object to get the range from
3811 * @return array Returns an array with min and max date.
3813 function core_course_core_calendar_get_valid_event_timestart_range(\calendar_event $event, $course) {
3814 $mindate = null;
3815 $maxdate = null;
3817 if ($course->startdate) {
3818 $mindate = [
3819 $course->startdate,
3820 get_string('errorbeforecoursestart', 'calendar')
3824 return [$mindate, $maxdate];
3828 * Returns course modules tagged with a specified tag ready for output on tag/index.php page
3830 * This is a callback used by the tag area core/course_modules to search for course modules
3831 * tagged with a specific tag.
3833 * @param core_tag_tag $tag
3834 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
3835 * are displayed on the page and the per-page limit may be bigger
3836 * @param int $fromcontextid context id where the link was displayed, may be used by callbacks
3837 * to display items in the same context first
3838 * @param int $contextid context id where to search for records
3839 * @param bool $recursivecontext search in subcontexts as well
3840 * @param int $page 0-based number of page being displayed
3841 * @return \core_tag\output\tagindex
3843 function course_get_tagged_course_modules($tag, $exclusivemode = false, $fromcontextid = 0, $contextid = 0,
3844 $recursivecontext = 1, $page = 0) {
3845 global $OUTPUT;
3846 $perpage = $exclusivemode ? 20 : 5;
3848 // Build select query.
3849 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
3850 $query = "SELECT cm.id AS cmid, c.id AS courseid, $ctxselect
3851 FROM {course_modules} cm
3852 JOIN {tag_instance} tt ON cm.id = tt.itemid
3853 JOIN {course} c ON cm.course = c.id
3854 JOIN {context} ctx ON ctx.instanceid = cm.id AND ctx.contextlevel = :coursemodulecontextlevel
3855 WHERE tt.itemtype = :itemtype AND tt.tagid = :tagid AND tt.component = :component
3856 AND cm.deletioninprogress = 0
3857 AND c.id %COURSEFILTER% AND cm.id %ITEMFILTER%";
3859 $params = array('itemtype' => 'course_modules', 'tagid' => $tag->id, 'component' => 'core',
3860 'coursemodulecontextlevel' => CONTEXT_MODULE);
3861 if ($contextid) {
3862 $context = context::instance_by_id($contextid);
3863 $query .= $recursivecontext ? ' AND (ctx.id = :contextid OR ctx.path LIKE :path)' : ' AND ctx.id = :contextid';
3864 $params['contextid'] = $context->id;
3865 $params['path'] = $context->path.'/%';
3868 $query .= ' ORDER BY';
3869 if ($fromcontextid) {
3870 // In order-clause specify that modules from inside "fromctx" context should be returned first.
3871 $fromcontext = context::instance_by_id($fromcontextid);
3872 $query .= ' (CASE WHEN ctx.id = :fromcontextid OR ctx.path LIKE :frompath THEN 0 ELSE 1 END),';
3873 $params['fromcontextid'] = $fromcontext->id;
3874 $params['frompath'] = $fromcontext->path.'/%';
3876 $query .= ' c.sortorder, cm.id';
3877 $totalpages = $page + 1;
3879 // Use core_tag_index_builder to build and filter the list of items.
3880 // Request one item more than we need so we know if next page exists.
3881 $builder = new core_tag_index_builder('core', 'course_modules', $query, $params, $page * $perpage, $perpage + 1);
3882 while ($item = $builder->has_item_that_needs_access_check()) {
3883 context_helper::preload_from_record($item);
3884 $courseid = $item->courseid;
3885 if (!$builder->can_access_course($courseid)) {
3886 $builder->set_accessible($item, false);
3887 continue;
3889 $modinfo = get_fast_modinfo($builder->get_course($courseid));
3890 // Set accessibility of this item and all other items in the same course.
3891 $builder->walk(function ($taggeditem) use ($courseid, $modinfo, $builder) {
3892 if ($taggeditem->courseid == $courseid) {
3893 $cm = $modinfo->get_cm($taggeditem->cmid);
3894 $builder->set_accessible($taggeditem, $cm->uservisible);
3899 $items = $builder->get_items();
3900 if (count($items) > $perpage) {
3901 $totalpages = $page + 2; // We don't need exact page count, just indicate that the next page exists.
3902 array_pop($items);
3905 // Build the display contents.
3906 if ($items) {
3907 $tagfeed = new core_tag\output\tagfeed();
3908 foreach ($items as $item) {
3909 context_helper::preload_from_record($item);
3910 $course = $builder->get_course($item->courseid);
3911 $modinfo = get_fast_modinfo($course);
3912 $cm = $modinfo->get_cm($item->cmid);
3913 $courseurl = course_get_url($item->courseid, $cm->sectionnum);
3914 $cmname = $cm->get_formatted_name();
3915 if (!$exclusivemode) {
3916 $cmname = shorten_text($cmname, 100);
3918 $cmname = html_writer::link($cm->url?:$courseurl, $cmname);
3919 $coursename = format_string($course->fullname, true,
3920 array('context' => context_course::instance($item->courseid)));
3921 $coursename = html_writer::link($courseurl, $coursename);
3922 $icon = html_writer::empty_tag('img', array('src' => $cm->get_icon_url()));
3923 $tagfeed->add($icon, $cmname, $coursename);
3926 $content = $OUTPUT->render_from_template('core_tag/tagfeed',
3927 $tagfeed->export_for_template($OUTPUT));
3929 return new core_tag\output\tagindex($tag, 'core', 'course_modules', $content,
3930 $exclusivemode, $fromcontextid, $contextid, $recursivecontext, $page, $totalpages);
3935 * Return an object with the list of navigation options in a course that are avaialable or not for the current user.
3936 * This function also handles the frontpage course.
3938 * @param stdClass $context context object (it can be a course context or the system context for frontpage settings)
3939 * @param stdClass $course the course where the settings are being rendered
3940 * @return stdClass the navigation options in a course and their availability status
3941 * @since Moodle 3.2
3943 function course_get_user_navigation_options($context, $course = null) {
3944 global $CFG;
3946 $isloggedin = isloggedin();
3947 $isguestuser = isguestuser();
3948 $isfrontpage = $context->contextlevel == CONTEXT_SYSTEM;
3950 if ($isfrontpage) {
3951 $sitecontext = $context;
3952 } else {
3953 $sitecontext = context_system::instance();
3956 // Sets defaults for all options.
3957 $options = (object) [
3958 'badges' => false,
3959 'blogs' => false,
3960 'calendar' => false,
3961 'competencies' => false,
3962 'grades' => false,
3963 'notes' => false,
3964 'participants' => false,
3965 'search' => false,
3966 'tags' => false,
3969 $options->blogs = !empty($CFG->enableblogs) &&
3970 ($CFG->bloglevel == BLOG_GLOBAL_LEVEL ||
3971 ($CFG->bloglevel == BLOG_SITE_LEVEL and ($isloggedin and !$isguestuser)))
3972 && has_capability('moodle/blog:view', $sitecontext);
3974 $options->notes = !empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $context);
3976 // Frontpage settings?
3977 if ($isfrontpage) {
3978 // We are on the front page, so make sure we use the proper capability (site:viewparticipants).
3979 $options->participants = course_can_view_participants($sitecontext);
3980 $options->badges = !empty($CFG->enablebadges) && has_capability('moodle/badges:viewbadges', $sitecontext);
3981 $options->tags = !empty($CFG->usetags) && $isloggedin;
3982 $options->search = !empty($CFG->enableglobalsearch) && has_capability('moodle/search:query', $sitecontext);
3983 $options->calendar = $isloggedin;
3984 } else {
3985 // We are in a course, so make sure we use the proper capability (course:viewparticipants).
3986 $options->participants = course_can_view_participants($context);
3987 $options->badges = !empty($CFG->enablebadges) && !empty($CFG->badges_allowcoursebadges) &&
3988 has_capability('moodle/badges:viewbadges', $context);
3989 // Add view grade report is permitted.
3990 $grades = false;
3992 if (has_capability('moodle/grade:viewall', $context)) {
3993 $grades = true;
3994 } else if (!empty($course->showgrades)) {
3995 $reports = core_component::get_plugin_list('gradereport');
3996 if (is_array($reports) && count($reports) > 0) { // Get all installed reports.
3997 arsort($reports); // User is last, we want to test it first.
3998 foreach ($reports as $plugin => $plugindir) {
3999 if (has_capability('gradereport/'.$plugin.':view', $context)) {
4000 // Stop when the first visible plugin is found.
4001 $grades = true;
4002 break;
4007 $options->grades = $grades;
4010 if (\core_competency\api::is_enabled()) {
4011 $capabilities = array('moodle/competency:coursecompetencyview', 'moodle/competency:coursecompetencymanage');
4012 $options->competencies = has_any_capability($capabilities, $context);
4014 return $options;
4018 * Return an object with the list of administration options in a course that are available or not for the current user.
4019 * This function also handles the frontpage settings.
4021 * @param stdClass $course course object (for frontpage it should be a clone of $SITE)
4022 * @param stdClass $context context object (course context)
4023 * @return stdClass the administration options in a course and their availability status
4024 * @since Moodle 3.2
4026 function course_get_user_administration_options($course, $context) {
4027 global $CFG;
4028 $isfrontpage = $course->id == SITEID;
4029 $completionenabled = $CFG->enablecompletion && $course->enablecompletion;
4030 $hascompletiontabs = count(core_completion\manager::get_available_completion_tabs($course, $context)) > 0;
4032 $options = new stdClass;
4033 $options->update = has_capability('moodle/course:update', $context);
4034 $options->editcompletion = $CFG->enablecompletion &&
4035 $course->enablecompletion &&
4036 ($options->update || $hascompletiontabs);
4037 $options->filters = has_capability('moodle/filter:manage', $context) &&
4038 count(filter_get_available_in_context($context)) > 0;
4039 $options->reports = has_capability('moodle/site:viewreports', $context);
4040 $options->backup = has_capability('moodle/backup:backupcourse', $context);
4041 $options->restore = has_capability('moodle/restore:restorecourse', $context);
4042 $options->files = ($course->legacyfiles == 2 && has_capability('moodle/course:managefiles', $context));
4044 if (!$isfrontpage) {
4045 $options->tags = has_capability('moodle/course:tag', $context);
4046 $options->gradebook = has_capability('moodle/grade:manage', $context);
4047 $options->outcomes = !empty($CFG->enableoutcomes) && has_capability('moodle/course:update', $context);
4048 $options->badges = !empty($CFG->enablebadges);
4049 $options->import = has_capability('moodle/restore:restoretargetimport', $context);
4050 $options->reset = has_capability('moodle/course:reset', $context);
4051 $options->roles = has_capability('moodle/role:switchroles', $context);
4052 } else {
4053 // Set default options to false.
4054 $listofoptions = array('tags', 'gradebook', 'outcomes', 'badges', 'import', 'publish', 'reset', 'roles', 'grades');
4056 foreach ($listofoptions as $option) {
4057 $options->$option = false;
4061 return $options;
4065 * Validates course start and end dates.
4067 * Checks that the end course date is not greater than the start course date.
4069 * $coursedata['startdate'] or $coursedata['enddate'] may not be set, it depends on the form and user input.
4071 * @param array $coursedata May contain startdate and enddate timestamps, depends on the user input.
4072 * @return mixed False if everything alright, error codes otherwise.
4074 function course_validate_dates($coursedata) {
4076 // If both start and end dates are set end date should be later than the start date.
4077 if (!empty($coursedata['startdate']) && !empty($coursedata['enddate']) &&
4078 ($coursedata['enddate'] < $coursedata['startdate'])) {
4079 return 'enddatebeforestartdate';
4082 // If start date is not set end date can not be set.
4083 if (empty($coursedata['startdate']) && !empty($coursedata['enddate'])) {
4084 return 'nostartdatenoenddate';
4087 return false;
4091 * Check for course updates in the given context level instances (only modules supported right Now)
4093 * @param stdClass $course course object
4094 * @param array $tocheck instances to check for updates
4095 * @param array $filter check only for updates in these areas
4096 * @return array list of warnings and instances with updates information
4097 * @since Moodle 3.2
4099 function course_check_updates($course, $tocheck, $filter = array()) {
4100 global $CFG, $DB;
4102 $instances = array();
4103 $warnings = array();
4104 $modulescallbacksupport = array();
4105 $modinfo = get_fast_modinfo($course);
4107 $supportedplugins = get_plugin_list_with_function('mod', 'check_updates_since');
4109 // Check instances.
4110 foreach ($tocheck as $instance) {
4111 if ($instance['contextlevel'] == 'module') {
4112 // Check module visibility.
4113 try {
4114 $cm = $modinfo->get_cm($instance['id']);
4115 } catch (Exception $e) {
4116 $warnings[] = array(
4117 'item' => 'module',
4118 'itemid' => $instance['id'],
4119 'warningcode' => 'cmidnotincourse',
4120 'message' => 'This module id does not belong to this course.'
4122 continue;
4125 if (!$cm->uservisible) {
4126 $warnings[] = array(
4127 'item' => 'module',
4128 'itemid' => $instance['id'],
4129 'warningcode' => 'nonuservisible',
4130 'message' => 'You don\'t have access to this module.'
4132 continue;
4134 if (empty($supportedplugins['mod_' . $cm->modname])) {
4135 $warnings[] = array(
4136 'item' => 'module',
4137 'itemid' => $instance['id'],
4138 'warningcode' => 'missingcallback',
4139 'message' => 'This module does not implement the check_updates_since callback: ' . $instance['contextlevel'],
4141 continue;
4143 // Retrieve the module instance.
4144 $instances[] = array(
4145 'contextlevel' => $instance['contextlevel'],
4146 'id' => $instance['id'],
4147 'updates' => call_user_func($cm->modname . '_check_updates_since', $cm, $instance['since'], $filter)
4150 } else {
4151 $warnings[] = array(
4152 'item' => 'contextlevel',
4153 'itemid' => $instance['id'],
4154 'warningcode' => 'contextlevelnotsupported',
4155 'message' => 'Context level not yet supported ' . $instance['contextlevel'],
4159 return array($instances, $warnings);
4163 * This function classifies a course as past, in progress or future.
4165 * This function may incur a DB hit to calculate course completion.
4166 * @param stdClass $course Course record
4167 * @param stdClass $user User record (optional - defaults to $USER).
4168 * @param completion_info $completioninfo Completion record for the user (optional - will be fetched if required).
4169 * @return string (one of COURSE_TIMELINE_FUTURE, COURSE_TIMELINE_INPROGRESS or COURSE_TIMELINE_PAST)
4171 function course_classify_for_timeline($course, $user = null, $completioninfo = null) {
4172 global $USER;
4174 if ($user == null) {
4175 $user = $USER;
4178 $today = time();
4179 // End date past.
4180 if (!empty($course->enddate) && (course_classify_end_date($course) < $today)) {
4181 return COURSE_TIMELINE_PAST;
4184 if ($completioninfo == null) {
4185 $completioninfo = new completion_info($course);
4188 // Course was completed.
4189 if ($completioninfo->is_enabled() && $completioninfo->is_course_complete($user->id)) {
4190 return COURSE_TIMELINE_PAST;
4193 // Start date not reached.
4194 if (!empty($course->startdate) && (course_classify_start_date($course) > $today)) {
4195 return COURSE_TIMELINE_FUTURE;
4198 // Everything else is in progress.
4199 return COURSE_TIMELINE_INPROGRESS;
4203 * This function calculates the end date to use for display classification purposes,
4204 * incorporating the grace period, if any.
4206 * @param stdClass $course The course record.
4207 * @return int The new enddate.
4209 function course_classify_end_date($course) {
4210 global $CFG;
4211 $coursegraceperiodafter = (empty($CFG->coursegraceperiodafter)) ? 0 : $CFG->coursegraceperiodafter;
4212 $enddate = (new \DateTimeImmutable())->setTimestamp($course->enddate)->modify("+{$coursegraceperiodafter} days");
4213 return $enddate->getTimestamp();
4217 * This function calculates the start date to use for display classification purposes,
4218 * incorporating the grace period, if any.
4220 * @param stdClass $course The course record.
4221 * @return int The new startdate.
4223 function course_classify_start_date($course) {
4224 global $CFG;
4225 $coursegraceperiodbefore = (empty($CFG->coursegraceperiodbefore)) ? 0 : $CFG->coursegraceperiodbefore;
4226 $startdate = (new \DateTimeImmutable())->setTimestamp($course->startdate)->modify("-{$coursegraceperiodbefore} days");
4227 return $startdate->getTimestamp();
4231 * Group a list of courses into either past, future, or in progress.
4233 * The return value will be an array indexed by the COURSE_TIMELINE_* constants
4234 * with each value being an array of courses in that group.
4235 * E.g.
4237 * COURSE_TIMELINE_PAST => [... list of past courses ...],
4238 * COURSE_TIMELINE_FUTURE => [],
4239 * COURSE_TIMELINE_INPROGRESS => []
4242 * @param array $courses List of courses to be grouped.
4243 * @return array
4245 function course_classify_courses_for_timeline(array $courses) {
4246 return array_reduce($courses, function($carry, $course) {
4247 $classification = course_classify_for_timeline($course);
4248 array_push($carry[$classification], $course);
4250 return $carry;
4251 }, [
4252 COURSE_TIMELINE_PAST => [],
4253 COURSE_TIMELINE_FUTURE => [],
4254 COURSE_TIMELINE_INPROGRESS => []
4259 * Get the list of enrolled courses for the current user.
4261 * This function returns a Generator. The courses will be loaded from the database
4262 * in chunks rather than a single query.
4264 * @param int $limit Restrict result set to this amount
4265 * @param int $offset Skip this number of records from the start of the result set
4266 * @param string|null $sort SQL string for sorting
4267 * @param string|null $fields SQL string for fields to be returned
4268 * @param int $dbquerylimit The number of records to load per DB request
4269 * @param array $includecourses courses ids to be restricted
4270 * @param array $hiddencourses courses ids to be excluded
4271 * @return Generator
4273 function course_get_enrolled_courses_for_logged_in_user(
4274 int $limit = 0,
4275 int $offset = 0,
4276 string $sort = null,
4277 string $fields = null,
4278 int $dbquerylimit = COURSE_DB_QUERY_LIMIT,
4279 array $includecourses = [],
4280 array $hiddencourses = []
4281 ) : Generator {
4283 $haslimit = !empty($limit);
4284 $recordsloaded = 0;
4285 $querylimit = (!$haslimit || $limit > $dbquerylimit) ? $dbquerylimit : $limit;
4287 while ($courses = enrol_get_my_courses($fields, $sort, $querylimit, $includecourses, false, $offset, $hiddencourses)) {
4288 yield from $courses;
4290 $recordsloaded += $querylimit;
4292 if (count($courses) < $querylimit) {
4293 break;
4295 if ($haslimit && $recordsloaded >= $limit) {
4296 break;
4299 $offset += $querylimit;
4304 * Search the given $courses for any that match the given $classification up to the specified
4305 * $limit.
4307 * This function will return the subset of courses that match the classification as well as the
4308 * number of courses it had to process to build that subset.
4310 * It is recommended that for larger sets of courses this function is given a Generator that loads
4311 * the courses from the database in chunks.
4313 * @param array|Traversable $courses List of courses to process
4314 * @param string $classification One of the COURSE_TIMELINE_* constants
4315 * @param int $limit Limit the number of results to this amount
4316 * @return array First value is the filtered courses, second value is the number of courses processed
4318 function course_filter_courses_by_timeline_classification(
4319 $courses,
4320 string $classification,
4321 int $limit = 0
4322 ) : array {
4324 if (!in_array($classification,
4325 [COURSE_TIMELINE_ALLINCLUDINGHIDDEN, COURSE_TIMELINE_ALL, COURSE_TIMELINE_PAST, COURSE_TIMELINE_INPROGRESS,
4326 COURSE_TIMELINE_FUTURE, COURSE_TIMELINE_HIDDEN])) {
4327 $message = 'Classification must be one of COURSE_TIMELINE_ALLINCLUDINGHIDDEN, COURSE_TIMELINE_ALL, COURSE_TIMELINE_PAST, '
4328 . 'COURSE_TIMELINE_INPROGRESS or COURSE_TIMELINE_FUTURE';
4329 throw new moodle_exception($message);
4332 $filteredcourses = [];
4333 $numberofcoursesprocessed = 0;
4334 $filtermatches = 0;
4336 foreach ($courses as $course) {
4337 $numberofcoursesprocessed++;
4338 $pref = get_user_preferences('block_myoverview_hidden_course_' . $course->id, 0);
4340 // Added as of MDL-63457 toggle viewability for each user.
4341 if ($classification == COURSE_TIMELINE_ALLINCLUDINGHIDDEN || ($classification == COURSE_TIMELINE_HIDDEN && $pref) ||
4342 (($classification == COURSE_TIMELINE_ALL || $classification == course_classify_for_timeline($course)) && !$pref)) {
4343 $filteredcourses[] = $course;
4344 $filtermatches++;
4347 if ($limit && $filtermatches >= $limit) {
4348 // We've found the number of requested courses. No need to continue searching.
4349 break;
4353 // Return the number of filtered courses as well as the number of courses that were searched
4354 // in order to find the matching courses. This allows the calling code to do some kind of
4355 // pagination.
4356 return [$filteredcourses, $numberofcoursesprocessed];
4360 * Search the given $courses for any that match the given $classification up to the specified
4361 * $limit.
4363 * This function will return the subset of courses that are favourites as well as the
4364 * number of courses it had to process to build that subset.
4366 * It is recommended that for larger sets of courses this function is given a Generator that loads
4367 * the courses from the database in chunks.
4369 * @param array|Traversable $courses List of courses to process
4370 * @param array $favouritecourseids Array of favourite courses.
4371 * @param int $limit Limit the number of results to this amount
4372 * @return array First value is the filtered courses, second value is the number of courses processed
4374 function course_filter_courses_by_favourites(
4375 $courses,
4376 $favouritecourseids,
4377 int $limit = 0
4378 ) : array {
4380 $filteredcourses = [];
4381 $numberofcoursesprocessed = 0;
4382 $filtermatches = 0;
4384 foreach ($courses as $course) {
4385 $numberofcoursesprocessed++;
4387 if (in_array($course->id, $favouritecourseids)) {
4388 $filteredcourses[] = $course;
4389 $filtermatches++;
4392 if ($limit && $filtermatches >= $limit) {
4393 // We've found the number of requested courses. No need to continue searching.
4394 break;
4398 // Return the number of filtered courses as well as the number of courses that were searched
4399 // in order to find the matching courses. This allows the calling code to do some kind of
4400 // pagination.
4401 return [$filteredcourses, $numberofcoursesprocessed];
4405 * Search the given $courses for any that have a $customfieldname value that matches the given
4406 * $customfieldvalue, up to the specified $limit.
4408 * This function will return the subset of courses that matches the value as well as the
4409 * number of courses it had to process to build that subset.
4411 * It is recommended that for larger sets of courses this function is given a Generator that loads
4412 * the courses from the database in chunks.
4414 * @param array|Traversable $courses List of courses to process
4415 * @param string $customfieldname the shortname of the custom field to match against
4416 * @param string $customfieldvalue the value this custom field needs to match
4417 * @param int $limit Limit the number of results to this amount
4418 * @return array First value is the filtered courses, second value is the number of courses processed
4420 function course_filter_courses_by_customfield(
4421 $courses,
4422 $customfieldname,
4423 $customfieldvalue,
4424 int $limit = 0
4425 ) : array {
4426 global $DB;
4428 if (!$courses) {
4429 return [[], 0];
4432 // Prepare the list of courses to search through.
4433 $coursesbyid = [];
4434 foreach ($courses as $course) {
4435 $coursesbyid[$course->id] = $course;
4437 if (!$coursesbyid) {
4438 return [[], 0];
4440 list($csql, $params) = $DB->get_in_or_equal(array_keys($coursesbyid), SQL_PARAMS_NAMED);
4442 // Get the id of the custom field.
4443 $sql = "
4444 SELECT f.id
4445 FROM {customfield_field} f
4446 JOIN {customfield_category} cat ON cat.id = f.categoryid
4447 WHERE f.shortname = ?
4448 AND cat.component = 'core_course'
4449 AND cat.area = 'course'
4451 $fieldid = $DB->get_field_sql($sql, [$customfieldname]);
4452 if (!$fieldid) {
4453 return [[], 0];
4456 // Get a list of courseids that match that custom field value.
4457 if ($customfieldvalue == COURSE_CUSTOMFIELD_EMPTY) {
4458 $comparevalue = $DB->sql_compare_text('cd.value');
4459 $sql = "
4460 SELECT c.id
4461 FROM {course} c
4462 LEFT JOIN {customfield_data} cd ON cd.instanceid = c.id AND cd.fieldid = :fieldid
4463 WHERE c.id $csql
4464 AND (cd.value IS NULL OR $comparevalue = '' OR $comparevalue = '0')
4466 $params['fieldid'] = $fieldid;
4467 $matchcourseids = $DB->get_fieldset_sql($sql, $params);
4468 } else {
4469 $comparevalue = $DB->sql_compare_text('value');
4470 $select = "fieldid = :fieldid AND $comparevalue = :customfieldvalue AND instanceid $csql";
4471 $params['fieldid'] = $fieldid;
4472 $params['customfieldvalue'] = $customfieldvalue;
4473 $matchcourseids = $DB->get_fieldset_select('customfield_data', 'instanceid', $select, $params);
4476 // Prepare the list of courses to return.
4477 $filteredcourses = [];
4478 $numberofcoursesprocessed = 0;
4479 $filtermatches = 0;
4481 foreach ($coursesbyid as $course) {
4482 $numberofcoursesprocessed++;
4484 if (in_array($course->id, $matchcourseids)) {
4485 $filteredcourses[] = $course;
4486 $filtermatches++;
4489 if ($limit && $filtermatches >= $limit) {
4490 // We've found the number of requested courses. No need to continue searching.
4491 break;
4495 // Return the number of filtered courses as well as the number of courses that were searched
4496 // in order to find the matching courses. This allows the calling code to do some kind of
4497 // pagination.
4498 return [$filteredcourses, $numberofcoursesprocessed];
4502 * Check module updates since a given time.
4503 * This function checks for updates in the module config, file areas, completion, grades, comments and ratings.
4505 * @param cm_info $cm course module data
4506 * @param int $from the time to check
4507 * @param array $fileareas additional file ares to check
4508 * @param array $filter if we need to filter and return only selected updates
4509 * @return stdClass object with the different updates
4510 * @since Moodle 3.2
4512 function course_check_module_updates_since($cm, $from, $fileareas = array(), $filter = array()) {
4513 global $DB, $CFG, $USER;
4515 $context = $cm->context;
4516 $mod = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
4518 $updates = new stdClass();
4519 $course = get_course($cm->course);
4520 $component = 'mod_' . $cm->modname;
4522 // Check changes in the module configuration.
4523 if (isset($mod->timemodified) and (empty($filter) or in_array('configuration', $filter))) {
4524 $updates->configuration = (object) array('updated' => false);
4525 if ($updates->configuration->updated = $mod->timemodified > $from) {
4526 $updates->configuration->timeupdated = $mod->timemodified;
4530 // Check for updates in files.
4531 if (plugin_supports('mod', $cm->modname, FEATURE_MOD_INTRO)) {
4532 $fileareas[] = 'intro';
4534 if (!empty($fileareas) and (empty($filter) or in_array('fileareas', $filter))) {
4535 $fs = get_file_storage();
4536 $files = $fs->get_area_files($context->id, $component, $fileareas, false, "filearea, timemodified DESC", false, $from);
4537 foreach ($fileareas as $filearea) {
4538 $updates->{$filearea . 'files'} = (object) array('updated' => false);
4540 foreach ($files as $file) {
4541 $updates->{$file->get_filearea() . 'files'}->updated = true;
4542 $updates->{$file->get_filearea() . 'files'}->itemids[] = $file->get_id();
4546 // Check completion.
4547 $supportcompletion = plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_HAS_RULES);
4548 $supportcompletion = $supportcompletion or plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_TRACKS_VIEWS);
4549 if ($supportcompletion and (empty($filter) or in_array('completion', $filter))) {
4550 $updates->completion = (object) array('updated' => false);
4551 $completion = new completion_info($course);
4552 // Use wholecourse to cache all the modules the first time.
4553 $completiondata = $completion->get_data($cm, true);
4554 if ($updates->completion->updated = !empty($completiondata->timemodified) && $completiondata->timemodified > $from) {
4555 $updates->completion->timemodified = $completiondata->timemodified;
4559 // Check grades.
4560 $supportgrades = plugin_supports('mod', $cm->modname, FEATURE_GRADE_HAS_GRADE);
4561 $supportgrades = $supportgrades or plugin_supports('mod', $cm->modname, FEATURE_GRADE_OUTCOMES);
4562 if ($supportgrades and (empty($filter) or (in_array('gradeitems', $filter) or in_array('outcomes', $filter)))) {
4563 require_once($CFG->libdir . '/gradelib.php');
4564 $grades = grade_get_grades($course->id, 'mod', $cm->modname, $mod->id, $USER->id);
4566 if (empty($filter) or in_array('gradeitems', $filter)) {
4567 $updates->gradeitems = (object) array('updated' => false);
4568 foreach ($grades->items as $gradeitem) {
4569 foreach ($gradeitem->grades as $grade) {
4570 if ($grade->datesubmitted > $from or $grade->dategraded > $from) {
4571 $updates->gradeitems->updated = true;
4572 $updates->gradeitems->itemids[] = $gradeitem->id;
4578 if (empty($filter) or in_array('outcomes', $filter)) {
4579 $updates->outcomes = (object) array('updated' => false);
4580 foreach ($grades->outcomes as $outcome) {
4581 foreach ($outcome->grades as $grade) {
4582 if ($grade->datesubmitted > $from or $grade->dategraded > $from) {
4583 $updates->outcomes->updated = true;
4584 $updates->outcomes->itemids[] = $outcome->id;
4591 // Check comments.
4592 if (plugin_supports('mod', $cm->modname, FEATURE_COMMENT) and (empty($filter) or in_array('comments', $filter))) {
4593 $updates->comments = (object) array('updated' => false);
4594 require_once($CFG->dirroot . '/comment/lib.php');
4595 require_once($CFG->dirroot . '/comment/locallib.php');
4596 $manager = new comment_manager();
4597 $comments = $manager->get_component_comments_since($course, $context, $component, $from, $cm);
4598 if (!empty($comments)) {
4599 $updates->comments->updated = true;
4600 $updates->comments->itemids = array_keys($comments);
4604 // Check ratings.
4605 if (plugin_supports('mod', $cm->modname, FEATURE_RATE) and (empty($filter) or in_array('ratings', $filter))) {
4606 $updates->ratings = (object) array('updated' => false);
4607 require_once($CFG->dirroot . '/rating/lib.php');
4608 $manager = new rating_manager();
4609 $ratings = $manager->get_component_ratings_since($context, $component, $from);
4610 if (!empty($ratings)) {
4611 $updates->ratings->updated = true;
4612 $updates->ratings->itemids = array_keys($ratings);
4616 return $updates;
4620 * Returns true if the user can view the participant page, false otherwise,
4622 * @param context $context The context we are checking.
4623 * @return bool
4625 function course_can_view_participants($context) {
4626 $viewparticipantscap = 'moodle/course:viewparticipants';
4627 if ($context->contextlevel == CONTEXT_SYSTEM) {
4628 $viewparticipantscap = 'moodle/site:viewparticipants';
4631 return has_any_capability([$viewparticipantscap, 'moodle/course:enrolreview'], $context);
4635 * Checks if a user can view the participant page, if not throws an exception.
4637 * @param context $context The context we are checking.
4638 * @throws required_capability_exception
4640 function course_require_view_participants($context) {
4641 if (!course_can_view_participants($context)) {
4642 $viewparticipantscap = 'moodle/course:viewparticipants';
4643 if ($context->contextlevel == CONTEXT_SYSTEM) {
4644 $viewparticipantscap = 'moodle/site:viewparticipants';
4646 throw new required_capability_exception($context, $viewparticipantscap, 'nopermissions', '');
4651 * Return whether the user can download from the specified backup file area in the given context.
4653 * @param string $filearea the backup file area. E.g. 'course', 'backup' or 'automated'.
4654 * @param \context $context
4655 * @param stdClass $user the user object. If not provided, the current user will be checked.
4656 * @return bool true if the user is allowed to download in the context, false otherwise.
4658 function can_download_from_backup_filearea($filearea, \context $context, stdClass $user = null) {
4659 $candownload = false;
4660 switch ($filearea) {
4661 case 'course':
4662 case 'backup':
4663 $candownload = has_capability('moodle/backup:downloadfile', $context, $user);
4664 break;
4665 case 'automated':
4666 // Given the automated backups may contain userinfo, we restrict access such that only users who are able to
4667 // restore with userinfo are able to download the file. Users can't create these backups, so checking 'backup:userinfo'
4668 // doesn't make sense here.
4669 $candownload = has_capability('moodle/backup:downloadfile', $context, $user) &&
4670 has_capability('moodle/restore:userinfo', $context, $user);
4671 break;
4672 default:
4673 break;
4676 return $candownload;
4680 * Get a list of hidden courses
4682 * @param int|object|null $user User override to get the filter from. Defaults to current user
4683 * @return array $ids List of hidden courses
4684 * @throws coding_exception
4686 function get_hidden_courses_on_timeline($user = null) {
4687 global $USER;
4689 if (empty($user)) {
4690 $user = $USER->id;
4693 $preferences = get_user_preferences(null, null, $user);
4694 $ids = [];
4695 foreach ($preferences as $key => $value) {
4696 if (preg_match('/block_myoverview_hidden_course_(\d)+/', $key)) {
4697 $id = preg_split('/block_myoverview_hidden_course_/', $key);
4698 $ids[] = $id[1];
4702 return $ids;
4706 * Returns a list of the most recently courses accessed by a user
4708 * @param int $userid User id from which the courses will be obtained
4709 * @param int $limit Restrict result set to this amount
4710 * @param int $offset Skip this number of records from the start of the result set
4711 * @param string|null $sort SQL string for sorting
4712 * @return array
4714 function course_get_recent_courses(int $userid = null, int $limit = 0, int $offset = 0, string $sort = null) {
4716 global $CFG, $USER, $DB;
4718 if (empty($userid)) {
4719 $userid = $USER->id;
4722 $basefields = array('id', 'idnumber', 'summary', 'summaryformat', 'startdate', 'enddate', 'category',
4723 'shortname', 'fullname', 'timeaccess', 'component', 'visible');
4725 $sort = trim($sort);
4726 if (empty($sort)) {
4727 $sort = 'timeaccess DESC';
4728 } else {
4729 $rawsorts = explode(',', $sort);
4730 $sorts = array();
4731 foreach ($rawsorts as $rawsort) {
4732 $rawsort = trim($rawsort);
4733 $sorts[] = trim($rawsort);
4735 $sort = implode(',', $sorts);
4738 $orderby = "ORDER BY $sort";
4740 $ctxfields = context_helper::get_preload_record_columns_sql('ctx');
4742 $coursefields = 'c.' .join(',', $basefields);
4744 // Ask the favourites service to give us the join SQL for favourited courses,
4745 // so we can include favourite information in the query.
4746 $usercontext = \context_user::instance($userid);
4747 $favservice = \core_favourites\service_factory::get_service_for_user_context($usercontext);
4748 list($favsql, $favparams) = $favservice->get_join_sql_by_type('core_course', 'courses', 'fav', 'ul.courseid');
4750 $sql = "SELECT $coursefields, $ctxfields
4751 FROM {course} c
4752 JOIN {context} ctx
4753 ON ctx.contextlevel = :contextlevel
4754 AND ctx.instanceid = c.id
4755 JOIN {user_lastaccess} ul
4756 ON ul.courseid = c.id
4757 $favsql
4758 WHERE ul.userid = :userid
4759 AND c.visible = :visible
4760 AND EXISTS (SELECT e.id
4761 FROM {enrol} e
4762 LEFT JOIN {user_enrolments} ue ON ue.enrolid = e.id
4763 WHERE e.courseid = c.id
4764 AND e.status = :statusenrol
4765 AND ((ue.status = :status
4766 AND ue.userid = ul.userid
4767 AND ue.timestart < :now1
4768 AND (ue.timeend = 0 OR ue.timeend > :now2)
4770 OR e.enrol = :guestenrol
4773 $orderby";
4775 $now = round(time(), -2); // Improves db caching.
4776 $params = ['userid' => $userid, 'contextlevel' => CONTEXT_COURSE, 'visible' => 1, 'status' => ENROL_USER_ACTIVE,
4777 'statusenrol' => ENROL_INSTANCE_ENABLED, 'guestenrol' => 'guest', 'now1' => $now, 'now2' => $now] + $favparams;
4779 $recentcourses = $DB->get_records_sql($sql, $params, $offset, $limit);
4781 // Filter courses if last access field is hidden.
4782 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
4784 if ($userid != $USER->id && isset($hiddenfields['lastaccess'])) {
4785 $recentcourses = array_filter($recentcourses, function($course) {
4786 context_helper::preload_from_record($course);
4787 $context = context_course::instance($course->id, IGNORE_MISSING);
4788 // If last access was a hidden field, a user requesting info about another user would need permission to view hidden
4789 // fields.
4790 return has_capability('moodle/course:viewhiddenuserfields', $context);
4794 return $recentcourses;
4798 * Calculate the course start date and offset for the given user ids.
4800 * If the course is a fixed date course then the course start date will be returned.
4801 * If the course is a relative date course then the course date will be calculated and
4802 * and offset provided.
4804 * The dates are returned as an array with the index being the user id. The array
4805 * contains the start date and start offset values for the user.
4807 * If the user is not enrolled in the course then the course start date will be returned.
4809 * If we have a course which starts on 1563244000 and 2 users, id 123 and 456, where the
4810 * former is enrolled in the course at 1563244693 and the latter is not enrolled then the
4811 * return value would look like:
4813 * '123' => [
4814 * 'start' => 1563244693,
4815 * 'startoffset' => 693
4816 * ],
4817 * '456' => [
4818 * 'start' => 1563244000,
4819 * 'startoffset' => 0
4823 * @param stdClass $course The course to fetch dates for.
4824 * @param array $userids The list of user ids to get dates for.
4825 * @return array
4827 function course_get_course_dates_for_user_ids(stdClass $course, array $userids): array {
4828 if (empty($course->relativedatesmode)) {
4829 // This course isn't set to relative dates so we can early return with the course
4830 // start date.
4831 return array_reduce($userids, function($carry, $userid) use ($course) {
4832 $carry[$userid] = [
4833 'start' => $course->startdate,
4834 'startoffset' => 0
4836 return $carry;
4837 }, []);
4840 // We're dealing with a relative dates course now so we need to calculate some dates.
4841 $cache = cache::make('core', 'course_user_dates');
4842 $dates = [];
4843 $uncacheduserids = [];
4845 // Try fetching the values from the cache so that we don't need to do a DB request.
4846 foreach ($userids as $userid) {
4847 $cachekey = "{$course->id}_{$userid}";
4848 $cachedvalue = $cache->get($cachekey);
4850 if ($cachedvalue === false) {
4851 // Looks like we haven't seen this user for this course before so we'll have
4852 // to fetch it.
4853 $uncacheduserids[] = $userid;
4854 } else {
4855 [$start, $startoffset] = $cachedvalue;
4856 $dates[$userid] = [
4857 'start' => $start,
4858 'startoffset' => $startoffset
4863 if (!empty($uncacheduserids)) {
4864 // Load the enrolments for any users we haven't seen yet. Set the "onlyactive" param
4865 // to false because it filters out users with enrolment start times in the future which
4866 // we don't want.
4867 $enrolments = enrol_get_course_users($course->id, false, $uncacheduserids);
4869 foreach ($uncacheduserids as $userid) {
4870 // Find the user enrolment that has the earliest start date.
4871 $enrolment = array_reduce(array_values($enrolments), function($carry, $enrolment) use ($userid) {
4872 // Only consider enrolments for this user if the user enrolment is active and the
4873 // enrolment method is enabled.
4874 if (
4875 $enrolment->uestatus == ENROL_USER_ACTIVE &&
4876 $enrolment->estatus == ENROL_INSTANCE_ENABLED &&
4877 $enrolment->id == $userid
4879 if (is_null($carry)) {
4880 // Haven't found an enrolment yet for this user so use the one we just found.
4881 $carry = $enrolment;
4882 } else {
4883 // We've already found an enrolment for this user so let's use which ever one
4884 // has the earliest start time.
4885 $carry = $carry->uetimestart < $enrolment->uetimestart ? $carry : $enrolment;
4889 return $carry;
4890 }, null);
4892 if ($enrolment) {
4893 // The course is in relative dates mode so we calculate the student's start
4894 // date based on their enrolment start date.
4895 $start = $course->startdate > $enrolment->uetimestart ? $course->startdate : $enrolment->uetimestart;
4896 $startoffset = $start - $course->startdate;
4897 } else {
4898 // The user is not enrolled in the course so default back to the course start date.
4899 $start = $course->startdate;
4900 $startoffset = 0;
4903 $dates[$userid] = [
4904 'start' => $start,
4905 'startoffset' => $startoffset
4908 $cachekey = "{$course->id}_{$userid}";
4909 $cache->set($cachekey, [$start, $startoffset]);
4913 return $dates;
4917 * Calculate the course start date and offset for the given user id.
4919 * If the course is a fixed date course then the course start date will be returned.
4920 * If the course is a relative date course then the course date will be calculated and
4921 * and offset provided.
4923 * The return array contains the start date and start offset values for the user.
4925 * If the user is not enrolled in the course then the course start date will be returned.
4927 * If we have a course which starts on 1563244000. If a user's enrolment starts on 1563244693
4928 * then the return would be:
4930 * 'start' => 1563244693,
4931 * 'startoffset' => 693
4934 * If the use was not enrolled then the return would be:
4936 * 'start' => 1563244000,
4937 * 'startoffset' => 0
4940 * @param stdClass $course The course to fetch dates for.
4941 * @param int $userid The user id to get dates for.
4942 * @return array
4944 function course_get_course_dates_for_user_id(stdClass $course, int $userid): array {
4945 return (course_get_course_dates_for_user_ids($course, [$userid]))[$userid];