MDL-66504 lang: Apply cantblockuser changes to behat tests
[moodle.git] / course / lib.php
blob3eec792058e91be6825d6b54a9f9dc225b3d488a
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_DB_QUERY_LIMIT', 1000);
68 function make_log_url($module, $url) {
69 switch ($module) {
70 case 'course':
71 if (strpos($url, 'report/') === 0) {
72 // there is only one report type, course reports are deprecated
73 $url = "/$url";
74 break;
76 case 'file':
77 case 'login':
78 case 'lib':
79 case 'admin':
80 case 'category':
81 case 'mnet course':
82 if (strpos($url, '../') === 0) {
83 $url = ltrim($url, '.');
84 } else {
85 $url = "/course/$url";
87 break;
88 case 'calendar':
89 $url = "/calendar/$url";
90 break;
91 case 'user':
92 case 'blog':
93 $url = "/$module/$url";
94 break;
95 case 'upload':
96 $url = $url;
97 break;
98 case 'coursetags':
99 $url = '/'.$url;
100 break;
101 case 'library':
102 case '':
103 $url = '/';
104 break;
105 case 'message':
106 $url = "/message/$url";
107 break;
108 case 'notes':
109 $url = "/notes/$url";
110 break;
111 case 'tag':
112 $url = "/tag/$url";
113 break;
114 case 'role':
115 $url = '/'.$url;
116 break;
117 case 'grade':
118 $url = "/grade/$url";
119 break;
120 default:
121 $url = "/mod/$module/$url";
122 break;
125 //now let's sanitise urls - there might be some ugly nasties:-(
126 $parts = explode('?', $url);
127 $script = array_shift($parts);
128 if (strpos($script, 'http') === 0) {
129 $script = clean_param($script, PARAM_URL);
130 } else {
131 $script = clean_param($script, PARAM_PATH);
134 $query = '';
135 if ($parts) {
136 $query = implode('', $parts);
137 $query = str_replace('&amp;', '&', $query); // both & and &amp; are stored in db :-|
138 $parts = explode('&', $query);
139 $eq = urlencode('=');
140 foreach ($parts as $key=>$part) {
141 $part = urlencode(urldecode($part));
142 $part = str_replace($eq, '=', $part);
143 $parts[$key] = $part;
145 $query = '?'.implode('&amp;', $parts);
148 return $script.$query;
152 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
153 $modname="", $modid=0, $modaction="", $groupid=0) {
154 global $CFG, $DB;
156 // It is assumed that $date is the GMT time of midnight for that day,
157 // and so the next 86400 seconds worth of logs are printed.
159 /// Setup for group handling.
161 // TODO: I don't understand group/context/etc. enough to be able to do
162 // something interesting with it here
163 // What is the context of a remote course?
165 /// If the group mode is separate, and this user does not have editing privileges,
166 /// then only the user's group can be viewed.
167 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
168 // $groupid = get_current_group($course->id);
170 /// If this course doesn't have groups, no groupid can be specified.
171 //else if (!$course->groupmode) {
172 // $groupid = 0;
175 $groupid = 0;
177 $joins = array();
178 $where = '';
180 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
181 FROM {mnet_log} l
182 LEFT JOIN {user} u ON l.userid = u.id
183 WHERE ";
184 $params = array();
186 $where .= "l.hostid = :hostid";
187 $params['hostid'] = $hostid;
189 // TODO: Is 1 really a magic number referring to the sitename?
190 if ($course != SITEID || $modid != 0) {
191 $where .= " AND l.course=:courseid";
192 $params['courseid'] = $course;
195 if ($modname) {
196 $where .= " AND l.module = :modname";
197 $params['modname'] = $modname;
200 if ('site_errors' === $modid) {
201 $where .= " AND ( l.action='error' OR l.action='infected' )";
202 } else if ($modid) {
203 //TODO: This assumes that modids are the same across sites... probably
204 //not true
205 $where .= " AND l.cmid = :modid";
206 $params['modid'] = $modid;
209 if ($modaction) {
210 $firstletter = substr($modaction, 0, 1);
211 if ($firstletter == '-') {
212 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
213 $params['modaction'] = '%'.substr($modaction, 1).'%';
214 } else {
215 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
216 $params['modaction'] = '%'.$modaction.'%';
220 if ($user) {
221 $where .= " AND l.userid = :user";
222 $params['user'] = $user;
225 if ($date) {
226 $enddate = $date + 86400;
227 $where .= " AND l.time > :date AND l.time < :enddate";
228 $params['date'] = $date;
229 $params['enddate'] = $enddate;
232 $result = array();
233 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
234 if(!empty($result['totalcount'])) {
235 $where .= " ORDER BY $order";
236 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
237 } else {
238 $result['logs'] = array();
240 return $result;
244 * Checks the integrity of the course data.
246 * In summary - compares course_sections.sequence and course_modules.section.
248 * More detailed, checks that:
249 * - course_sections.sequence contains each module id not more than once in the course
250 * - for each moduleid from course_sections.sequence the field course_modules.section
251 * refers to the same section id (this means course_sections.sequence is more
252 * important if they are different)
253 * - ($fullcheck only) each module in the course is present in one of
254 * course_sections.sequence
255 * - ($fullcheck only) removes non-existing course modules from section sequences
257 * If there are any mismatches, the changes are made and records are updated in DB.
259 * Course cache is NOT rebuilt if there are any errors!
261 * This function is used each time when course cache is being rebuilt with $fullcheck = false
262 * and in CLI script admin/cli/fix_course_sequence.php with $fullcheck = true
264 * @param int $courseid id of the course
265 * @param array $rawmods result of funciton {@link get_course_mods()} - containst
266 * the list of enabled course modules in the course. Retrieved from DB if not specified.
267 * Argument ignored in cashe of $fullcheck, the list is retrieved form DB anyway.
268 * @param array $sections records from course_sections table for this course.
269 * Retrieved from DB if not specified
270 * @param bool $fullcheck Will add orphaned modules to their sections and remove non-existing
271 * course modules from sequences. Only to be used in site maintenance mode when we are
272 * sure that another user is not in the middle of the process of moving/removing a module.
273 * @param bool $checkonly Only performs the check without updating DB, outputs all errors as debug messages.
274 * @return array array of messages with found problems. Empty output means everything is ok
276 function course_integrity_check($courseid, $rawmods = null, $sections = null, $fullcheck = false, $checkonly = false) {
277 global $DB;
278 $messages = array();
279 if ($sections === null) {
280 $sections = $DB->get_records('course_sections', array('course' => $courseid), 'section', 'id,section,sequence');
282 if ($fullcheck) {
283 // Retrieve all records from course_modules regardless of module type visibility.
284 $rawmods = $DB->get_records('course_modules', array('course' => $courseid), 'id', 'id,section');
286 if ($rawmods === null) {
287 $rawmods = get_course_mods($courseid);
289 if (!$fullcheck && (empty($sections) || empty($rawmods))) {
290 // If either of the arrays is empty, no modules are displayed anyway.
291 return true;
293 $debuggingprefix = 'Failed integrity check for course ['.$courseid.']. ';
295 // First make sure that each module id appears in section sequences only once.
296 // If it appears in several section sequences the last section wins.
297 // If it appears twice in one section sequence, the first occurence wins.
298 $modsection = array();
299 foreach ($sections as $sectionid => $section) {
300 $sections[$sectionid]->newsequence = $section->sequence;
301 if (!empty($section->sequence)) {
302 $sequence = explode(",", $section->sequence);
303 $sequenceunique = array_unique($sequence);
304 if (count($sequenceunique) != count($sequence)) {
305 // Some course module id appears in this section sequence more than once.
306 ksort($sequenceunique); // Preserve initial order of modules.
307 $sequence = array_values($sequenceunique);
308 $sections[$sectionid]->newsequence = join(',', $sequence);
309 $messages[] = $debuggingprefix.'Sequence for course section ['.
310 $sectionid.'] is "'.$sections[$sectionid]->sequence.'", must be "'.$sections[$sectionid]->newsequence.'"';
312 foreach ($sequence as $cmid) {
313 if (array_key_exists($cmid, $modsection) && isset($rawmods[$cmid])) {
314 // Some course module id appears to be in more than one section's sequences.
315 $wrongsectionid = $modsection[$cmid];
316 $sections[$wrongsectionid]->newsequence = trim(preg_replace("/,$cmid,/", ',', ','.$sections[$wrongsectionid]->newsequence. ','), ',');
317 $messages[] = $debuggingprefix.'Course module ['.$cmid.'] must be removed from sequence of section ['.
318 $wrongsectionid.'] because it is also present in sequence of section ['.$sectionid.']';
320 $modsection[$cmid] = $sectionid;
325 // Add orphaned modules to their sections if they exist or to section 0 otherwise.
326 if ($fullcheck) {
327 foreach ($rawmods as $cmid => $mod) {
328 if (!isset($modsection[$cmid])) {
329 // This is a module that is not mentioned in course_section.sequence at all.
330 // Add it to the section $mod->section or to the last available section.
331 if ($mod->section && isset($sections[$mod->section])) {
332 $modsection[$cmid] = $mod->section;
333 } else {
334 $firstsection = reset($sections);
335 $modsection[$cmid] = $firstsection->id;
337 $sections[$modsection[$cmid]]->newsequence = trim($sections[$modsection[$cmid]]->newsequence.','.$cmid, ',');
338 $messages[] = $debuggingprefix.'Course module ['.$cmid.'] is missing from sequence of section ['.
339 $modsection[$cmid].']';
342 foreach ($modsection as $cmid => $sectionid) {
343 if (!isset($rawmods[$cmid])) {
344 // Section $sectionid refers to module id that does not exist.
345 $sections[$sectionid]->newsequence = trim(preg_replace("/,$cmid,/", ',', ','.$sections[$sectionid]->newsequence.','), ',');
346 $messages[] = $debuggingprefix.'Course module ['.$cmid.
347 '] does not exist but is present in the sequence of section ['.$sectionid.']';
352 // Update changed sections.
353 if (!$checkonly && !empty($messages)) {
354 foreach ($sections as $sectionid => $section) {
355 if ($section->newsequence !== $section->sequence) {
356 $DB->update_record('course_sections', array('id' => $sectionid, 'sequence' => $section->newsequence));
361 // Now make sure that all modules point to the correct sections.
362 foreach ($rawmods as $cmid => $mod) {
363 if (isset($modsection[$cmid]) && $modsection[$cmid] != $mod->section) {
364 if (!$checkonly) {
365 $DB->update_record('course_modules', array('id' => $cmid, 'section' => $modsection[$cmid]));
367 $messages[] = $debuggingprefix.'Course module ['.$cmid.
368 '] points to section ['.$mod->section.'] instead of ['.$modsection[$cmid].']';
372 return $messages;
376 * For a given course, returns an array of course activity objects
377 * Each item in the array contains he following properties:
379 function get_array_of_activities($courseid) {
380 // cm - course module id
381 // mod - name of the module (eg forum)
382 // section - the number of the section (eg week or topic)
383 // name - the name of the instance
384 // visible - is the instance visible or not
385 // groupingid - grouping id
386 // extra - contains extra string to include in any link
387 global $CFG, $DB;
389 $course = $DB->get_record('course', array('id'=>$courseid));
391 if (empty($course)) {
392 throw new moodle_exception('courseidnotfound');
395 $mod = array();
397 $rawmods = get_course_mods($courseid);
398 if (empty($rawmods)) {
399 return $mod; // always return array
401 $courseformat = course_get_format($course);
403 if ($sections = $DB->get_records('course_sections', array('course' => $courseid),
404 'section ASC', 'id,section,sequence,visible')) {
405 // First check and correct obvious mismatches between course_sections.sequence and course_modules.section.
406 if ($errormessages = course_integrity_check($courseid, $rawmods, $sections)) {
407 debugging(join('<br>', $errormessages));
408 $rawmods = get_course_mods($courseid);
409 $sections = $DB->get_records('course_sections', array('course' => $courseid),
410 'section ASC', 'id,section,sequence,visible');
412 // Build array of activities.
413 foreach ($sections as $section) {
414 if (!empty($section->sequence)) {
415 $sequence = explode(",", $section->sequence);
416 foreach ($sequence as $seq) {
417 if (empty($rawmods[$seq])) {
418 continue;
420 // Adjust visibleoncoursepage, value in DB may not respect format availability.
421 $rawmods[$seq]->visibleoncoursepage = (!$rawmods[$seq]->visible
422 || $rawmods[$seq]->visibleoncoursepage
423 || empty($CFG->allowstealth)
424 || !$courseformat->allow_stealth_module_visibility($rawmods[$seq], $section)) ? 1 : 0;
426 // Create an object that will be cached.
427 $mod[$seq] = new stdClass();
428 $mod[$seq]->id = $rawmods[$seq]->instance;
429 $mod[$seq]->cm = $rawmods[$seq]->id;
430 $mod[$seq]->mod = $rawmods[$seq]->modname;
432 // Oh dear. Inconsistent names left here for backward compatibility.
433 $mod[$seq]->section = $section->section;
434 $mod[$seq]->sectionid = $rawmods[$seq]->section;
436 $mod[$seq]->module = $rawmods[$seq]->module;
437 $mod[$seq]->added = $rawmods[$seq]->added;
438 $mod[$seq]->score = $rawmods[$seq]->score;
439 $mod[$seq]->idnumber = $rawmods[$seq]->idnumber;
440 $mod[$seq]->visible = $rawmods[$seq]->visible;
441 $mod[$seq]->visibleoncoursepage = $rawmods[$seq]->visibleoncoursepage;
442 $mod[$seq]->visibleold = $rawmods[$seq]->visibleold;
443 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
444 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
445 $mod[$seq]->indent = $rawmods[$seq]->indent;
446 $mod[$seq]->completion = $rawmods[$seq]->completion;
447 $mod[$seq]->extra = "";
448 $mod[$seq]->completiongradeitemnumber =
449 $rawmods[$seq]->completiongradeitemnumber;
450 $mod[$seq]->completionview = $rawmods[$seq]->completionview;
451 $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected;
452 $mod[$seq]->showdescription = $rawmods[$seq]->showdescription;
453 $mod[$seq]->availability = $rawmods[$seq]->availability;
454 $mod[$seq]->deletioninprogress = $rawmods[$seq]->deletioninprogress;
456 $modname = $mod[$seq]->mod;
457 $functionname = $modname."_get_coursemodule_info";
459 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
460 continue;
463 include_once("$CFG->dirroot/mod/$modname/lib.php");
465 if ($hasfunction = function_exists($functionname)) {
466 if ($info = $functionname($rawmods[$seq])) {
467 if (!empty($info->icon)) {
468 $mod[$seq]->icon = $info->icon;
470 if (!empty($info->iconcomponent)) {
471 $mod[$seq]->iconcomponent = $info->iconcomponent;
473 if (!empty($info->name)) {
474 $mod[$seq]->name = $info->name;
476 if ($info instanceof cached_cm_info) {
477 // When using cached_cm_info you can include three new fields
478 // that aren't available for legacy code
479 if (!empty($info->content)) {
480 $mod[$seq]->content = $info->content;
482 if (!empty($info->extraclasses)) {
483 $mod[$seq]->extraclasses = $info->extraclasses;
485 if (!empty($info->iconurl)) {
486 // Convert URL to string as it's easier to store. Also serialized object contains \0 byte and can not be written to Postgres DB.
487 $url = new moodle_url($info->iconurl);
488 $mod[$seq]->iconurl = $url->out(false);
490 if (!empty($info->onclick)) {
491 $mod[$seq]->onclick = $info->onclick;
493 if (!empty($info->customdata)) {
494 $mod[$seq]->customdata = $info->customdata;
496 } else {
497 // When using a stdclass, the (horrible) deprecated ->extra field
498 // is available for BC
499 if (!empty($info->extra)) {
500 $mod[$seq]->extra = $info->extra;
505 // When there is no modname_get_coursemodule_info function,
506 // but showdescriptions is enabled, then we use the 'intro'
507 // and 'introformat' fields in the module table
508 if (!$hasfunction && $rawmods[$seq]->showdescription) {
509 if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
510 array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
511 // Set content from intro and introformat. Filters are disabled
512 // because we filter it with format_text at display time
513 $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
514 $modvalues, $rawmods[$seq]->id, false);
516 // To save making another query just below, put name in here
517 $mod[$seq]->name = $modvalues->name;
520 if (!isset($mod[$seq]->name)) {
521 $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
524 // Minimise the database size by unsetting default options when they are
525 // 'empty'. This list corresponds to code in the cm_info constructor.
526 foreach (array('idnumber', 'groupmode', 'groupingid',
527 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
528 'icon', 'iconcomponent', 'customdata', 'availability', 'completionview',
529 'completionexpected', 'score', 'showdescription', 'deletioninprogress') as $property) {
530 if (property_exists($mod[$seq], $property) &&
531 empty($mod[$seq]->{$property})) {
532 unset($mod[$seq]->{$property});
535 // Special case: this value is usually set to null, but may be 0
536 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
537 is_null($mod[$seq]->completiongradeitemnumber)) {
538 unset($mod[$seq]->completiongradeitemnumber);
544 return $mod;
548 * Returns the localised human-readable names of all used modules
550 * @param bool $plural if true returns the plural forms of the names
551 * @return array where key is the module name (component name without 'mod_') and
552 * the value is the human-readable string. Array sorted alphabetically by value
554 function get_module_types_names($plural = false) {
555 static $modnames = null;
556 global $DB, $CFG;
557 if ($modnames === null) {
558 $modnames = array(0 => array(), 1 => array());
559 if ($allmods = $DB->get_records("modules")) {
560 foreach ($allmods as $mod) {
561 if (file_exists("$CFG->dirroot/mod/$mod->name/lib.php") && $mod->visible) {
562 $modnames[0][$mod->name] = get_string("modulename", "$mod->name");
563 $modnames[1][$mod->name] = get_string("modulenameplural", "$mod->name");
566 core_collator::asort($modnames[0]);
567 core_collator::asort($modnames[1]);
570 return $modnames[(int)$plural];
574 * Set highlighted section. Only one section can be highlighted at the time.
576 * @param int $courseid course id
577 * @param int $marker highlight section with this number, 0 means remove higlightin
578 * @return void
580 function course_set_marker($courseid, $marker) {
581 global $DB, $COURSE;
582 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
583 if ($COURSE && $COURSE->id == $courseid) {
584 $COURSE->marker = $marker;
586 if (class_exists('format_base')) {
587 format_base::reset_course_cache($courseid);
589 course_modinfo::clear_instance_cache($courseid);
593 * For a given course section, marks it visible or hidden,
594 * and does the same for every activity in that section
596 * @param int $courseid course id
597 * @param int $sectionnumber The section number to adjust
598 * @param int $visibility The new visibility
599 * @return array A list of resources which were hidden in the section
601 function set_section_visible($courseid, $sectionnumber, $visibility) {
602 global $DB;
604 $resourcestotoggle = array();
605 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
606 course_update_section($courseid, $section, array('visible' => $visibility));
608 // Determine which modules are visible for AJAX update
609 $modules = !empty($section->sequence) ? explode(',', $section->sequence) : array();
610 if (!empty($modules)) {
611 list($insql, $params) = $DB->get_in_or_equal($modules);
612 $select = 'id ' . $insql . ' AND visible = ?';
613 array_push($params, $visibility);
614 if (!$visibility) {
615 $select .= ' AND visibleold = 1';
617 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
620 return $resourcestotoggle;
624 * Retrieve all metadata for the requested modules
626 * @param object $course The Course
627 * @param array $modnames An array containing the list of modules and their
628 * names
629 * @param int $sectionreturn The section to return to
630 * @return array A list of stdClass objects containing metadata about each
631 * module
633 function get_module_metadata($course, $modnames, $sectionreturn = null) {
634 global $OUTPUT;
636 // get_module_metadata will be called once per section on the page and courses may show
637 // different modules to one another
638 static $modlist = array();
639 if (!isset($modlist[$course->id])) {
640 $modlist[$course->id] = array();
643 $return = array();
644 $urlbase = new moodle_url('/course/mod.php', array('id' => $course->id, 'sesskey' => sesskey()));
645 if ($sectionreturn !== null) {
646 $urlbase->param('sr', $sectionreturn);
648 foreach($modnames as $modname => $modnamestr) {
649 if (!course_allowed_module($course, $modname)) {
650 continue;
652 if (isset($modlist[$course->id][$modname])) {
653 // This module is already cached
654 $return += $modlist[$course->id][$modname];
655 continue;
657 $modlist[$course->id][$modname] = array();
659 // Create an object for a default representation of this module type in the activity chooser. It will be used
660 // if module does not implement callback get_shortcuts() and it will also be passed to the callback if it exists.
661 $defaultmodule = new stdClass();
662 $defaultmodule->title = $modnamestr;
663 $defaultmodule->name = $modname;
664 $defaultmodule->link = new moodle_url($urlbase, array('add' => $modname));
665 $defaultmodule->icon = $OUTPUT->pix_icon('icon', '', $defaultmodule->name, array('class' => 'icon'));
666 $sm = get_string_manager();
667 if ($sm->string_exists('modulename_help', $modname)) {
668 $defaultmodule->help = get_string('modulename_help', $modname);
669 if ($sm->string_exists('modulename_link', $modname)) { // Link to further info in Moodle docs.
670 $link = get_string('modulename_link', $modname);
671 $linktext = get_string('morehelp');
672 $defaultmodule->help .= html_writer::tag('div',
673 $OUTPUT->doc_link($link, $linktext, true), array('class' => 'helpdoclink'));
676 $defaultmodule->archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
678 // Each module can implement callback modulename_get_shortcuts() in its lib.php and return the list
679 // of elements to be added to activity chooser.
680 $items = component_callback($modname, 'get_shortcuts', array($defaultmodule), null);
681 if ($items !== null) {
682 foreach ($items as $item) {
683 // Add all items to the return array. All items must have different links, use them as a key in the return array.
684 if (!isset($item->archetype)) {
685 $item->archetype = $defaultmodule->archetype;
687 if (!isset($item->icon)) {
688 $item->icon = $defaultmodule->icon;
690 // If plugin returned the only one item with the same link as default item - cache it as $modname,
691 // otherwise append the link url to the module name.
692 $item->name = (count($items) == 1 &&
693 $item->link->out() === $defaultmodule->link->out()) ? $modname : $modname . ':' . $item->link;
695 // If the module provides the helptext property, append it to the help text to match the look and feel
696 // of the default course modules.
697 if (isset($item->help) && isset($item->helplink)) {
698 $linktext = get_string('morehelp');
699 $item->help .= html_writer::tag('div',
700 $OUTPUT->doc_link($item->helplink, $linktext, true), array('class' => 'helpdoclink'));
702 $modlist[$course->id][$modname][$item->name] = $item;
704 $return += $modlist[$course->id][$modname];
705 // If get_shortcuts() callback is defined, the default module action is not added.
706 // It is a responsibility of the callback to add it to the return value unless it is not needed.
707 continue;
710 // The callback get_shortcuts() was not found, use the default item for the activity chooser.
711 $modlist[$course->id][$modname][$modname] = $defaultmodule;
712 $return[$modname] = $defaultmodule;
715 core_collator::asort_objects_by_property($return, 'title');
716 return $return;
720 * Return the course category context for the category with id $categoryid, except
721 * that if $categoryid is 0, return the system context.
723 * @param integer $categoryid a category id or 0.
724 * @return context the corresponding context
726 function get_category_or_system_context($categoryid) {
727 if ($categoryid) {
728 return context_coursecat::instance($categoryid, IGNORE_MISSING);
729 } else {
730 return context_system::instance();
735 * Returns full course categories trees to be used in html_writer::select()
737 * Calls {@link core_course_category::make_categories_list()} to build the tree and
738 * adds whitespace to denote nesting
740 * @return array array mapping course category id to the display name
742 function make_categories_options() {
743 $cats = core_course_category::make_categories_list('', 0, ' / ');
744 foreach ($cats as $key => $value) {
745 // Prefix the value with the number of spaces equal to category depth (number of separators in the value).
746 $cats[$key] = str_repeat('&nbsp;', substr_count($value, ' / ')). $value;
748 return $cats;
752 * Print the buttons relating to course requests.
754 * @param object $context current page context.
756 function print_course_request_buttons($context) {
757 global $CFG, $DB, $OUTPUT;
758 if (empty($CFG->enablecourserequests)) {
759 return;
761 if (!has_capability('moodle/course:create', $context) && has_capability('moodle/course:request', $context)) {
762 /// Print a button to request a new course
763 echo $OUTPUT->single_button(new moodle_url('/course/request.php'), get_string('requestcourse'), 'get');
765 /// Print a button to manage pending requests
766 if (has_capability('moodle/site:approvecourse', $context)) {
767 $disabled = !$DB->record_exists('course_request', array());
768 echo $OUTPUT->single_button(new moodle_url('/course/pending.php'), get_string('coursespending'), 'get', array('disabled' => $disabled));
773 * Does the user have permission to edit things in this category?
775 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
776 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
778 function can_edit_in_category($categoryid = 0) {
779 $context = get_category_or_system_context($categoryid);
780 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
783 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
785 function add_course_module($mod) {
786 global $DB;
788 $mod->added = time();
789 unset($mod->id);
791 $cmid = $DB->insert_record("course_modules", $mod);
792 rebuild_course_cache($mod->course, true);
793 return $cmid;
797 * Creates a course section and adds it to the specified position
799 * @param int|stdClass $courseorid course id or course object
800 * @param int $position position to add to, 0 means to the end. If position is greater than
801 * number of existing secitons, the section is added to the end. This will become sectionnum of the
802 * new section. All existing sections at this or bigger position will be shifted down.
803 * @param bool $skipcheck the check has already been made and we know that the section with this position does not exist
804 * @return stdClass created section object
806 function course_create_section($courseorid, $position = 0, $skipcheck = false) {
807 global $DB;
808 $courseid = is_object($courseorid) ? $courseorid->id : $courseorid;
810 // Find the last sectionnum among existing sections.
811 if ($skipcheck) {
812 $lastsection = $position - 1;
813 } else {
814 $lastsection = (int)$DB->get_field_sql('SELECT max(section) from {course_sections} WHERE course = ?', [$courseid]);
817 // First add section to the end.
818 $cw = new stdClass();
819 $cw->course = $courseid;
820 $cw->section = $lastsection + 1;
821 $cw->summary = '';
822 $cw->summaryformat = FORMAT_HTML;
823 $cw->sequence = '';
824 $cw->name = null;
825 $cw->visible = 1;
826 $cw->availability = null;
827 $cw->timemodified = time();
828 $cw->id = $DB->insert_record("course_sections", $cw);
830 // Now move it to the specified position.
831 if ($position > 0 && $position <= $lastsection) {
832 $course = is_object($courseorid) ? $courseorid : get_course($courseorid);
833 move_section_to($course, $cw->section, $position, true);
834 $cw->section = $position;
837 core\event\course_section_created::create_from_section($cw)->trigger();
839 rebuild_course_cache($courseid, true);
840 return $cw;
844 * Creates missing course section(s) and rebuilds course cache
846 * @param int|stdClass $courseorid course id or course object
847 * @param int|array $sections list of relative section numbers to create
848 * @return bool if there were any sections created
850 function course_create_sections_if_missing($courseorid, $sections) {
851 if (!is_array($sections)) {
852 $sections = array($sections);
854 $existing = array_keys(get_fast_modinfo($courseorid)->get_section_info_all());
855 if ($newsections = array_diff($sections, $existing)) {
856 foreach ($newsections as $sectionnum) {
857 course_create_section($courseorid, $sectionnum, true);
859 return true;
861 return false;
865 * Adds an existing module to the section
867 * Updates both tables {course_sections} and {course_modules}
869 * Note: This function does not use modinfo PROVIDED that the section you are
870 * adding the module to already exists. If the section does not exist, it will
871 * build modinfo if necessary and create the section.
873 * @param int|stdClass $courseorid course id or course object
874 * @param int $cmid id of the module already existing in course_modules table
875 * @param int $sectionnum relative number of the section (field course_sections.section)
876 * If section does not exist it will be created
877 * @param int|stdClass $beforemod id or object with field id corresponding to the module
878 * before which the module needs to be included. Null for inserting in the
879 * end of the section
880 * @return int The course_sections ID where the module is inserted
882 function course_add_cm_to_section($courseorid, $cmid, $sectionnum, $beforemod = null) {
883 global $DB, $COURSE;
884 if (is_object($beforemod)) {
885 $beforemod = $beforemod->id;
887 if (is_object($courseorid)) {
888 $courseid = $courseorid->id;
889 } else {
890 $courseid = $courseorid;
892 // Do not try to use modinfo here, there is no guarantee it is valid!
893 $section = $DB->get_record('course_sections',
894 array('course' => $courseid, 'section' => $sectionnum), '*', IGNORE_MISSING);
895 if (!$section) {
896 // This function call requires modinfo.
897 course_create_sections_if_missing($courseorid, $sectionnum);
898 $section = $DB->get_record('course_sections',
899 array('course' => $courseid, 'section' => $sectionnum), '*', MUST_EXIST);
902 $modarray = explode(",", trim($section->sequence));
903 if (empty($section->sequence)) {
904 $newsequence = "$cmid";
905 } else if ($beforemod && ($key = array_keys($modarray, $beforemod))) {
906 $insertarray = array($cmid, $beforemod);
907 array_splice($modarray, $key[0], 1, $insertarray);
908 $newsequence = implode(",", $modarray);
909 } else {
910 $newsequence = "$section->sequence,$cmid";
912 $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id));
913 $DB->set_field('course_modules', 'section', $section->id, array('id' => $cmid));
914 if (is_object($courseorid)) {
915 rebuild_course_cache($courseorid->id, true);
916 } else {
917 rebuild_course_cache($courseorid, true);
919 return $section->id; // Return course_sections ID that was used.
923 * Change the group mode of a course module.
925 * Note: Do not forget to trigger the event \core\event\course_module_updated as it needs
926 * to be triggered manually, refer to {@link \core\event\course_module_updated::create_from_cm()}.
928 * @param int $id course module ID.
929 * @param int $groupmode the new groupmode value.
930 * @return bool True if the $groupmode was updated.
932 function set_coursemodule_groupmode($id, $groupmode) {
933 global $DB;
934 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST);
935 if ($cm->groupmode != $groupmode) {
936 $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id));
937 rebuild_course_cache($cm->course, true);
939 return ($cm->groupmode != $groupmode);
942 function set_coursemodule_idnumber($id, $idnumber) {
943 global $DB;
944 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST);
945 if ($cm->idnumber != $idnumber) {
946 $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id));
947 rebuild_course_cache($cm->course, true);
949 return ($cm->idnumber != $idnumber);
953 * Set the visibility of a module and inherent properties.
955 * Note: Do not forget to trigger the event \core\event\course_module_updated as it needs
956 * to be triggered manually, refer to {@link \core\event\course_module_updated::create_from_cm()}.
958 * From 2.4 the parameter $prevstateoverrides has been removed, the logic it triggered
959 * has been moved to {@link set_section_visible()} which was the only place from which
960 * the parameter was used.
962 * @param int $id of the module
963 * @param int $visible state of the module
964 * @param int $visibleoncoursepage state of the module on the course page
965 * @return bool false when the module was not found, true otherwise
967 function set_coursemodule_visible($id, $visible, $visibleoncoursepage = 1) {
968 global $DB, $CFG;
969 require_once($CFG->libdir.'/gradelib.php');
970 require_once($CFG->dirroot.'/calendar/lib.php');
972 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
973 return false;
976 // Create events and propagate visibility to associated grade items if the value has changed.
977 // Only do this if it's changed to avoid accidently overwriting manual showing/hiding of student grades.
978 if ($cm->visible == $visible && $cm->visibleoncoursepage == $visibleoncoursepage) {
979 return true;
982 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
983 return false;
985 if (($cm->visible != $visible) &&
986 ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename)))) {
987 foreach($events as $event) {
988 if ($visible) {
989 $event = new calendar_event($event);
990 $event->toggle_visibility(true);
991 } else {
992 $event = new calendar_event($event);
993 $event->toggle_visibility(false);
998 // Updating visible and visibleold to keep them in sync. Only changing a section visibility will
999 // affect visibleold to allow for an original visibility restore. See set_section_visible().
1000 $cminfo = new stdClass();
1001 $cminfo->id = $id;
1002 $cminfo->visible = $visible;
1003 $cminfo->visibleoncoursepage = $visibleoncoursepage;
1004 $cminfo->visibleold = $visible;
1005 $DB->update_record('course_modules', $cminfo);
1007 // Hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there.
1008 // Note that this must be done after updating the row in course_modules, in case
1009 // the modules grade_item_update function needs to access $cm->visible.
1010 if ($cm->visible != $visible &&
1011 plugin_supports('mod', $modulename, FEATURE_CONTROLS_GRADE_VISIBILITY) &&
1012 component_callback_exists('mod_' . $modulename, 'grade_item_update')) {
1013 $instance = $DB->get_record($modulename, array('id' => $cm->instance), '*', MUST_EXIST);
1014 component_callback('mod_' . $modulename, 'grade_item_update', array($instance));
1015 } else if ($cm->visible != $visible) {
1016 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
1017 if ($grade_items) {
1018 foreach ($grade_items as $grade_item) {
1019 $grade_item->set_hidden(!$visible);
1024 rebuild_course_cache($cm->course, true);
1025 return true;
1029 * Changes the course module name
1031 * @param int $id course module id
1032 * @param string $name new value for a name
1033 * @return bool whether a change was made
1035 function set_coursemodule_name($id, $name) {
1036 global $CFG, $DB;
1037 require_once($CFG->libdir . '/gradelib.php');
1039 $cm = get_coursemodule_from_id('', $id, 0, false, MUST_EXIST);
1041 $module = new \stdClass();
1042 $module->id = $cm->instance;
1044 // Escape strings as they would be by mform.
1045 if (!empty($CFG->formatstringstriptags)) {
1046 $module->name = clean_param($name, PARAM_TEXT);
1047 } else {
1048 $module->name = clean_param($name, PARAM_CLEANHTML);
1050 if ($module->name === $cm->name || strval($module->name) === '') {
1051 return false;
1053 if (\core_text::strlen($module->name) > 255) {
1054 throw new \moodle_exception('maximumchars', 'moodle', '', 255);
1057 $module->timemodified = time();
1058 $DB->update_record($cm->modname, $module);
1059 $cm->name = $module->name;
1060 \core\event\course_module_updated::create_from_cm($cm)->trigger();
1061 rebuild_course_cache($cm->course, true);
1063 // Attempt to update the grade item if relevant.
1064 $grademodule = $DB->get_record($cm->modname, array('id' => $cm->instance));
1065 $grademodule->cmidnumber = $cm->idnumber;
1066 $grademodule->modname = $cm->modname;
1067 grade_update_mod_grades($grademodule);
1069 // Update calendar events with the new name.
1070 course_module_update_calendar_events($cm->modname, $grademodule, $cm);
1072 return true;
1076 * This function will handle the whole deletion process of a module. This includes calling
1077 * the modules delete_instance function, deleting files, events, grades, conditional data,
1078 * the data in the course_module and course_sections table and adding a module deletion
1079 * event to the DB.
1081 * @param int $cmid the course module id
1082 * @param bool $async whether or not to try to delete the module using an adhoc task. Async also depends on a plugin hook.
1083 * @throws moodle_exception
1084 * @since Moodle 2.5
1086 function course_delete_module($cmid, $async = false) {
1087 // Check the 'course_module_background_deletion_recommended' hook first.
1088 // Only use asynchronous deletion if at least one plugin returns true and if async deletion has been requested.
1089 // Both are checked because plugins should not be allowed to dictate the deletion behaviour, only support/decline it.
1090 // It's up to plugins to handle things like whether or not they are enabled.
1091 if ($async && $pluginsfunction = get_plugins_with_function('course_module_background_deletion_recommended')) {
1092 foreach ($pluginsfunction as $plugintype => $plugins) {
1093 foreach ($plugins as $pluginfunction) {
1094 if ($pluginfunction()) {
1095 return course_module_flag_for_async_deletion($cmid);
1101 global $CFG, $DB;
1103 require_once($CFG->libdir.'/gradelib.php');
1104 require_once($CFG->libdir.'/questionlib.php');
1105 require_once($CFG->dirroot.'/blog/lib.php');
1106 require_once($CFG->dirroot.'/calendar/lib.php');
1108 // Get the course module.
1109 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
1110 return true;
1113 // Get the module context.
1114 $modcontext = context_module::instance($cm->id);
1116 // Get the course module name.
1117 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
1119 // Get the file location of the delete_instance function for this module.
1120 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
1122 // Include the file required to call the delete_instance function for this module.
1123 if (file_exists($modlib)) {
1124 require_once($modlib);
1125 } else {
1126 throw new moodle_exception('cannotdeletemodulemissinglib', '', '', null,
1127 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
1130 $deleteinstancefunction = $modulename . '_delete_instance';
1132 // Ensure the delete_instance function exists for this module.
1133 if (!function_exists($deleteinstancefunction)) {
1134 throw new moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
1135 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
1138 // Allow plugins to use this course module before we completely delete it.
1139 if ($pluginsfunction = get_plugins_with_function('pre_course_module_delete')) {
1140 foreach ($pluginsfunction as $plugintype => $plugins) {
1141 foreach ($plugins as $pluginfunction) {
1142 $pluginfunction($cm);
1147 // Delete activity context questions and question categories.
1148 question_delete_activity($cm);
1150 // Call the delete_instance function, if it returns false throw an exception.
1151 if (!$deleteinstancefunction($cm->instance)) {
1152 throw new moodle_exception('cannotdeletemoduleinstance', '', '', null,
1153 "Cannot delete the module $modulename (instance).");
1156 // Remove all module files in case modules forget to do that.
1157 $fs = get_file_storage();
1158 $fs->delete_area_files($modcontext->id);
1160 // Delete events from calendar.
1161 if ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename))) {
1162 $coursecontext = context_course::instance($cm->course);
1163 foreach($events as $event) {
1164 $event->context = $coursecontext;
1165 $calendarevent = calendar_event::load($event);
1166 $calendarevent->delete();
1170 // Delete grade items, outcome items and grades attached to modules.
1171 if ($grade_items = grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $modulename,
1172 'iteminstance' => $cm->instance, 'courseid' => $cm->course))) {
1173 foreach ($grade_items as $grade_item) {
1174 $grade_item->delete('moddelete');
1178 // Delete associated blogs and blog tag instances.
1179 blog_remove_associations_for_module($modcontext->id);
1181 // Delete completion and availability data; it is better to do this even if the
1182 // features are not turned on, in case they were turned on previously (these will be
1183 // very quick on an empty table).
1184 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
1185 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
1186 'course' => $cm->course,
1187 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
1189 // Delete all tag instances associated with the instance of this module.
1190 core_tag_tag::delete_instances('mod_' . $modulename, null, $modcontext->id);
1191 core_tag_tag::remove_all_item_tags('core', 'course_modules', $cm->id);
1193 // Notify the competency subsystem.
1194 \core_competency\api::hook_course_module_deleted($cm);
1196 // Delete the context.
1197 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
1199 // Delete the module from the course_modules table.
1200 $DB->delete_records('course_modules', array('id' => $cm->id));
1202 // Delete module from that section.
1203 if (!delete_mod_from_section($cm->id, $cm->section)) {
1204 throw new moodle_exception('cannotdeletemodulefromsection', '', '', null,
1205 "Cannot delete the module $modulename (instance) from section.");
1208 // Trigger event for course module delete action.
1209 $event = \core\event\course_module_deleted::create(array(
1210 'courseid' => $cm->course,
1211 'context' => $modcontext,
1212 'objectid' => $cm->id,
1213 'other' => array(
1214 'modulename' => $modulename,
1215 'instanceid' => $cm->instance,
1218 $event->add_record_snapshot('course_modules', $cm);
1219 $event->trigger();
1220 rebuild_course_cache($cm->course, true);
1224 * Schedule a course module for deletion in the background using an adhoc task.
1226 * This method should not be called directly. Instead, please use course_delete_module($cmid, true), to denote async deletion.
1227 * The real deletion of the module is handled by the task, which calls 'course_delete_module($cmid)'.
1229 * @param int $cmid the course module id.
1230 * @return bool whether the module was successfully scheduled for deletion.
1231 * @throws \moodle_exception
1233 function course_module_flag_for_async_deletion($cmid) {
1234 global $CFG, $DB, $USER;
1235 require_once($CFG->libdir.'/gradelib.php');
1236 require_once($CFG->libdir.'/questionlib.php');
1237 require_once($CFG->dirroot.'/blog/lib.php');
1238 require_once($CFG->dirroot.'/calendar/lib.php');
1240 // Get the course module.
1241 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
1242 return true;
1245 // We need to be reasonably certain the deletion is going to succeed before we background the process.
1246 // Make the necessary delete_instance checks, etc. before proceeding further. Throw exceptions if required.
1248 // Get the course module name.
1249 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
1251 // Get the file location of the delete_instance function for this module.
1252 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
1254 // Include the file required to call the delete_instance function for this module.
1255 if (file_exists($modlib)) {
1256 require_once($modlib);
1257 } else {
1258 throw new \moodle_exception('cannotdeletemodulemissinglib', '', '', null,
1259 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
1262 $deleteinstancefunction = $modulename . '_delete_instance';
1264 // Ensure the delete_instance function exists for this module.
1265 if (!function_exists($deleteinstancefunction)) {
1266 throw new \moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
1267 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
1270 // We are going to defer the deletion as we can't be sure how long the module's pre_delete code will run for.
1271 $cm->deletioninprogress = '1';
1272 $DB->update_record('course_modules', $cm);
1274 // Create an adhoc task for the deletion of the course module. The task takes an array of course modules for removal.
1275 $removaltask = new \core_course\task\course_delete_modules();
1276 $removaltask->set_custom_data(array(
1277 'cms' => array($cm),
1278 'userid' => $USER->id,
1279 'realuserid' => \core\session\manager::get_realuser()->id
1282 // Queue the task for the next run.
1283 \core\task\manager::queue_adhoc_task($removaltask);
1285 // Reset the course cache to hide the module.
1286 rebuild_course_cache($cm->course, true);
1290 * Checks whether the given course has any course modules scheduled for adhoc deletion.
1292 * @param int $courseid the id of the course.
1293 * @param bool $onlygradable whether to check only gradable modules or all modules.
1294 * @return bool true if the course contains any modules pending deletion, false otherwise.
1296 function course_modules_pending_deletion(int $courseid, bool $onlygradable = false) : bool {
1297 if (empty($courseid)) {
1298 return false;
1301 if ($onlygradable) {
1302 // Fetch modules with grade items.
1303 if (!$coursegradeitems = grade_item::fetch_all(['itemtype' => 'mod', 'courseid' => $courseid])) {
1304 // Return early when there is none.
1305 return false;
1309 $modinfo = get_fast_modinfo($courseid);
1310 foreach ($modinfo->get_cms() as $module) {
1311 if ($module->deletioninprogress == '1') {
1312 if ($onlygradable) {
1313 // Check if the module being deleted is in the list of course modules with grade items.
1314 foreach ($coursegradeitems as $coursegradeitem) {
1315 if ($coursegradeitem->itemmodule == $module->modname && $coursegradeitem->iteminstance == $module->instance) {
1316 // The module being deleted is within the gradable modules.
1317 return true;
1320 } else {
1321 return true;
1325 return false;
1329 * Checks whether the course module, as defined by modulename and instanceid, is scheduled for deletion within the given course.
1331 * @param int $courseid the course id.
1332 * @param string $modulename the module name. E.g. 'assign', 'book', etc.
1333 * @param int $instanceid the module instance id.
1334 * @return bool true if the course module is pending deletion, false otherwise.
1336 function course_module_instance_pending_deletion($courseid, $modulename, $instanceid) {
1337 if (empty($courseid) || empty($modulename) || empty($instanceid)) {
1338 return false;
1340 $modinfo = get_fast_modinfo($courseid);
1341 $instances = $modinfo->get_instances_of($modulename);
1342 return isset($instances[$instanceid]) && $instances[$instanceid]->deletioninprogress;
1345 function delete_mod_from_section($modid, $sectionid) {
1346 global $DB;
1348 if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
1350 $modarray = explode(",", $section->sequence);
1352 if ($key = array_keys ($modarray, $modid)) {
1353 array_splice($modarray, $key[0], 1);
1354 $newsequence = implode(",", $modarray);
1355 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
1356 rebuild_course_cache($section->course, true);
1357 return true;
1358 } else {
1359 return false;
1363 return false;
1367 * This function updates the calendar events from the information stored in the module table and the course
1368 * module table.
1370 * @param string $modulename Module name
1371 * @param stdClass $instance Module object. Either the $instance or the $cm must be supplied.
1372 * @param stdClass $cm Course module object. Either the $instance or the $cm must be supplied.
1373 * @return bool Returns true if calendar events are updated.
1374 * @since Moodle 3.3.4
1376 function course_module_update_calendar_events($modulename, $instance = null, $cm = null) {
1377 global $DB;
1379 if (isset($instance) || isset($cm)) {
1381 if (!isset($instance)) {
1382 $instance = $DB->get_record($modulename, array('id' => $cm->instance), '*', MUST_EXIST);
1384 if (!isset($cm)) {
1385 $cm = get_coursemodule_from_instance($modulename, $instance->id, $instance->course);
1387 if (!empty($cm)) {
1388 course_module_calendar_event_update_process($instance, $cm);
1390 return true;
1392 return false;
1396 * Update all instances through out the site or in a course.
1398 * @param string $modulename Module type to update.
1399 * @param integer $courseid Course id to update events. 0 for the whole site.
1400 * @return bool Returns True if the update was successful.
1401 * @since Moodle 3.3.4
1403 function course_module_bulk_update_calendar_events($modulename, $courseid = 0) {
1404 global $DB;
1406 $instances = null;
1407 if ($courseid) {
1408 if (!$instances = $DB->get_records($modulename, array('course' => $courseid))) {
1409 return false;
1411 } else {
1412 if (!$instances = $DB->get_records($modulename)) {
1413 return false;
1417 foreach ($instances as $instance) {
1418 if ($cm = get_coursemodule_from_instance($modulename, $instance->id, $instance->course)) {
1419 course_module_calendar_event_update_process($instance, $cm);
1422 return true;
1426 * Calendar events for a module instance are updated.
1428 * @param stdClass $instance Module instance object.
1429 * @param stdClass $cm Course Module object.
1430 * @since Moodle 3.3.4
1432 function course_module_calendar_event_update_process($instance, $cm) {
1433 // We need to call *_refresh_events() first because some modules delete 'old' events at the end of the code which
1434 // will remove the completion events.
1435 $refresheventsfunction = $cm->modname . '_refresh_events';
1436 if (function_exists($refresheventsfunction)) {
1437 call_user_func($refresheventsfunction, $cm->course, $instance, $cm);
1439 $completionexpected = (!empty($cm->completionexpected)) ? $cm->completionexpected : null;
1440 \core_completion\api::update_completion_date_event($cm->id, $cm->modname, $instance, $completionexpected);
1444 * Moves a section within a course, from a position to another.
1445 * Be very careful: $section and $destination refer to section number,
1446 * not id!.
1448 * @param object $course
1449 * @param int $section Section number (not id!!!)
1450 * @param int $destination
1451 * @param bool $ignorenumsections
1452 * @return boolean Result
1454 function move_section_to($course, $section, $destination, $ignorenumsections = false) {
1455 /// Moves a whole course section up and down within the course
1456 global $USER, $DB;
1458 if (!$destination && $destination != 0) {
1459 return true;
1462 // compartibility with course formats using field 'numsections'
1463 $courseformatoptions = course_get_format($course)->get_format_options();
1464 if ((!$ignorenumsections && array_key_exists('numsections', $courseformatoptions) &&
1465 ($destination > $courseformatoptions['numsections'])) || ($destination < 1)) {
1466 return false;
1469 // Get all sections for this course and re-order them (2 of them should now share the same section number)
1470 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
1471 'section ASC, id ASC', 'id, section')) {
1472 return false;
1475 $movedsections = reorder_sections($sections, $section, $destination);
1477 // Update all sections. Do this in 2 steps to avoid breaking database
1478 // uniqueness constraint
1479 $transaction = $DB->start_delegated_transaction();
1480 foreach ($movedsections as $id => $position) {
1481 if ($sections[$id] !== $position) {
1482 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
1485 foreach ($movedsections as $id => $position) {
1486 if ($sections[$id] !== $position) {
1487 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
1491 // If we move the highlighted section itself, then just highlight the destination.
1492 // Adjust the higlighted section location if we move something over it either direction.
1493 if ($section == $course->marker) {
1494 course_set_marker($course->id, $destination);
1495 } elseif ($section > $course->marker && $course->marker >= $destination) {
1496 course_set_marker($course->id, $course->marker+1);
1497 } elseif ($section < $course->marker && $course->marker <= $destination) {
1498 course_set_marker($course->id, $course->marker-1);
1501 $transaction->allow_commit();
1502 rebuild_course_cache($course->id, true);
1503 return true;
1507 * This method will delete a course section and may delete all modules inside it.
1509 * No permissions are checked here, use {@link course_can_delete_section()} to
1510 * check if section can actually be deleted.
1512 * @param int|stdClass $course
1513 * @param int|stdClass|section_info $section
1514 * @param bool $forcedeleteifnotempty if set to false section will not be deleted if it has modules in it.
1515 * @param bool $async whether or not to try to delete the section using an adhoc task. Async also depends on a plugin hook.
1516 * @return bool whether section was deleted
1518 function course_delete_section($course, $section, $forcedeleteifnotempty = true, $async = false) {
1519 global $DB;
1521 // Prepare variables.
1522 $courseid = (is_object($course)) ? $course->id : (int)$course;
1523 $sectionnum = (is_object($section)) ? $section->section : (int)$section;
1524 $section = $DB->get_record('course_sections', array('course' => $courseid, 'section' => $sectionnum));
1525 if (!$section) {
1526 // No section exists, can't proceed.
1527 return false;
1530 // Check the 'course_module_background_deletion_recommended' hook first.
1531 // Only use asynchronous deletion if at least one plugin returns true and if async deletion has been requested.
1532 // Both are checked because plugins should not be allowed to dictate the deletion behaviour, only support/decline it.
1533 // It's up to plugins to handle things like whether or not they are enabled.
1534 if ($async && $pluginsfunction = get_plugins_with_function('course_module_background_deletion_recommended')) {
1535 foreach ($pluginsfunction as $plugintype => $plugins) {
1536 foreach ($plugins as $pluginfunction) {
1537 if ($pluginfunction()) {
1538 return course_delete_section_async($section, $forcedeleteifnotempty);
1544 $format = course_get_format($course);
1545 $sectionname = $format->get_section_name($section);
1547 // Delete section.
1548 $result = $format->delete_section($section, $forcedeleteifnotempty);
1550 // Trigger an event for course section deletion.
1551 if ($result) {
1552 $context = context_course::instance($courseid);
1553 $event = \core\event\course_section_deleted::create(
1554 array(
1555 'objectid' => $section->id,
1556 'courseid' => $courseid,
1557 'context' => $context,
1558 'other' => array(
1559 'sectionnum' => $section->section,
1560 'sectionname' => $sectionname,
1564 $event->add_record_snapshot('course_sections', $section);
1565 $event->trigger();
1567 return $result;
1571 * Course section deletion, using an adhoc task for deletion of the modules it contains.
1572 * 1. Schedule all modules within the section for adhoc removal.
1573 * 2. Move all modules to course section 0.
1574 * 3. Delete the resulting empty section.
1576 * @param \stdClass $section the section to schedule for deletion.
1577 * @param bool $forcedeleteifnotempty whether to force section deletion if it contains modules.
1578 * @return bool true if the section was scheduled for deletion, false otherwise.
1580 function course_delete_section_async($section, $forcedeleteifnotempty = true) {
1581 global $DB, $USER;
1583 // Objects only, and only valid ones.
1584 if (!is_object($section) || empty($section->id)) {
1585 return false;
1588 // Does the object currently exist in the DB for removal (check for stale objects).
1589 $section = $DB->get_record('course_sections', array('id' => $section->id));
1590 if (!$section || !$section->section) {
1591 // No section exists, or the section is 0. Can't proceed.
1592 return false;
1595 // Check whether the section can be removed.
1596 if (!$forcedeleteifnotempty && (!empty($section->sequence) || !empty($section->summary))) {
1597 return false;
1600 $format = course_get_format($section->course);
1601 $sectionname = $format->get_section_name($section);
1603 // Flag those modules having no existing deletion flag. Some modules may have been scheduled for deletion manually, and we don't
1604 // want to create additional adhoc deletion tasks for these. Moving them to section 0 will suffice.
1605 $affectedmods = $DB->get_records_select('course_modules', 'course = ? AND section = ? AND deletioninprogress <> ?',
1606 [$section->course, $section->id, 1], '', 'id');
1607 $DB->set_field('course_modules', 'deletioninprogress', '1', ['course' => $section->course, 'section' => $section->id]);
1609 // Move all modules to section 0.
1610 $modules = $DB->get_records('course_modules', ['section' => $section->id], '');
1611 $sectionzero = $DB->get_record('course_sections', ['course' => $section->course, 'section' => '0']);
1612 foreach ($modules as $mod) {
1613 moveto_module($mod, $sectionzero);
1616 // Create and queue an adhoc task for the deletion of the modules.
1617 $removaltask = new \core_course\task\course_delete_modules();
1618 $data = array(
1619 'cms' => $affectedmods,
1620 'userid' => $USER->id,
1621 'realuserid' => \core\session\manager::get_realuser()->id
1623 $removaltask->set_custom_data($data);
1624 \core\task\manager::queue_adhoc_task($removaltask);
1626 // Delete the now empty section, passing in only the section number, which forces the function to fetch a new object.
1627 // The refresh is needed because the section->sequence is now stale.
1628 $result = $format->delete_section($section->section, $forcedeleteifnotempty);
1630 // Trigger an event for course section deletion.
1631 if ($result) {
1632 $context = \context_course::instance($section->course);
1633 $event = \core\event\course_section_deleted::create(
1634 array(
1635 'objectid' => $section->id,
1636 'courseid' => $section->course,
1637 'context' => $context,
1638 'other' => array(
1639 'sectionnum' => $section->section,
1640 'sectionname' => $sectionname,
1644 $event->add_record_snapshot('course_sections', $section);
1645 $event->trigger();
1647 rebuild_course_cache($section->course, true);
1649 return $result;
1653 * Updates the course section
1655 * This function does not check permissions or clean values - this has to be done prior to calling it.
1657 * @param int|stdClass $course
1658 * @param stdClass $section record from course_sections table - it will be updated with the new values
1659 * @param array|stdClass $data
1661 function course_update_section($course, $section, $data) {
1662 global $DB;
1664 $courseid = (is_object($course)) ? $course->id : (int)$course;
1666 // Some fields can not be updated using this method.
1667 $data = array_diff_key((array)$data, array('id', 'course', 'section', 'sequence'));
1668 $changevisibility = (array_key_exists('visible', $data) && (bool)$data['visible'] != (bool)$section->visible);
1669 if (array_key_exists('name', $data) && \core_text::strlen($data['name']) > 255) {
1670 throw new moodle_exception('maximumchars', 'moodle', '', 255);
1673 // Update record in the DB and course format options.
1674 $data['id'] = $section->id;
1675 $data['timemodified'] = time();
1676 $DB->update_record('course_sections', $data);
1677 rebuild_course_cache($courseid, true);
1678 course_get_format($courseid)->update_section_format_options($data);
1680 // Update fields of the $section object.
1681 foreach ($data as $key => $value) {
1682 if (property_exists($section, $key)) {
1683 $section->$key = $value;
1687 // Trigger an event for course section update.
1688 $event = \core\event\course_section_updated::create(
1689 array(
1690 'objectid' => $section->id,
1691 'courseid' => $courseid,
1692 'context' => context_course::instance($courseid),
1693 'other' => array('sectionnum' => $section->section)
1696 $event->trigger();
1698 // If section visibility was changed, hide the modules in this section too.
1699 if ($changevisibility && !empty($section->sequence)) {
1700 $modules = explode(',', $section->sequence);
1701 foreach ($modules as $moduleid) {
1702 if ($cm = get_coursemodule_from_id(null, $moduleid, $courseid)) {
1703 if ($data['visible']) {
1704 // As we unhide the section, we use the previously saved visibility stored in visibleold.
1705 set_coursemodule_visible($moduleid, $cm->visibleold, $cm->visibleoncoursepage);
1706 } else {
1707 // We hide the section, so we hide the module but we store the original state in visibleold.
1708 set_coursemodule_visible($moduleid, 0, $cm->visibleoncoursepage);
1709 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id' => $moduleid));
1711 \core\event\course_module_updated::create_from_cm($cm)->trigger();
1718 * Checks if the current user can delete a section (if course format allows it and user has proper permissions).
1720 * @param int|stdClass $course
1721 * @param int|stdClass|section_info $section
1722 * @return bool
1724 function course_can_delete_section($course, $section) {
1725 if (is_object($section)) {
1726 $section = $section->section;
1728 if (!$section) {
1729 // Not possible to delete 0-section.
1730 return false;
1732 // Course format should allow to delete sections.
1733 if (!course_get_format($course)->can_delete_section($section)) {
1734 return false;
1736 // Make sure user has capability to update course and move sections.
1737 $context = context_course::instance(is_object($course) ? $course->id : $course);
1738 if (!has_all_capabilities(array('moodle/course:movesections', 'moodle/course:update'), $context)) {
1739 return false;
1741 // Make sure user has capability to delete each activity in this section.
1742 $modinfo = get_fast_modinfo($course);
1743 if (!empty($modinfo->sections[$section])) {
1744 foreach ($modinfo->sections[$section] as $cmid) {
1745 if (!has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
1746 return false;
1750 return true;
1754 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
1755 * an original position number and a target position number, rebuilds the array so that the
1756 * move is made without any duplication of section positions.
1757 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
1758 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
1760 * @param array $sections
1761 * @param int $origin_position
1762 * @param int $target_position
1763 * @return array
1765 function reorder_sections($sections, $origin_position, $target_position) {
1766 if (!is_array($sections)) {
1767 return false;
1770 // We can't move section position 0
1771 if ($origin_position < 1) {
1772 echo "We can't move section position 0";
1773 return false;
1776 // Locate origin section in sections array
1777 if (!$origin_key = array_search($origin_position, $sections)) {
1778 echo "searched position not in sections array";
1779 return false; // searched position not in sections array
1782 // Extract origin section
1783 $origin_section = $sections[$origin_key];
1784 unset($sections[$origin_key]);
1786 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
1787 $found = false;
1788 $append_array = array();
1789 foreach ($sections as $id => $position) {
1790 if ($found) {
1791 $append_array[$id] = $position;
1792 unset($sections[$id]);
1794 if ($position == $target_position) {
1795 if ($target_position < $origin_position) {
1796 $append_array[$id] = $position;
1797 unset($sections[$id]);
1799 $found = true;
1803 // Append moved section
1804 $sections[$origin_key] = $origin_section;
1806 // Append rest of array (if applicable)
1807 if (!empty($append_array)) {
1808 foreach ($append_array as $id => $position) {
1809 $sections[$id] = $position;
1813 // Renumber positions
1814 $position = 0;
1815 foreach ($sections as $id => $p) {
1816 $sections[$id] = $position;
1817 $position++;
1820 return $sections;
1825 * Move the module object $mod to the specified $section
1826 * If $beforemod exists then that is the module
1827 * before which $modid should be inserted
1829 * @param stdClass|cm_info $mod
1830 * @param stdClass|section_info $section
1831 * @param int|stdClass $beforemod id or object with field id corresponding to the module
1832 * before which the module needs to be included. Null for inserting in the
1833 * end of the section
1834 * @return int new value for module visibility (0 or 1)
1836 function moveto_module($mod, $section, $beforemod=NULL) {
1837 global $OUTPUT, $DB;
1839 // Current module visibility state - return value of this function.
1840 $modvisible = $mod->visible;
1842 // Remove original module from original section.
1843 if (! delete_mod_from_section($mod->id, $mod->section)) {
1844 echo $OUTPUT->notification("Could not delete module from existing section");
1847 // If moving to a hidden section then hide module.
1848 if ($mod->section != $section->id) {
1849 if (!$section->visible && $mod->visible) {
1850 // Module was visible but must become hidden after moving to hidden section.
1851 $modvisible = 0;
1852 set_coursemodule_visible($mod->id, 0);
1853 // Set visibleold to 1 so module will be visible when section is made visible.
1854 $DB->set_field('course_modules', 'visibleold', 1, array('id' => $mod->id));
1856 if ($section->visible && !$mod->visible) {
1857 // Hidden module was moved to the visible section, restore the module visibility from visibleold.
1858 set_coursemodule_visible($mod->id, $mod->visibleold);
1859 $modvisible = $mod->visibleold;
1863 // Add the module into the new section.
1864 course_add_cm_to_section($section->course, $mod->id, $section->section, $beforemod);
1865 return $modvisible;
1869 * Returns the list of all editing actions that current user can perform on the module
1871 * @param cm_info $mod The module to produce editing buttons for
1872 * @param int $indent The current indenting (default -1 means no move left-right actions)
1873 * @param int $sr The section to link back to (used for creating the links)
1874 * @return array array of action_link or pix_icon objects
1876 function course_get_cm_edit_actions(cm_info $mod, $indent = -1, $sr = null) {
1877 global $COURSE, $SITE, $CFG;
1879 static $str;
1881 $coursecontext = context_course::instance($mod->course);
1882 $modcontext = context_module::instance($mod->id);
1883 $courseformat = course_get_format($mod->get_course());
1885 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
1886 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
1888 // No permission to edit anything.
1889 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
1890 return array();
1893 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
1895 if (!isset($str)) {
1896 $str = get_strings(array('delete', 'move', 'moveright', 'moveleft',
1897 'editsettings', 'duplicate', 'modhide', 'makeavailable', 'makeunavailable', 'modshow'), 'moodle');
1898 $str->assign = get_string('assignroles', 'role');
1899 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
1900 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
1901 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
1904 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
1906 if ($sr !== null) {
1907 $baseurl->param('sr', $sr);
1909 $actions = array();
1911 // Update.
1912 if ($hasmanageactivities) {
1913 $actions['update'] = new action_menu_link_secondary(
1914 new moodle_url($baseurl, array('update' => $mod->id)),
1915 new pix_icon('t/edit', '', 'moodle', array('class' => 'iconsmall')),
1916 $str->editsettings,
1917 array('class' => 'editing_update', 'data-action' => 'update')
1921 // Indent.
1922 if ($hasmanageactivities && $indent >= 0) {
1923 $indentlimits = new stdClass();
1924 $indentlimits->min = 0;
1925 $indentlimits->max = 16;
1926 if (right_to_left()) { // Exchange arrows on RTL
1927 $rightarrow = 't/left';
1928 $leftarrow = 't/right';
1929 } else {
1930 $rightarrow = 't/right';
1931 $leftarrow = 't/left';
1934 if ($indent >= $indentlimits->max) {
1935 $enabledclass = 'hidden';
1936 } else {
1937 $enabledclass = '';
1939 $actions['moveright'] = new action_menu_link_secondary(
1940 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
1941 new pix_icon($rightarrow, '', 'moodle', array('class' => 'iconsmall')),
1942 $str->moveright,
1943 array('class' => 'editing_moveright ' . $enabledclass, 'data-action' => 'moveright',
1944 'data-keepopen' => true, 'data-sectionreturn' => $sr)
1947 if ($indent <= $indentlimits->min) {
1948 $enabledclass = 'hidden';
1949 } else {
1950 $enabledclass = '';
1952 $actions['moveleft'] = new action_menu_link_secondary(
1953 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
1954 new pix_icon($leftarrow, '', 'moodle', array('class' => 'iconsmall')),
1955 $str->moveleft,
1956 array('class' => 'editing_moveleft ' . $enabledclass, 'data-action' => 'moveleft',
1957 'data-keepopen' => true, 'data-sectionreturn' => $sr)
1962 // Hide/Show/Available/Unavailable.
1963 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
1964 $allowstealth = !empty($CFG->allowstealth) && $courseformat->allow_stealth_module_visibility($mod, $mod->get_section_info());
1966 $sectionvisible = $mod->get_section_info()->visible;
1967 // The module on the course page may be in one of the following states:
1968 // - Available and displayed on the course page ($displayedoncoursepage);
1969 // - Not available and not displayed on the course page ($unavailable);
1970 // - Available but not displayed on the course page ($stealth) - this can also be a visible activity in a hidden section.
1971 $displayedoncoursepage = $mod->visible && $mod->visibleoncoursepage && $sectionvisible;
1972 $unavailable = !$mod->visible;
1973 $stealth = $mod->visible && (!$mod->visibleoncoursepage || !$sectionvisible);
1974 if ($displayedoncoursepage) {
1975 $actions['hide'] = new action_menu_link_secondary(
1976 new moodle_url($baseurl, array('hide' => $mod->id)),
1977 new pix_icon('t/hide', '', 'moodle', array('class' => 'iconsmall')),
1978 $str->modhide,
1979 array('class' => 'editing_hide', 'data-action' => 'hide')
1981 } else if (!$displayedoncoursepage && $sectionvisible) {
1982 // Offer to "show" only if the section is visible.
1983 $actions['show'] = new action_menu_link_secondary(
1984 new moodle_url($baseurl, array('show' => $mod->id)),
1985 new pix_icon('t/show', '', 'moodle', array('class' => 'iconsmall')),
1986 $str->modshow,
1987 array('class' => 'editing_show', 'data-action' => 'show')
1991 if ($stealth) {
1992 // When making the "stealth" module unavailable we perform the same action as hiding the visible module.
1993 $actions['hide'] = new action_menu_link_secondary(
1994 new moodle_url($baseurl, array('hide' => $mod->id)),
1995 new pix_icon('t/unblock', '', 'moodle', array('class' => 'iconsmall')),
1996 $str->makeunavailable,
1997 array('class' => 'editing_makeunavailable', 'data-action' => 'hide', 'data-sectionreturn' => $sr)
1999 } else if ($unavailable && (!$sectionvisible || $allowstealth) && $mod->has_view()) {
2000 // Allow to make visually hidden module available in gradebook and other reports by making it a "stealth" module.
2001 // When the section is hidden it is an equivalent of "showing" the module.
2002 // Activities without the link (i.e. labels) can not be made available but hidden on course page.
2003 $action = $sectionvisible ? 'stealth' : 'show';
2004 $actions[$action] = new action_menu_link_secondary(
2005 new moodle_url($baseurl, array($action => $mod->id)),
2006 new pix_icon('t/block', '', 'moodle', array('class' => 'iconsmall')),
2007 $str->makeavailable,
2008 array('class' => 'editing_makeavailable', 'data-action' => $action, 'data-sectionreturn' => $sr)
2013 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
2014 if (has_all_capabilities($dupecaps, $coursecontext) &&
2015 plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2) &&
2016 course_allowed_module($mod->get_course(), $mod->modname)) {
2017 $actions['duplicate'] = new action_menu_link_secondary(
2018 new moodle_url($baseurl, array('duplicate' => $mod->id)),
2019 new pix_icon('t/copy', '', 'moodle', array('class' => 'iconsmall')),
2020 $str->duplicate,
2021 array('class' => 'editing_duplicate', 'data-action' => 'duplicate', 'data-sectionreturn' => $sr)
2025 // Groupmode.
2026 if ($hasmanageactivities && !$mod->coursegroupmodeforce) {
2027 if (plugin_supports('mod', $mod->modname, FEATURE_GROUPS, false)) {
2028 if ($mod->effectivegroupmode == SEPARATEGROUPS) {
2029 $nextgroupmode = VISIBLEGROUPS;
2030 $grouptitle = $str->groupsseparate;
2031 $actionname = 'groupsseparate';
2032 $nextactionname = 'groupsvisible';
2033 $groupimage = 'i/groups';
2034 } else if ($mod->effectivegroupmode == VISIBLEGROUPS) {
2035 $nextgroupmode = NOGROUPS;
2036 $grouptitle = $str->groupsvisible;
2037 $actionname = 'groupsvisible';
2038 $nextactionname = 'groupsnone';
2039 $groupimage = 'i/groupv';
2040 } else {
2041 $nextgroupmode = SEPARATEGROUPS;
2042 $grouptitle = $str->groupsnone;
2043 $actionname = 'groupsnone';
2044 $nextactionname = 'groupsseparate';
2045 $groupimage = 'i/groupn';
2048 $actions[$actionname] = new action_menu_link_primary(
2049 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $nextgroupmode)),
2050 new pix_icon($groupimage, '', 'moodle', array('class' => 'iconsmall')),
2051 $grouptitle,
2052 array('class' => 'editing_'. $actionname, 'data-action' => $nextactionname,
2053 'aria-live' => 'assertive', 'data-sectionreturn' => $sr)
2055 } else {
2056 $actions['nogroupsupport'] = new action_menu_filler();
2060 // Assign.
2061 if (has_capability('moodle/role:assign', $modcontext)){
2062 $actions['assign'] = new action_menu_link_secondary(
2063 new moodle_url('/admin/roles/assign.php', array('contextid' => $modcontext->id)),
2064 new pix_icon('t/assignroles', '', 'moodle', array('class' => 'iconsmall')),
2065 $str->assign,
2066 array('class' => 'editing_assign', 'data-action' => 'assignroles', 'data-sectionreturn' => $sr)
2070 // Delete.
2071 if ($hasmanageactivities) {
2072 $actions['delete'] = new action_menu_link_secondary(
2073 new moodle_url($baseurl, array('delete' => $mod->id)),
2074 new pix_icon('t/delete', '', 'moodle', array('class' => 'iconsmall')),
2075 $str->delete,
2076 array('class' => 'editing_delete', 'data-action' => 'delete', 'data-sectionreturn' => $sr)
2080 return $actions;
2084 * Returns the move action.
2086 * @param cm_info $mod The module to produce a move button for
2087 * @param int $sr The section to link back to (used for creating the links)
2088 * @return The markup for the move action, or an empty string if not available.
2090 function course_get_cm_move(cm_info $mod, $sr = null) {
2091 global $OUTPUT;
2093 static $str;
2094 static $baseurl;
2096 $modcontext = context_module::instance($mod->id);
2097 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
2099 if (!isset($str)) {
2100 $str = get_strings(array('move'));
2103 if (!isset($baseurl)) {
2104 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
2106 if ($sr !== null) {
2107 $baseurl->param('sr', $sr);
2111 if ($hasmanageactivities) {
2112 $pixicon = 'i/dragdrop';
2114 if (!course_ajax_enabled($mod->get_course())) {
2115 // Override for course frontpage until we get drag/drop working there.
2116 $pixicon = 't/move';
2119 return html_writer::link(
2120 new moodle_url($baseurl, array('copy' => $mod->id)),
2121 $OUTPUT->pix_icon($pixicon, $str->move, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2122 array('class' => 'editing_move', 'data-action' => 'move', 'data-sectionreturn' => $sr)
2125 return '';
2129 * given a course object with shortname & fullname, this function will
2130 * truncate the the number of chars allowed and add ... if it was too long
2132 function course_format_name ($course,$max=100) {
2134 $context = context_course::instance($course->id);
2135 $shortname = format_string($course->shortname, true, array('context' => $context));
2136 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
2137 $str = $shortname.': '. $fullname;
2138 if (core_text::strlen($str) <= $max) {
2139 return $str;
2141 else {
2142 return core_text::substr($str,0,$max-3).'...';
2147 * Is the user allowed to add this type of module to this course?
2148 * @param object $course the course settings. Only $course->id is used.
2149 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
2150 * @return bool whether the current user is allowed to add this type of module to this course.
2152 function course_allowed_module($course, $modname) {
2153 if (is_numeric($modname)) {
2154 throw new coding_exception('Function course_allowed_module no longer
2155 supports numeric module ids. Please update your code to pass the module name.');
2158 $capability = 'mod/' . $modname . ':addinstance';
2159 if (!get_capability_info($capability)) {
2160 // Debug warning that the capability does not exist, but no more than once per page.
2161 static $warned = array();
2162 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
2163 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
2164 debugging('The module ' . $modname . ' does not define the standard capability ' .
2165 $capability , DEBUG_DEVELOPER);
2166 $warned[$modname] = 1;
2169 // If the capability does not exist, the module can always be added.
2170 return true;
2173 $coursecontext = context_course::instance($course->id);
2174 return has_capability($capability, $coursecontext);
2178 * Efficiently moves many courses around while maintaining
2179 * sortorder in order.
2181 * @param array $courseids is an array of course ids
2182 * @param int $categoryid
2183 * @return bool success
2185 function move_courses($courseids, $categoryid) {
2186 global $DB;
2188 if (empty($courseids)) {
2189 // Nothing to do.
2190 return false;
2193 if (!$category = $DB->get_record('course_categories', array('id' => $categoryid))) {
2194 return false;
2197 $courseids = array_reverse($courseids);
2198 $newparent = context_coursecat::instance($category->id);
2199 $i = 1;
2201 list($where, $params) = $DB->get_in_or_equal($courseids);
2202 $dbcourses = $DB->get_records_select('course', 'id ' . $where, $params, '', 'id, category, shortname, fullname');
2203 foreach ($dbcourses as $dbcourse) {
2204 $course = new stdClass();
2205 $course->id = $dbcourse->id;
2206 $course->category = $category->id;
2207 $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
2208 if ($category->visible == 0) {
2209 // Hide the course when moving into hidden category, do not update the visibleold flag - we want to get
2210 // to previous state if somebody unhides the category.
2211 $course->visible = 0;
2214 $DB->update_record('course', $course);
2216 // Update context, so it can be passed to event.
2217 $context = context_course::instance($course->id);
2218 $context->update_moved($newparent);
2220 // Trigger a course updated event.
2221 $event = \core\event\course_updated::create(array(
2222 'objectid' => $course->id,
2223 'context' => context_course::instance($course->id),
2224 'other' => array('shortname' => $dbcourse->shortname,
2225 'fullname' => $dbcourse->fullname,
2226 'updatedfields' => array('category' => $category->id))
2228 $event->set_legacy_logdata(array($course->id, 'course', 'move', 'edit.php?id=' . $course->id, $course->id));
2229 $event->trigger();
2231 fix_course_sortorder();
2232 cache_helper::purge_by_event('changesincourse');
2234 return true;
2238 * Returns the display name of the given section that the course prefers
2240 * Implementation of this function is provided by course format
2241 * @see format_base::get_section_name()
2243 * @param int|stdClass $courseorid The course to get the section name for (object or just course id)
2244 * @param int|stdClass $section Section object from database or just field course_sections.section
2245 * @return string Display name that the course format prefers, e.g. "Week 2"
2247 function get_section_name($courseorid, $section) {
2248 return course_get_format($courseorid)->get_section_name($section);
2252 * Tells if current course format uses sections
2254 * @param string $format Course format ID e.g. 'weeks' $course->format
2255 * @return bool
2257 function course_format_uses_sections($format) {
2258 $course = new stdClass();
2259 $course->format = $format;
2260 return course_get_format($course)->uses_sections();
2264 * Returns the information about the ajax support in the given source format
2266 * The returned object's property (boolean)capable indicates that
2267 * the course format supports Moodle course ajax features.
2269 * @param string $format
2270 * @return stdClass
2272 function course_format_ajax_support($format) {
2273 $course = new stdClass();
2274 $course->format = $format;
2275 return course_get_format($course)->supports_ajax();
2279 * Can the current user delete this course?
2280 * Course creators have exception,
2281 * 1 day after the creation they can sill delete the course.
2282 * @param int $courseid
2283 * @return boolean
2285 function can_delete_course($courseid) {
2286 global $USER;
2288 $context = context_course::instance($courseid);
2290 if (has_capability('moodle/course:delete', $context)) {
2291 return true;
2294 // hack: now try to find out if creator created this course recently (1 day)
2295 if (!has_capability('moodle/course:create', $context)) {
2296 return false;
2299 $since = time() - 60*60*24;
2300 $course = get_course($courseid);
2302 if ($course->timecreated < $since) {
2303 return false; // Return if the course was not created in last 24 hours.
2306 $logmanger = get_log_manager();
2307 $readers = $logmanger->get_readers('\core\log\sql_reader');
2308 $reader = reset($readers);
2310 if (empty($reader)) {
2311 return false; // No log reader found.
2314 // A proper reader.
2315 $select = "userid = :userid AND courseid = :courseid AND eventname = :eventname AND timecreated > :since";
2316 $params = array('userid' => $USER->id, 'since' => $since, 'courseid' => $course->id, 'eventname' => '\core\event\course_created');
2318 return (bool)$reader->get_events_select_count($select, $params);
2322 * Save the Your name for 'Some role' strings.
2324 * @param integer $courseid the id of this course.
2325 * @param array $data the data that came from the course settings form.
2327 function save_local_role_names($courseid, $data) {
2328 global $DB;
2329 $context = context_course::instance($courseid);
2331 foreach ($data as $fieldname => $value) {
2332 if (strpos($fieldname, 'role_') !== 0) {
2333 continue;
2335 list($ignored, $roleid) = explode('_', $fieldname);
2337 // make up our mind whether we want to delete, update or insert
2338 if (!$value) {
2339 $DB->delete_records('role_names', array('contextid' => $context->id, 'roleid' => $roleid));
2341 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id, 'roleid' => $roleid))) {
2342 $rolename->name = $value;
2343 $DB->update_record('role_names', $rolename);
2345 } else {
2346 $rolename = new stdClass;
2347 $rolename->contextid = $context->id;
2348 $rolename->roleid = $roleid;
2349 $rolename->name = $value;
2350 $DB->insert_record('role_names', $rolename);
2352 // This will ensure the course contacts cache is purged..
2353 core_course_category::role_assignment_changed($roleid, $context);
2358 * Returns options to use in course overviewfiles filemanager
2360 * @param null|stdClass|core_course_list_element|int $course either object that has 'id' property or just the course id;
2361 * may be empty if course does not exist yet (course create form)
2362 * @return array|null array of options such as maxfiles, maxbytes, accepted_types, etc.
2363 * or null if overviewfiles are disabled
2365 function course_overviewfiles_options($course) {
2366 global $CFG;
2367 if (empty($CFG->courseoverviewfileslimit)) {
2368 return null;
2370 $accepted_types = preg_split('/\s*,\s*/', trim($CFG->courseoverviewfilesext), -1, PREG_SPLIT_NO_EMPTY);
2371 if (in_array('*', $accepted_types) || empty($accepted_types)) {
2372 $accepted_types = '*';
2373 } else {
2374 // Since config for $CFG->courseoverviewfilesext is a text box, human factor must be considered.
2375 // Make sure extensions are prefixed with dot unless they are valid typegroups
2376 foreach ($accepted_types as $i => $type) {
2377 if (substr($type, 0, 1) !== '.') {
2378 require_once($CFG->libdir. '/filelib.php');
2379 if (!count(file_get_typegroup('extension', $type))) {
2380 // It does not start with dot and is not a valid typegroup, this is most likely extension.
2381 $accepted_types[$i] = '.'. $type;
2382 $corrected = true;
2386 if (!empty($corrected)) {
2387 set_config('courseoverviewfilesext', join(',', $accepted_types));
2390 $options = array(
2391 'maxfiles' => $CFG->courseoverviewfileslimit,
2392 'maxbytes' => $CFG->maxbytes,
2393 'subdirs' => 0,
2394 'accepted_types' => $accepted_types
2396 if (!empty($course->id)) {
2397 $options['context'] = context_course::instance($course->id);
2398 } else if (is_int($course) && $course > 0) {
2399 $options['context'] = context_course::instance($course);
2401 return $options;
2405 * Create a course and either return a $course object
2407 * Please note this functions does not verify any access control,
2408 * the calling code is responsible for all validation (usually it is the form definition).
2410 * @param array $editoroptions course description editor options
2411 * @param object $data - all the data needed for an entry in the 'course' table
2412 * @return object new course instance
2414 function create_course($data, $editoroptions = NULL) {
2415 global $DB, $CFG;
2417 //check the categoryid - must be given for all new courses
2418 $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
2420 // Check if the shortname already exists.
2421 if (!empty($data->shortname)) {
2422 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
2423 throw new moodle_exception('shortnametaken', '', '', $data->shortname);
2427 // Check if the idnumber already exists.
2428 if (!empty($data->idnumber)) {
2429 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
2430 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber);
2434 if (empty($CFG->enablecourserelativedates)) {
2435 // Make sure we're not setting the relative dates mode when the setting is disabled.
2436 unset($data->relativedatesmode);
2439 if ($errorcode = course_validate_dates((array)$data)) {
2440 throw new moodle_exception($errorcode);
2443 // Check if timecreated is given.
2444 $data->timecreated = !empty($data->timecreated) ? $data->timecreated : time();
2445 $data->timemodified = $data->timecreated;
2447 // place at beginning of any category
2448 $data->sortorder = 0;
2450 if ($editoroptions) {
2451 // summary text is updated later, we need context to store the files first
2452 $data->summary = '';
2453 $data->summary_format = FORMAT_HTML;
2456 if (!isset($data->visible)) {
2457 // data not from form, add missing visibility info
2458 $data->visible = $category->visible;
2460 $data->visibleold = $data->visible;
2462 $newcourseid = $DB->insert_record('course', $data);
2463 $context = context_course::instance($newcourseid, MUST_EXIST);
2465 if ($editoroptions) {
2466 // Save the files used in the summary editor and store
2467 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2468 $DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid));
2469 $DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid));
2471 if ($overviewfilesoptions = course_overviewfiles_options($newcourseid)) {
2472 // Save the course overviewfiles
2473 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2476 // update course format options
2477 course_get_format($newcourseid)->update_course_format_options($data);
2479 $course = course_get_format($newcourseid)->get_course();
2481 fix_course_sortorder();
2482 // purge appropriate caches in case fix_course_sortorder() did not change anything
2483 cache_helper::purge_by_event('changesincourse');
2485 // Trigger a course created event.
2486 $event = \core\event\course_created::create(array(
2487 'objectid' => $course->id,
2488 'context' => context_course::instance($course->id),
2489 'other' => array('shortname' => $course->shortname,
2490 'fullname' => $course->fullname)
2493 $event->trigger();
2495 // Setup the blocks
2496 blocks_add_default_course_blocks($course);
2498 // Create default section and initial sections if specified (unless they've already been created earlier).
2499 // We do not want to call course_create_sections_if_missing() because to avoid creating course cache.
2500 $numsections = isset($data->numsections) ? $data->numsections : 0;
2501 $existingsections = $DB->get_fieldset_sql('SELECT section from {course_sections} WHERE course = ?', [$newcourseid]);
2502 $newsections = array_diff(range(0, $numsections), $existingsections);
2503 foreach ($newsections as $sectionnum) {
2504 course_create_section($newcourseid, $sectionnum, true);
2507 // Save any custom role names.
2508 save_local_role_names($course->id, (array)$data);
2510 // set up enrolments
2511 enrol_course_updated(true, $course, $data);
2513 // Update course tags.
2514 if (isset($data->tags)) {
2515 core_tag_tag::set_item_tags('core', 'course', $course->id, context_course::instance($course->id), $data->tags);
2518 // Save custom fields if there are any of them in the form.
2519 $handler = core_course\customfield\course_handler::create();
2520 // Make sure to set the handler's parent context first.
2521 $coursecatcontext = context_coursecat::instance($category->id);
2522 $handler->set_parent_context($coursecatcontext);
2523 // Save the custom field data.
2524 $data->id = $course->id;
2525 $handler->instance_form_save($data, true);
2527 return $course;
2531 * Update a course.
2533 * Please note this functions does not verify any access control,
2534 * the calling code is responsible for all validation (usually it is the form definition).
2536 * @param object $data - all the data needed for an entry in the 'course' table
2537 * @param array $editoroptions course description editor options
2538 * @return void
2540 function update_course($data, $editoroptions = NULL) {
2541 global $DB, $CFG;
2543 // Prevent changes on front page course.
2544 if ($data->id == SITEID) {
2545 throw new moodle_exception('invalidcourse', 'error');
2548 $oldcourse = course_get_format($data->id)->get_course();
2549 $context = context_course::instance($oldcourse->id);
2551 // Make sure we're not changing whatever the course's relativedatesmode setting is.
2552 unset($data->relativedatesmode);
2554 // Capture the updated fields for the log data.
2555 $updatedfields = [];
2556 foreach (get_object_vars($oldcourse) as $field => $value) {
2557 if ($field == 'summary_editor') {
2558 if (($data->$field)['text'] !== $value['text']) {
2559 // The summary might be very long, we don't wan't to fill up the log record with the full text.
2560 $updatedfields[$field] = '(updated)';
2562 } else if ($field == 'tags' && !empty($CFG->usetags)) {
2563 // Tags might not have the same array keys, just check the values.
2564 if (array_values($data->$field) !== array_values($value)) {
2565 $updatedfields[$field] = $data->$field;
2567 } else {
2568 if (isset($data->$field) && $data->$field != $value) {
2569 $updatedfields[$field] = $data->$field;
2574 $data->timemodified = time();
2576 if ($editoroptions) {
2577 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2579 if ($overviewfilesoptions = course_overviewfiles_options($data->id)) {
2580 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2583 // Check we don't have a duplicate shortname.
2584 if (!empty($data->shortname) && $oldcourse->shortname != $data->shortname) {
2585 if ($DB->record_exists_sql('SELECT id from {course} WHERE shortname = ? AND id <> ?', array($data->shortname, $data->id))) {
2586 throw new moodle_exception('shortnametaken', '', '', $data->shortname);
2590 // Check we don't have a duplicate idnumber.
2591 if (!empty($data->idnumber) && $oldcourse->idnumber != $data->idnumber) {
2592 if ($DB->record_exists_sql('SELECT id from {course} WHERE idnumber = ? AND id <> ?', array($data->idnumber, $data->id))) {
2593 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber);
2597 if ($errorcode = course_validate_dates((array)$data)) {
2598 throw new moodle_exception($errorcode);
2601 if (!isset($data->category) or empty($data->category)) {
2602 // prevent nulls and 0 in category field
2603 unset($data->category);
2605 $changesincoursecat = $movecat = (isset($data->category) and $oldcourse->category != $data->category);
2607 if (!isset($data->visible)) {
2608 // data not from form, add missing visibility info
2609 $data->visible = $oldcourse->visible;
2612 if ($data->visible != $oldcourse->visible) {
2613 // reset the visibleold flag when manually hiding/unhiding course
2614 $data->visibleold = $data->visible;
2615 $changesincoursecat = true;
2616 } else {
2617 if ($movecat) {
2618 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category));
2619 if (empty($newcategory->visible)) {
2620 // make sure when moving into hidden category the course is hidden automatically
2621 $data->visible = 0;
2626 // Set newsitems to 0 if format does not support announcements.
2627 if (isset($data->format)) {
2628 $newcourseformat = course_get_format((object)['format' => $data->format]);
2629 if (!$newcourseformat->supports_news()) {
2630 $data->newsitems = 0;
2634 // Update custom fields if there are any of them in the form.
2635 $handler = core_course\customfield\course_handler::create();
2636 $handler->instance_form_save($data);
2638 // Update with the new data
2639 $DB->update_record('course', $data);
2640 // make sure the modinfo cache is reset
2641 rebuild_course_cache($data->id);
2643 // update course format options with full course data
2644 course_get_format($data->id)->update_course_format_options($data, $oldcourse);
2646 $course = $DB->get_record('course', array('id'=>$data->id));
2648 if ($movecat) {
2649 $newparent = context_coursecat::instance($course->category);
2650 $context->update_moved($newparent);
2652 $fixcoursesortorder = $movecat || (isset($data->sortorder) && ($oldcourse->sortorder != $data->sortorder));
2653 if ($fixcoursesortorder) {
2654 fix_course_sortorder();
2657 // purge appropriate caches in case fix_course_sortorder() did not change anything
2658 cache_helper::purge_by_event('changesincourse');
2659 if ($changesincoursecat) {
2660 cache_helper::purge_by_event('changesincoursecat');
2663 // Test for and remove blocks which aren't appropriate anymore
2664 blocks_remove_inappropriate($course);
2666 // Save any custom role names.
2667 save_local_role_names($course->id, $data);
2669 // update enrol settings
2670 enrol_course_updated(false, $course, $data);
2672 // Update course tags.
2673 if (isset($data->tags)) {
2674 core_tag_tag::set_item_tags('core', 'course', $course->id, context_course::instance($course->id), $data->tags);
2677 // Trigger a course updated event.
2678 $event = \core\event\course_updated::create(array(
2679 'objectid' => $course->id,
2680 'context' => context_course::instance($course->id),
2681 'other' => array('shortname' => $course->shortname,
2682 'fullname' => $course->fullname,
2683 'updatedfields' => $updatedfields)
2686 $event->set_legacy_logdata(array($course->id, 'course', 'update', 'edit.php?id=' . $course->id, $course->id));
2687 $event->trigger();
2689 if ($oldcourse->format !== $course->format) {
2690 // Remove all options stored for the previous format
2691 // We assume that new course format migrated everything it needed watching trigger
2692 // 'course_updated' and in method format_XXX::update_course_format_options()
2693 $DB->delete_records('course_format_options',
2694 array('courseid' => $course->id, 'format' => $oldcourse->format));
2699 * Average number of participants
2700 * @return integer
2702 function average_number_of_participants() {
2703 global $DB, $SITE;
2705 //count total of enrolments for visible course (except front page)
2706 $sql = 'SELECT COUNT(*) FROM (
2707 SELECT DISTINCT ue.userid, e.courseid
2708 FROM {user_enrolments} ue, {enrol} e, {course} c
2709 WHERE ue.enrolid = e.id
2710 AND e.courseid <> :siteid
2711 AND c.id = e.courseid
2712 AND c.visible = 1) total';
2713 $params = array('siteid' => $SITE->id);
2714 $enrolmenttotal = $DB->count_records_sql($sql, $params);
2717 //count total of visible courses (minus front page)
2718 $coursetotal = $DB->count_records('course', array('visible' => 1));
2719 $coursetotal = $coursetotal - 1 ;
2721 //average of enrolment
2722 if (empty($coursetotal)) {
2723 $participantaverage = 0;
2724 } else {
2725 $participantaverage = $enrolmenttotal / $coursetotal;
2728 return $participantaverage;
2732 * Average number of course modules
2733 * @return integer
2735 function average_number_of_courses_modules() {
2736 global $DB, $SITE;
2738 //count total of visible course module (except front page)
2739 $sql = 'SELECT COUNT(*) FROM (
2740 SELECT cm.course, cm.module
2741 FROM {course} c, {course_modules} cm
2742 WHERE c.id = cm.course
2743 AND c.id <> :siteid
2744 AND cm.visible = 1
2745 AND c.visible = 1) total';
2746 $params = array('siteid' => $SITE->id);
2747 $moduletotal = $DB->count_records_sql($sql, $params);
2750 //count total of visible courses (minus front page)
2751 $coursetotal = $DB->count_records('course', array('visible' => 1));
2752 $coursetotal = $coursetotal - 1 ;
2754 //average of course module
2755 if (empty($coursetotal)) {
2756 $coursemoduleaverage = 0;
2757 } else {
2758 $coursemoduleaverage = $moduletotal / $coursetotal;
2761 return $coursemoduleaverage;
2765 * This class pertains to course requests and contains methods associated with
2766 * create, approving, and removing course requests.
2768 * Please note we do not allow embedded images here because there is no context
2769 * to store them with proper access control.
2771 * @copyright 2009 Sam Hemelryk
2772 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2773 * @since Moodle 2.0
2775 * @property-read int $id
2776 * @property-read string $fullname
2777 * @property-read string $shortname
2778 * @property-read string $summary
2779 * @property-read int $summaryformat
2780 * @property-read int $summarytrust
2781 * @property-read string $reason
2782 * @property-read int $requester
2784 class course_request {
2787 * This is the stdClass that stores the properties for the course request
2788 * and is externally accessed through the __get magic method
2789 * @var stdClass
2791 protected $properties;
2794 * An array of options for the summary editor used by course request forms.
2795 * This is initially set by {@link summary_editor_options()}
2796 * @var array
2797 * @static
2799 protected static $summaryeditoroptions;
2802 * Static function to prepare the summary editor for working with a course
2803 * request.
2805 * @static
2806 * @param null|stdClass $data Optional, an object containing the default values
2807 * for the form, these may be modified when preparing the
2808 * editor so this should be called before creating the form
2809 * @return stdClass An object that can be used to set the default values for
2810 * an mforms form
2812 public static function prepare($data=null) {
2813 if ($data === null) {
2814 $data = new stdClass;
2816 $data = file_prepare_standard_editor($data, 'summary', self::summary_editor_options());
2817 return $data;
2821 * Static function to create a new course request when passed an array of properties
2822 * for it.
2824 * This function also handles saving any files that may have been used in the editor
2826 * @static
2827 * @param stdClass $data
2828 * @return course_request The newly created course request
2830 public static function create($data) {
2831 global $USER, $DB, $CFG;
2832 $data->requester = $USER->id;
2834 // Setting the default category if none set.
2835 if (empty($data->category) || empty($CFG->requestcategoryselection)) {
2836 $data->category = $CFG->defaultrequestcategory;
2839 // Summary is a required field so copy the text over
2840 $data->summary = $data->summary_editor['text'];
2841 $data->summaryformat = $data->summary_editor['format'];
2843 $data->id = $DB->insert_record('course_request', $data);
2845 // Create a new course_request object and return it
2846 $request = new course_request($data);
2848 // Notify the admin if required.
2849 if ($users = get_users_from_config($CFG->courserequestnotify, 'moodle/site:approvecourse')) {
2851 $a = new stdClass;
2852 $a->link = "$CFG->wwwroot/course/pending.php";
2853 $a->user = fullname($USER);
2854 $subject = get_string('courserequest');
2855 $message = get_string('courserequestnotifyemail', 'admin', $a);
2856 foreach ($users as $user) {
2857 $request->notify($user, $USER, 'courserequested', $subject, $message);
2861 return $request;
2865 * Returns an array of options to use with a summary editor
2867 * @uses course_request::$summaryeditoroptions
2868 * @return array An array of options to use with the editor
2870 public static function summary_editor_options() {
2871 global $CFG;
2872 if (self::$summaryeditoroptions === null) {
2873 self::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
2875 return self::$summaryeditoroptions;
2879 * Loads the properties for this course request object. Id is required and if
2880 * only id is provided then we load the rest of the properties from the database
2882 * @param stdClass|int $properties Either an object containing properties
2883 * or the course_request id to load
2885 public function __construct($properties) {
2886 global $DB;
2887 if (empty($properties->id)) {
2888 if (empty($properties)) {
2889 throw new coding_exception('You must provide a course request id when creating a course_request object');
2891 $id = $properties;
2892 $properties = new stdClass;
2893 $properties->id = (int)$id;
2894 unset($id);
2896 if (empty($properties->requester)) {
2897 if (!($this->properties = $DB->get_record('course_request', array('id' => $properties->id)))) {
2898 print_error('unknowncourserequest');
2900 } else {
2901 $this->properties = $properties;
2903 $this->properties->collision = null;
2907 * Returns the requested property
2909 * @param string $key
2910 * @return mixed
2912 public function __get($key) {
2913 return $this->properties->$key;
2917 * Override this to ensure empty($request->blah) calls return a reliable answer...
2919 * This is required because we define the __get method
2921 * @param mixed $key
2922 * @return bool True is it not empty, false otherwise
2924 public function __isset($key) {
2925 return (!empty($this->properties->$key));
2929 * Returns the user who requested this course
2931 * Uses a static var to cache the results and cut down the number of db queries
2933 * @staticvar array $requesters An array of cached users
2934 * @return stdClass The user who requested the course
2936 public function get_requester() {
2937 global $DB;
2938 static $requesters= array();
2939 if (!array_key_exists($this->properties->requester, $requesters)) {
2940 $requesters[$this->properties->requester] = $DB->get_record('user', array('id'=>$this->properties->requester));
2942 return $requesters[$this->properties->requester];
2946 * Checks that the shortname used by the course does not conflict with any other
2947 * courses that exist
2949 * @param string|null $shortnamemark The string to append to the requests shortname
2950 * should a conflict be found
2951 * @return bool true is there is a conflict, false otherwise
2953 public function check_shortname_collision($shortnamemark = '[*]') {
2954 global $DB;
2956 if ($this->properties->collision !== null) {
2957 return $this->properties->collision;
2960 if (empty($this->properties->shortname)) {
2961 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER);
2962 $this->properties->collision = false;
2963 } else if ($DB->record_exists('course', array('shortname' => $this->properties->shortname))) {
2964 if (!empty($shortnamemark)) {
2965 $this->properties->shortname .= ' '.$shortnamemark;
2967 $this->properties->collision = true;
2968 } else {
2969 $this->properties->collision = false;
2971 return $this->properties->collision;
2975 * Returns the category where this course request should be created
2977 * Note that we don't check here that user has a capability to view
2978 * hidden categories if he has capabilities 'moodle/site:approvecourse' and
2979 * 'moodle/course:changecategory'
2981 * @return core_course_category
2983 public function get_category() {
2984 global $CFG;
2985 // If the category is not set, if the current user does not have the rights to change the category, or if the
2986 // category does not exist, we set the default category to the course to be approved.
2987 // The system level is used because the capability moodle/site:approvecourse is based on a system level.
2988 if (empty($this->properties->category) || !has_capability('moodle/course:changecategory', context_system::instance()) ||
2989 (!$category = core_course_category::get($this->properties->category, IGNORE_MISSING, true))) {
2990 $category = core_course_category::get($CFG->defaultrequestcategory, IGNORE_MISSING, true);
2992 if (!$category) {
2993 $category = core_course_category::get_default();
2995 return $category;
2999 * This function approves the request turning it into a course
3001 * This function converts the course request into a course, at the same time
3002 * transferring any files used in the summary to the new course and then removing
3003 * the course request and the files associated with it.
3005 * @return int The id of the course that was created from this request
3007 public function approve() {
3008 global $CFG, $DB, $USER;
3010 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
3012 $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted'=>0), '*', MUST_EXIST);
3014 $courseconfig = get_config('moodlecourse');
3016 // Transfer appropriate settings
3017 $data = clone($this->properties);
3018 unset($data->id);
3019 unset($data->reason);
3020 unset($data->requester);
3022 // Set category
3023 $category = $this->get_category();
3024 $data->category = $category->id;
3025 // Set misc settings
3026 $data->requested = 1;
3028 // Apply course default settings
3029 $data->format = $courseconfig->format;
3030 $data->newsitems = $courseconfig->newsitems;
3031 $data->showgrades = $courseconfig->showgrades;
3032 $data->showreports = $courseconfig->showreports;
3033 $data->maxbytes = $courseconfig->maxbytes;
3034 $data->groupmode = $courseconfig->groupmode;
3035 $data->groupmodeforce = $courseconfig->groupmodeforce;
3036 $data->visible = $courseconfig->visible;
3037 $data->visibleold = $data->visible;
3038 $data->lang = $courseconfig->lang;
3039 $data->enablecompletion = $courseconfig->enablecompletion;
3040 $data->numsections = $courseconfig->numsections;
3041 $data->startdate = usergetmidnight(time());
3042 if ($courseconfig->courseenddateenabled) {
3043 $data->enddate = usergetmidnight(time()) + $courseconfig->courseduration;
3046 list($data->fullname, $data->shortname) = restore_dbops::calculate_course_names(0, $data->fullname, $data->shortname);
3048 $course = create_course($data);
3049 $context = context_course::instance($course->id, MUST_EXIST);
3051 // add enrol instances
3052 if (!$DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
3053 if ($manual = enrol_get_plugin('manual')) {
3054 $manual->add_default_instance($course);
3058 // enrol the requester as teacher if necessary
3059 if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
3060 enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid);
3063 $this->delete();
3065 $a = new stdClass();
3066 $a->name = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
3067 $a->url = $CFG->wwwroot.'/course/view.php?id=' . $course->id;
3068 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a), $course->id);
3070 return $course->id;
3074 * Reject a course request
3076 * This function rejects a course request, emailing the requesting user the
3077 * provided notice and then removing the request from the database
3079 * @param string $notice The message to display to the user
3081 public function reject($notice) {
3082 global $USER, $DB;
3083 $user = $DB->get_record('user', array('id' => $this->properties->requester), '*', MUST_EXIST);
3084 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
3085 $this->delete();
3089 * Deletes the course request and any associated files
3091 public function delete() {
3092 global $DB;
3093 $DB->delete_records('course_request', array('id' => $this->properties->id));
3097 * Send a message from one user to another using events_trigger
3099 * @param object $touser
3100 * @param object $fromuser
3101 * @param string $name
3102 * @param string $subject
3103 * @param string $message
3104 * @param int|null $courseid
3106 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message, $courseid = null) {
3107 $eventdata = new \core\message\message();
3108 $eventdata->courseid = empty($courseid) ? SITEID : $courseid;
3109 $eventdata->component = 'moodle';
3110 $eventdata->name = $name;
3111 $eventdata->userfrom = $fromuser;
3112 $eventdata->userto = $touser;
3113 $eventdata->subject = $subject;
3114 $eventdata->fullmessage = $message;
3115 $eventdata->fullmessageformat = FORMAT_PLAIN;
3116 $eventdata->fullmessagehtml = '';
3117 $eventdata->smallmessage = '';
3118 $eventdata->notification = 1;
3119 message_send($eventdata);
3124 * Return a list of page types
3125 * @param string $pagetype current page type
3126 * @param context $parentcontext Block's parent context
3127 * @param context $currentcontext Current context of block
3128 * @return array array of page types
3130 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
3131 if ($pagetype === 'course-index' || $pagetype === 'course-index-category') {
3132 // For courses and categories browsing pages (/course/index.php) add option to show on ANY category page
3133 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
3134 'course-index-*' => get_string('page-course-index-x', 'pagetype'),
3136 } else if ($currentcontext && (!($coursecontext = $currentcontext->get_course_context(false)) || $coursecontext->instanceid == SITEID)) {
3137 // We know for sure that despite pagetype starts with 'course-' this is not a page in course context (i.e. /course/search.php, etc.)
3138 $pagetypes = array('*' => get_string('page-x', 'pagetype'));
3139 } else {
3140 // Otherwise consider it a page inside a course even if $currentcontext is null
3141 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
3142 'course-*' => get_string('page-course-x', 'pagetype'),
3143 'course-view-*' => get_string('page-course-view-x', 'pagetype')
3146 return $pagetypes;
3150 * Determine whether course ajax should be enabled for the specified course
3152 * @param stdClass $course The course to test against
3153 * @return boolean Whether course ajax is enabled or note
3155 function course_ajax_enabled($course) {
3156 global $CFG, $PAGE, $SITE;
3158 // The user must be editing for AJAX to be included
3159 if (!$PAGE->user_is_editing()) {
3160 return false;
3163 // Check that the theme suports
3164 if (!$PAGE->theme->enablecourseajax) {
3165 return false;
3168 // Check that the course format supports ajax functionality
3169 // The site 'format' doesn't have information on course format support
3170 if ($SITE->id !== $course->id) {
3171 $courseformatajaxsupport = course_format_ajax_support($course->format);
3172 if (!$courseformatajaxsupport->capable) {
3173 return false;
3177 // All conditions have been met so course ajax should be enabled
3178 return true;
3182 * Include the relevant javascript and language strings for the resource
3183 * toolbox YUI module
3185 * @param integer $id The ID of the course being applied to
3186 * @param array $usedmodules An array containing the names of the modules in use on the page
3187 * @param array $enabledmodules An array containing the names of the enabled (visible) modules on this site
3188 * @param stdClass $config An object containing configuration parameters for ajax modules including:
3189 * * resourceurl The URL to post changes to for resource changes
3190 * * sectionurl The URL to post changes to for section changes
3191 * * pageparams Additional parameters to pass through in the post
3192 * @return bool
3194 function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) {
3195 global $CFG, $PAGE, $SITE;
3197 // Ensure that ajax should be included
3198 if (!course_ajax_enabled($course)) {
3199 return false;
3202 if (!$config) {
3203 $config = new stdClass();
3206 // The URL to use for resource changes
3207 if (!isset($config->resourceurl)) {
3208 $config->resourceurl = '/course/rest.php';
3211 // The URL to use for section changes
3212 if (!isset($config->sectionurl)) {
3213 $config->sectionurl = '/course/rest.php';
3216 // Any additional parameters which need to be included on page submission
3217 if (!isset($config->pageparams)) {
3218 $config->pageparams = array();
3221 // Include course dragdrop
3222 if (course_format_uses_sections($course->format)) {
3223 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_section_dragdrop',
3224 array(array(
3225 'courseid' => $course->id,
3226 'ajaxurl' => $config->sectionurl,
3227 'config' => $config,
3228 )), null, true);
3230 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_resource_dragdrop',
3231 array(array(
3232 'courseid' => $course->id,
3233 'ajaxurl' => $config->resourceurl,
3234 'config' => $config,
3235 )), null, true);
3238 // Require various strings for the command toolbox
3239 $PAGE->requires->strings_for_js(array(
3240 'moveleft',
3241 'deletechecktype',
3242 'deletechecktypename',
3243 'edittitle',
3244 'edittitleinstructions',
3245 'show',
3246 'hide',
3247 'highlight',
3248 'highlightoff',
3249 'groupsnone',
3250 'groupsvisible',
3251 'groupsseparate',
3252 'clicktochangeinbrackets',
3253 'markthistopic',
3254 'markedthistopic',
3255 'movesection',
3256 'movecoursemodule',
3257 'movecoursesection',
3258 'movecontent',
3259 'tocontent',
3260 'emptydragdropregion',
3261 'afterresource',
3262 'aftersection',
3263 'totopofsection',
3264 ), 'moodle');
3266 // Include section-specific strings for formats which support sections.
3267 if (course_format_uses_sections($course->format)) {
3268 $PAGE->requires->strings_for_js(array(
3269 'showfromothers',
3270 'hidefromothers',
3271 ), 'format_' . $course->format);
3274 // For confirming resource deletion we need the name of the module in question
3275 foreach ($usedmodules as $module => $modname) {
3276 $PAGE->requires->string_for_js('pluginname', $module);
3279 // Load drag and drop upload AJAX.
3280 require_once($CFG->dirroot.'/course/dnduploadlib.php');
3281 dndupload_add_to_course($course, $enabledmodules);
3283 $PAGE->requires->js_call_amd('core_course/actions', 'initCoursePage', array($course->format));
3285 return true;
3289 * Returns the sorted list of available course formats, filtered by enabled if necessary
3291 * @param bool $enabledonly return only formats that are enabled
3292 * @return array array of sorted format names
3294 function get_sorted_course_formats($enabledonly = false) {
3295 global $CFG;
3296 $formats = core_component::get_plugin_list('format');
3298 if (!empty($CFG->format_plugins_sortorder)) {
3299 $order = explode(',', $CFG->format_plugins_sortorder);
3300 $order = array_merge(array_intersect($order, array_keys($formats)),
3301 array_diff(array_keys($formats), $order));
3302 } else {
3303 $order = array_keys($formats);
3305 if (!$enabledonly) {
3306 return $order;
3308 $sortedformats = array();
3309 foreach ($order as $formatname) {
3310 if (!get_config('format_'.$formatname, 'disabled')) {
3311 $sortedformats[] = $formatname;
3314 return $sortedformats;
3318 * The URL to use for the specified course (with section)
3320 * @param int|stdClass $courseorid The course to get the section name for (either object or just course id)
3321 * @param int|stdClass $section Section object from database or just field course_sections.section
3322 * if omitted the course view page is returned
3323 * @param array $options options for view URL. At the moment core uses:
3324 * 'navigation' (bool) if true and section has no separate page, the function returns null
3325 * 'sr' (int) used by multipage formats to specify to which section to return
3326 * @return moodle_url The url of course
3328 function course_get_url($courseorid, $section = null, $options = array()) {
3329 return course_get_format($courseorid)->get_view_url($section, $options);
3333 * Create a module.
3335 * It includes:
3336 * - capability checks and other checks
3337 * - create the module from the module info
3339 * @param object $module
3340 * @return object the created module info
3341 * @throws moodle_exception if user is not allowed to perform the action or module is not allowed in this course
3343 function create_module($moduleinfo) {
3344 global $DB, $CFG;
3346 require_once($CFG->dirroot . '/course/modlib.php');
3348 // Check manadatory attributs.
3349 $mandatoryfields = array('modulename', 'course', 'section', 'visible');
3350 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
3351 $mandatoryfields[] = 'introeditor';
3353 foreach($mandatoryfields as $mandatoryfield) {
3354 if (!isset($moduleinfo->{$mandatoryfield})) {
3355 throw new moodle_exception('createmodulemissingattribut', '', '', $mandatoryfield);
3359 // Some additional checks (capability / existing instances).
3360 $course = $DB->get_record('course', array('id'=>$moduleinfo->course), '*', MUST_EXIST);
3361 list($module, $context, $cw) = can_add_moduleinfo($course, $moduleinfo->modulename, $moduleinfo->section);
3363 // Add the module.
3364 $moduleinfo->module = $module->id;
3365 $moduleinfo = add_moduleinfo($moduleinfo, $course, null);
3367 return $moduleinfo;
3371 * Update a module.
3373 * It includes:
3374 * - capability and other checks
3375 * - update the module
3377 * @param object $module
3378 * @return object the updated module info
3379 * @throws moodle_exception if current user is not allowed to update the module
3381 function update_module($moduleinfo) {
3382 global $DB, $CFG;
3384 require_once($CFG->dirroot . '/course/modlib.php');
3386 // Check the course module exists.
3387 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule, 0, false, MUST_EXIST);
3389 // Check the course exists.
3390 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
3392 // Some checks (capaibility / existing instances).
3393 list($cm, $context, $module, $data, $cw) = can_update_moduleinfo($cm);
3395 // Retrieve few information needed by update_moduleinfo.
3396 $moduleinfo->modulename = $cm->modname;
3397 if (!isset($moduleinfo->scale)) {
3398 $moduleinfo->scale = 0;
3400 $moduleinfo->type = 'mod';
3402 // Update the module.
3403 list($cm, $moduleinfo) = update_moduleinfo($cm, $moduleinfo, $course, null);
3405 return $moduleinfo;
3409 * Duplicate a module on the course for ajax.
3411 * @see mod_duplicate_module()
3412 * @param object $course The course
3413 * @param object $cm The course module to duplicate
3414 * @param int $sr The section to link back to (used for creating the links)
3415 * @throws moodle_exception if the plugin doesn't support duplication
3416 * @return Object containing:
3417 * - fullcontent: The HTML markup for the created CM
3418 * - cmid: The CMID of the newly created CM
3419 * - redirect: Whether to trigger a redirect following this change
3421 function mod_duplicate_activity($course, $cm, $sr = null) {
3422 global $PAGE;
3424 $newcm = duplicate_module($course, $cm);
3426 $resp = new stdClass();
3427 if ($newcm) {
3428 $courserenderer = $PAGE->get_renderer('core', 'course');
3429 $completioninfo = new completion_info($course);
3430 $modulehtml = $courserenderer->course_section_cm($course, $completioninfo,
3431 $newcm, null, array());
3433 $resp->fullcontent = $courserenderer->course_section_cm_list_item($course, $completioninfo, $newcm, $sr);
3434 $resp->cmid = $newcm->id;
3435 } else {
3436 // Trigger a redirect.
3437 $resp->redirect = true;
3439 return $resp;
3443 * Api to duplicate a module.
3445 * @param object $course course object.
3446 * @param object $cm course module object to be duplicated.
3447 * @since Moodle 2.8
3449 * @throws Exception
3450 * @throws coding_exception
3451 * @throws moodle_exception
3452 * @throws restore_controller_exception
3454 * @return cm_info|null cminfo object if we sucessfully duplicated the mod and found the new cm.
3456 function duplicate_module($course, $cm) {
3457 global $CFG, $DB, $USER;
3458 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
3459 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
3460 require_once($CFG->libdir . '/filelib.php');
3462 $a = new stdClass();
3463 $a->modtype = get_string('modulename', $cm->modname);
3464 $a->modname = format_string($cm->name);
3466 if (!plugin_supports('mod', $cm->modname, FEATURE_BACKUP_MOODLE2)) {
3467 throw new moodle_exception('duplicatenosupport', 'error', '', $a);
3470 // Backup the activity.
3472 $bc = new backup_controller(backup::TYPE_1ACTIVITY, $cm->id, backup::FORMAT_MOODLE,
3473 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
3475 $backupid = $bc->get_backupid();
3476 $backupbasepath = $bc->get_plan()->get_basepath();
3478 $bc->execute_plan();
3480 $bc->destroy();
3482 // Restore the backup immediately.
3484 $rc = new restore_controller($backupid, $course->id,
3485 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, backup::TARGET_CURRENT_ADDING);
3487 // Make sure that the restore_general_groups setting is always enabled when duplicating an activity.
3488 $plan = $rc->get_plan();
3489 $groupsetting = $plan->get_setting('groups');
3490 if (empty($groupsetting->get_value())) {
3491 $groupsetting->set_value(true);
3494 $cmcontext = context_module::instance($cm->id);
3495 if (!$rc->execute_precheck()) {
3496 $precheckresults = $rc->get_precheck_results();
3497 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
3498 if (empty($CFG->keeptempdirectoriesonbackup)) {
3499 fulldelete($backupbasepath);
3504 $rc->execute_plan();
3506 // Now a bit hacky part follows - we try to get the cmid of the newly
3507 // restored copy of the module.
3508 $newcmid = null;
3509 $tasks = $rc->get_plan()->get_tasks();
3510 foreach ($tasks as $task) {
3511 if (is_subclass_of($task, 'restore_activity_task')) {
3512 if ($task->get_old_contextid() == $cmcontext->id) {
3513 $newcmid = $task->get_moduleid();
3514 break;
3519 $rc->destroy();
3521 if (empty($CFG->keeptempdirectoriesonbackup)) {
3522 fulldelete($backupbasepath);
3525 // If we know the cmid of the new course module, let us move it
3526 // right below the original one. otherwise it will stay at the
3527 // end of the section.
3528 if ($newcmid) {
3529 // Proceed with activity renaming before everything else. We don't use APIs here to avoid
3530 // triggering a lot of create/update duplicated events.
3531 $newcm = get_coursemodule_from_id($cm->modname, $newcmid, $cm->course);
3532 // Add ' (copy)' to duplicates. Note we don't cleanup or validate lengths here. It comes
3533 // from original name that was valid, so the copy should be too.
3534 $newname = get_string('duplicatedmodule', 'moodle', $newcm->name);
3535 $DB->set_field($cm->modname, 'name', $newname, ['id' => $newcm->instance]);
3537 $section = $DB->get_record('course_sections', array('id' => $cm->section, 'course' => $cm->course));
3538 $modarray = explode(",", trim($section->sequence));
3539 $cmindex = array_search($cm->id, $modarray);
3540 if ($cmindex !== false && $cmindex < count($modarray) - 1) {
3541 moveto_module($newcm, $section, $modarray[$cmindex + 1]);
3544 // Update calendar events with the duplicated module.
3545 // The following line is to be removed in MDL-58906.
3546 course_module_update_calendar_events($newcm->modname, null, $newcm);
3548 // Trigger course module created event. We can trigger the event only if we know the newcmid.
3549 $newcm = get_fast_modinfo($cm->course)->get_cm($newcmid);
3550 $event = \core\event\course_module_created::create_from_cm($newcm);
3551 $event->trigger();
3554 return isset($newcm) ? $newcm : null;
3558 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3559 * Sorts by descending order of time.
3561 * @param stdClass $a First object
3562 * @param stdClass $b Second object
3563 * @return int 0,1,-1 representing the order
3565 function compare_activities_by_time_desc($a, $b) {
3566 // Make sure the activities actually have a timestamp property.
3567 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3568 return 0;
3570 // We treat instances without timestamp as if they have a timestamp of 0.
3571 if ((!property_exists($a, 'timestamp')) && (property_exists($b,'timestamp'))) {
3572 return 1;
3574 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3575 return -1;
3577 if ($a->timestamp == $b->timestamp) {
3578 return 0;
3580 return ($a->timestamp > $b->timestamp) ? -1 : 1;
3584 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3585 * Sorts by ascending order of time.
3587 * @param stdClass $a First object
3588 * @param stdClass $b Second object
3589 * @return int 0,1,-1 representing the order
3591 function compare_activities_by_time_asc($a, $b) {
3592 // Make sure the activities actually have a timestamp property.
3593 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3594 return 0;
3596 // We treat instances without timestamp as if they have a timestamp of 0.
3597 if ((!property_exists($a, 'timestamp')) && (property_exists($b, 'timestamp'))) {
3598 return -1;
3600 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3601 return 1;
3603 if ($a->timestamp == $b->timestamp) {
3604 return 0;
3606 return ($a->timestamp < $b->timestamp) ? -1 : 1;
3610 * Changes the visibility of a course.
3612 * @param int $courseid The course to change.
3613 * @param bool $show True to make it visible, false otherwise.
3614 * @return bool
3616 function course_change_visibility($courseid, $show = true) {
3617 $course = new stdClass;
3618 $course->id = $courseid;
3619 $course->visible = ($show) ? '1' : '0';
3620 $course->visibleold = $course->visible;
3621 update_course($course);
3622 return true;
3626 * Changes the course sortorder by one, moving it up or down one in respect to sort order.
3628 * @param stdClass|core_course_list_element $course
3629 * @param bool $up If set to true the course will be moved up one. Otherwise down one.
3630 * @return bool
3632 function course_change_sortorder_by_one($course, $up) {
3633 global $DB;
3634 $params = array($course->sortorder, $course->category);
3635 if ($up) {
3636 $select = 'sortorder < ? AND category = ?';
3637 $sort = 'sortorder DESC';
3638 } else {
3639 $select = 'sortorder > ? AND category = ?';
3640 $sort = 'sortorder ASC';
3642 fix_course_sortorder();
3643 $swapcourse = $DB->get_records_select('course', $select, $params, $sort, '*', 0, 1);
3644 if ($swapcourse) {
3645 $swapcourse = reset($swapcourse);
3646 $DB->set_field('course', 'sortorder', $swapcourse->sortorder, array('id' => $course->id));
3647 $DB->set_field('course', 'sortorder', $course->sortorder, array('id' => $swapcourse->id));
3648 // Finally reorder courses.
3649 fix_course_sortorder();
3650 cache_helper::purge_by_event('changesincourse');
3651 return true;
3653 return false;
3657 * Changes the sort order of courses in a category so that the first course appears after the second.
3659 * @param int|stdClass $courseorid The course to focus on.
3660 * @param int $moveaftercourseid The course to shifter after or 0 if you want it to be the first course in the category.
3661 * @return bool
3663 function course_change_sortorder_after_course($courseorid, $moveaftercourseid) {
3664 global $DB;
3666 if (!is_object($courseorid)) {
3667 $course = get_course($courseorid);
3668 } else {
3669 $course = $courseorid;
3672 if ((int)$moveaftercourseid === 0) {
3673 // We've moving the course to the start of the queue.
3674 $sql = 'SELECT sortorder
3675 FROM {course}
3676 WHERE category = :categoryid
3677 ORDER BY sortorder';
3678 $params = array(
3679 'categoryid' => $course->category
3681 $sortorder = $DB->get_field_sql($sql, $params, IGNORE_MULTIPLE);
3683 $sql = 'UPDATE {course}
3684 SET sortorder = sortorder + 1
3685 WHERE category = :categoryid
3686 AND id <> :id';
3687 $params = array(
3688 'categoryid' => $course->category,
3689 'id' => $course->id,
3691 $DB->execute($sql, $params);
3692 $DB->set_field('course', 'sortorder', $sortorder, array('id' => $course->id));
3693 } else if ($course->id === $moveaftercourseid) {
3694 // They're the same - moronic.
3695 debugging("Invalid move after course given.", DEBUG_DEVELOPER);
3696 return false;
3697 } else {
3698 // Moving this course after the given course. It could be before it could be after.
3699 $moveaftercourse = get_course($moveaftercourseid);
3700 if ($course->category !== $moveaftercourse->category) {
3701 debugging("Cannot re-order courses. The given courses do not belong to the same category.", DEBUG_DEVELOPER);
3702 return false;
3704 // Increment all courses in the same category that are ordered after the moveafter course.
3705 // This makes a space for the course we're moving.
3706 $sql = 'UPDATE {course}
3707 SET sortorder = sortorder + 1
3708 WHERE category = :categoryid
3709 AND sortorder > :sortorder';
3710 $params = array(
3711 'categoryid' => $moveaftercourse->category,
3712 'sortorder' => $moveaftercourse->sortorder
3714 $DB->execute($sql, $params);
3715 $DB->set_field('course', 'sortorder', $moveaftercourse->sortorder + 1, array('id' => $course->id));
3717 fix_course_sortorder();
3718 cache_helper::purge_by_event('changesincourse');
3719 return true;
3723 * Trigger course viewed event. This API function is used when course view actions happens,
3724 * usually in course/view.php but also in external functions.
3726 * @param stdClass $context course context object
3727 * @param int $sectionnumber section number
3728 * @since Moodle 2.9
3730 function course_view($context, $sectionnumber = 0) {
3732 $eventdata = array('context' => $context);
3734 if (!empty($sectionnumber)) {
3735 $eventdata['other']['coursesectionnumber'] = $sectionnumber;
3738 $event = \core\event\course_viewed::create($eventdata);
3739 $event->trigger();
3741 user_accesstime_log($context->instanceid);
3745 * Returns courses tagged with a specified tag.
3747 * @param core_tag_tag $tag
3748 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
3749 * are displayed on the page and the per-page limit may be bigger
3750 * @param int $fromctx context id where the link was displayed, may be used by callbacks
3751 * to display items in the same context first
3752 * @param int $ctx context id where to search for records
3753 * @param bool $rec search in subcontexts as well
3754 * @param int $page 0-based number of page being displayed
3755 * @return \core_tag\output\tagindex
3757 function course_get_tagged_courses($tag, $exclusivemode = false, $fromctx = 0, $ctx = 0, $rec = 1, $page = 0) {
3758 global $CFG, $PAGE;
3760 $perpage = $exclusivemode ? $CFG->coursesperpage : 5;
3761 $displayoptions = array(
3762 'limit' => $perpage,
3763 'offset' => $page * $perpage,
3764 'viewmoreurl' => null,
3767 $courserenderer = $PAGE->get_renderer('core', 'course');
3768 $totalcount = core_course_category::search_courses_count(array('tagid' => $tag->id, 'ctx' => $ctx, 'rec' => $rec));
3769 $content = $courserenderer->tagged_courses($tag->id, $exclusivemode, $ctx, $rec, $displayoptions);
3770 $totalpages = ceil($totalcount / $perpage);
3772 return new core_tag\output\tagindex($tag, 'core', 'course', $content,
3773 $exclusivemode, $fromctx, $ctx, $rec, $page, $totalpages);
3777 * Implements callback inplace_editable() allowing to edit values in-place
3779 * @param string $itemtype
3780 * @param int $itemid
3781 * @param mixed $newvalue
3782 * @return \core\output\inplace_editable
3784 function core_course_inplace_editable($itemtype, $itemid, $newvalue) {
3785 if ($itemtype === 'activityname') {
3786 return \core_course\output\course_module_name::update($itemid, $newvalue);
3791 * This function calculates the minimum and maximum cutoff values for the timestart of
3792 * the given event.
3794 * It will return an array with two values, the first being the minimum cutoff value and
3795 * the second being the maximum cutoff value. Either or both values can be null, which
3796 * indicates there is no minimum or maximum, respectively.
3798 * If a cutoff is required then the function must return an array containing the cutoff
3799 * timestamp and error string to display to the user if the cutoff value is violated.
3801 * A minimum and maximum cutoff return value will look like:
3803 * [1505704373, 'The date must be after this date'],
3804 * [1506741172, 'The date must be before this date']
3807 * @param calendar_event $event The calendar event to get the time range for
3808 * @param stdClass $course The course object to get the range from
3809 * @return array Returns an array with min and max date.
3811 function core_course_core_calendar_get_valid_event_timestart_range(\calendar_event $event, $course) {
3812 $mindate = null;
3813 $maxdate = null;
3815 if ($course->startdate) {
3816 $mindate = [
3817 $course->startdate,
3818 get_string('errorbeforecoursestart', 'calendar')
3822 return [$mindate, $maxdate];
3826 * Returns course modules tagged with a specified tag ready for output on tag/index.php page
3828 * This is a callback used by the tag area core/course_modules to search for course modules
3829 * tagged with a specific tag.
3831 * @param core_tag_tag $tag
3832 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
3833 * are displayed on the page and the per-page limit may be bigger
3834 * @param int $fromcontextid context id where the link was displayed, may be used by callbacks
3835 * to display items in the same context first
3836 * @param int $contextid context id where to search for records
3837 * @param bool $recursivecontext search in subcontexts as well
3838 * @param int $page 0-based number of page being displayed
3839 * @return \core_tag\output\tagindex
3841 function course_get_tagged_course_modules($tag, $exclusivemode = false, $fromcontextid = 0, $contextid = 0,
3842 $recursivecontext = 1, $page = 0) {
3843 global $OUTPUT;
3844 $perpage = $exclusivemode ? 20 : 5;
3846 // Build select query.
3847 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
3848 $query = "SELECT cm.id AS cmid, c.id AS courseid, $ctxselect
3849 FROM {course_modules} cm
3850 JOIN {tag_instance} tt ON cm.id = tt.itemid
3851 JOIN {course} c ON cm.course = c.id
3852 JOIN {context} ctx ON ctx.instanceid = cm.id AND ctx.contextlevel = :coursemodulecontextlevel
3853 WHERE tt.itemtype = :itemtype AND tt.tagid = :tagid AND tt.component = :component
3854 AND cm.deletioninprogress = 0
3855 AND c.id %COURSEFILTER% AND cm.id %ITEMFILTER%";
3857 $params = array('itemtype' => 'course_modules', 'tagid' => $tag->id, 'component' => 'core',
3858 'coursemodulecontextlevel' => CONTEXT_MODULE);
3859 if ($contextid) {
3860 $context = context::instance_by_id($contextid);
3861 $query .= $recursivecontext ? ' AND (ctx.id = :contextid OR ctx.path LIKE :path)' : ' AND ctx.id = :contextid';
3862 $params['contextid'] = $context->id;
3863 $params['path'] = $context->path.'/%';
3866 $query .= ' ORDER BY';
3867 if ($fromcontextid) {
3868 // In order-clause specify that modules from inside "fromctx" context should be returned first.
3869 $fromcontext = context::instance_by_id($fromcontextid);
3870 $query .= ' (CASE WHEN ctx.id = :fromcontextid OR ctx.path LIKE :frompath THEN 0 ELSE 1 END),';
3871 $params['fromcontextid'] = $fromcontext->id;
3872 $params['frompath'] = $fromcontext->path.'/%';
3874 $query .= ' c.sortorder, cm.id';
3875 $totalpages = $page + 1;
3877 // Use core_tag_index_builder to build and filter the list of items.
3878 // Request one item more than we need so we know if next page exists.
3879 $builder = new core_tag_index_builder('core', 'course_modules', $query, $params, $page * $perpage, $perpage + 1);
3880 while ($item = $builder->has_item_that_needs_access_check()) {
3881 context_helper::preload_from_record($item);
3882 $courseid = $item->courseid;
3883 if (!$builder->can_access_course($courseid)) {
3884 $builder->set_accessible($item, false);
3885 continue;
3887 $modinfo = get_fast_modinfo($builder->get_course($courseid));
3888 // Set accessibility of this item and all other items in the same course.
3889 $builder->walk(function ($taggeditem) use ($courseid, $modinfo, $builder) {
3890 if ($taggeditem->courseid == $courseid) {
3891 $cm = $modinfo->get_cm($taggeditem->cmid);
3892 $builder->set_accessible($taggeditem, $cm->uservisible);
3897 $items = $builder->get_items();
3898 if (count($items) > $perpage) {
3899 $totalpages = $page + 2; // We don't need exact page count, just indicate that the next page exists.
3900 array_pop($items);
3903 // Build the display contents.
3904 if ($items) {
3905 $tagfeed = new core_tag\output\tagfeed();
3906 foreach ($items as $item) {
3907 context_helper::preload_from_record($item);
3908 $course = $builder->get_course($item->courseid);
3909 $modinfo = get_fast_modinfo($course);
3910 $cm = $modinfo->get_cm($item->cmid);
3911 $courseurl = course_get_url($item->courseid, $cm->sectionnum);
3912 $cmname = $cm->get_formatted_name();
3913 if (!$exclusivemode) {
3914 $cmname = shorten_text($cmname, 100);
3916 $cmname = html_writer::link($cm->url?:$courseurl, $cmname);
3917 $coursename = format_string($course->fullname, true,
3918 array('context' => context_course::instance($item->courseid)));
3919 $coursename = html_writer::link($courseurl, $coursename);
3920 $icon = html_writer::empty_tag('img', array('src' => $cm->get_icon_url()));
3921 $tagfeed->add($icon, $cmname, $coursename);
3924 $content = $OUTPUT->render_from_template('core_tag/tagfeed',
3925 $tagfeed->export_for_template($OUTPUT));
3927 return new core_tag\output\tagindex($tag, 'core', 'course_modules', $content,
3928 $exclusivemode, $fromcontextid, $contextid, $recursivecontext, $page, $totalpages);
3933 * Return an object with the list of navigation options in a course that are avaialable or not for the current user.
3934 * This function also handles the frontpage course.
3936 * @param stdClass $context context object (it can be a course context or the system context for frontpage settings)
3937 * @param stdClass $course the course where the settings are being rendered
3938 * @return stdClass the navigation options in a course and their availability status
3939 * @since Moodle 3.2
3941 function course_get_user_navigation_options($context, $course = null) {
3942 global $CFG;
3944 $isloggedin = isloggedin();
3945 $isguestuser = isguestuser();
3946 $isfrontpage = $context->contextlevel == CONTEXT_SYSTEM;
3948 if ($isfrontpage) {
3949 $sitecontext = $context;
3950 } else {
3951 $sitecontext = context_system::instance();
3954 // Sets defaults for all options.
3955 $options = (object) [
3956 'badges' => false,
3957 'blogs' => false,
3958 'calendar' => false,
3959 'competencies' => false,
3960 'grades' => false,
3961 'notes' => false,
3962 'participants' => false,
3963 'search' => false,
3964 'tags' => false,
3967 $options->blogs = !empty($CFG->enableblogs) &&
3968 ($CFG->bloglevel == BLOG_GLOBAL_LEVEL ||
3969 ($CFG->bloglevel == BLOG_SITE_LEVEL and ($isloggedin and !$isguestuser)))
3970 && has_capability('moodle/blog:view', $sitecontext);
3972 $options->notes = !empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $context);
3974 // Frontpage settings?
3975 if ($isfrontpage) {
3976 // We are on the front page, so make sure we use the proper capability (site:viewparticipants).
3977 $options->participants = course_can_view_participants($sitecontext);
3978 $options->badges = !empty($CFG->enablebadges) && has_capability('moodle/badges:viewbadges', $sitecontext);
3979 $options->tags = !empty($CFG->usetags) && $isloggedin;
3980 $options->search = !empty($CFG->enableglobalsearch) && has_capability('moodle/search:query', $sitecontext);
3981 $options->calendar = $isloggedin;
3982 } else {
3983 // We are in a course, so make sure we use the proper capability (course:viewparticipants).
3984 $options->participants = course_can_view_participants($context);
3985 $options->badges = !empty($CFG->enablebadges) && !empty($CFG->badges_allowcoursebadges) &&
3986 has_capability('moodle/badges:viewbadges', $context);
3987 // Add view grade report is permitted.
3988 $grades = false;
3990 if (has_capability('moodle/grade:viewall', $context)) {
3991 $grades = true;
3992 } else if (!empty($course->showgrades)) {
3993 $reports = core_component::get_plugin_list('gradereport');
3994 if (is_array($reports) && count($reports) > 0) { // Get all installed reports.
3995 arsort($reports); // User is last, we want to test it first.
3996 foreach ($reports as $plugin => $plugindir) {
3997 if (has_capability('gradereport/'.$plugin.':view', $context)) {
3998 // Stop when the first visible plugin is found.
3999 $grades = true;
4000 break;
4005 $options->grades = $grades;
4008 if (\core_competency\api::is_enabled()) {
4009 $capabilities = array('moodle/competency:coursecompetencyview', 'moodle/competency:coursecompetencymanage');
4010 $options->competencies = has_any_capability($capabilities, $context);
4012 return $options;
4016 * Return an object with the list of administration options in a course that are available or not for the current user.
4017 * This function also handles the frontpage settings.
4019 * @param stdClass $course course object (for frontpage it should be a clone of $SITE)
4020 * @param stdClass $context context object (course context)
4021 * @return stdClass the administration options in a course and their availability status
4022 * @since Moodle 3.2
4024 function course_get_user_administration_options($course, $context) {
4025 global $CFG;
4026 $isfrontpage = $course->id == SITEID;
4027 $completionenabled = $CFG->enablecompletion && $course->enablecompletion;
4028 $hascompletiontabs = count(core_completion\manager::get_available_completion_tabs($course, $context)) > 0;
4030 $options = new stdClass;
4031 $options->update = has_capability('moodle/course:update', $context);
4032 $options->editcompletion = $CFG->enablecompletion &&
4033 $course->enablecompletion &&
4034 ($options->update || $hascompletiontabs);
4035 $options->filters = has_capability('moodle/filter:manage', $context) &&
4036 count(filter_get_available_in_context($context)) > 0;
4037 $options->reports = has_capability('moodle/site:viewreports', $context);
4038 $options->backup = has_capability('moodle/backup:backupcourse', $context);
4039 $options->restore = has_capability('moodle/restore:restorecourse', $context);
4040 $options->files = ($course->legacyfiles == 2 && has_capability('moodle/course:managefiles', $context));
4042 if (!$isfrontpage) {
4043 $options->tags = has_capability('moodle/course:tag', $context);
4044 $options->gradebook = has_capability('moodle/grade:manage', $context);
4045 $options->outcomes = !empty($CFG->enableoutcomes) && has_capability('moodle/course:update', $context);
4046 $options->badges = !empty($CFG->enablebadges);
4047 $options->import = has_capability('moodle/restore:restoretargetimport', $context);
4048 $options->publish = !empty($CFG->enablecoursepublishing) && has_capability('moodle/course:publish', $context);
4049 $options->reset = has_capability('moodle/course:reset', $context);
4050 $options->roles = has_capability('moodle/role:switchroles', $context);
4051 } else {
4052 // Set default options to false.
4053 $listofoptions = array('tags', 'gradebook', 'outcomes', 'badges', 'import', 'publish', 'reset', 'roles', 'grades');
4055 foreach ($listofoptions as $option) {
4056 $options->$option = false;
4060 return $options;
4064 * Validates course start and end dates.
4066 * Checks that the end course date is not greater than the start course date.
4068 * $coursedata['startdate'] or $coursedata['enddate'] may not be set, it depends on the form and user input.
4070 * @param array $coursedata May contain startdate and enddate timestamps, depends on the user input.
4071 * @return mixed False if everything alright, error codes otherwise.
4073 function course_validate_dates($coursedata) {
4075 // If both start and end dates are set end date should be later than the start date.
4076 if (!empty($coursedata['startdate']) && !empty($coursedata['enddate']) &&
4077 ($coursedata['enddate'] < $coursedata['startdate'])) {
4078 return 'enddatebeforestartdate';
4081 // If start date is not set end date can not be set.
4082 if (empty($coursedata['startdate']) && !empty($coursedata['enddate'])) {
4083 return 'nostartdatenoenddate';
4086 return false;
4090 * Check for course updates in the given context level instances (only modules supported right Now)
4092 * @param stdClass $course course object
4093 * @param array $tocheck instances to check for updates
4094 * @param array $filter check only for updates in these areas
4095 * @return array list of warnings and instances with updates information
4096 * @since Moodle 3.2
4098 function course_check_updates($course, $tocheck, $filter = array()) {
4099 global $CFG, $DB;
4101 $instances = array();
4102 $warnings = array();
4103 $modulescallbacksupport = array();
4104 $modinfo = get_fast_modinfo($course);
4106 $supportedplugins = get_plugin_list_with_function('mod', 'check_updates_since');
4108 // Check instances.
4109 foreach ($tocheck as $instance) {
4110 if ($instance['contextlevel'] == 'module') {
4111 // Check module visibility.
4112 try {
4113 $cm = $modinfo->get_cm($instance['id']);
4114 } catch (Exception $e) {
4115 $warnings[] = array(
4116 'item' => 'module',
4117 'itemid' => $instance['id'],
4118 'warningcode' => 'cmidnotincourse',
4119 'message' => 'This module id does not belong to this course.'
4121 continue;
4124 if (!$cm->uservisible) {
4125 $warnings[] = array(
4126 'item' => 'module',
4127 'itemid' => $instance['id'],
4128 'warningcode' => 'nonuservisible',
4129 'message' => 'You don\'t have access to this module.'
4131 continue;
4133 if (empty($supportedplugins['mod_' . $cm->modname])) {
4134 $warnings[] = array(
4135 'item' => 'module',
4136 'itemid' => $instance['id'],
4137 'warningcode' => 'missingcallback',
4138 'message' => 'This module does not implement the check_updates_since callback: ' . $instance['contextlevel'],
4140 continue;
4142 // Retrieve the module instance.
4143 $instances[] = array(
4144 'contextlevel' => $instance['contextlevel'],
4145 'id' => $instance['id'],
4146 'updates' => call_user_func($cm->modname . '_check_updates_since', $cm, $instance['since'], $filter)
4149 } else {
4150 $warnings[] = array(
4151 'item' => 'contextlevel',
4152 'itemid' => $instance['id'],
4153 'warningcode' => 'contextlevelnotsupported',
4154 'message' => 'Context level not yet supported ' . $instance['contextlevel'],
4158 return array($instances, $warnings);
4162 * This function classifies a course as past, in progress or future.
4164 * This function may incur a DB hit to calculate course completion.
4165 * @param stdClass $course Course record
4166 * @param stdClass $user User record (optional - defaults to $USER).
4167 * @param completion_info $completioninfo Completion record for the user (optional - will be fetched if required).
4168 * @return string (one of COURSE_TIMELINE_FUTURE, COURSE_TIMELINE_INPROGRESS or COURSE_TIMELINE_PAST)
4170 function course_classify_for_timeline($course, $user = null, $completioninfo = null) {
4171 global $USER;
4173 if ($user == null) {
4174 $user = $USER;
4177 $today = time();
4178 // End date past.
4179 if (!empty($course->enddate) && (course_classify_end_date($course) < $today)) {
4180 return COURSE_TIMELINE_PAST;
4183 if ($completioninfo == null) {
4184 $completioninfo = new completion_info($course);
4187 // Course was completed.
4188 if ($completioninfo->is_enabled() && $completioninfo->is_course_complete($user->id)) {
4189 return COURSE_TIMELINE_PAST;
4192 // Start date not reached.
4193 if (!empty($course->startdate) && (course_classify_start_date($course) > $today)) {
4194 return COURSE_TIMELINE_FUTURE;
4197 // Everything else is in progress.
4198 return COURSE_TIMELINE_INPROGRESS;
4202 * This function calculates the end date to use for display classification purposes,
4203 * incorporating the grace period, if any.
4205 * @param stdClass $course The course record.
4206 * @return int The new enddate.
4208 function course_classify_end_date($course) {
4209 global $CFG;
4210 $coursegraceperiodafter = (empty($CFG->coursegraceperiodafter)) ? 0 : $CFG->coursegraceperiodafter;
4211 $enddate = (new \DateTimeImmutable())->setTimestamp($course->enddate)->modify("+{$coursegraceperiodafter} days");
4212 return $enddate->getTimestamp();
4216 * This function calculates the start date to use for display classification purposes,
4217 * incorporating the grace period, if any.
4219 * @param stdClass $course The course record.
4220 * @return int The new startdate.
4222 function course_classify_start_date($course) {
4223 global $CFG;
4224 $coursegraceperiodbefore = (empty($CFG->coursegraceperiodbefore)) ? 0 : $CFG->coursegraceperiodbefore;
4225 $startdate = (new \DateTimeImmutable())->setTimestamp($course->startdate)->modify("-{$coursegraceperiodbefore} days");
4226 return $startdate->getTimestamp();
4230 * Group a list of courses into either past, future, or in progress.
4232 * The return value will be an array indexed by the COURSE_TIMELINE_* constants
4233 * with each value being an array of courses in that group.
4234 * E.g.
4236 * COURSE_TIMELINE_PAST => [... list of past courses ...],
4237 * COURSE_TIMELINE_FUTURE => [],
4238 * COURSE_TIMELINE_INPROGRESS => []
4241 * @param array $courses List of courses to be grouped.
4242 * @return array
4244 function course_classify_courses_for_timeline(array $courses) {
4245 return array_reduce($courses, function($carry, $course) {
4246 $classification = course_classify_for_timeline($course);
4247 array_push($carry[$classification], $course);
4249 return $carry;
4250 }, [
4251 COURSE_TIMELINE_PAST => [],
4252 COURSE_TIMELINE_FUTURE => [],
4253 COURSE_TIMELINE_INPROGRESS => []
4258 * Get the list of enrolled courses for the current user.
4260 * This function returns a Generator. The courses will be loaded from the database
4261 * in chunks rather than a single query.
4263 * @param int $limit Restrict result set to this amount
4264 * @param int $offset Skip this number of records from the start of the result set
4265 * @param string|null $sort SQL string for sorting
4266 * @param string|null $fields SQL string for fields to be returned
4267 * @param int $dbquerylimit The number of records to load per DB request
4268 * @param array $includecourses courses ids to be restricted
4269 * @param array $hiddencourses courses ids to be excluded
4270 * @return Generator
4272 function course_get_enrolled_courses_for_logged_in_user(
4273 int $limit = 0,
4274 int $offset = 0,
4275 string $sort = null,
4276 string $fields = null,
4277 int $dbquerylimit = COURSE_DB_QUERY_LIMIT,
4278 array $includecourses = [],
4279 array $hiddencourses = []
4280 ) : Generator {
4282 $haslimit = !empty($limit);
4283 $recordsloaded = 0;
4284 $querylimit = (!$haslimit || $limit > $dbquerylimit) ? $dbquerylimit : $limit;
4286 while ($courses = enrol_get_my_courses($fields, $sort, $querylimit, $includecourses, false, $offset, $hiddencourses)) {
4287 yield from $courses;
4289 $recordsloaded += $querylimit;
4291 if (count($courses) < $querylimit) {
4292 break;
4294 if ($haslimit && $recordsloaded >= $limit) {
4295 break;
4298 $offset += $querylimit;
4303 * Search the given $courses for any that match the given $classification up to the specified
4304 * $limit.
4306 * This function will return the subset of courses that match the classification as well as the
4307 * number of courses it had to process to build that subset.
4309 * It is recommended that for larger sets of courses this function is given a Generator that loads
4310 * the courses from the database in chunks.
4312 * @param array|Traversable $courses List of courses to process
4313 * @param string $classification One of the COURSE_TIMELINE_* constants
4314 * @param int $limit Limit the number of results to this amount
4315 * @return array First value is the filtered courses, second value is the number of courses processed
4317 function course_filter_courses_by_timeline_classification(
4318 $courses,
4319 string $classification,
4320 int $limit = 0
4321 ) : array {
4323 if (!in_array($classification,
4324 [COURSE_TIMELINE_ALLINCLUDINGHIDDEN, COURSE_TIMELINE_ALL, COURSE_TIMELINE_PAST, COURSE_TIMELINE_INPROGRESS,
4325 COURSE_TIMELINE_FUTURE, COURSE_TIMELINE_HIDDEN])) {
4326 $message = 'Classification must be one of COURSE_TIMELINE_ALLINCLUDINGHIDDEN, COURSE_TIMELINE_ALL, COURSE_TIMELINE_PAST, '
4327 . 'COURSE_TIMELINE_INPROGRESS or COURSE_TIMELINE_FUTURE';
4328 throw new moodle_exception($message);
4331 $filteredcourses = [];
4332 $numberofcoursesprocessed = 0;
4333 $filtermatches = 0;
4335 foreach ($courses as $course) {
4336 $numberofcoursesprocessed++;
4337 $pref = get_user_preferences('block_myoverview_hidden_course_' . $course->id, 0);
4339 // Added as of MDL-63457 toggle viewability for each user.
4340 if ($classification == COURSE_TIMELINE_ALLINCLUDINGHIDDEN || ($classification == COURSE_TIMELINE_HIDDEN && $pref) ||
4341 (($classification == COURSE_TIMELINE_ALL || $classification == course_classify_for_timeline($course)) && !$pref)) {
4342 $filteredcourses[] = $course;
4343 $filtermatches++;
4346 if ($limit && $filtermatches >= $limit) {
4347 // We've found the number of requested courses. No need to continue searching.
4348 break;
4352 // Return the number of filtered courses as well as the number of courses that were searched
4353 // in order to find the matching courses. This allows the calling code to do some kind of
4354 // pagination.
4355 return [$filteredcourses, $numberofcoursesprocessed];
4359 * Search the given $courses for any that match the given $classification up to the specified
4360 * $limit.
4362 * This function will return the subset of courses that are favourites as well as the
4363 * number of courses it had to process to build that subset.
4365 * It is recommended that for larger sets of courses this function is given a Generator that loads
4366 * the courses from the database in chunks.
4368 * @param array|Traversable $courses List of courses to process
4369 * @param array $favouritecourseids Array of favourite courses.
4370 * @param int $limit Limit the number of results to this amount
4371 * @return array First value is the filtered courses, second value is the number of courses processed
4373 function course_filter_courses_by_favourites(
4374 $courses,
4375 $favouritecourseids,
4376 int $limit = 0
4377 ) : array {
4379 $filteredcourses = [];
4380 $numberofcoursesprocessed = 0;
4381 $filtermatches = 0;
4383 foreach ($courses as $course) {
4384 $numberofcoursesprocessed++;
4386 if (in_array($course->id, $favouritecourseids)) {
4387 $filteredcourses[] = $course;
4388 $filtermatches++;
4391 if ($limit && $filtermatches >= $limit) {
4392 // We've found the number of requested courses. No need to continue searching.
4393 break;
4397 // Return the number of filtered courses as well as the number of courses that were searched
4398 // in order to find the matching courses. This allows the calling code to do some kind of
4399 // pagination.
4400 return [$filteredcourses, $numberofcoursesprocessed];
4404 * Check module updates since a given time.
4405 * This function checks for updates in the module config, file areas, completion, grades, comments and ratings.
4407 * @param cm_info $cm course module data
4408 * @param int $from the time to check
4409 * @param array $fileareas additional file ares to check
4410 * @param array $filter if we need to filter and return only selected updates
4411 * @return stdClass object with the different updates
4412 * @since Moodle 3.2
4414 function course_check_module_updates_since($cm, $from, $fileareas = array(), $filter = array()) {
4415 global $DB, $CFG, $USER;
4417 $context = $cm->context;
4418 $mod = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
4420 $updates = new stdClass();
4421 $course = get_course($cm->course);
4422 $component = 'mod_' . $cm->modname;
4424 // Check changes in the module configuration.
4425 if (isset($mod->timemodified) and (empty($filter) or in_array('configuration', $filter))) {
4426 $updates->configuration = (object) array('updated' => false);
4427 if ($updates->configuration->updated = $mod->timemodified > $from) {
4428 $updates->configuration->timeupdated = $mod->timemodified;
4432 // Check for updates in files.
4433 if (plugin_supports('mod', $cm->modname, FEATURE_MOD_INTRO)) {
4434 $fileareas[] = 'intro';
4436 if (!empty($fileareas) and (empty($filter) or in_array('fileareas', $filter))) {
4437 $fs = get_file_storage();
4438 $files = $fs->get_area_files($context->id, $component, $fileareas, false, "filearea, timemodified DESC", false, $from);
4439 foreach ($fileareas as $filearea) {
4440 $updates->{$filearea . 'files'} = (object) array('updated' => false);
4442 foreach ($files as $file) {
4443 $updates->{$file->get_filearea() . 'files'}->updated = true;
4444 $updates->{$file->get_filearea() . 'files'}->itemids[] = $file->get_id();
4448 // Check completion.
4449 $supportcompletion = plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_HAS_RULES);
4450 $supportcompletion = $supportcompletion or plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_TRACKS_VIEWS);
4451 if ($supportcompletion and (empty($filter) or in_array('completion', $filter))) {
4452 $updates->completion = (object) array('updated' => false);
4453 $completion = new completion_info($course);
4454 // Use wholecourse to cache all the modules the first time.
4455 $completiondata = $completion->get_data($cm, true);
4456 if ($updates->completion->updated = !empty($completiondata->timemodified) && $completiondata->timemodified > $from) {
4457 $updates->completion->timemodified = $completiondata->timemodified;
4461 // Check grades.
4462 $supportgrades = plugin_supports('mod', $cm->modname, FEATURE_GRADE_HAS_GRADE);
4463 $supportgrades = $supportgrades or plugin_supports('mod', $cm->modname, FEATURE_GRADE_OUTCOMES);
4464 if ($supportgrades and (empty($filter) or (in_array('gradeitems', $filter) or in_array('outcomes', $filter)))) {
4465 require_once($CFG->libdir . '/gradelib.php');
4466 $grades = grade_get_grades($course->id, 'mod', $cm->modname, $mod->id, $USER->id);
4468 if (empty($filter) or in_array('gradeitems', $filter)) {
4469 $updates->gradeitems = (object) array('updated' => false);
4470 foreach ($grades->items as $gradeitem) {
4471 foreach ($gradeitem->grades as $grade) {
4472 if ($grade->datesubmitted > $from or $grade->dategraded > $from) {
4473 $updates->gradeitems->updated = true;
4474 $updates->gradeitems->itemids[] = $gradeitem->id;
4480 if (empty($filter) or in_array('outcomes', $filter)) {
4481 $updates->outcomes = (object) array('updated' => false);
4482 foreach ($grades->outcomes as $outcome) {
4483 foreach ($outcome->grades as $grade) {
4484 if ($grade->datesubmitted > $from or $grade->dategraded > $from) {
4485 $updates->outcomes->updated = true;
4486 $updates->outcomes->itemids[] = $outcome->id;
4493 // Check comments.
4494 if (plugin_supports('mod', $cm->modname, FEATURE_COMMENT) and (empty($filter) or in_array('comments', $filter))) {
4495 $updates->comments = (object) array('updated' => false);
4496 require_once($CFG->dirroot . '/comment/lib.php');
4497 require_once($CFG->dirroot . '/comment/locallib.php');
4498 $manager = new comment_manager();
4499 $comments = $manager->get_component_comments_since($course, $context, $component, $from, $cm);
4500 if (!empty($comments)) {
4501 $updates->comments->updated = true;
4502 $updates->comments->itemids = array_keys($comments);
4506 // Check ratings.
4507 if (plugin_supports('mod', $cm->modname, FEATURE_RATE) and (empty($filter) or in_array('ratings', $filter))) {
4508 $updates->ratings = (object) array('updated' => false);
4509 require_once($CFG->dirroot . '/rating/lib.php');
4510 $manager = new rating_manager();
4511 $ratings = $manager->get_component_ratings_since($context, $component, $from);
4512 if (!empty($ratings)) {
4513 $updates->ratings->updated = true;
4514 $updates->ratings->itemids = array_keys($ratings);
4518 return $updates;
4522 * Returns true if the user can view the participant page, false otherwise,
4524 * @param context $context The context we are checking.
4525 * @return bool
4527 function course_can_view_participants($context) {
4528 $viewparticipantscap = 'moodle/course:viewparticipants';
4529 if ($context->contextlevel == CONTEXT_SYSTEM) {
4530 $viewparticipantscap = 'moodle/site:viewparticipants';
4533 return has_any_capability([$viewparticipantscap, 'moodle/course:enrolreview'], $context);
4537 * Checks if a user can view the participant page, if not throws an exception.
4539 * @param context $context The context we are checking.
4540 * @throws required_capability_exception
4542 function course_require_view_participants($context) {
4543 if (!course_can_view_participants($context)) {
4544 $viewparticipantscap = 'moodle/course:viewparticipants';
4545 if ($context->contextlevel == CONTEXT_SYSTEM) {
4546 $viewparticipantscap = 'moodle/site:viewparticipants';
4548 throw new required_capability_exception($context, $viewparticipantscap, 'nopermissions', '');
4553 * Return whether the user can download from the specified backup file area in the given context.
4555 * @param string $filearea the backup file area. E.g. 'course', 'backup' or 'automated'.
4556 * @param \context $context
4557 * @param stdClass $user the user object. If not provided, the current user will be checked.
4558 * @return bool true if the user is allowed to download in the context, false otherwise.
4560 function can_download_from_backup_filearea($filearea, \context $context, stdClass $user = null) {
4561 $candownload = false;
4562 switch ($filearea) {
4563 case 'course':
4564 case 'backup':
4565 $candownload = has_capability('moodle/backup:downloadfile', $context, $user);
4566 break;
4567 case 'automated':
4568 // Given the automated backups may contain userinfo, we restrict access such that only users who are able to
4569 // restore with userinfo are able to download the file. Users can't create these backups, so checking 'backup:userinfo'
4570 // doesn't make sense here.
4571 $candownload = has_capability('moodle/backup:downloadfile', $context, $user) &&
4572 has_capability('moodle/restore:userinfo', $context, $user);
4573 break;
4574 default:
4575 break;
4578 return $candownload;
4582 * Get a list of hidden courses
4584 * @param int|object|null $user User override to get the filter from. Defaults to current user
4585 * @return array $ids List of hidden courses
4586 * @throws coding_exception
4588 function get_hidden_courses_on_timeline($user = null) {
4589 global $USER;
4591 if (empty($user)) {
4592 $user = $USER->id;
4595 $preferences = get_user_preferences(null, null, $user);
4596 $ids = [];
4597 foreach ($preferences as $key => $value) {
4598 if (preg_match('/block_myoverview_hidden_course_(\d)+/', $key)) {
4599 $id = preg_split('/block_myoverview_hidden_course_/', $key);
4600 $ids[] = $id[1];
4604 return $ids;
4608 * Returns a list of the most recently courses accessed by a user
4610 * @param int $userid User id from which the courses will be obtained
4611 * @param int $limit Restrict result set to this amount
4612 * @param int $offset Skip this number of records from the start of the result set
4613 * @param string|null $sort SQL string for sorting
4614 * @return array
4616 function course_get_recent_courses(int $userid = null, int $limit = 0, int $offset = 0, string $sort = null) {
4618 global $CFG, $USER, $DB;
4620 if (empty($userid)) {
4621 $userid = $USER->id;
4624 $basefields = array('id', 'idnumber', 'summary', 'summaryformat', 'startdate', 'enddate', 'category',
4625 'shortname', 'fullname', 'timeaccess', 'component', 'visible');
4627 $sort = trim($sort);
4628 if (empty($sort)) {
4629 $sort = 'timeaccess DESC';
4630 } else {
4631 $rawsorts = explode(',', $sort);
4632 $sorts = array();
4633 foreach ($rawsorts as $rawsort) {
4634 $rawsort = trim($rawsort);
4635 $sorts[] = trim($rawsort);
4637 $sort = implode(',', $sorts);
4640 $orderby = "ORDER BY $sort";
4642 $ctxfields = context_helper::get_preload_record_columns_sql('ctx');
4644 $coursefields = 'c.' .join(',', $basefields);
4646 // Ask the favourites service to give us the join SQL for favourited courses,
4647 // so we can include favourite information in the query.
4648 $usercontext = \context_user::instance($userid);
4649 $favservice = \core_favourites\service_factory::get_service_for_user_context($usercontext);
4650 list($favsql, $favparams) = $favservice->get_join_sql_by_type('core_course', 'courses', 'fav', 'ul.courseid');
4652 $sql = "SELECT $coursefields, $ctxfields
4653 FROM {course} c
4654 JOIN {context} ctx
4655 ON ctx.contextlevel = :contextlevel
4656 AND ctx.instanceid = c.id
4657 JOIN {user_lastaccess} ul
4658 ON ul.courseid = c.id
4659 $favsql
4660 WHERE ul.userid = :userid
4661 AND c.visible = :visible
4662 AND EXISTS (SELECT e.id
4663 FROM {enrol} e
4664 LEFT JOIN {user_enrolments} ue ON ue.enrolid = e.id
4665 WHERE e.courseid = c.id
4666 AND e.status = :statusenrol
4667 AND ((ue.status = :status
4668 AND ue.userid = ul.userid
4669 AND ue.timestart < :now1
4670 AND (ue.timeend = 0 OR ue.timeend > :now2)
4672 OR e.enrol = :guestenrol
4675 $orderby";
4677 $now = round(time(), -2); // Improves db caching.
4678 $params = ['userid' => $userid, 'contextlevel' => CONTEXT_COURSE, 'visible' => 1, 'status' => ENROL_USER_ACTIVE,
4679 'statusenrol' => ENROL_INSTANCE_ENABLED, 'guestenrol' => 'guest', 'now1' => $now, 'now2' => $now] + $favparams;
4681 $recentcourses = $DB->get_records_sql($sql, $params, $offset, $limit);
4683 // Filter courses if last access field is hidden.
4684 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
4686 if ($userid != $USER->id && isset($hiddenfields['lastaccess'])) {
4687 $recentcourses = array_filter($recentcourses, function($course) {
4688 context_helper::preload_from_record($course);
4689 $context = context_course::instance($course->id, IGNORE_MISSING);
4690 // If last access was a hidden field, a user requesting info about another user would need permission to view hidden
4691 // fields.
4692 return has_capability('moodle/course:viewhiddenuserfields', $context);
4696 return $recentcourses;
4700 * Calculate the course start date and offset for the given user ids.
4702 * If the course is a fixed date course then the course start date will be returned.
4703 * If the course is a relative date course then the course date will be calculated and
4704 * and offset provided.
4706 * The dates are returned as an array with the index being the user id. The array
4707 * contains the start date and start offset values for the user.
4709 * If the user is not enrolled in the course then the course start date will be returned.
4711 * If we have a course which starts on 1563244000 and 2 users, id 123 and 456, where the
4712 * former is enrolled in the course at 1563244693 and the latter is not enrolled then the
4713 * return value would look like:
4715 * '123' => [
4716 * 'start' => 1563244693,
4717 * 'startoffset' => 693
4718 * ],
4719 * '456' => [
4720 * 'start' => 1563244000,
4721 * 'startoffset' => 0
4725 * @param stdClass $course The course to fetch dates for.
4726 * @param array $userids The list of user ids to get dates for.
4727 * @return array
4729 function course_get_course_dates_for_user_ids(stdClass $course, array $userids): array {
4730 if (empty($course->relativedatesmode)) {
4731 // This course isn't set to relative dates so we can early return with the course
4732 // start date.
4733 return array_reduce($userids, function($carry, $userid) use ($course) {
4734 $carry[$userid] = [
4735 'start' => $course->startdate,
4736 'startoffset' => 0
4738 return $carry;
4739 }, []);
4742 // We're dealing with a relative dates course now so we need to calculate some dates.
4743 $cache = cache::make('core', 'course_user_dates');
4744 $dates = [];
4745 $uncacheduserids = [];
4747 // Try fetching the values from the cache so that we don't need to do a DB request.
4748 foreach ($userids as $userid) {
4749 $cachekey = "{$course->id}_{$userid}";
4750 $cachedvalue = $cache->get($cachekey);
4752 if ($cachedvalue === false) {
4753 // Looks like we haven't seen this user for this course before so we'll have
4754 // to fetch it.
4755 $uncacheduserids[] = $userid;
4756 } else {
4757 [$start, $startoffset] = $cachedvalue;
4758 $dates[$userid] = [
4759 'start' => $start,
4760 'startoffset' => $startoffset
4765 if (!empty($uncacheduserids)) {
4766 // Load the enrolments for any users we haven't seen yet. Set the "onlyactive" param
4767 // to false because it filters out users with enrolment start times in the future which
4768 // we don't want.
4769 $enrolments = enrol_get_course_users($course->id, false, $uncacheduserids);
4771 foreach ($uncacheduserids as $userid) {
4772 // Find the user enrolment that has the earliest start date.
4773 $enrolment = array_reduce(array_values($enrolments), function($carry, $enrolment) use ($userid) {
4774 // Only consider enrolments for this user if the user enrolment is active and the
4775 // enrolment method is enabled.
4776 if (
4777 $enrolment->uestatus == ENROL_USER_ACTIVE &&
4778 $enrolment->estatus == ENROL_INSTANCE_ENABLED &&
4779 $enrolment->id == $userid
4781 if (is_null($carry)) {
4782 // Haven't found an enrolment yet for this user so use the one we just found.
4783 $carry = $enrolment;
4784 } else {
4785 // We've already found an enrolment for this user so let's use which ever one
4786 // has the earliest start time.
4787 $carry = $carry->uetimestart < $enrolment->uetimestart ? $carry : $enrolment;
4791 return $carry;
4792 }, null);
4794 if ($enrolment) {
4795 // The course is in relative dates mode so we calculate the student's start
4796 // date based on their enrolment start date.
4797 $start = $course->startdate > $enrolment->uetimestart ? $course->startdate : $enrolment->uetimestart;
4798 $startoffset = $start - $course->startdate;
4799 } else {
4800 // The user is not enrolled in the course so default back to the course start date.
4801 $start = $course->startdate;
4802 $startoffset = 0;
4805 $dates[$userid] = [
4806 'start' => $start,
4807 'startoffset' => $startoffset
4810 $cachekey = "{$course->id}_{$userid}";
4811 $cache->set($cachekey, [$start, $startoffset]);
4815 return $dates;
4819 * Calculate the course start date and offset for the given user id.
4821 * If the course is a fixed date course then the course start date will be returned.
4822 * If the course is a relative date course then the course date will be calculated and
4823 * and offset provided.
4825 * The return array contains the start date and start offset values for the user.
4827 * If the user is not enrolled in the course then the course start date will be returned.
4829 * If we have a course which starts on 1563244000. If a user's enrolment starts on 1563244693
4830 * then the return would be:
4832 * 'start' => 1563244693,
4833 * 'startoffset' => 693
4836 * If the use was not enrolled then the return would be:
4838 * 'start' => 1563244000,
4839 * 'startoffset' => 0
4842 * @param stdClass $course The course to fetch dates for.
4843 * @param int $userid The user id to get dates for.
4844 * @return array
4846 function course_get_course_dates_for_user_id(stdClass $course, int $userid): array {
4847 return (course_get_course_dates_for_user_ids($course, [$userid]))[$userid];