MDL-70265 travis: Only run highest phpunit if configured via env
[moodle.git] / course / lib.php
blobfb288af6c36c7db6ff888733e8aef9271cc92c80
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Library of useful functions
20 * @copyright 1999 Martin Dougiamas http://dougiamas.com
21 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
22 * @package core_course
25 defined('MOODLE_INTERNAL') || die;
27 require_once($CFG->libdir.'/completionlib.php');
28 require_once($CFG->libdir.'/filelib.php');
29 require_once($CFG->libdir.'/datalib.php');
30 require_once($CFG->dirroot.'/course/format/lib.php');
32 define('COURSE_MAX_LOGS_PER_PAGE', 1000); // Records.
33 define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds.
35 /**
36 * Number of courses to display when summaries are included.
37 * @var int
38 * @deprecated since 2.4, use $CFG->courseswithsummarieslimit instead.
40 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10);
42 // Max courses in log dropdown before switching to optional.
43 define('COURSE_MAX_COURSES_PER_DROPDOWN', 1000);
44 // Max users in log dropdown before switching to optional.
45 define('COURSE_MAX_USERS_PER_DROPDOWN', 1000);
46 define('FRONTPAGENEWS', '0');
47 define('FRONTPAGECATEGORYNAMES', '2');
48 define('FRONTPAGECATEGORYCOMBO', '4');
49 define('FRONTPAGEENROLLEDCOURSELIST', '5');
50 define('FRONTPAGEALLCOURSELIST', '6');
51 define('FRONTPAGECOURSESEARCH', '7');
52 // Important! Replaced with $CFG->frontpagecourselimit - maximum number of courses displayed on the frontpage.
53 define('EXCELROWS', 65535);
54 define('FIRSTUSEDEXCELROW', 3);
56 define('MOD_CLASS_ACTIVITY', 0);
57 define('MOD_CLASS_RESOURCE', 1);
59 define('COURSE_TIMELINE_ALLINCLUDINGHIDDEN', 'allincludinghidden');
60 define('COURSE_TIMELINE_ALL', 'all');
61 define('COURSE_TIMELINE_PAST', 'past');
62 define('COURSE_TIMELINE_INPROGRESS', 'inprogress');
63 define('COURSE_TIMELINE_FUTURE', 'future');
64 define('COURSE_FAVOURITES', 'favourites');
65 define('COURSE_TIMELINE_HIDDEN', 'hidden');
66 define('COURSE_CUSTOMFIELD', 'customfield');
67 define('COURSE_DB_QUERY_LIMIT', 1000);
68 /** Searching for all courses that have no value for the specified custom field. */
69 define('COURSE_CUSTOMFIELD_EMPTY', -1);
71 function make_log_url($module, $url) {
72 switch ($module) {
73 case 'course':
74 if (strpos($url, 'report/') === 0) {
75 // there is only one report type, course reports are deprecated
76 $url = "/$url";
77 break;
79 case 'file':
80 case 'login':
81 case 'lib':
82 case 'admin':
83 case 'category':
84 case 'mnet course':
85 if (strpos($url, '../') === 0) {
86 $url = ltrim($url, '.');
87 } else {
88 $url = "/course/$url";
90 break;
91 case 'calendar':
92 $url = "/calendar/$url";
93 break;
94 case 'user':
95 case 'blog':
96 $url = "/$module/$url";
97 break;
98 case 'upload':
99 $url = $url;
100 break;
101 case 'coursetags':
102 $url = '/'.$url;
103 break;
104 case 'library':
105 case '':
106 $url = '/';
107 break;
108 case 'message':
109 $url = "/message/$url";
110 break;
111 case 'notes':
112 $url = "/notes/$url";
113 break;
114 case 'tag':
115 $url = "/tag/$url";
116 break;
117 case 'role':
118 $url = '/'.$url;
119 break;
120 case 'grade':
121 $url = "/grade/$url";
122 break;
123 default:
124 $url = "/mod/$module/$url";
125 break;
128 //now let's sanitise urls - there might be some ugly nasties:-(
129 $parts = explode('?', $url);
130 $script = array_shift($parts);
131 if (strpos($script, 'http') === 0) {
132 $script = clean_param($script, PARAM_URL);
133 } else {
134 $script = clean_param($script, PARAM_PATH);
137 $query = '';
138 if ($parts) {
139 $query = implode('', $parts);
140 $query = str_replace('&amp;', '&', $query); // both & and &amp; are stored in db :-|
141 $parts = explode('&', $query);
142 $eq = urlencode('=');
143 foreach ($parts as $key=>$part) {
144 $part = urlencode(urldecode($part));
145 $part = str_replace($eq, '=', $part);
146 $parts[$key] = $part;
148 $query = '?'.implode('&amp;', $parts);
151 return $script.$query;
155 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
156 $modname="", $modid=0, $modaction="", $groupid=0) {
157 global $CFG, $DB;
159 // It is assumed that $date is the GMT time of midnight for that day,
160 // and so the next 86400 seconds worth of logs are printed.
162 /// Setup for group handling.
164 // TODO: I don't understand group/context/etc. enough to be able to do
165 // something interesting with it here
166 // What is the context of a remote course?
168 /// If the group mode is separate, and this user does not have editing privileges,
169 /// then only the user's group can be viewed.
170 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
171 // $groupid = get_current_group($course->id);
173 /// If this course doesn't have groups, no groupid can be specified.
174 //else if (!$course->groupmode) {
175 // $groupid = 0;
178 $groupid = 0;
180 $joins = array();
181 $where = '';
183 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
184 FROM {mnet_log} l
185 LEFT JOIN {user} u ON l.userid = u.id
186 WHERE ";
187 $params = array();
189 $where .= "l.hostid = :hostid";
190 $params['hostid'] = $hostid;
192 // TODO: Is 1 really a magic number referring to the sitename?
193 if ($course != SITEID || $modid != 0) {
194 $where .= " AND l.course=:courseid";
195 $params['courseid'] = $course;
198 if ($modname) {
199 $where .= " AND l.module = :modname";
200 $params['modname'] = $modname;
203 if ('site_errors' === $modid) {
204 $where .= " AND ( l.action='error' OR l.action='infected' )";
205 } else if ($modid) {
206 //TODO: This assumes that modids are the same across sites... probably
207 //not true
208 $where .= " AND l.cmid = :modid";
209 $params['modid'] = $modid;
212 if ($modaction) {
213 $firstletter = substr($modaction, 0, 1);
214 if ($firstletter == '-') {
215 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
216 $params['modaction'] = '%'.substr($modaction, 1).'%';
217 } else {
218 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
219 $params['modaction'] = '%'.$modaction.'%';
223 if ($user) {
224 $where .= " AND l.userid = :user";
225 $params['user'] = $user;
228 if ($date) {
229 $enddate = $date + 86400;
230 $where .= " AND l.time > :date AND l.time < :enddate";
231 $params['date'] = $date;
232 $params['enddate'] = $enddate;
235 $result = array();
236 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
237 if(!empty($result['totalcount'])) {
238 $where .= " ORDER BY $order";
239 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
240 } else {
241 $result['logs'] = array();
243 return $result;
247 * Checks the integrity of the course data.
249 * In summary - compares course_sections.sequence and course_modules.section.
251 * More detailed, checks that:
252 * - course_sections.sequence contains each module id not more than once in the course
253 * - for each moduleid from course_sections.sequence the field course_modules.section
254 * refers to the same section id (this means course_sections.sequence is more
255 * important if they are different)
256 * - ($fullcheck only) each module in the course is present in one of
257 * course_sections.sequence
258 * - ($fullcheck only) removes non-existing course modules from section sequences
260 * If there are any mismatches, the changes are made and records are updated in DB.
262 * Course cache is NOT rebuilt if there are any errors!
264 * This function is used each time when course cache is being rebuilt with $fullcheck = false
265 * and in CLI script admin/cli/fix_course_sequence.php with $fullcheck = true
267 * @param int $courseid id of the course
268 * @param array $rawmods result of funciton {@link get_course_mods()} - containst
269 * the list of enabled course modules in the course. Retrieved from DB if not specified.
270 * Argument ignored in cashe of $fullcheck, the list is retrieved form DB anyway.
271 * @param array $sections records from course_sections table for this course.
272 * Retrieved from DB if not specified
273 * @param bool $fullcheck Will add orphaned modules to their sections and remove non-existing
274 * course modules from sequences. Only to be used in site maintenance mode when we are
275 * sure that another user is not in the middle of the process of moving/removing a module.
276 * @param bool $checkonly Only performs the check without updating DB, outputs all errors as debug messages.
277 * @return array array of messages with found problems. Empty output means everything is ok
279 function course_integrity_check($courseid, $rawmods = null, $sections = null, $fullcheck = false, $checkonly = false) {
280 global $DB;
281 $messages = array();
282 if ($sections === null) {
283 $sections = $DB->get_records('course_sections', array('course' => $courseid), 'section', 'id,section,sequence');
285 if ($fullcheck) {
286 // Retrieve all records from course_modules regardless of module type visibility.
287 $rawmods = $DB->get_records('course_modules', array('course' => $courseid), 'id', 'id,section');
289 if ($rawmods === null) {
290 $rawmods = get_course_mods($courseid);
292 if (!$fullcheck && (empty($sections) || empty($rawmods))) {
293 // If either of the arrays is empty, no modules are displayed anyway.
294 return true;
296 $debuggingprefix = 'Failed integrity check for course ['.$courseid.']. ';
298 // First make sure that each module id appears in section sequences only once.
299 // If it appears in several section sequences the last section wins.
300 // If it appears twice in one section sequence, the first occurence wins.
301 $modsection = array();
302 foreach ($sections as $sectionid => $section) {
303 $sections[$sectionid]->newsequence = $section->sequence;
304 if (!empty($section->sequence)) {
305 $sequence = explode(",", $section->sequence);
306 $sequenceunique = array_unique($sequence);
307 if (count($sequenceunique) != count($sequence)) {
308 // Some course module id appears in this section sequence more than once.
309 ksort($sequenceunique); // Preserve initial order of modules.
310 $sequence = array_values($sequenceunique);
311 $sections[$sectionid]->newsequence = join(',', $sequence);
312 $messages[] = $debuggingprefix.'Sequence for course section ['.
313 $sectionid.'] is "'.$sections[$sectionid]->sequence.'", must be "'.$sections[$sectionid]->newsequence.'"';
315 foreach ($sequence as $cmid) {
316 if (array_key_exists($cmid, $modsection) && isset($rawmods[$cmid])) {
317 // Some course module id appears to be in more than one section's sequences.
318 $wrongsectionid = $modsection[$cmid];
319 $sections[$wrongsectionid]->newsequence = trim(preg_replace("/,$cmid,/", ',', ','.$sections[$wrongsectionid]->newsequence. ','), ',');
320 $messages[] = $debuggingprefix.'Course module ['.$cmid.'] must be removed from sequence of section ['.
321 $wrongsectionid.'] because it is also present in sequence of section ['.$sectionid.']';
323 $modsection[$cmid] = $sectionid;
328 // Add orphaned modules to their sections if they exist or to section 0 otherwise.
329 if ($fullcheck) {
330 foreach ($rawmods as $cmid => $mod) {
331 if (!isset($modsection[$cmid])) {
332 // This is a module that is not mentioned in course_section.sequence at all.
333 // Add it to the section $mod->section or to the last available section.
334 if ($mod->section && isset($sections[$mod->section])) {
335 $modsection[$cmid] = $mod->section;
336 } else {
337 $firstsection = reset($sections);
338 $modsection[$cmid] = $firstsection->id;
340 $sections[$modsection[$cmid]]->newsequence = trim($sections[$modsection[$cmid]]->newsequence.','.$cmid, ',');
341 $messages[] = $debuggingprefix.'Course module ['.$cmid.'] is missing from sequence of section ['.
342 $modsection[$cmid].']';
345 foreach ($modsection as $cmid => $sectionid) {
346 if (!isset($rawmods[$cmid])) {
347 // Section $sectionid refers to module id that does not exist.
348 $sections[$sectionid]->newsequence = trim(preg_replace("/,$cmid,/", ',', ','.$sections[$sectionid]->newsequence.','), ',');
349 $messages[] = $debuggingprefix.'Course module ['.$cmid.
350 '] does not exist but is present in the sequence of section ['.$sectionid.']';
355 // Update changed sections.
356 if (!$checkonly && !empty($messages)) {
357 foreach ($sections as $sectionid => $section) {
358 if ($section->newsequence !== $section->sequence) {
359 $DB->update_record('course_sections', array('id' => $sectionid, 'sequence' => $section->newsequence));
364 // Now make sure that all modules point to the correct sections.
365 foreach ($rawmods as $cmid => $mod) {
366 if (isset($modsection[$cmid]) && $modsection[$cmid] != $mod->section) {
367 if (!$checkonly) {
368 $DB->update_record('course_modules', array('id' => $cmid, 'section' => $modsection[$cmid]));
370 $messages[] = $debuggingprefix.'Course module ['.$cmid.
371 '] points to section ['.$mod->section.'] instead of ['.$modsection[$cmid].']';
375 return $messages;
379 * For a given course, returns an array of course activity objects
380 * Each item in the array contains he following properties:
382 function get_array_of_activities($courseid) {
383 // cm - course module id
384 // mod - name of the module (eg forum)
385 // section - the number of the section (eg week or topic)
386 // name - the name of the instance
387 // visible - is the instance visible or not
388 // groupingid - grouping id
389 // extra - contains extra string to include in any link
390 global $CFG, $DB;
392 $course = $DB->get_record('course', array('id'=>$courseid));
394 if (empty($course)) {
395 throw new moodle_exception('courseidnotfound');
398 $mod = array();
400 $rawmods = get_course_mods($courseid);
401 if (empty($rawmods)) {
402 return $mod; // always return array
404 $courseformat = course_get_format($course);
406 if ($sections = $DB->get_records('course_sections', array('course' => $courseid),
407 'section ASC', 'id,section,sequence,visible')) {
408 // First check and correct obvious mismatches between course_sections.sequence and course_modules.section.
409 if ($errormessages = course_integrity_check($courseid, $rawmods, $sections)) {
410 debugging(join('<br>', $errormessages));
411 $rawmods = get_course_mods($courseid);
412 $sections = $DB->get_records('course_sections', array('course' => $courseid),
413 'section ASC', 'id,section,sequence,visible');
415 // Build array of activities.
416 foreach ($sections as $section) {
417 if (!empty($section->sequence)) {
418 $sequence = explode(",", $section->sequence);
419 foreach ($sequence as $seq) {
420 if (empty($rawmods[$seq])) {
421 continue;
423 // Adjust visibleoncoursepage, value in DB may not respect format availability.
424 $rawmods[$seq]->visibleoncoursepage = (!$rawmods[$seq]->visible
425 || $rawmods[$seq]->visibleoncoursepage
426 || empty($CFG->allowstealth)
427 || !$courseformat->allow_stealth_module_visibility($rawmods[$seq], $section)) ? 1 : 0;
429 // Create an object that will be cached.
430 $mod[$seq] = new stdClass();
431 $mod[$seq]->id = $rawmods[$seq]->instance;
432 $mod[$seq]->cm = $rawmods[$seq]->id;
433 $mod[$seq]->mod = $rawmods[$seq]->modname;
435 // Oh dear. Inconsistent names left here for backward compatibility.
436 $mod[$seq]->section = $section->section;
437 $mod[$seq]->sectionid = $rawmods[$seq]->section;
439 $mod[$seq]->module = $rawmods[$seq]->module;
440 $mod[$seq]->added = $rawmods[$seq]->added;
441 $mod[$seq]->score = $rawmods[$seq]->score;
442 $mod[$seq]->idnumber = $rawmods[$seq]->idnumber;
443 $mod[$seq]->visible = $rawmods[$seq]->visible;
444 $mod[$seq]->visibleoncoursepage = $rawmods[$seq]->visibleoncoursepage;
445 $mod[$seq]->visibleold = $rawmods[$seq]->visibleold;
446 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
447 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
448 $mod[$seq]->indent = $rawmods[$seq]->indent;
449 $mod[$seq]->completion = $rawmods[$seq]->completion;
450 $mod[$seq]->extra = "";
451 $mod[$seq]->completiongradeitemnumber =
452 $rawmods[$seq]->completiongradeitemnumber;
453 $mod[$seq]->completionview = $rawmods[$seq]->completionview;
454 $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected;
455 $mod[$seq]->showdescription = $rawmods[$seq]->showdescription;
456 $mod[$seq]->availability = $rawmods[$seq]->availability;
457 $mod[$seq]->deletioninprogress = $rawmods[$seq]->deletioninprogress;
459 $modname = $mod[$seq]->mod;
460 $functionname = $modname."_get_coursemodule_info";
462 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
463 continue;
466 include_once("$CFG->dirroot/mod/$modname/lib.php");
468 if ($hasfunction = function_exists($functionname)) {
469 if ($info = $functionname($rawmods[$seq])) {
470 if (!empty($info->icon)) {
471 $mod[$seq]->icon = $info->icon;
473 if (!empty($info->iconcomponent)) {
474 $mod[$seq]->iconcomponent = $info->iconcomponent;
476 if (!empty($info->name)) {
477 $mod[$seq]->name = $info->name;
479 if ($info instanceof cached_cm_info) {
480 // When using cached_cm_info you can include three new fields
481 // that aren't available for legacy code
482 if (!empty($info->content)) {
483 $mod[$seq]->content = $info->content;
485 if (!empty($info->extraclasses)) {
486 $mod[$seq]->extraclasses = $info->extraclasses;
488 if (!empty($info->iconurl)) {
489 // Convert URL to string as it's easier to store. Also serialized object contains \0 byte and can not be written to Postgres DB.
490 $url = new moodle_url($info->iconurl);
491 $mod[$seq]->iconurl = $url->out(false);
493 if (!empty($info->onclick)) {
494 $mod[$seq]->onclick = $info->onclick;
496 if (!empty($info->customdata)) {
497 $mod[$seq]->customdata = $info->customdata;
499 } else {
500 // When using a stdclass, the (horrible) deprecated ->extra field
501 // is available for BC
502 if (!empty($info->extra)) {
503 $mod[$seq]->extra = $info->extra;
508 // When there is no modname_get_coursemodule_info function,
509 // but showdescriptions is enabled, then we use the 'intro'
510 // and 'introformat' fields in the module table
511 if (!$hasfunction && $rawmods[$seq]->showdescription) {
512 if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
513 array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
514 // Set content from intro and introformat. Filters are disabled
515 // because we filter it with format_text at display time
516 $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
517 $modvalues, $rawmods[$seq]->id, false);
519 // To save making another query just below, put name in here
520 $mod[$seq]->name = $modvalues->name;
523 if (!isset($mod[$seq]->name)) {
524 $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
527 // Minimise the database size by unsetting default options when they are
528 // 'empty'. This list corresponds to code in the cm_info constructor.
529 foreach (array('idnumber', 'groupmode', 'groupingid',
530 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
531 'icon', 'iconcomponent', 'customdata', 'availability', 'completionview',
532 'completionexpected', 'score', 'showdescription', 'deletioninprogress') as $property) {
533 if (property_exists($mod[$seq], $property) &&
534 empty($mod[$seq]->{$property})) {
535 unset($mod[$seq]->{$property});
538 // Special case: this value is usually set to null, but may be 0
539 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
540 is_null($mod[$seq]->completiongradeitemnumber)) {
541 unset($mod[$seq]->completiongradeitemnumber);
547 return $mod;
551 * Returns the localised human-readable names of all used modules
553 * @param bool $plural if true returns the plural forms of the names
554 * @return array where key is the module name (component name without 'mod_') and
555 * the value is the human-readable string. Array sorted alphabetically by value
557 function get_module_types_names($plural = false) {
558 static $modnames = null;
559 global $DB, $CFG;
560 if ($modnames === null) {
561 $modnames = array(0 => array(), 1 => array());
562 if ($allmods = $DB->get_records("modules")) {
563 foreach ($allmods as $mod) {
564 if (file_exists("$CFG->dirroot/mod/$mod->name/lib.php") && $mod->visible) {
565 $modnames[0][$mod->name] = get_string("modulename", "$mod->name", null, true);
566 $modnames[1][$mod->name] = get_string("modulenameplural", "$mod->name", null, true);
571 return $modnames[(int)$plural];
575 * Set highlighted section. Only one section can be highlighted at the time.
577 * @param int $courseid course id
578 * @param int $marker highlight section with this number, 0 means remove higlightin
579 * @return void
581 function course_set_marker($courseid, $marker) {
582 global $DB, $COURSE;
583 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
584 if ($COURSE && $COURSE->id == $courseid) {
585 $COURSE->marker = $marker;
587 if (class_exists('format_base')) {
588 format_base::reset_course_cache($courseid);
590 course_modinfo::clear_instance_cache($courseid);
594 * For a given course section, marks it visible or hidden,
595 * and does the same for every activity in that section
597 * @param int $courseid course id
598 * @param int $sectionnumber The section number to adjust
599 * @param int $visibility The new visibility
600 * @return array A list of resources which were hidden in the section
602 function set_section_visible($courseid, $sectionnumber, $visibility) {
603 global $DB;
605 $resourcestotoggle = array();
606 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
607 course_update_section($courseid, $section, array('visible' => $visibility));
609 // Determine which modules are visible for AJAX update
610 $modules = !empty($section->sequence) ? explode(',', $section->sequence) : array();
611 if (!empty($modules)) {
612 list($insql, $params) = $DB->get_in_or_equal($modules);
613 $select = 'id ' . $insql . ' AND visible = ?';
614 array_push($params, $visibility);
615 if (!$visibility) {
616 $select .= ' AND visibleold = 1';
618 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
621 return $resourcestotoggle;
625 * Retrieve all metadata for the requested modules
627 * @param object $course The Course
628 * @param array $modnames An array containing the list of modules and their
629 * names
630 * @param int $sectionreturn The section to return to
631 * @return array A list of stdClass objects containing metadata about each
632 * module
634 function get_module_metadata($course, $modnames, $sectionreturn = null) {
635 global $OUTPUT;
637 // get_module_metadata will be called once per section on the page and courses may show
638 // different modules to one another
639 static $modlist = array();
640 if (!isset($modlist[$course->id])) {
641 $modlist[$course->id] = array();
644 $return = array();
645 $urlbase = new moodle_url('/course/mod.php', array('id' => $course->id, 'sesskey' => sesskey()));
646 if ($sectionreturn !== null) {
647 $urlbase->param('sr', $sectionreturn);
649 foreach($modnames as $modname => $modnamestr) {
650 if (!course_allowed_module($course, $modname)) {
651 continue;
653 if (isset($modlist[$course->id][$modname])) {
654 // This module is already cached
655 $return += $modlist[$course->id][$modname];
656 continue;
658 $modlist[$course->id][$modname] = array();
660 // Create an object for a default representation of this module type in the activity chooser. It will be used
661 // if module does not implement callback get_shortcuts() and it will also be passed to the callback if it exists.
662 $defaultmodule = new stdClass();
663 $defaultmodule->title = $modnamestr;
664 $defaultmodule->name = $modname;
665 $defaultmodule->link = new moodle_url($urlbase, array('add' => $modname));
666 $defaultmodule->icon = $OUTPUT->pix_icon('icon', '', $defaultmodule->name, array('class' => 'icon'));
667 $sm = get_string_manager();
668 if ($sm->string_exists('modulename_help', $modname)) {
669 $defaultmodule->help = get_string('modulename_help', $modname);
670 if ($sm->string_exists('modulename_link', $modname)) { // Link to further info in Moodle docs.
671 $link = get_string('modulename_link', $modname);
672 $linktext = get_string('morehelp');
673 $defaultmodule->help .= html_writer::tag('div',
674 $OUTPUT->doc_link($link, $linktext, true), array('class' => 'helpdoclink'));
677 $defaultmodule->archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
679 // Each module can implement callback modulename_get_shortcuts() in its lib.php and return the list
680 // of elements to be added to activity chooser.
681 $items = component_callback($modname, 'get_shortcuts', array($defaultmodule), null);
682 if ($items !== null) {
683 foreach ($items as $item) {
684 // Add all items to the return array. All items must have different links, use them as a key in the return array.
685 if (!isset($item->archetype)) {
686 $item->archetype = $defaultmodule->archetype;
688 if (!isset($item->icon)) {
689 $item->icon = $defaultmodule->icon;
691 // If plugin returned the only one item with the same link as default item - cache it as $modname,
692 // otherwise append the link url to the module name.
693 $item->name = (count($items) == 1 &&
694 $item->link->out() === $defaultmodule->link->out()) ? $modname : $modname . ':' . $item->link;
696 // If the module provides the helptext property, append it to the help text to match the look and feel
697 // of the default course modules.
698 if (isset($item->help) && isset($item->helplink)) {
699 $linktext = get_string('morehelp');
700 $item->help .= html_writer::tag('div',
701 $OUTPUT->doc_link($item->helplink, $linktext, true), array('class' => 'helpdoclink'));
703 $modlist[$course->id][$modname][$item->name] = $item;
705 $return += $modlist[$course->id][$modname];
706 // If get_shortcuts() callback is defined, the default module action is not added.
707 // It is a responsibility of the callback to add it to the return value unless it is not needed.
708 continue;
711 // The callback get_shortcuts() was not found, use the default item for the activity chooser.
712 $modlist[$course->id][$modname][$modname] = $defaultmodule;
713 $return[$modname] = $defaultmodule;
716 core_collator::asort_objects_by_property($return, 'title');
717 return $return;
721 * Return the course category context for the category with id $categoryid, except
722 * that if $categoryid is 0, return the system context.
724 * @param integer $categoryid a category id or 0.
725 * @return context the corresponding context
727 function get_category_or_system_context($categoryid) {
728 if ($categoryid) {
729 return context_coursecat::instance($categoryid, IGNORE_MISSING);
730 } else {
731 return context_system::instance();
736 * Returns the list of full course categories to be used in html_writer::select()
738 * Calls {@see core_course_category::make_categories_list()} to build the list.
740 * @return array array mapping course category id to the display name
742 function make_categories_options() {
743 return core_course_category::make_categories_list('', 0, ' / ');
747 * Print the buttons relating to course requests.
749 * @param context $context current page context.
751 function print_course_request_buttons($context) {
752 global $CFG, $DB, $OUTPUT;
753 if (empty($CFG->enablecourserequests)) {
754 return;
756 if (course_request::can_request($context)) {
757 // Print a button to request a new course.
758 $params = [];
759 if ($context instanceof context_coursecat) {
760 $params['category'] = $context->instanceid;
762 echo $OUTPUT->single_button(new moodle_url('/course/request.php', $params),
763 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 $showinfo = !defined('AJAX_SCRIPT') || AJAX_SCRIPT == '0';
1150 question_delete_activity($cm, $showinfo);
1152 // Call the delete_instance function, if it returns false throw an exception.
1153 if (!$deleteinstancefunction($cm->instance)) {
1154 throw new moodle_exception('cannotdeletemoduleinstance', '', '', null,
1155 "Cannot delete the module $modulename (instance).");
1158 // Remove all module files in case modules forget to do that.
1159 $fs = get_file_storage();
1160 $fs->delete_area_files($modcontext->id);
1162 // Delete events from calendar.
1163 if ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename))) {
1164 $coursecontext = context_course::instance($cm->course);
1165 foreach($events as $event) {
1166 $event->context = $coursecontext;
1167 $calendarevent = calendar_event::load($event);
1168 $calendarevent->delete();
1172 // Delete grade items, outcome items and grades attached to modules.
1173 if ($grade_items = grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $modulename,
1174 'iteminstance' => $cm->instance, 'courseid' => $cm->course))) {
1175 foreach ($grade_items as $grade_item) {
1176 $grade_item->delete('moddelete');
1180 // Delete associated blogs and blog tag instances.
1181 blog_remove_associations_for_module($modcontext->id);
1183 // Delete completion and availability data; it is better to do this even if the
1184 // features are not turned on, in case they were turned on previously (these will be
1185 // very quick on an empty table).
1186 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
1187 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
1188 'course' => $cm->course,
1189 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
1191 // Delete all tag instances associated with the instance of this module.
1192 core_tag_tag::delete_instances('mod_' . $modulename, null, $modcontext->id);
1193 core_tag_tag::remove_all_item_tags('core', 'course_modules', $cm->id);
1195 // Notify the competency subsystem.
1196 \core_competency\api::hook_course_module_deleted($cm);
1198 // Delete the context.
1199 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
1201 // Delete the module from the course_modules table.
1202 $DB->delete_records('course_modules', array('id' => $cm->id));
1204 // Delete module from that section.
1205 if (!delete_mod_from_section($cm->id, $cm->section)) {
1206 throw new moodle_exception('cannotdeletemodulefromsection', '', '', null,
1207 "Cannot delete the module $modulename (instance) from section.");
1210 // Trigger event for course module delete action.
1211 $event = \core\event\course_module_deleted::create(array(
1212 'courseid' => $cm->course,
1213 'context' => $modcontext,
1214 'objectid' => $cm->id,
1215 'other' => array(
1216 'modulename' => $modulename,
1217 'instanceid' => $cm->instance,
1220 $event->add_record_snapshot('course_modules', $cm);
1221 $event->trigger();
1222 rebuild_course_cache($cm->course, true);
1226 * Schedule a course module for deletion in the background using an adhoc task.
1228 * This method should not be called directly. Instead, please use course_delete_module($cmid, true), to denote async deletion.
1229 * The real deletion of the module is handled by the task, which calls 'course_delete_module($cmid)'.
1231 * @param int $cmid the course module id.
1232 * @return bool whether the module was successfully scheduled for deletion.
1233 * @throws \moodle_exception
1235 function course_module_flag_for_async_deletion($cmid) {
1236 global $CFG, $DB, $USER;
1237 require_once($CFG->libdir.'/gradelib.php');
1238 require_once($CFG->libdir.'/questionlib.php');
1239 require_once($CFG->dirroot.'/blog/lib.php');
1240 require_once($CFG->dirroot.'/calendar/lib.php');
1242 // Get the course module.
1243 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
1244 return true;
1247 // We need to be reasonably certain the deletion is going to succeed before we background the process.
1248 // Make the necessary delete_instance checks, etc. before proceeding further. Throw exceptions if required.
1250 // Get the course module name.
1251 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
1253 // Get the file location of the delete_instance function for this module.
1254 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
1256 // Include the file required to call the delete_instance function for this module.
1257 if (file_exists($modlib)) {
1258 require_once($modlib);
1259 } else {
1260 throw new \moodle_exception('cannotdeletemodulemissinglib', '', '', null,
1261 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
1264 $deleteinstancefunction = $modulename . '_delete_instance';
1266 // Ensure the delete_instance function exists for this module.
1267 if (!function_exists($deleteinstancefunction)) {
1268 throw new \moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
1269 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
1272 // We are going to defer the deletion as we can't be sure how long the module's pre_delete code will run for.
1273 $cm->deletioninprogress = '1';
1274 $DB->update_record('course_modules', $cm);
1276 // Create an adhoc task for the deletion of the course module. The task takes an array of course modules for removal.
1277 $removaltask = new \core_course\task\course_delete_modules();
1278 $removaltask->set_custom_data(array(
1279 'cms' => array($cm),
1280 'userid' => $USER->id,
1281 'realuserid' => \core\session\manager::get_realuser()->id
1284 // Queue the task for the next run.
1285 \core\task\manager::queue_adhoc_task($removaltask);
1287 // Reset the course cache to hide the module.
1288 rebuild_course_cache($cm->course, true);
1292 * Checks whether the given course has any course modules scheduled for adhoc deletion.
1294 * @param int $courseid the id of the course.
1295 * @param bool $onlygradable whether to check only gradable modules or all modules.
1296 * @return bool true if the course contains any modules pending deletion, false otherwise.
1298 function course_modules_pending_deletion(int $courseid, bool $onlygradable = false) : bool {
1299 if (empty($courseid)) {
1300 return false;
1303 if ($onlygradable) {
1304 // Fetch modules with grade items.
1305 if (!$coursegradeitems = grade_item::fetch_all(['itemtype' => 'mod', 'courseid' => $courseid])) {
1306 // Return early when there is none.
1307 return false;
1311 $modinfo = get_fast_modinfo($courseid);
1312 foreach ($modinfo->get_cms() as $module) {
1313 if ($module->deletioninprogress == '1') {
1314 if ($onlygradable) {
1315 // Check if the module being deleted is in the list of course modules with grade items.
1316 foreach ($coursegradeitems as $coursegradeitem) {
1317 if ($coursegradeitem->itemmodule == $module->modname && $coursegradeitem->iteminstance == $module->instance) {
1318 // The module being deleted is within the gradable modules.
1319 return true;
1322 } else {
1323 return true;
1327 return false;
1331 * Checks whether the course module, as defined by modulename and instanceid, is scheduled for deletion within the given course.
1333 * @param int $courseid the course id.
1334 * @param string $modulename the module name. E.g. 'assign', 'book', etc.
1335 * @param int $instanceid the module instance id.
1336 * @return bool true if the course module is pending deletion, false otherwise.
1338 function course_module_instance_pending_deletion($courseid, $modulename, $instanceid) {
1339 if (empty($courseid) || empty($modulename) || empty($instanceid)) {
1340 return false;
1342 $modinfo = get_fast_modinfo($courseid);
1343 $instances = $modinfo->get_instances_of($modulename);
1344 return isset($instances[$instanceid]) && $instances[$instanceid]->deletioninprogress;
1347 function delete_mod_from_section($modid, $sectionid) {
1348 global $DB;
1350 if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
1352 $modarray = explode(",", $section->sequence);
1354 if ($key = array_keys ($modarray, $modid)) {
1355 array_splice($modarray, $key[0], 1);
1356 $newsequence = implode(",", $modarray);
1357 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
1358 rebuild_course_cache($section->course, true);
1359 return true;
1360 } else {
1361 return false;
1365 return false;
1369 * This function updates the calendar events from the information stored in the module table and the course
1370 * module table.
1372 * @param string $modulename Module name
1373 * @param stdClass $instance Module object. Either the $instance or the $cm must be supplied.
1374 * @param stdClass $cm Course module object. Either the $instance or the $cm must be supplied.
1375 * @return bool Returns true if calendar events are updated.
1376 * @since Moodle 3.3.4
1378 function course_module_update_calendar_events($modulename, $instance = null, $cm = null) {
1379 global $DB;
1381 if (isset($instance) || isset($cm)) {
1383 if (!isset($instance)) {
1384 $instance = $DB->get_record($modulename, array('id' => $cm->instance), '*', MUST_EXIST);
1386 if (!isset($cm)) {
1387 $cm = get_coursemodule_from_instance($modulename, $instance->id, $instance->course);
1389 if (!empty($cm)) {
1390 course_module_calendar_event_update_process($instance, $cm);
1392 return true;
1394 return false;
1398 * Update all instances through out the site or in a course.
1400 * @param string $modulename Module type to update.
1401 * @param integer $courseid Course id to update events. 0 for the whole site.
1402 * @return bool Returns True if the update was successful.
1403 * @since Moodle 3.3.4
1405 function course_module_bulk_update_calendar_events($modulename, $courseid = 0) {
1406 global $DB;
1408 $instances = null;
1409 if ($courseid) {
1410 if (!$instances = $DB->get_records($modulename, array('course' => $courseid))) {
1411 return false;
1413 } else {
1414 if (!$instances = $DB->get_records($modulename)) {
1415 return false;
1419 foreach ($instances as $instance) {
1420 if ($cm = get_coursemodule_from_instance($modulename, $instance->id, $instance->course)) {
1421 course_module_calendar_event_update_process($instance, $cm);
1424 return true;
1428 * Calendar events for a module instance are updated.
1430 * @param stdClass $instance Module instance object.
1431 * @param stdClass $cm Course Module object.
1432 * @since Moodle 3.3.4
1434 function course_module_calendar_event_update_process($instance, $cm) {
1435 // We need to call *_refresh_events() first because some modules delete 'old' events at the end of the code which
1436 // will remove the completion events.
1437 $refresheventsfunction = $cm->modname . '_refresh_events';
1438 if (function_exists($refresheventsfunction)) {
1439 call_user_func($refresheventsfunction, $cm->course, $instance, $cm);
1441 $completionexpected = (!empty($cm->completionexpected)) ? $cm->completionexpected : null;
1442 \core_completion\api::update_completion_date_event($cm->id, $cm->modname, $instance, $completionexpected);
1446 * Moves a section within a course, from a position to another.
1447 * Be very careful: $section and $destination refer to section number,
1448 * not id!.
1450 * @param object $course
1451 * @param int $section Section number (not id!!!)
1452 * @param int $destination
1453 * @param bool $ignorenumsections
1454 * @return boolean Result
1456 function move_section_to($course, $section, $destination, $ignorenumsections = false) {
1457 /// Moves a whole course section up and down within the course
1458 global $USER, $DB;
1460 if (!$destination && $destination != 0) {
1461 return true;
1464 // compartibility with course formats using field 'numsections'
1465 $courseformatoptions = course_get_format($course)->get_format_options();
1466 if ((!$ignorenumsections && array_key_exists('numsections', $courseformatoptions) &&
1467 ($destination > $courseformatoptions['numsections'])) || ($destination < 1)) {
1468 return false;
1471 // Get all sections for this course and re-order them (2 of them should now share the same section number)
1472 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
1473 'section ASC, id ASC', 'id, section')) {
1474 return false;
1477 $movedsections = reorder_sections($sections, $section, $destination);
1479 // Update all sections. Do this in 2 steps to avoid breaking database
1480 // uniqueness constraint
1481 $transaction = $DB->start_delegated_transaction();
1482 foreach ($movedsections as $id => $position) {
1483 if ($sections[$id] !== $position) {
1484 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
1487 foreach ($movedsections as $id => $position) {
1488 if ($sections[$id] !== $position) {
1489 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
1493 // If we move the highlighted section itself, then just highlight the destination.
1494 // Adjust the higlighted section location if we move something over it either direction.
1495 if ($section == $course->marker) {
1496 course_set_marker($course->id, $destination);
1497 } elseif ($section > $course->marker && $course->marker >= $destination) {
1498 course_set_marker($course->id, $course->marker+1);
1499 } elseif ($section < $course->marker && $course->marker <= $destination) {
1500 course_set_marker($course->id, $course->marker-1);
1503 $transaction->allow_commit();
1504 rebuild_course_cache($course->id, true);
1505 return true;
1509 * This method will delete a course section and may delete all modules inside it.
1511 * No permissions are checked here, use {@link course_can_delete_section()} to
1512 * check if section can actually be deleted.
1514 * @param int|stdClass $course
1515 * @param int|stdClass|section_info $section
1516 * @param bool $forcedeleteifnotempty if set to false section will not be deleted if it has modules in it.
1517 * @param bool $async whether or not to try to delete the section using an adhoc task. Async also depends on a plugin hook.
1518 * @return bool whether section was deleted
1520 function course_delete_section($course, $section, $forcedeleteifnotempty = true, $async = false) {
1521 global $DB;
1523 // Prepare variables.
1524 $courseid = (is_object($course)) ? $course->id : (int)$course;
1525 $sectionnum = (is_object($section)) ? $section->section : (int)$section;
1526 $section = $DB->get_record('course_sections', array('course' => $courseid, 'section' => $sectionnum));
1527 if (!$section) {
1528 // No section exists, can't proceed.
1529 return false;
1532 // Check the 'course_module_background_deletion_recommended' hook first.
1533 // Only use asynchronous deletion if at least one plugin returns true and if async deletion has been requested.
1534 // Both are checked because plugins should not be allowed to dictate the deletion behaviour, only support/decline it.
1535 // It's up to plugins to handle things like whether or not they are enabled.
1536 if ($async && $pluginsfunction = get_plugins_with_function('course_module_background_deletion_recommended')) {
1537 foreach ($pluginsfunction as $plugintype => $plugins) {
1538 foreach ($plugins as $pluginfunction) {
1539 if ($pluginfunction()) {
1540 return course_delete_section_async($section, $forcedeleteifnotempty);
1546 $format = course_get_format($course);
1547 $sectionname = $format->get_section_name($section);
1549 // Delete section.
1550 $result = $format->delete_section($section, $forcedeleteifnotempty);
1552 // Trigger an event for course section deletion.
1553 if ($result) {
1554 $context = context_course::instance($courseid);
1555 $event = \core\event\course_section_deleted::create(
1556 array(
1557 'objectid' => $section->id,
1558 'courseid' => $courseid,
1559 'context' => $context,
1560 'other' => array(
1561 'sectionnum' => $section->section,
1562 'sectionname' => $sectionname,
1566 $event->add_record_snapshot('course_sections', $section);
1567 $event->trigger();
1569 return $result;
1573 * Course section deletion, using an adhoc task for deletion of the modules it contains.
1574 * 1. Schedule all modules within the section for adhoc removal.
1575 * 2. Move all modules to course section 0.
1576 * 3. Delete the resulting empty section.
1578 * @param \stdClass $section the section to schedule for deletion.
1579 * @param bool $forcedeleteifnotempty whether to force section deletion if it contains modules.
1580 * @return bool true if the section was scheduled for deletion, false otherwise.
1582 function course_delete_section_async($section, $forcedeleteifnotempty = true) {
1583 global $DB, $USER;
1585 // Objects only, and only valid ones.
1586 if (!is_object($section) || empty($section->id)) {
1587 return false;
1590 // Does the object currently exist in the DB for removal (check for stale objects).
1591 $section = $DB->get_record('course_sections', array('id' => $section->id));
1592 if (!$section || !$section->section) {
1593 // No section exists, or the section is 0. Can't proceed.
1594 return false;
1597 // Check whether the section can be removed.
1598 if (!$forcedeleteifnotempty && (!empty($section->sequence) || !empty($section->summary))) {
1599 return false;
1602 $format = course_get_format($section->course);
1603 $sectionname = $format->get_section_name($section);
1605 // Flag those modules having no existing deletion flag. Some modules may have been scheduled for deletion manually, and we don't
1606 // want to create additional adhoc deletion tasks for these. Moving them to section 0 will suffice.
1607 $affectedmods = $DB->get_records_select('course_modules', 'course = ? AND section = ? AND deletioninprogress <> ?',
1608 [$section->course, $section->id, 1], '', 'id');
1609 $DB->set_field('course_modules', 'deletioninprogress', '1', ['course' => $section->course, 'section' => $section->id]);
1611 // Move all modules to section 0.
1612 $modules = $DB->get_records('course_modules', ['section' => $section->id], '');
1613 $sectionzero = $DB->get_record('course_sections', ['course' => $section->course, 'section' => '0']);
1614 foreach ($modules as $mod) {
1615 moveto_module($mod, $sectionzero);
1618 // Create and queue an adhoc task for the deletion of the modules.
1619 $removaltask = new \core_course\task\course_delete_modules();
1620 $data = array(
1621 'cms' => $affectedmods,
1622 'userid' => $USER->id,
1623 'realuserid' => \core\session\manager::get_realuser()->id
1625 $removaltask->set_custom_data($data);
1626 \core\task\manager::queue_adhoc_task($removaltask);
1628 // Delete the now empty section, passing in only the section number, which forces the function to fetch a new object.
1629 // The refresh is needed because the section->sequence is now stale.
1630 $result = $format->delete_section($section->section, $forcedeleteifnotempty);
1632 // Trigger an event for course section deletion.
1633 if ($result) {
1634 $context = \context_course::instance($section->course);
1635 $event = \core\event\course_section_deleted::create(
1636 array(
1637 'objectid' => $section->id,
1638 'courseid' => $section->course,
1639 'context' => $context,
1640 'other' => array(
1641 'sectionnum' => $section->section,
1642 'sectionname' => $sectionname,
1646 $event->add_record_snapshot('course_sections', $section);
1647 $event->trigger();
1649 rebuild_course_cache($section->course, true);
1651 return $result;
1655 * Updates the course section
1657 * This function does not check permissions or clean values - this has to be done prior to calling it.
1659 * @param int|stdClass $course
1660 * @param stdClass $section record from course_sections table - it will be updated with the new values
1661 * @param array|stdClass $data
1663 function course_update_section($course, $section, $data) {
1664 global $DB;
1666 $courseid = (is_object($course)) ? $course->id : (int)$course;
1668 // Some fields can not be updated using this method.
1669 $data = array_diff_key((array)$data, array('id', 'course', 'section', 'sequence'));
1670 $changevisibility = (array_key_exists('visible', $data) && (bool)$data['visible'] != (bool)$section->visible);
1671 if (array_key_exists('name', $data) && \core_text::strlen($data['name']) > 255) {
1672 throw new moodle_exception('maximumchars', 'moodle', '', 255);
1675 // Update record in the DB and course format options.
1676 $data['id'] = $section->id;
1677 $data['timemodified'] = time();
1678 $DB->update_record('course_sections', $data);
1679 rebuild_course_cache($courseid, true);
1680 course_get_format($courseid)->update_section_format_options($data);
1682 // Update fields of the $section object.
1683 foreach ($data as $key => $value) {
1684 if (property_exists($section, $key)) {
1685 $section->$key = $value;
1689 // Trigger an event for course section update.
1690 $event = \core\event\course_section_updated::create(
1691 array(
1692 'objectid' => $section->id,
1693 'courseid' => $courseid,
1694 'context' => context_course::instance($courseid),
1695 'other' => array('sectionnum' => $section->section)
1698 $event->trigger();
1700 // If section visibility was changed, hide the modules in this section too.
1701 if ($changevisibility && !empty($section->sequence)) {
1702 $modules = explode(',', $section->sequence);
1703 foreach ($modules as $moduleid) {
1704 if ($cm = get_coursemodule_from_id(null, $moduleid, $courseid)) {
1705 if ($data['visible']) {
1706 // As we unhide the section, we use the previously saved visibility stored in visibleold.
1707 set_coursemodule_visible($moduleid, $cm->visibleold, $cm->visibleoncoursepage);
1708 } else {
1709 // We hide the section, so we hide the module but we store the original state in visibleold.
1710 set_coursemodule_visible($moduleid, 0, $cm->visibleoncoursepage);
1711 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id' => $moduleid));
1713 \core\event\course_module_updated::create_from_cm($cm)->trigger();
1720 * Checks if the current user can delete a section (if course format allows it and user has proper permissions).
1722 * @param int|stdClass $course
1723 * @param int|stdClass|section_info $section
1724 * @return bool
1726 function course_can_delete_section($course, $section) {
1727 if (is_object($section)) {
1728 $section = $section->section;
1730 if (!$section) {
1731 // Not possible to delete 0-section.
1732 return false;
1734 // Course format should allow to delete sections.
1735 if (!course_get_format($course)->can_delete_section($section)) {
1736 return false;
1738 // Make sure user has capability to update course and move sections.
1739 $context = context_course::instance(is_object($course) ? $course->id : $course);
1740 if (!has_all_capabilities(array('moodle/course:movesections', 'moodle/course:update'), $context)) {
1741 return false;
1743 // Make sure user has capability to delete each activity in this section.
1744 $modinfo = get_fast_modinfo($course);
1745 if (!empty($modinfo->sections[$section])) {
1746 foreach ($modinfo->sections[$section] as $cmid) {
1747 if (!has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
1748 return false;
1752 return true;
1756 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
1757 * an original position number and a target position number, rebuilds the array so that the
1758 * move is made without any duplication of section positions.
1759 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
1760 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
1762 * @param array $sections
1763 * @param int $origin_position
1764 * @param int $target_position
1765 * @return array
1767 function reorder_sections($sections, $origin_position, $target_position) {
1768 if (!is_array($sections)) {
1769 return false;
1772 // We can't move section position 0
1773 if ($origin_position < 1) {
1774 echo "We can't move section position 0";
1775 return false;
1778 // Locate origin section in sections array
1779 if (!$origin_key = array_search($origin_position, $sections)) {
1780 echo "searched position not in sections array";
1781 return false; // searched position not in sections array
1784 // Extract origin section
1785 $origin_section = $sections[$origin_key];
1786 unset($sections[$origin_key]);
1788 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
1789 $found = false;
1790 $append_array = array();
1791 foreach ($sections as $id => $position) {
1792 if ($found) {
1793 $append_array[$id] = $position;
1794 unset($sections[$id]);
1796 if ($position == $target_position) {
1797 if ($target_position < $origin_position) {
1798 $append_array[$id] = $position;
1799 unset($sections[$id]);
1801 $found = true;
1805 // Append moved section
1806 $sections[$origin_key] = $origin_section;
1808 // Append rest of array (if applicable)
1809 if (!empty($append_array)) {
1810 foreach ($append_array as $id => $position) {
1811 $sections[$id] = $position;
1815 // Renumber positions
1816 $position = 0;
1817 foreach ($sections as $id => $p) {
1818 $sections[$id] = $position;
1819 $position++;
1822 return $sections;
1827 * Move the module object $mod to the specified $section
1828 * If $beforemod exists then that is the module
1829 * before which $modid should be inserted
1831 * @param stdClass|cm_info $mod
1832 * @param stdClass|section_info $section
1833 * @param int|stdClass $beforemod id or object with field id corresponding to the module
1834 * before which the module needs to be included. Null for inserting in the
1835 * end of the section
1836 * @return int new value for module visibility (0 or 1)
1838 function moveto_module($mod, $section, $beforemod=NULL) {
1839 global $OUTPUT, $DB;
1841 // Current module visibility state - return value of this function.
1842 $modvisible = $mod->visible;
1844 // Remove original module from original section.
1845 if (! delete_mod_from_section($mod->id, $mod->section)) {
1846 echo $OUTPUT->notification("Could not delete module from existing section");
1849 // If moving to a hidden section then hide module.
1850 if ($mod->section != $section->id) {
1851 if (!$section->visible && $mod->visible) {
1852 // Module was visible but must become hidden after moving to hidden section.
1853 $modvisible = 0;
1854 set_coursemodule_visible($mod->id, 0);
1855 // Set visibleold to 1 so module will be visible when section is made visible.
1856 $DB->set_field('course_modules', 'visibleold', 1, array('id' => $mod->id));
1858 if ($section->visible && !$mod->visible) {
1859 // Hidden module was moved to the visible section, restore the module visibility from visibleold.
1860 set_coursemodule_visible($mod->id, $mod->visibleold);
1861 $modvisible = $mod->visibleold;
1865 // Add the module into the new section.
1866 course_add_cm_to_section($section->course, $mod->id, $section->section, $beforemod);
1867 return $modvisible;
1871 * Returns the list of all editing actions that current user can perform on the module
1873 * @param cm_info $mod The module to produce editing buttons for
1874 * @param int $indent The current indenting (default -1 means no move left-right actions)
1875 * @param int $sr The section to link back to (used for creating the links)
1876 * @return array array of action_link or pix_icon objects
1878 function course_get_cm_edit_actions(cm_info $mod, $indent = -1, $sr = null) {
1879 global $COURSE, $SITE, $CFG;
1881 static $str;
1883 $coursecontext = context_course::instance($mod->course);
1884 $modcontext = context_module::instance($mod->id);
1885 $courseformat = course_get_format($mod->get_course());
1887 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
1888 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
1890 // No permission to edit anything.
1891 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
1892 return array();
1895 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
1897 if (!isset($str)) {
1898 $str = get_strings(array('delete', 'move', 'moveright', 'moveleft',
1899 'editsettings', 'duplicate', 'modhide', 'makeavailable', 'makeunavailable', 'modshow'), 'moodle');
1900 $str->assign = get_string('assignroles', 'role');
1901 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
1902 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
1903 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
1906 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
1908 if ($sr !== null) {
1909 $baseurl->param('sr', $sr);
1911 $actions = array();
1913 // Update.
1914 if ($hasmanageactivities) {
1915 $actions['update'] = new action_menu_link_secondary(
1916 new moodle_url($baseurl, array('update' => $mod->id)),
1917 new pix_icon('t/edit', '', 'moodle', array('class' => 'iconsmall')),
1918 $str->editsettings,
1919 array('class' => 'editing_update', 'data-action' => 'update')
1923 // Indent.
1924 if ($hasmanageactivities && $indent >= 0) {
1925 $indentlimits = new stdClass();
1926 $indentlimits->min = 0;
1927 $indentlimits->max = 16;
1928 if (right_to_left()) { // Exchange arrows on RTL
1929 $rightarrow = 't/left';
1930 $leftarrow = 't/right';
1931 } else {
1932 $rightarrow = 't/right';
1933 $leftarrow = 't/left';
1936 if ($indent >= $indentlimits->max) {
1937 $enabledclass = 'hidden';
1938 } else {
1939 $enabledclass = '';
1941 $actions['moveright'] = new action_menu_link_secondary(
1942 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
1943 new pix_icon($rightarrow, '', 'moodle', array('class' => 'iconsmall')),
1944 $str->moveright,
1945 array('class' => 'editing_moveright ' . $enabledclass, 'data-action' => 'moveright',
1946 'data-keepopen' => true, 'data-sectionreturn' => $sr)
1949 if ($indent <= $indentlimits->min) {
1950 $enabledclass = 'hidden';
1951 } else {
1952 $enabledclass = '';
1954 $actions['moveleft'] = new action_menu_link_secondary(
1955 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
1956 new pix_icon($leftarrow, '', 'moodle', array('class' => 'iconsmall')),
1957 $str->moveleft,
1958 array('class' => 'editing_moveleft ' . $enabledclass, 'data-action' => 'moveleft',
1959 'data-keepopen' => true, 'data-sectionreturn' => $sr)
1964 // Hide/Show/Available/Unavailable.
1965 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
1966 $allowstealth = !empty($CFG->allowstealth) && $courseformat->allow_stealth_module_visibility($mod, $mod->get_section_info());
1968 $sectionvisible = $mod->get_section_info()->visible;
1969 // The module on the course page may be in one of the following states:
1970 // - Available and displayed on the course page ($displayedoncoursepage);
1971 // - Not available and not displayed on the course page ($unavailable);
1972 // - Available but not displayed on the course page ($stealth) - this can also be a visible activity in a hidden section.
1973 $displayedoncoursepage = $mod->visible && $mod->visibleoncoursepage && $sectionvisible;
1974 $unavailable = !$mod->visible;
1975 $stealth = $mod->visible && (!$mod->visibleoncoursepage || !$sectionvisible);
1976 if ($displayedoncoursepage) {
1977 $actions['hide'] = new action_menu_link_secondary(
1978 new moodle_url($baseurl, array('hide' => $mod->id)),
1979 new pix_icon('t/hide', '', 'moodle', array('class' => 'iconsmall')),
1980 $str->modhide,
1981 array('class' => 'editing_hide', 'data-action' => 'hide')
1983 } else if (!$displayedoncoursepage && $sectionvisible) {
1984 // Offer to "show" only if the section is visible.
1985 $actions['show'] = new action_menu_link_secondary(
1986 new moodle_url($baseurl, array('show' => $mod->id)),
1987 new pix_icon('t/show', '', 'moodle', array('class' => 'iconsmall')),
1988 $str->modshow,
1989 array('class' => 'editing_show', 'data-action' => 'show')
1993 if ($stealth) {
1994 // When making the "stealth" module unavailable we perform the same action as hiding the visible module.
1995 $actions['hide'] = new action_menu_link_secondary(
1996 new moodle_url($baseurl, array('hide' => $mod->id)),
1997 new pix_icon('t/unblock', '', 'moodle', array('class' => 'iconsmall')),
1998 $str->makeunavailable,
1999 array('class' => 'editing_makeunavailable', 'data-action' => 'hide', 'data-sectionreturn' => $sr)
2001 } else if ($unavailable && (!$sectionvisible || $allowstealth) && $mod->has_view()) {
2002 // Allow to make visually hidden module available in gradebook and other reports by making it a "stealth" module.
2003 // When the section is hidden it is an equivalent of "showing" the module.
2004 // Activities without the link (i.e. labels) can not be made available but hidden on course page.
2005 $action = $sectionvisible ? 'stealth' : 'show';
2006 $actions[$action] = new action_menu_link_secondary(
2007 new moodle_url($baseurl, array($action => $mod->id)),
2008 new pix_icon('t/block', '', 'moodle', array('class' => 'iconsmall')),
2009 $str->makeavailable,
2010 array('class' => 'editing_makeavailable', 'data-action' => $action, 'data-sectionreturn' => $sr)
2015 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
2016 if (has_all_capabilities($dupecaps, $coursecontext) &&
2017 plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2) &&
2018 course_allowed_module($mod->get_course(), $mod->modname)) {
2019 $actions['duplicate'] = new action_menu_link_secondary(
2020 new moodle_url($baseurl, array('duplicate' => $mod->id)),
2021 new pix_icon('t/copy', '', 'moodle', array('class' => 'iconsmall')),
2022 $str->duplicate,
2023 array('class' => 'editing_duplicate', 'data-action' => 'duplicate', 'data-sectionreturn' => $sr)
2027 // Groupmode.
2028 if ($hasmanageactivities && !$mod->coursegroupmodeforce) {
2029 if (plugin_supports('mod', $mod->modname, FEATURE_GROUPS, false)) {
2030 if ($mod->effectivegroupmode == SEPARATEGROUPS) {
2031 $nextgroupmode = VISIBLEGROUPS;
2032 $grouptitle = $str->groupsseparate;
2033 $actionname = 'groupsseparate';
2034 $nextactionname = 'groupsvisible';
2035 $groupimage = 'i/groups';
2036 } else if ($mod->effectivegroupmode == VISIBLEGROUPS) {
2037 $nextgroupmode = NOGROUPS;
2038 $grouptitle = $str->groupsvisible;
2039 $actionname = 'groupsvisible';
2040 $nextactionname = 'groupsnone';
2041 $groupimage = 'i/groupv';
2042 } else {
2043 $nextgroupmode = SEPARATEGROUPS;
2044 $grouptitle = $str->groupsnone;
2045 $actionname = 'groupsnone';
2046 $nextactionname = 'groupsseparate';
2047 $groupimage = 'i/groupn';
2050 $actions[$actionname] = new action_menu_link_primary(
2051 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $nextgroupmode)),
2052 new pix_icon($groupimage, '', 'moodle', array('class' => 'iconsmall')),
2053 $grouptitle,
2054 array('class' => 'editing_'. $actionname, 'data-action' => $nextactionname,
2055 'aria-live' => 'assertive', 'data-sectionreturn' => $sr)
2057 } else {
2058 $actions['nogroupsupport'] = new action_menu_filler();
2062 // Assign.
2063 if (has_capability('moodle/role:assign', $modcontext)){
2064 $actions['assign'] = new action_menu_link_secondary(
2065 new moodle_url('/admin/roles/assign.php', array('contextid' => $modcontext->id)),
2066 new pix_icon('t/assignroles', '', 'moodle', array('class' => 'iconsmall')),
2067 $str->assign,
2068 array('class' => 'editing_assign', 'data-action' => 'assignroles', 'data-sectionreturn' => $sr)
2072 // Delete.
2073 if ($hasmanageactivities) {
2074 $actions['delete'] = new action_menu_link_secondary(
2075 new moodle_url($baseurl, array('delete' => $mod->id)),
2076 new pix_icon('t/delete', '', 'moodle', array('class' => 'iconsmall')),
2077 $str->delete,
2078 array('class' => 'editing_delete', 'data-action' => 'delete', 'data-sectionreturn' => $sr)
2082 return $actions;
2086 * Returns the move action.
2088 * @param cm_info $mod The module to produce a move button for
2089 * @param int $sr The section to link back to (used for creating the links)
2090 * @return The markup for the move action, or an empty string if not available.
2092 function course_get_cm_move(cm_info $mod, $sr = null) {
2093 global $OUTPUT;
2095 static $str;
2096 static $baseurl;
2098 $modcontext = context_module::instance($mod->id);
2099 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
2101 if (!isset($str)) {
2102 $str = get_strings(array('move'));
2105 if (!isset($baseurl)) {
2106 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
2108 if ($sr !== null) {
2109 $baseurl->param('sr', $sr);
2113 if ($hasmanageactivities) {
2114 $pixicon = 'i/dragdrop';
2116 if (!course_ajax_enabled($mod->get_course())) {
2117 // Override for course frontpage until we get drag/drop working there.
2118 $pixicon = 't/move';
2121 return html_writer::link(
2122 new moodle_url($baseurl, array('copy' => $mod->id)),
2123 $OUTPUT->pix_icon($pixicon, $str->move, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2124 array('class' => 'editing_move', 'data-action' => 'move', 'data-sectionreturn' => $sr)
2127 return '';
2131 * given a course object with shortname & fullname, this function will
2132 * truncate the the number of chars allowed and add ... if it was too long
2134 function course_format_name ($course,$max=100) {
2136 $context = context_course::instance($course->id);
2137 $shortname = format_string($course->shortname, true, array('context' => $context));
2138 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
2139 $str = $shortname.': '. $fullname;
2140 if (core_text::strlen($str) <= $max) {
2141 return $str;
2143 else {
2144 return core_text::substr($str,0,$max-3).'...';
2149 * Is the user allowed to add this type of module to this course?
2150 * @param object $course the course settings. Only $course->id is used.
2151 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
2152 * @return bool whether the current user is allowed to add this type of module to this course.
2154 function course_allowed_module($course, $modname) {
2155 if (is_numeric($modname)) {
2156 throw new coding_exception('Function course_allowed_module no longer
2157 supports numeric module ids. Please update your code to pass the module name.');
2160 $capability = 'mod/' . $modname . ':addinstance';
2161 if (!get_capability_info($capability)) {
2162 // Debug warning that the capability does not exist, but no more than once per page.
2163 static $warned = array();
2164 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
2165 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
2166 debugging('The module ' . $modname . ' does not define the standard capability ' .
2167 $capability , DEBUG_DEVELOPER);
2168 $warned[$modname] = 1;
2171 // If the capability does not exist, the module can always be added.
2172 return true;
2175 $coursecontext = context_course::instance($course->id);
2176 return has_capability($capability, $coursecontext);
2180 * Efficiently moves many courses around while maintaining
2181 * sortorder in order.
2183 * @param array $courseids is an array of course ids
2184 * @param int $categoryid
2185 * @return bool success
2187 function move_courses($courseids, $categoryid) {
2188 global $DB;
2190 if (empty($courseids)) {
2191 // Nothing to do.
2192 return false;
2195 if (!$category = $DB->get_record('course_categories', array('id' => $categoryid))) {
2196 return false;
2199 $courseids = array_reverse($courseids);
2200 $newparent = context_coursecat::instance($category->id);
2201 $i = 1;
2203 list($where, $params) = $DB->get_in_or_equal($courseids);
2204 $dbcourses = $DB->get_records_select('course', 'id ' . $where, $params, '', 'id, category, shortname, fullname');
2205 foreach ($dbcourses as $dbcourse) {
2206 $course = new stdClass();
2207 $course->id = $dbcourse->id;
2208 $course->timemodified = time();
2209 $course->category = $category->id;
2210 $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
2211 if ($category->visible == 0) {
2212 // Hide the course when moving into hidden category, do not update the visibleold flag - we want to get
2213 // to previous state if somebody unhides the category.
2214 $course->visible = 0;
2217 $DB->update_record('course', $course);
2219 // Update context, so it can be passed to event.
2220 $context = context_course::instance($course->id);
2221 $context->update_moved($newparent);
2223 // Trigger a course updated event.
2224 $event = \core\event\course_updated::create(array(
2225 'objectid' => $course->id,
2226 'context' => context_course::instance($course->id),
2227 'other' => array('shortname' => $dbcourse->shortname,
2228 'fullname' => $dbcourse->fullname,
2229 'updatedfields' => array('category' => $category->id))
2231 $event->set_legacy_logdata(array($course->id, 'course', 'move', 'edit.php?id=' . $course->id, $course->id));
2232 $event->trigger();
2234 fix_course_sortorder();
2235 cache_helper::purge_by_event('changesincourse');
2237 return true;
2241 * Returns the display name of the given section that the course prefers
2243 * Implementation of this function is provided by course format
2244 * @see format_base::get_section_name()
2246 * @param int|stdClass $courseorid The course to get the section name for (object or just course id)
2247 * @param int|stdClass $section Section object from database or just field course_sections.section
2248 * @return string Display name that the course format prefers, e.g. "Week 2"
2250 function get_section_name($courseorid, $section) {
2251 return course_get_format($courseorid)->get_section_name($section);
2255 * Tells if current course format uses sections
2257 * @param string $format Course format ID e.g. 'weeks' $course->format
2258 * @return bool
2260 function course_format_uses_sections($format) {
2261 $course = new stdClass();
2262 $course->format = $format;
2263 return course_get_format($course)->uses_sections();
2267 * Returns the information about the ajax support in the given source format
2269 * The returned object's property (boolean)capable indicates that
2270 * the course format supports Moodle course ajax features.
2272 * @param string $format
2273 * @return stdClass
2275 function course_format_ajax_support($format) {
2276 $course = new stdClass();
2277 $course->format = $format;
2278 return course_get_format($course)->supports_ajax();
2282 * Can the current user delete this course?
2283 * Course creators have exception,
2284 * 1 day after the creation they can sill delete the course.
2285 * @param int $courseid
2286 * @return boolean
2288 function can_delete_course($courseid) {
2289 global $USER;
2291 $context = context_course::instance($courseid);
2293 if (has_capability('moodle/course:delete', $context)) {
2294 return true;
2297 // hack: now try to find out if creator created this course recently (1 day)
2298 if (!has_capability('moodle/course:create', $context)) {
2299 return false;
2302 $since = time() - 60*60*24;
2303 $course = get_course($courseid);
2305 if ($course->timecreated < $since) {
2306 return false; // Return if the course was not created in last 24 hours.
2309 $logmanger = get_log_manager();
2310 $readers = $logmanger->get_readers('\core\log\sql_reader');
2311 $reader = reset($readers);
2313 if (empty($reader)) {
2314 return false; // No log reader found.
2317 // A proper reader.
2318 $select = "userid = :userid AND courseid = :courseid AND eventname = :eventname AND timecreated > :since";
2319 $params = array('userid' => $USER->id, 'since' => $since, 'courseid' => $course->id, 'eventname' => '\core\event\course_created');
2321 return (bool)$reader->get_events_select_count($select, $params);
2325 * Save the Your name for 'Some role' strings.
2327 * @param integer $courseid the id of this course.
2328 * @param array $data the data that came from the course settings form.
2330 function save_local_role_names($courseid, $data) {
2331 global $DB;
2332 $context = context_course::instance($courseid);
2334 foreach ($data as $fieldname => $value) {
2335 if (strpos($fieldname, 'role_') !== 0) {
2336 continue;
2338 list($ignored, $roleid) = explode('_', $fieldname);
2340 // make up our mind whether we want to delete, update or insert
2341 if (!$value) {
2342 $DB->delete_records('role_names', array('contextid' => $context->id, 'roleid' => $roleid));
2344 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id, 'roleid' => $roleid))) {
2345 $rolename->name = $value;
2346 $DB->update_record('role_names', $rolename);
2348 } else {
2349 $rolename = new stdClass;
2350 $rolename->contextid = $context->id;
2351 $rolename->roleid = $roleid;
2352 $rolename->name = $value;
2353 $DB->insert_record('role_names', $rolename);
2355 // This will ensure the course contacts cache is purged..
2356 core_course_category::role_assignment_changed($roleid, $context);
2361 * Returns options to use in course overviewfiles filemanager
2363 * @param null|stdClass|core_course_list_element|int $course either object that has 'id' property or just the course id;
2364 * may be empty if course does not exist yet (course create form)
2365 * @return array|null array of options such as maxfiles, maxbytes, accepted_types, etc.
2366 * or null if overviewfiles are disabled
2368 function course_overviewfiles_options($course) {
2369 global $CFG;
2370 if (empty($CFG->courseoverviewfileslimit)) {
2371 return null;
2373 $accepted_types = preg_split('/\s*,\s*/', trim($CFG->courseoverviewfilesext), -1, PREG_SPLIT_NO_EMPTY);
2374 if (in_array('*', $accepted_types) || empty($accepted_types)) {
2375 $accepted_types = '*';
2376 } else {
2377 // Since config for $CFG->courseoverviewfilesext is a text box, human factor must be considered.
2378 // Make sure extensions are prefixed with dot unless they are valid typegroups
2379 foreach ($accepted_types as $i => $type) {
2380 if (substr($type, 0, 1) !== '.') {
2381 require_once($CFG->libdir. '/filelib.php');
2382 if (!count(file_get_typegroup('extension', $type))) {
2383 // It does not start with dot and is not a valid typegroup, this is most likely extension.
2384 $accepted_types[$i] = '.'. $type;
2385 $corrected = true;
2389 if (!empty($corrected)) {
2390 set_config('courseoverviewfilesext', join(',', $accepted_types));
2393 $options = array(
2394 'maxfiles' => $CFG->courseoverviewfileslimit,
2395 'maxbytes' => $CFG->maxbytes,
2396 'subdirs' => 0,
2397 'accepted_types' => $accepted_types
2399 if (!empty($course->id)) {
2400 $options['context'] = context_course::instance($course->id);
2401 } else if (is_int($course) && $course > 0) {
2402 $options['context'] = context_course::instance($course);
2404 return $options;
2408 * Create a course and either return a $course object
2410 * Please note this functions does not verify any access control,
2411 * the calling code is responsible for all validation (usually it is the form definition).
2413 * @param array $editoroptions course description editor options
2414 * @param object $data - all the data needed for an entry in the 'course' table
2415 * @return object new course instance
2417 function create_course($data, $editoroptions = NULL) {
2418 global $DB, $CFG;
2420 //check the categoryid - must be given for all new courses
2421 $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
2423 // Check if the shortname already exists.
2424 if (!empty($data->shortname)) {
2425 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
2426 throw new moodle_exception('shortnametaken', '', '', $data->shortname);
2430 // Check if the idnumber already exists.
2431 if (!empty($data->idnumber)) {
2432 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
2433 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber);
2437 if (empty($CFG->enablecourserelativedates)) {
2438 // Make sure we're not setting the relative dates mode when the setting is disabled.
2439 unset($data->relativedatesmode);
2442 if ($errorcode = course_validate_dates((array)$data)) {
2443 throw new moodle_exception($errorcode);
2446 // Check if timecreated is given.
2447 $data->timecreated = !empty($data->timecreated) ? $data->timecreated : time();
2448 $data->timemodified = $data->timecreated;
2450 // place at beginning of any category
2451 $data->sortorder = 0;
2453 if ($editoroptions) {
2454 // summary text is updated later, we need context to store the files first
2455 $data->summary = '';
2456 $data->summary_format = FORMAT_HTML;
2459 if (!isset($data->visible)) {
2460 // data not from form, add missing visibility info
2461 $data->visible = $category->visible;
2463 $data->visibleold = $data->visible;
2465 $newcourseid = $DB->insert_record('course', $data);
2466 $context = context_course::instance($newcourseid, MUST_EXIST);
2468 if ($editoroptions) {
2469 // Save the files used in the summary editor and store
2470 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2471 $DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid));
2472 $DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid));
2474 if ($overviewfilesoptions = course_overviewfiles_options($newcourseid)) {
2475 // Save the course overviewfiles
2476 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2479 // update course format options
2480 course_get_format($newcourseid)->update_course_format_options($data);
2482 $course = course_get_format($newcourseid)->get_course();
2484 fix_course_sortorder();
2485 // purge appropriate caches in case fix_course_sortorder() did not change anything
2486 cache_helper::purge_by_event('changesincourse');
2488 // Trigger a course created event.
2489 $event = \core\event\course_created::create(array(
2490 'objectid' => $course->id,
2491 'context' => context_course::instance($course->id),
2492 'other' => array('shortname' => $course->shortname,
2493 'fullname' => $course->fullname)
2496 $event->trigger();
2498 // Setup the blocks
2499 blocks_add_default_course_blocks($course);
2501 // Create default section and initial sections if specified (unless they've already been created earlier).
2502 // We do not want to call course_create_sections_if_missing() because to avoid creating course cache.
2503 $numsections = isset($data->numsections) ? $data->numsections : 0;
2504 $existingsections = $DB->get_fieldset_sql('SELECT section from {course_sections} WHERE course = ?', [$newcourseid]);
2505 $newsections = array_diff(range(0, $numsections), $existingsections);
2506 foreach ($newsections as $sectionnum) {
2507 course_create_section($newcourseid, $sectionnum, true);
2510 // Save any custom role names.
2511 save_local_role_names($course->id, (array)$data);
2513 // set up enrolments
2514 enrol_course_updated(true, $course, $data);
2516 // Update course tags.
2517 if (isset($data->tags)) {
2518 core_tag_tag::set_item_tags('core', 'course', $course->id, context_course::instance($course->id), $data->tags);
2521 // Save custom fields if there are any of them in the form.
2522 $handler = core_course\customfield\course_handler::create();
2523 // Make sure to set the handler's parent context first.
2524 $coursecatcontext = context_coursecat::instance($category->id);
2525 $handler->set_parent_context($coursecatcontext);
2526 // Save the custom field data.
2527 $data->id = $course->id;
2528 $handler->instance_form_save($data, true);
2530 return $course;
2534 * Update a course.
2536 * Please note this functions does not verify any access control,
2537 * the calling code is responsible for all validation (usually it is the form definition).
2539 * @param object $data - all the data needed for an entry in the 'course' table
2540 * @param array $editoroptions course description editor options
2541 * @return void
2543 function update_course($data, $editoroptions = NULL) {
2544 global $DB, $CFG;
2546 // Prevent changes on front page course.
2547 if ($data->id == SITEID) {
2548 throw new moodle_exception('invalidcourse', 'error');
2551 $oldcourse = course_get_format($data->id)->get_course();
2552 $context = context_course::instance($oldcourse->id);
2554 // Make sure we're not changing whatever the course's relativedatesmode setting is.
2555 unset($data->relativedatesmode);
2557 // Capture the updated fields for the log data.
2558 $updatedfields = [];
2559 foreach (get_object_vars($oldcourse) as $field => $value) {
2560 if ($field == 'summary_editor') {
2561 if (($data->$field)['text'] !== $value['text']) {
2562 // The summary might be very long, we don't wan't to fill up the log record with the full text.
2563 $updatedfields[$field] = '(updated)';
2565 } else if ($field == 'tags' && isset($data->tags)) {
2566 // Tags might not have the same array keys, just check the values.
2567 if (array_values($data->$field) !== array_values($value)) {
2568 $updatedfields[$field] = $data->$field;
2570 } else {
2571 if (isset($data->$field) && $data->$field != $value) {
2572 $updatedfields[$field] = $data->$field;
2577 $data->timemodified = time();
2579 if ($editoroptions) {
2580 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2582 if ($overviewfilesoptions = course_overviewfiles_options($data->id)) {
2583 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2586 // Check we don't have a duplicate shortname.
2587 if (!empty($data->shortname) && $oldcourse->shortname != $data->shortname) {
2588 if ($DB->record_exists_sql('SELECT id from {course} WHERE shortname = ? AND id <> ?', array($data->shortname, $data->id))) {
2589 throw new moodle_exception('shortnametaken', '', '', $data->shortname);
2593 // Check we don't have a duplicate idnumber.
2594 if (!empty($data->idnumber) && $oldcourse->idnumber != $data->idnumber) {
2595 if ($DB->record_exists_sql('SELECT id from {course} WHERE idnumber = ? AND id <> ?', array($data->idnumber, $data->id))) {
2596 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber);
2600 if ($errorcode = course_validate_dates((array)$data)) {
2601 throw new moodle_exception($errorcode);
2604 if (!isset($data->category) or empty($data->category)) {
2605 // prevent nulls and 0 in category field
2606 unset($data->category);
2608 $changesincoursecat = $movecat = (isset($data->category) and $oldcourse->category != $data->category);
2610 if (!isset($data->visible)) {
2611 // data not from form, add missing visibility info
2612 $data->visible = $oldcourse->visible;
2615 if ($data->visible != $oldcourse->visible) {
2616 // reset the visibleold flag when manually hiding/unhiding course
2617 $data->visibleold = $data->visible;
2618 $changesincoursecat = true;
2619 } else {
2620 if ($movecat) {
2621 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category));
2622 if (empty($newcategory->visible)) {
2623 // make sure when moving into hidden category the course is hidden automatically
2624 $data->visible = 0;
2629 // Set newsitems to 0 if format does not support announcements.
2630 if (isset($data->format)) {
2631 $newcourseformat = course_get_format((object)['format' => $data->format]);
2632 if (!$newcourseformat->supports_news()) {
2633 $data->newsitems = 0;
2637 // Update custom fields if there are any of them in the form.
2638 $handler = core_course\customfield\course_handler::create();
2639 $handler->instance_form_save($data);
2641 // Update with the new data
2642 $DB->update_record('course', $data);
2643 // make sure the modinfo cache is reset
2644 rebuild_course_cache($data->id);
2646 // update course format options with full course data
2647 course_get_format($data->id)->update_course_format_options($data, $oldcourse);
2649 $course = $DB->get_record('course', array('id'=>$data->id));
2651 if ($movecat) {
2652 $newparent = context_coursecat::instance($course->category);
2653 $context->update_moved($newparent);
2655 $fixcoursesortorder = $movecat || (isset($data->sortorder) && ($oldcourse->sortorder != $data->sortorder));
2656 if ($fixcoursesortorder) {
2657 fix_course_sortorder();
2660 // purge appropriate caches in case fix_course_sortorder() did not change anything
2661 cache_helper::purge_by_event('changesincourse');
2662 if ($changesincoursecat) {
2663 cache_helper::purge_by_event('changesincoursecat');
2666 // Test for and remove blocks which aren't appropriate anymore
2667 blocks_remove_inappropriate($course);
2669 // Save any custom role names.
2670 save_local_role_names($course->id, $data);
2672 // update enrol settings
2673 enrol_course_updated(false, $course, $data);
2675 // Update course tags.
2676 if (isset($data->tags)) {
2677 core_tag_tag::set_item_tags('core', 'course', $course->id, context_course::instance($course->id), $data->tags);
2680 // Trigger a course updated event.
2681 $event = \core\event\course_updated::create(array(
2682 'objectid' => $course->id,
2683 'context' => context_course::instance($course->id),
2684 'other' => array('shortname' => $course->shortname,
2685 'fullname' => $course->fullname,
2686 'updatedfields' => $updatedfields)
2689 $event->set_legacy_logdata(array($course->id, 'course', 'update', 'edit.php?id=' . $course->id, $course->id));
2690 $event->trigger();
2692 if ($oldcourse->format !== $course->format) {
2693 // Remove all options stored for the previous format
2694 // We assume that new course format migrated everything it needed watching trigger
2695 // 'course_updated' and in method format_XXX::update_course_format_options()
2696 $DB->delete_records('course_format_options',
2697 array('courseid' => $course->id, 'format' => $oldcourse->format));
2702 * Average number of participants
2703 * @return integer
2705 function average_number_of_participants() {
2706 global $DB, $SITE;
2708 //count total of enrolments for visible course (except front page)
2709 $sql = 'SELECT COUNT(*) FROM (
2710 SELECT DISTINCT ue.userid, e.courseid
2711 FROM {user_enrolments} ue, {enrol} e, {course} c
2712 WHERE ue.enrolid = e.id
2713 AND e.courseid <> :siteid
2714 AND c.id = e.courseid
2715 AND c.visible = 1) total';
2716 $params = array('siteid' => $SITE->id);
2717 $enrolmenttotal = $DB->count_records_sql($sql, $params);
2720 //count total of visible courses (minus front page)
2721 $coursetotal = $DB->count_records('course', array('visible' => 1));
2722 $coursetotal = $coursetotal - 1 ;
2724 //average of enrolment
2725 if (empty($coursetotal)) {
2726 $participantaverage = 0;
2727 } else {
2728 $participantaverage = $enrolmenttotal / $coursetotal;
2731 return $participantaverage;
2735 * Average number of course modules
2736 * @return integer
2738 function average_number_of_courses_modules() {
2739 global $DB, $SITE;
2741 //count total of visible course module (except front page)
2742 $sql = 'SELECT COUNT(*) FROM (
2743 SELECT cm.course, cm.module
2744 FROM {course} c, {course_modules} cm
2745 WHERE c.id = cm.course
2746 AND c.id <> :siteid
2747 AND cm.visible = 1
2748 AND c.visible = 1) total';
2749 $params = array('siteid' => $SITE->id);
2750 $moduletotal = $DB->count_records_sql($sql, $params);
2753 //count total of visible courses (minus front page)
2754 $coursetotal = $DB->count_records('course', array('visible' => 1));
2755 $coursetotal = $coursetotal - 1 ;
2757 //average of course module
2758 if (empty($coursetotal)) {
2759 $coursemoduleaverage = 0;
2760 } else {
2761 $coursemoduleaverage = $moduletotal / $coursetotal;
2764 return $coursemoduleaverage;
2768 * This class pertains to course requests and contains methods associated with
2769 * create, approving, and removing course requests.
2771 * Please note we do not allow embedded images here because there is no context
2772 * to store them with proper access control.
2774 * @copyright 2009 Sam Hemelryk
2775 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2776 * @since Moodle 2.0
2778 * @property-read int $id
2779 * @property-read string $fullname
2780 * @property-read string $shortname
2781 * @property-read string $summary
2782 * @property-read int $summaryformat
2783 * @property-read int $summarytrust
2784 * @property-read string $reason
2785 * @property-read int $requester
2787 class course_request {
2790 * This is the stdClass that stores the properties for the course request
2791 * and is externally accessed through the __get magic method
2792 * @var stdClass
2794 protected $properties;
2797 * An array of options for the summary editor used by course request forms.
2798 * This is initially set by {@link summary_editor_options()}
2799 * @var array
2800 * @static
2802 protected static $summaryeditoroptions;
2805 * Static function to prepare the summary editor for working with a course
2806 * request.
2808 * @static
2809 * @param null|stdClass $data Optional, an object containing the default values
2810 * for the form, these may be modified when preparing the
2811 * editor so this should be called before creating the form
2812 * @return stdClass An object that can be used to set the default values for
2813 * an mforms form
2815 public static function prepare($data=null) {
2816 if ($data === null) {
2817 $data = new stdClass;
2819 $data = file_prepare_standard_editor($data, 'summary', self::summary_editor_options());
2820 return $data;
2824 * Static function to create a new course request when passed an array of properties
2825 * for it.
2827 * This function also handles saving any files that may have been used in the editor
2829 * @static
2830 * @param stdClass $data
2831 * @return course_request The newly created course request
2833 public static function create($data) {
2834 global $USER, $DB, $CFG;
2835 $data->requester = $USER->id;
2837 // Setting the default category if none set.
2838 if (empty($data->category) || !empty($CFG->lockrequestcategory)) {
2839 $data->category = $CFG->defaultrequestcategory;
2842 // Summary is a required field so copy the text over
2843 $data->summary = $data->summary_editor['text'];
2844 $data->summaryformat = $data->summary_editor['format'];
2846 $data->id = $DB->insert_record('course_request', $data);
2848 // Create a new course_request object and return it
2849 $request = new course_request($data);
2851 // Notify the admin if required.
2852 if ($users = get_users_from_config($CFG->courserequestnotify, 'moodle/site:approvecourse')) {
2854 $a = new stdClass;
2855 $a->link = "$CFG->wwwroot/course/pending.php";
2856 $a->user = fullname($USER);
2857 $subject = get_string('courserequest');
2858 $message = get_string('courserequestnotifyemail', 'admin', $a);
2859 foreach ($users as $user) {
2860 $request->notify($user, $USER, 'courserequested', $subject, $message);
2864 return $request;
2868 * Returns an array of options to use with a summary editor
2870 * @uses course_request::$summaryeditoroptions
2871 * @return array An array of options to use with the editor
2873 public static function summary_editor_options() {
2874 global $CFG;
2875 if (self::$summaryeditoroptions === null) {
2876 self::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
2878 return self::$summaryeditoroptions;
2882 * Loads the properties for this course request object. Id is required and if
2883 * only id is provided then we load the rest of the properties from the database
2885 * @param stdClass|int $properties Either an object containing properties
2886 * or the course_request id to load
2888 public function __construct($properties) {
2889 global $DB;
2890 if (empty($properties->id)) {
2891 if (empty($properties)) {
2892 throw new coding_exception('You must provide a course request id when creating a course_request object');
2894 $id = $properties;
2895 $properties = new stdClass;
2896 $properties->id = (int)$id;
2897 unset($id);
2899 if (empty($properties->requester)) {
2900 if (!($this->properties = $DB->get_record('course_request', array('id' => $properties->id)))) {
2901 print_error('unknowncourserequest');
2903 } else {
2904 $this->properties = $properties;
2906 $this->properties->collision = null;
2910 * Returns the requested property
2912 * @param string $key
2913 * @return mixed
2915 public function __get($key) {
2916 return $this->properties->$key;
2920 * Override this to ensure empty($request->blah) calls return a reliable answer...
2922 * This is required because we define the __get method
2924 * @param mixed $key
2925 * @return bool True is it not empty, false otherwise
2927 public function __isset($key) {
2928 return (!empty($this->properties->$key));
2932 * Returns the user who requested this course
2934 * Uses a static var to cache the results and cut down the number of db queries
2936 * @staticvar array $requesters An array of cached users
2937 * @return stdClass The user who requested the course
2939 public function get_requester() {
2940 global $DB;
2941 static $requesters= array();
2942 if (!array_key_exists($this->properties->requester, $requesters)) {
2943 $requesters[$this->properties->requester] = $DB->get_record('user', array('id'=>$this->properties->requester));
2945 return $requesters[$this->properties->requester];
2949 * Checks that the shortname used by the course does not conflict with any other
2950 * courses that exist
2952 * @param string|null $shortnamemark The string to append to the requests shortname
2953 * should a conflict be found
2954 * @return bool true is there is a conflict, false otherwise
2956 public function check_shortname_collision($shortnamemark = '[*]') {
2957 global $DB;
2959 if ($this->properties->collision !== null) {
2960 return $this->properties->collision;
2963 if (empty($this->properties->shortname)) {
2964 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER);
2965 $this->properties->collision = false;
2966 } else if ($DB->record_exists('course', array('shortname' => $this->properties->shortname))) {
2967 if (!empty($shortnamemark)) {
2968 $this->properties->shortname .= ' '.$shortnamemark;
2970 $this->properties->collision = true;
2971 } else {
2972 $this->properties->collision = false;
2974 return $this->properties->collision;
2978 * Checks user capability to approve a requested course
2980 * If course was requested without category for some reason (might happen if $CFG->defaultrequestcategory is
2981 * misconfigured), we check capabilities 'moodle/site:approvecourse' and 'moodle/course:changecategory'.
2983 * @return bool
2985 public function can_approve() {
2986 global $CFG;
2987 $category = null;
2988 if ($this->properties->category) {
2989 $category = core_course_category::get($this->properties->category, IGNORE_MISSING);
2990 } else if ($CFG->defaultrequestcategory) {
2991 $category = core_course_category::get($CFG->defaultrequestcategory, IGNORE_MISSING);
2993 if ($category) {
2994 return has_capability('moodle/site:approvecourse', $category->get_context());
2997 // We can not determine the context where the course should be created. The approver should have
2998 // both capabilities to approve courses and change course category in the system context.
2999 return has_all_capabilities(['moodle/site:approvecourse', 'moodle/course:changecategory'], context_system::instance());
3003 * Returns the category where this course request should be created
3005 * Note that we don't check here that user has a capability to view
3006 * hidden categories if he has capabilities 'moodle/site:approvecourse' and
3007 * 'moodle/course:changecategory'
3009 * @return core_course_category
3011 public function get_category() {
3012 global $CFG;
3013 if ($this->properties->category && ($category = core_course_category::get($this->properties->category, IGNORE_MISSING))) {
3014 return $category;
3015 } else if ($CFG->defaultrequestcategory &&
3016 ($category = core_course_category::get($CFG->defaultrequestcategory, IGNORE_MISSING))) {
3017 return $category;
3018 } else {
3019 return core_course_category::get_default();
3024 * This function approves the request turning it into a course
3026 * This function converts the course request into a course, at the same time
3027 * transferring any files used in the summary to the new course and then removing
3028 * the course request and the files associated with it.
3030 * @return int The id of the course that was created from this request
3032 public function approve() {
3033 global $CFG, $DB, $USER;
3035 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
3037 $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted'=>0), '*', MUST_EXIST);
3039 $courseconfig = get_config('moodlecourse');
3041 // Transfer appropriate settings
3042 $data = clone($this->properties);
3043 unset($data->id);
3044 unset($data->reason);
3045 unset($data->requester);
3047 // Set category
3048 $category = $this->get_category();
3049 $data->category = $category->id;
3050 // Set misc settings
3051 $data->requested = 1;
3053 // Apply course default settings
3054 $data->format = $courseconfig->format;
3055 $data->newsitems = $courseconfig->newsitems;
3056 $data->showgrades = $courseconfig->showgrades;
3057 $data->showreports = $courseconfig->showreports;
3058 $data->maxbytes = $courseconfig->maxbytes;
3059 $data->groupmode = $courseconfig->groupmode;
3060 $data->groupmodeforce = $courseconfig->groupmodeforce;
3061 $data->visible = $courseconfig->visible;
3062 $data->visibleold = $data->visible;
3063 $data->lang = $courseconfig->lang;
3064 $data->enablecompletion = $courseconfig->enablecompletion;
3065 $data->numsections = $courseconfig->numsections;
3066 $data->startdate = usergetmidnight(time());
3067 if ($courseconfig->courseenddateenabled) {
3068 $data->enddate = usergetmidnight(time()) + $courseconfig->courseduration;
3071 list($data->fullname, $data->shortname) = restore_dbops::calculate_course_names(0, $data->fullname, $data->shortname);
3073 $course = create_course($data);
3074 $context = context_course::instance($course->id, MUST_EXIST);
3076 // add enrol instances
3077 if (!$DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
3078 if ($manual = enrol_get_plugin('manual')) {
3079 $manual->add_default_instance($course);
3083 // enrol the requester as teacher if necessary
3084 if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
3085 enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid);
3088 $this->delete();
3090 $a = new stdClass();
3091 $a->name = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
3092 $a->url = $CFG->wwwroot.'/course/view.php?id=' . $course->id;
3093 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a), $course->id);
3095 return $course->id;
3099 * Reject a course request
3101 * This function rejects a course request, emailing the requesting user the
3102 * provided notice and then removing the request from the database
3104 * @param string $notice The message to display to the user
3106 public function reject($notice) {
3107 global $USER, $DB;
3108 $user = $DB->get_record('user', array('id' => $this->properties->requester), '*', MUST_EXIST);
3109 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
3110 $this->delete();
3114 * Deletes the course request and any associated files
3116 public function delete() {
3117 global $DB;
3118 $DB->delete_records('course_request', array('id' => $this->properties->id));
3122 * Send a message from one user to another using events_trigger
3124 * @param object $touser
3125 * @param object $fromuser
3126 * @param string $name
3127 * @param string $subject
3128 * @param string $message
3129 * @param int|null $courseid
3131 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message, $courseid = null) {
3132 $eventdata = new \core\message\message();
3133 $eventdata->courseid = empty($courseid) ? SITEID : $courseid;
3134 $eventdata->component = 'moodle';
3135 $eventdata->name = $name;
3136 $eventdata->userfrom = $fromuser;
3137 $eventdata->userto = $touser;
3138 $eventdata->subject = $subject;
3139 $eventdata->fullmessage = $message;
3140 $eventdata->fullmessageformat = FORMAT_PLAIN;
3141 $eventdata->fullmessagehtml = '';
3142 $eventdata->smallmessage = '';
3143 $eventdata->notification = 1;
3144 message_send($eventdata);
3148 * Checks if current user can request a course in this context
3150 * @param context $context
3151 * @return bool
3153 public static function can_request(context $context) {
3154 global $CFG;
3155 if (empty($CFG->enablecourserequests)) {
3156 return false;
3158 if (has_capability('moodle/course:create', $context)) {
3159 return false;
3162 if ($context instanceof context_system) {
3163 $defaultcontext = context_coursecat::instance($CFG->defaultrequestcategory, IGNORE_MISSING);
3164 return $defaultcontext &&
3165 has_capability('moodle/course:request', $defaultcontext);
3166 } else if ($context instanceof context_coursecat) {
3167 if (!$CFG->lockrequestcategory || $CFG->defaultrequestcategory == $context->instanceid) {
3168 return has_capability('moodle/course:request', $context);
3171 return false;
3176 * Return a list of page types
3177 * @param string $pagetype current page type
3178 * @param context $parentcontext Block's parent context
3179 * @param context $currentcontext Current context of block
3180 * @return array array of page types
3182 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
3183 if ($pagetype === 'course-index' || $pagetype === 'course-index-category') {
3184 // For courses and categories browsing pages (/course/index.php) add option to show on ANY category page
3185 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
3186 'course-index-*' => get_string('page-course-index-x', 'pagetype'),
3188 } else if ($currentcontext && (!($coursecontext = $currentcontext->get_course_context(false)) || $coursecontext->instanceid == SITEID)) {
3189 // We know for sure that despite pagetype starts with 'course-' this is not a page in course context (i.e. /course/search.php, etc.)
3190 $pagetypes = array('*' => get_string('page-x', 'pagetype'));
3191 } else {
3192 // Otherwise consider it a page inside a course even if $currentcontext is null
3193 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
3194 'course-*' => get_string('page-course-x', 'pagetype'),
3195 'course-view-*' => get_string('page-course-view-x', 'pagetype')
3198 return $pagetypes;
3202 * Determine whether course ajax should be enabled for the specified course
3204 * @param stdClass $course The course to test against
3205 * @return boolean Whether course ajax is enabled or note
3207 function course_ajax_enabled($course) {
3208 global $CFG, $PAGE, $SITE;
3210 // The user must be editing for AJAX to be included
3211 if (!$PAGE->user_is_editing()) {
3212 return false;
3215 // Check that the theme suports
3216 if (!$PAGE->theme->enablecourseajax) {
3217 return false;
3220 // Check that the course format supports ajax functionality
3221 // The site 'format' doesn't have information on course format support
3222 if ($SITE->id !== $course->id) {
3223 $courseformatajaxsupport = course_format_ajax_support($course->format);
3224 if (!$courseformatajaxsupport->capable) {
3225 return false;
3229 // All conditions have been met so course ajax should be enabled
3230 return true;
3234 * Include the relevant javascript and language strings for the resource
3235 * toolbox YUI module
3237 * @param integer $id The ID of the course being applied to
3238 * @param array $usedmodules An array containing the names of the modules in use on the page
3239 * @param array $enabledmodules An array containing the names of the enabled (visible) modules on this site
3240 * @param stdClass $config An object containing configuration parameters for ajax modules including:
3241 * * resourceurl The URL to post changes to for resource changes
3242 * * sectionurl The URL to post changes to for section changes
3243 * * pageparams Additional parameters to pass through in the post
3244 * @return bool
3246 function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) {
3247 global $CFG, $PAGE, $SITE;
3249 // Ensure that ajax should be included
3250 if (!course_ajax_enabled($course)) {
3251 return false;
3254 if (!$config) {
3255 $config = new stdClass();
3258 // The URL to use for resource changes
3259 if (!isset($config->resourceurl)) {
3260 $config->resourceurl = '/course/rest.php';
3263 // The URL to use for section changes
3264 if (!isset($config->sectionurl)) {
3265 $config->sectionurl = '/course/rest.php';
3268 // Any additional parameters which need to be included on page submission
3269 if (!isset($config->pageparams)) {
3270 $config->pageparams = array();
3273 // Include course dragdrop
3274 if (course_format_uses_sections($course->format)) {
3275 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_section_dragdrop',
3276 array(array(
3277 'courseid' => $course->id,
3278 'ajaxurl' => $config->sectionurl,
3279 'config' => $config,
3280 )), null, true);
3282 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_resource_dragdrop',
3283 array(array(
3284 'courseid' => $course->id,
3285 'ajaxurl' => $config->resourceurl,
3286 'config' => $config,
3287 )), null, true);
3290 // Require various strings for the command toolbox
3291 $PAGE->requires->strings_for_js(array(
3292 'moveleft',
3293 'deletechecktype',
3294 'deletechecktypename',
3295 'edittitle',
3296 'edittitleinstructions',
3297 'show',
3298 'hide',
3299 'highlight',
3300 'highlightoff',
3301 'groupsnone',
3302 'groupsvisible',
3303 'groupsseparate',
3304 'clicktochangeinbrackets',
3305 'markthistopic',
3306 'markedthistopic',
3307 'movesection',
3308 'movecoursemodule',
3309 'movecoursesection',
3310 'movecontent',
3311 'tocontent',
3312 'emptydragdropregion',
3313 'afterresource',
3314 'aftersection',
3315 'totopofsection',
3316 ), 'moodle');
3318 // Include section-specific strings for formats which support sections.
3319 if (course_format_uses_sections($course->format)) {
3320 $PAGE->requires->strings_for_js(array(
3321 'showfromothers',
3322 'hidefromothers',
3323 ), 'format_' . $course->format);
3326 // For confirming resource deletion we need the name of the module in question
3327 foreach ($usedmodules as $module => $modname) {
3328 $PAGE->requires->string_for_js('pluginname', $module);
3331 // Load drag and drop upload AJAX.
3332 require_once($CFG->dirroot.'/course/dnduploadlib.php');
3333 dndupload_add_to_course($course, $enabledmodules);
3335 $PAGE->requires->js_call_amd('core_course/actions', 'initCoursePage', array($course->format));
3337 return true;
3341 * Returns the sorted list of available course formats, filtered by enabled if necessary
3343 * @param bool $enabledonly return only formats that are enabled
3344 * @return array array of sorted format names
3346 function get_sorted_course_formats($enabledonly = false) {
3347 global $CFG;
3348 $formats = core_component::get_plugin_list('format');
3350 if (!empty($CFG->format_plugins_sortorder)) {
3351 $order = explode(',', $CFG->format_plugins_sortorder);
3352 $order = array_merge(array_intersect($order, array_keys($formats)),
3353 array_diff(array_keys($formats), $order));
3354 } else {
3355 $order = array_keys($formats);
3357 if (!$enabledonly) {
3358 return $order;
3360 $sortedformats = array();
3361 foreach ($order as $formatname) {
3362 if (!get_config('format_'.$formatname, 'disabled')) {
3363 $sortedformats[] = $formatname;
3366 return $sortedformats;
3370 * The URL to use for the specified course (with section)
3372 * @param int|stdClass $courseorid The course to get the section name for (either object or just course id)
3373 * @param int|stdClass $section Section object from database or just field course_sections.section
3374 * if omitted the course view page is returned
3375 * @param array $options options for view URL. At the moment core uses:
3376 * 'navigation' (bool) if true and section has no separate page, the function returns null
3377 * 'sr' (int) used by multipage formats to specify to which section to return
3378 * @return moodle_url The url of course
3380 function course_get_url($courseorid, $section = null, $options = array()) {
3381 return course_get_format($courseorid)->get_view_url($section, $options);
3385 * Create a module.
3387 * It includes:
3388 * - capability checks and other checks
3389 * - create the module from the module info
3391 * @param object $module
3392 * @return object the created module info
3393 * @throws moodle_exception if user is not allowed to perform the action or module is not allowed in this course
3395 function create_module($moduleinfo) {
3396 global $DB, $CFG;
3398 require_once($CFG->dirroot . '/course/modlib.php');
3400 // Check manadatory attributs.
3401 $mandatoryfields = array('modulename', 'course', 'section', 'visible');
3402 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
3403 $mandatoryfields[] = 'introeditor';
3405 foreach($mandatoryfields as $mandatoryfield) {
3406 if (!isset($moduleinfo->{$mandatoryfield})) {
3407 throw new moodle_exception('createmodulemissingattribut', '', '', $mandatoryfield);
3411 // Some additional checks (capability / existing instances).
3412 $course = $DB->get_record('course', array('id'=>$moduleinfo->course), '*', MUST_EXIST);
3413 list($module, $context, $cw) = can_add_moduleinfo($course, $moduleinfo->modulename, $moduleinfo->section);
3415 // Add the module.
3416 $moduleinfo->module = $module->id;
3417 $moduleinfo = add_moduleinfo($moduleinfo, $course, null);
3419 return $moduleinfo;
3423 * Update a module.
3425 * It includes:
3426 * - capability and other checks
3427 * - update the module
3429 * @param object $module
3430 * @return object the updated module info
3431 * @throws moodle_exception if current user is not allowed to update the module
3433 function update_module($moduleinfo) {
3434 global $DB, $CFG;
3436 require_once($CFG->dirroot . '/course/modlib.php');
3438 // Check the course module exists.
3439 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule, 0, false, MUST_EXIST);
3441 // Check the course exists.
3442 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
3444 // Some checks (capaibility / existing instances).
3445 list($cm, $context, $module, $data, $cw) = can_update_moduleinfo($cm);
3447 // Retrieve few information needed by update_moduleinfo.
3448 $moduleinfo->modulename = $cm->modname;
3449 if (!isset($moduleinfo->scale)) {
3450 $moduleinfo->scale = 0;
3452 $moduleinfo->type = 'mod';
3454 // Update the module.
3455 list($cm, $moduleinfo) = update_moduleinfo($cm, $moduleinfo, $course, null);
3457 return $moduleinfo;
3461 * Duplicate a module on the course for ajax.
3463 * @see mod_duplicate_module()
3464 * @param object $course The course
3465 * @param object $cm The course module to duplicate
3466 * @param int $sr The section to link back to (used for creating the links)
3467 * @throws moodle_exception if the plugin doesn't support duplication
3468 * @return Object containing:
3469 * - fullcontent: The HTML markup for the created CM
3470 * - cmid: The CMID of the newly created CM
3471 * - redirect: Whether to trigger a redirect following this change
3473 function mod_duplicate_activity($course, $cm, $sr = null) {
3474 global $PAGE;
3476 $newcm = duplicate_module($course, $cm);
3478 $resp = new stdClass();
3479 if ($newcm) {
3480 $courserenderer = $PAGE->get_renderer('core', 'course');
3481 $completioninfo = new completion_info($course);
3482 $modulehtml = $courserenderer->course_section_cm($course, $completioninfo,
3483 $newcm, null, array());
3485 $resp->fullcontent = $courserenderer->course_section_cm_list_item($course, $completioninfo, $newcm, $sr);
3486 $resp->cmid = $newcm->id;
3487 } else {
3488 // Trigger a redirect.
3489 $resp->redirect = true;
3491 return $resp;
3495 * Api to duplicate a module.
3497 * @param object $course course object.
3498 * @param object $cm course module object to be duplicated.
3499 * @since Moodle 2.8
3501 * @throws Exception
3502 * @throws coding_exception
3503 * @throws moodle_exception
3504 * @throws restore_controller_exception
3506 * @return cm_info|null cminfo object if we sucessfully duplicated the mod and found the new cm.
3508 function duplicate_module($course, $cm) {
3509 global $CFG, $DB, $USER;
3510 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
3511 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
3512 require_once($CFG->libdir . '/filelib.php');
3514 $a = new stdClass();
3515 $a->modtype = get_string('modulename', $cm->modname);
3516 $a->modname = format_string($cm->name);
3518 if (!plugin_supports('mod', $cm->modname, FEATURE_BACKUP_MOODLE2)) {
3519 throw new moodle_exception('duplicatenosupport', 'error', '', $a);
3522 // Backup the activity.
3524 $bc = new backup_controller(backup::TYPE_1ACTIVITY, $cm->id, backup::FORMAT_MOODLE,
3525 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
3527 $backupid = $bc->get_backupid();
3528 $backupbasepath = $bc->get_plan()->get_basepath();
3530 $bc->execute_plan();
3532 $bc->destroy();
3534 // Restore the backup immediately.
3536 $rc = new restore_controller($backupid, $course->id,
3537 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, backup::TARGET_CURRENT_ADDING);
3539 // Make sure that the restore_general_groups setting is always enabled when duplicating an activity.
3540 $plan = $rc->get_plan();
3541 $groupsetting = $plan->get_setting('groups');
3542 if (empty($groupsetting->get_value())) {
3543 $groupsetting->set_value(true);
3546 $cmcontext = context_module::instance($cm->id);
3547 if (!$rc->execute_precheck()) {
3548 $precheckresults = $rc->get_precheck_results();
3549 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
3550 if (empty($CFG->keeptempdirectoriesonbackup)) {
3551 fulldelete($backupbasepath);
3556 $rc->execute_plan();
3558 // Now a bit hacky part follows - we try to get the cmid of the newly
3559 // restored copy of the module.
3560 $newcmid = null;
3561 $tasks = $rc->get_plan()->get_tasks();
3562 foreach ($tasks as $task) {
3563 if (is_subclass_of($task, 'restore_activity_task')) {
3564 if ($task->get_old_contextid() == $cmcontext->id) {
3565 $newcmid = $task->get_moduleid();
3566 break;
3571 $rc->destroy();
3573 if (empty($CFG->keeptempdirectoriesonbackup)) {
3574 fulldelete($backupbasepath);
3577 // If we know the cmid of the new course module, let us move it
3578 // right below the original one. otherwise it will stay at the
3579 // end of the section.
3580 if ($newcmid) {
3581 // Proceed with activity renaming before everything else. We don't use APIs here to avoid
3582 // triggering a lot of create/update duplicated events.
3583 $newcm = get_coursemodule_from_id($cm->modname, $newcmid, $cm->course);
3584 // Add ' (copy)' to duplicates. Note we don't cleanup or validate lengths here. It comes
3585 // from original name that was valid, so the copy should be too.
3586 $newname = get_string('duplicatedmodule', 'moodle', $newcm->name);
3587 $DB->set_field($cm->modname, 'name', $newname, ['id' => $newcm->instance]);
3589 $section = $DB->get_record('course_sections', array('id' => $cm->section, 'course' => $cm->course));
3590 $modarray = explode(",", trim($section->sequence));
3591 $cmindex = array_search($cm->id, $modarray);
3592 if ($cmindex !== false && $cmindex < count($modarray) - 1) {
3593 moveto_module($newcm, $section, $modarray[$cmindex + 1]);
3596 // Update calendar events with the duplicated module.
3597 // The following line is to be removed in MDL-58906.
3598 course_module_update_calendar_events($newcm->modname, null, $newcm);
3600 // Trigger course module created event. We can trigger the event only if we know the newcmid.
3601 $newcm = get_fast_modinfo($cm->course)->get_cm($newcmid);
3602 $event = \core\event\course_module_created::create_from_cm($newcm);
3603 $event->trigger();
3606 return isset($newcm) ? $newcm : null;
3610 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3611 * Sorts by descending order of time.
3613 * @param stdClass $a First object
3614 * @param stdClass $b Second object
3615 * @return int 0,1,-1 representing the order
3617 function compare_activities_by_time_desc($a, $b) {
3618 // Make sure the activities actually have a timestamp property.
3619 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3620 return 0;
3622 // We treat instances without timestamp as if they have a timestamp of 0.
3623 if ((!property_exists($a, 'timestamp')) && (property_exists($b,'timestamp'))) {
3624 return 1;
3626 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3627 return -1;
3629 if ($a->timestamp == $b->timestamp) {
3630 return 0;
3632 return ($a->timestamp > $b->timestamp) ? -1 : 1;
3636 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3637 * Sorts by ascending order of time.
3639 * @param stdClass $a First object
3640 * @param stdClass $b Second object
3641 * @return int 0,1,-1 representing the order
3643 function compare_activities_by_time_asc($a, $b) {
3644 // Make sure the activities actually have a timestamp property.
3645 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3646 return 0;
3648 // We treat instances without timestamp as if they have a timestamp of 0.
3649 if ((!property_exists($a, 'timestamp')) && (property_exists($b, 'timestamp'))) {
3650 return -1;
3652 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3653 return 1;
3655 if ($a->timestamp == $b->timestamp) {
3656 return 0;
3658 return ($a->timestamp < $b->timestamp) ? -1 : 1;
3662 * Changes the visibility of a course.
3664 * @param int $courseid The course to change.
3665 * @param bool $show True to make it visible, false otherwise.
3666 * @return bool
3668 function course_change_visibility($courseid, $show = true) {
3669 $course = new stdClass;
3670 $course->id = $courseid;
3671 $course->visible = ($show) ? '1' : '0';
3672 $course->visibleold = $course->visible;
3673 update_course($course);
3674 return true;
3678 * Changes the course sortorder by one, moving it up or down one in respect to sort order.
3680 * @param stdClass|core_course_list_element $course
3681 * @param bool $up If set to true the course will be moved up one. Otherwise down one.
3682 * @return bool
3684 function course_change_sortorder_by_one($course, $up) {
3685 global $DB;
3686 $params = array($course->sortorder, $course->category);
3687 if ($up) {
3688 $select = 'sortorder < ? AND category = ?';
3689 $sort = 'sortorder DESC';
3690 } else {
3691 $select = 'sortorder > ? AND category = ?';
3692 $sort = 'sortorder ASC';
3694 fix_course_sortorder();
3695 $swapcourse = $DB->get_records_select('course', $select, $params, $sort, '*', 0, 1);
3696 if ($swapcourse) {
3697 $swapcourse = reset($swapcourse);
3698 $DB->set_field('course', 'sortorder', $swapcourse->sortorder, array('id' => $course->id));
3699 $DB->set_field('course', 'sortorder', $course->sortorder, array('id' => $swapcourse->id));
3700 // Finally reorder courses.
3701 fix_course_sortorder();
3702 cache_helper::purge_by_event('changesincourse');
3703 return true;
3705 return false;
3709 * Changes the sort order of courses in a category so that the first course appears after the second.
3711 * @param int|stdClass $courseorid The course to focus on.
3712 * @param int $moveaftercourseid The course to shifter after or 0 if you want it to be the first course in the category.
3713 * @return bool
3715 function course_change_sortorder_after_course($courseorid, $moveaftercourseid) {
3716 global $DB;
3718 if (!is_object($courseorid)) {
3719 $course = get_course($courseorid);
3720 } else {
3721 $course = $courseorid;
3724 if ((int)$moveaftercourseid === 0) {
3725 // We've moving the course to the start of the queue.
3726 $sql = 'SELECT sortorder
3727 FROM {course}
3728 WHERE category = :categoryid
3729 ORDER BY sortorder';
3730 $params = array(
3731 'categoryid' => $course->category
3733 $sortorder = $DB->get_field_sql($sql, $params, IGNORE_MULTIPLE);
3735 $sql = 'UPDATE {course}
3736 SET sortorder = sortorder + 1
3737 WHERE category = :categoryid
3738 AND id <> :id';
3739 $params = array(
3740 'categoryid' => $course->category,
3741 'id' => $course->id,
3743 $DB->execute($sql, $params);
3744 $DB->set_field('course', 'sortorder', $sortorder, array('id' => $course->id));
3745 } else if ($course->id === $moveaftercourseid) {
3746 // They're the same - moronic.
3747 debugging("Invalid move after course given.", DEBUG_DEVELOPER);
3748 return false;
3749 } else {
3750 // Moving this course after the given course. It could be before it could be after.
3751 $moveaftercourse = get_course($moveaftercourseid);
3752 if ($course->category !== $moveaftercourse->category) {
3753 debugging("Cannot re-order courses. The given courses do not belong to the same category.", DEBUG_DEVELOPER);
3754 return false;
3756 // Increment all courses in the same category that are ordered after the moveafter course.
3757 // This makes a space for the course we're moving.
3758 $sql = 'UPDATE {course}
3759 SET sortorder = sortorder + 1
3760 WHERE category = :categoryid
3761 AND sortorder > :sortorder';
3762 $params = array(
3763 'categoryid' => $moveaftercourse->category,
3764 'sortorder' => $moveaftercourse->sortorder
3766 $DB->execute($sql, $params);
3767 $DB->set_field('course', 'sortorder', $moveaftercourse->sortorder + 1, array('id' => $course->id));
3769 fix_course_sortorder();
3770 cache_helper::purge_by_event('changesincourse');
3771 return true;
3775 * Trigger course viewed event. This API function is used when course view actions happens,
3776 * usually in course/view.php but also in external functions.
3778 * @param stdClass $context course context object
3779 * @param int $sectionnumber section number
3780 * @since Moodle 2.9
3782 function course_view($context, $sectionnumber = 0) {
3784 $eventdata = array('context' => $context);
3786 if (!empty($sectionnumber)) {
3787 $eventdata['other']['coursesectionnumber'] = $sectionnumber;
3790 $event = \core\event\course_viewed::create($eventdata);
3791 $event->trigger();
3793 user_accesstime_log($context->instanceid);
3797 * Returns courses tagged with a specified tag.
3799 * @param core_tag_tag $tag
3800 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
3801 * are displayed on the page and the per-page limit may be bigger
3802 * @param int $fromctx context id where the link was displayed, may be used by callbacks
3803 * to display items in the same context first
3804 * @param int $ctx context id where to search for records
3805 * @param bool $rec search in subcontexts as well
3806 * @param int $page 0-based number of page being displayed
3807 * @return \core_tag\output\tagindex
3809 function course_get_tagged_courses($tag, $exclusivemode = false, $fromctx = 0, $ctx = 0, $rec = 1, $page = 0) {
3810 global $CFG, $PAGE;
3812 $perpage = $exclusivemode ? $CFG->coursesperpage : 5;
3813 $displayoptions = array(
3814 'limit' => $perpage,
3815 'offset' => $page * $perpage,
3816 'viewmoreurl' => null,
3819 $courserenderer = $PAGE->get_renderer('core', 'course');
3820 $totalcount = core_course_category::search_courses_count(array('tagid' => $tag->id, 'ctx' => $ctx, 'rec' => $rec));
3821 $content = $courserenderer->tagged_courses($tag->id, $exclusivemode, $ctx, $rec, $displayoptions);
3822 $totalpages = ceil($totalcount / $perpage);
3824 return new core_tag\output\tagindex($tag, 'core', 'course', $content,
3825 $exclusivemode, $fromctx, $ctx, $rec, $page, $totalpages);
3829 * Implements callback inplace_editable() allowing to edit values in-place
3831 * @param string $itemtype
3832 * @param int $itemid
3833 * @param mixed $newvalue
3834 * @return \core\output\inplace_editable
3836 function core_course_inplace_editable($itemtype, $itemid, $newvalue) {
3837 if ($itemtype === 'activityname') {
3838 return \core_course\output\course_module_name::update($itemid, $newvalue);
3843 * This function calculates the minimum and maximum cutoff values for the timestart of
3844 * the given event.
3846 * It will return an array with two values, the first being the minimum cutoff value and
3847 * the second being the maximum cutoff value. Either or both values can be null, which
3848 * indicates there is no minimum or maximum, respectively.
3850 * If a cutoff is required then the function must return an array containing the cutoff
3851 * timestamp and error string to display to the user if the cutoff value is violated.
3853 * A minimum and maximum cutoff return value will look like:
3855 * [1505704373, 'The date must be after this date'],
3856 * [1506741172, 'The date must be before this date']
3859 * @param calendar_event $event The calendar event to get the time range for
3860 * @param stdClass $course The course object to get the range from
3861 * @return array Returns an array with min and max date.
3863 function core_course_core_calendar_get_valid_event_timestart_range(\calendar_event $event, $course) {
3864 $mindate = null;
3865 $maxdate = null;
3867 if ($course->startdate) {
3868 $mindate = [
3869 $course->startdate,
3870 get_string('errorbeforecoursestart', 'calendar')
3874 return [$mindate, $maxdate];
3878 * Returns course modules tagged with a specified tag ready for output on tag/index.php page
3880 * This is a callback used by the tag area core/course_modules to search for course modules
3881 * tagged with a specific tag.
3883 * @param core_tag_tag $tag
3884 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
3885 * are displayed on the page and the per-page limit may be bigger
3886 * @param int $fromcontextid context id where the link was displayed, may be used by callbacks
3887 * to display items in the same context first
3888 * @param int $contextid context id where to search for records
3889 * @param bool $recursivecontext search in subcontexts as well
3890 * @param int $page 0-based number of page being displayed
3891 * @return \core_tag\output\tagindex
3893 function course_get_tagged_course_modules($tag, $exclusivemode = false, $fromcontextid = 0, $contextid = 0,
3894 $recursivecontext = 1, $page = 0) {
3895 global $OUTPUT;
3896 $perpage = $exclusivemode ? 20 : 5;
3898 // Build select query.
3899 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
3900 $query = "SELECT cm.id AS cmid, c.id AS courseid, $ctxselect
3901 FROM {course_modules} cm
3902 JOIN {tag_instance} tt ON cm.id = tt.itemid
3903 JOIN {course} c ON cm.course = c.id
3904 JOIN {context} ctx ON ctx.instanceid = cm.id AND ctx.contextlevel = :coursemodulecontextlevel
3905 WHERE tt.itemtype = :itemtype AND tt.tagid = :tagid AND tt.component = :component
3906 AND cm.deletioninprogress = 0
3907 AND c.id %COURSEFILTER% AND cm.id %ITEMFILTER%";
3909 $params = array('itemtype' => 'course_modules', 'tagid' => $tag->id, 'component' => 'core',
3910 'coursemodulecontextlevel' => CONTEXT_MODULE);
3911 if ($contextid) {
3912 $context = context::instance_by_id($contextid);
3913 $query .= $recursivecontext ? ' AND (ctx.id = :contextid OR ctx.path LIKE :path)' : ' AND ctx.id = :contextid';
3914 $params['contextid'] = $context->id;
3915 $params['path'] = $context->path.'/%';
3918 $query .= ' ORDER BY';
3919 if ($fromcontextid) {
3920 // In order-clause specify that modules from inside "fromctx" context should be returned first.
3921 $fromcontext = context::instance_by_id($fromcontextid);
3922 $query .= ' (CASE WHEN ctx.id = :fromcontextid OR ctx.path LIKE :frompath THEN 0 ELSE 1 END),';
3923 $params['fromcontextid'] = $fromcontext->id;
3924 $params['frompath'] = $fromcontext->path.'/%';
3926 $query .= ' c.sortorder, cm.id';
3927 $totalpages = $page + 1;
3929 // Use core_tag_index_builder to build and filter the list of items.
3930 // Request one item more than we need so we know if next page exists.
3931 $builder = new core_tag_index_builder('core', 'course_modules', $query, $params, $page * $perpage, $perpage + 1);
3932 while ($item = $builder->has_item_that_needs_access_check()) {
3933 context_helper::preload_from_record($item);
3934 $courseid = $item->courseid;
3935 if (!$builder->can_access_course($courseid)) {
3936 $builder->set_accessible($item, false);
3937 continue;
3939 $modinfo = get_fast_modinfo($builder->get_course($courseid));
3940 // Set accessibility of this item and all other items in the same course.
3941 $builder->walk(function ($taggeditem) use ($courseid, $modinfo, $builder) {
3942 if ($taggeditem->courseid == $courseid) {
3943 $cm = $modinfo->get_cm($taggeditem->cmid);
3944 $builder->set_accessible($taggeditem, $cm->uservisible);
3949 $items = $builder->get_items();
3950 if (count($items) > $perpage) {
3951 $totalpages = $page + 2; // We don't need exact page count, just indicate that the next page exists.
3952 array_pop($items);
3955 // Build the display contents.
3956 if ($items) {
3957 $tagfeed = new core_tag\output\tagfeed();
3958 foreach ($items as $item) {
3959 context_helper::preload_from_record($item);
3960 $course = $builder->get_course($item->courseid);
3961 $modinfo = get_fast_modinfo($course);
3962 $cm = $modinfo->get_cm($item->cmid);
3963 $courseurl = course_get_url($item->courseid, $cm->sectionnum);
3964 $cmname = $cm->get_formatted_name();
3965 if (!$exclusivemode) {
3966 $cmname = shorten_text($cmname, 100);
3968 $cmname = html_writer::link($cm->url?:$courseurl, $cmname);
3969 $coursename = format_string($course->fullname, true,
3970 array('context' => context_course::instance($item->courseid)));
3971 $coursename = html_writer::link($courseurl, $coursename);
3972 $icon = html_writer::empty_tag('img', array('src' => $cm->get_icon_url()));
3973 $tagfeed->add($icon, $cmname, $coursename);
3976 $content = $OUTPUT->render_from_template('core_tag/tagfeed',
3977 $tagfeed->export_for_template($OUTPUT));
3979 return new core_tag\output\tagindex($tag, 'core', 'course_modules', $content,
3980 $exclusivemode, $fromcontextid, $contextid, $recursivecontext, $page, $totalpages);
3985 * Return an object with the list of navigation options in a course that are avaialable or not for the current user.
3986 * This function also handles the frontpage course.
3988 * @param stdClass $context context object (it can be a course context or the system context for frontpage settings)
3989 * @param stdClass $course the course where the settings are being rendered
3990 * @return stdClass the navigation options in a course and their availability status
3991 * @since Moodle 3.2
3993 function course_get_user_navigation_options($context, $course = null) {
3994 global $CFG;
3996 $isloggedin = isloggedin();
3997 $isguestuser = isguestuser();
3998 $isfrontpage = $context->contextlevel == CONTEXT_SYSTEM;
4000 if ($isfrontpage) {
4001 $sitecontext = $context;
4002 } else {
4003 $sitecontext = context_system::instance();
4006 // Sets defaults for all options.
4007 $options = (object) [
4008 'badges' => false,
4009 'blogs' => false,
4010 'calendar' => false,
4011 'competencies' => false,
4012 'grades' => false,
4013 'notes' => false,
4014 'participants' => false,
4015 'search' => false,
4016 'tags' => false,
4019 $options->blogs = !empty($CFG->enableblogs) &&
4020 ($CFG->bloglevel == BLOG_GLOBAL_LEVEL ||
4021 ($CFG->bloglevel == BLOG_SITE_LEVEL and ($isloggedin and !$isguestuser)))
4022 && has_capability('moodle/blog:view', $sitecontext);
4024 $options->notes = !empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $context);
4026 // Frontpage settings?
4027 if ($isfrontpage) {
4028 // We are on the front page, so make sure we use the proper capability (site:viewparticipants).
4029 $options->participants = course_can_view_participants($sitecontext);
4030 $options->badges = !empty($CFG->enablebadges) && has_capability('moodle/badges:viewbadges', $sitecontext);
4031 $options->tags = !empty($CFG->usetags) && $isloggedin;
4032 $options->search = !empty($CFG->enableglobalsearch) && has_capability('moodle/search:query', $sitecontext);
4033 $options->calendar = $isloggedin;
4034 } else {
4035 // We are in a course, so make sure we use the proper capability (course:viewparticipants).
4036 $options->participants = course_can_view_participants($context);
4037 $options->badges = !empty($CFG->enablebadges) && !empty($CFG->badges_allowcoursebadges) &&
4038 has_capability('moodle/badges:viewbadges', $context);
4039 // Add view grade report is permitted.
4040 $grades = false;
4042 if (has_capability('moodle/grade:viewall', $context)) {
4043 $grades = true;
4044 } else if (!empty($course->showgrades)) {
4045 $reports = core_component::get_plugin_list('gradereport');
4046 if (is_array($reports) && count($reports) > 0) { // Get all installed reports.
4047 arsort($reports); // User is last, we want to test it first.
4048 foreach ($reports as $plugin => $plugindir) {
4049 if (has_capability('gradereport/'.$plugin.':view', $context)) {
4050 // Stop when the first visible plugin is found.
4051 $grades = true;
4052 break;
4057 $options->grades = $grades;
4060 if (\core_competency\api::is_enabled()) {
4061 $capabilities = array('moodle/competency:coursecompetencyview', 'moodle/competency:coursecompetencymanage');
4062 $options->competencies = has_any_capability($capabilities, $context);
4064 return $options;
4068 * Return an object with the list of administration options in a course that are available or not for the current user.
4069 * This function also handles the frontpage settings.
4071 * @param stdClass $course course object (for frontpage it should be a clone of $SITE)
4072 * @param stdClass $context context object (course context)
4073 * @return stdClass the administration options in a course and their availability status
4074 * @since Moodle 3.2
4076 function course_get_user_administration_options($course, $context) {
4077 global $CFG;
4078 $isfrontpage = $course->id == SITEID;
4079 $completionenabled = $CFG->enablecompletion && $course->enablecompletion;
4080 $hascompletiontabs = count(core_completion\manager::get_available_completion_tabs($course, $context)) > 0;
4082 $options = new stdClass;
4083 $options->update = has_capability('moodle/course:update', $context);
4084 $options->editcompletion = $CFG->enablecompletion &&
4085 $course->enablecompletion &&
4086 ($options->update || $hascompletiontabs);
4087 $options->filters = has_capability('moodle/filter:manage', $context) &&
4088 count(filter_get_available_in_context($context)) > 0;
4089 $options->reports = has_capability('moodle/site:viewreports', $context);
4090 $options->backup = has_capability('moodle/backup:backupcourse', $context);
4091 $options->restore = has_capability('moodle/restore:restorecourse', $context);
4092 $options->files = ($course->legacyfiles == 2 && has_capability('moodle/course:managefiles', $context));
4094 if (!$isfrontpage) {
4095 $options->tags = has_capability('moodle/course:tag', $context);
4096 $options->gradebook = has_capability('moodle/grade:manage', $context);
4097 $options->outcomes = !empty($CFG->enableoutcomes) && has_capability('moodle/course:update', $context);
4098 $options->badges = !empty($CFG->enablebadges);
4099 $options->import = has_capability('moodle/restore:restoretargetimport', $context);
4100 $options->reset = has_capability('moodle/course:reset', $context);
4101 $options->roles = has_capability('moodle/role:switchroles', $context);
4102 } else {
4103 // Set default options to false.
4104 $listofoptions = array('tags', 'gradebook', 'outcomes', 'badges', 'import', 'publish', 'reset', 'roles', 'grades');
4106 foreach ($listofoptions as $option) {
4107 $options->$option = false;
4111 return $options;
4115 * Validates course start and end dates.
4117 * Checks that the end course date is not greater than the start course date.
4119 * $coursedata['startdate'] or $coursedata['enddate'] may not be set, it depends on the form and user input.
4121 * @param array $coursedata May contain startdate and enddate timestamps, depends on the user input.
4122 * @return mixed False if everything alright, error codes otherwise.
4124 function course_validate_dates($coursedata) {
4126 // If both start and end dates are set end date should be later than the start date.
4127 if (!empty($coursedata['startdate']) && !empty($coursedata['enddate']) &&
4128 ($coursedata['enddate'] < $coursedata['startdate'])) {
4129 return 'enddatebeforestartdate';
4132 // If start date is not set end date can not be set.
4133 if (empty($coursedata['startdate']) && !empty($coursedata['enddate'])) {
4134 return 'nostartdatenoenddate';
4137 return false;
4141 * Check for course updates in the given context level instances (only modules supported right Now)
4143 * @param stdClass $course course object
4144 * @param array $tocheck instances to check for updates
4145 * @param array $filter check only for updates in these areas
4146 * @return array list of warnings and instances with updates information
4147 * @since Moodle 3.2
4149 function course_check_updates($course, $tocheck, $filter = array()) {
4150 global $CFG, $DB;
4152 $instances = array();
4153 $warnings = array();
4154 $modulescallbacksupport = array();
4155 $modinfo = get_fast_modinfo($course);
4157 $supportedplugins = get_plugin_list_with_function('mod', 'check_updates_since');
4159 // Check instances.
4160 foreach ($tocheck as $instance) {
4161 if ($instance['contextlevel'] == 'module') {
4162 // Check module visibility.
4163 try {
4164 $cm = $modinfo->get_cm($instance['id']);
4165 } catch (Exception $e) {
4166 $warnings[] = array(
4167 'item' => 'module',
4168 'itemid' => $instance['id'],
4169 'warningcode' => 'cmidnotincourse',
4170 'message' => 'This module id does not belong to this course.'
4172 continue;
4175 if (!$cm->uservisible) {
4176 $warnings[] = array(
4177 'item' => 'module',
4178 'itemid' => $instance['id'],
4179 'warningcode' => 'nonuservisible',
4180 'message' => 'You don\'t have access to this module.'
4182 continue;
4184 if (empty($supportedplugins['mod_' . $cm->modname])) {
4185 $warnings[] = array(
4186 'item' => 'module',
4187 'itemid' => $instance['id'],
4188 'warningcode' => 'missingcallback',
4189 'message' => 'This module does not implement the check_updates_since callback: ' . $instance['contextlevel'],
4191 continue;
4193 // Retrieve the module instance.
4194 $instances[] = array(
4195 'contextlevel' => $instance['contextlevel'],
4196 'id' => $instance['id'],
4197 'updates' => call_user_func($cm->modname . '_check_updates_since', $cm, $instance['since'], $filter)
4200 } else {
4201 $warnings[] = array(
4202 'item' => 'contextlevel',
4203 'itemid' => $instance['id'],
4204 'warningcode' => 'contextlevelnotsupported',
4205 'message' => 'Context level not yet supported ' . $instance['contextlevel'],
4209 return array($instances, $warnings);
4213 * This function classifies a course as past, in progress or future.
4215 * This function may incur a DB hit to calculate course completion.
4216 * @param stdClass $course Course record
4217 * @param stdClass $user User record (optional - defaults to $USER).
4218 * @param completion_info $completioninfo Completion record for the user (optional - will be fetched if required).
4219 * @return string (one of COURSE_TIMELINE_FUTURE, COURSE_TIMELINE_INPROGRESS or COURSE_TIMELINE_PAST)
4221 function course_classify_for_timeline($course, $user = null, $completioninfo = null) {
4222 global $USER;
4224 if ($user == null) {
4225 $user = $USER;
4228 $today = time();
4229 // End date past.
4230 if (!empty($course->enddate) && (course_classify_end_date($course) < $today)) {
4231 return COURSE_TIMELINE_PAST;
4234 if ($completioninfo == null) {
4235 $completioninfo = new completion_info($course);
4238 // Course was completed.
4239 if ($completioninfo->is_enabled() && $completioninfo->is_course_complete($user->id)) {
4240 return COURSE_TIMELINE_PAST;
4243 // Start date not reached.
4244 if (!empty($course->startdate) && (course_classify_start_date($course) > $today)) {
4245 return COURSE_TIMELINE_FUTURE;
4248 // Everything else is in progress.
4249 return COURSE_TIMELINE_INPROGRESS;
4253 * This function calculates the end date to use for display classification purposes,
4254 * incorporating the grace period, if any.
4256 * @param stdClass $course The course record.
4257 * @return int The new enddate.
4259 function course_classify_end_date($course) {
4260 global $CFG;
4261 $coursegraceperiodafter = (empty($CFG->coursegraceperiodafter)) ? 0 : $CFG->coursegraceperiodafter;
4262 $enddate = (new \DateTimeImmutable())->setTimestamp($course->enddate)->modify("+{$coursegraceperiodafter} days");
4263 return $enddate->getTimestamp();
4267 * This function calculates the start date to use for display classification purposes,
4268 * incorporating the grace period, if any.
4270 * @param stdClass $course The course record.
4271 * @return int The new startdate.
4273 function course_classify_start_date($course) {
4274 global $CFG;
4275 $coursegraceperiodbefore = (empty($CFG->coursegraceperiodbefore)) ? 0 : $CFG->coursegraceperiodbefore;
4276 $startdate = (new \DateTimeImmutable())->setTimestamp($course->startdate)->modify("-{$coursegraceperiodbefore} days");
4277 return $startdate->getTimestamp();
4281 * Group a list of courses into either past, future, or in progress.
4283 * The return value will be an array indexed by the COURSE_TIMELINE_* constants
4284 * with each value being an array of courses in that group.
4285 * E.g.
4287 * COURSE_TIMELINE_PAST => [... list of past courses ...],
4288 * COURSE_TIMELINE_FUTURE => [],
4289 * COURSE_TIMELINE_INPROGRESS => []
4292 * @param array $courses List of courses to be grouped.
4293 * @return array
4295 function course_classify_courses_for_timeline(array $courses) {
4296 return array_reduce($courses, function($carry, $course) {
4297 $classification = course_classify_for_timeline($course);
4298 array_push($carry[$classification], $course);
4300 return $carry;
4301 }, [
4302 COURSE_TIMELINE_PAST => [],
4303 COURSE_TIMELINE_FUTURE => [],
4304 COURSE_TIMELINE_INPROGRESS => []
4309 * Get the list of enrolled courses for the current user.
4311 * This function returns a Generator. The courses will be loaded from the database
4312 * in chunks rather than a single query.
4314 * @param int $limit Restrict result set to this amount
4315 * @param int $offset Skip this number of records from the start of the result set
4316 * @param string|null $sort SQL string for sorting
4317 * @param string|null $fields SQL string for fields to be returned
4318 * @param int $dbquerylimit The number of records to load per DB request
4319 * @param array $includecourses courses ids to be restricted
4320 * @param array $hiddencourses courses ids to be excluded
4321 * @return Generator
4323 function course_get_enrolled_courses_for_logged_in_user(
4324 int $limit = 0,
4325 int $offset = 0,
4326 string $sort = null,
4327 string $fields = null,
4328 int $dbquerylimit = COURSE_DB_QUERY_LIMIT,
4329 array $includecourses = [],
4330 array $hiddencourses = []
4331 ) : Generator {
4333 $haslimit = !empty($limit);
4334 $recordsloaded = 0;
4335 $querylimit = (!$haslimit || $limit > $dbquerylimit) ? $dbquerylimit : $limit;
4337 while ($courses = enrol_get_my_courses($fields, $sort, $querylimit, $includecourses, false, $offset, $hiddencourses)) {
4338 yield from $courses;
4340 $recordsloaded += $querylimit;
4342 if (count($courses) < $querylimit) {
4343 break;
4345 if ($haslimit && $recordsloaded >= $limit) {
4346 break;
4349 $offset += $querylimit;
4354 * Search the given $courses for any that match the given $classification up to the specified
4355 * $limit.
4357 * This function will return the subset of courses that match the classification as well as the
4358 * number of courses it had to process to build that subset.
4360 * It is recommended that for larger sets of courses this function is given a Generator that loads
4361 * the courses from the database in chunks.
4363 * @param array|Traversable $courses List of courses to process
4364 * @param string $classification One of the COURSE_TIMELINE_* constants
4365 * @param int $limit Limit the number of results to this amount
4366 * @return array First value is the filtered courses, second value is the number of courses processed
4368 function course_filter_courses_by_timeline_classification(
4369 $courses,
4370 string $classification,
4371 int $limit = 0
4372 ) : array {
4374 if (!in_array($classification,
4375 [COURSE_TIMELINE_ALLINCLUDINGHIDDEN, COURSE_TIMELINE_ALL, COURSE_TIMELINE_PAST, COURSE_TIMELINE_INPROGRESS,
4376 COURSE_TIMELINE_FUTURE, COURSE_TIMELINE_HIDDEN])) {
4377 $message = 'Classification must be one of COURSE_TIMELINE_ALLINCLUDINGHIDDEN, COURSE_TIMELINE_ALL, COURSE_TIMELINE_PAST, '
4378 . 'COURSE_TIMELINE_INPROGRESS or COURSE_TIMELINE_FUTURE';
4379 throw new moodle_exception($message);
4382 $filteredcourses = [];
4383 $numberofcoursesprocessed = 0;
4384 $filtermatches = 0;
4386 foreach ($courses as $course) {
4387 $numberofcoursesprocessed++;
4388 $pref = get_user_preferences('block_myoverview_hidden_course_' . $course->id, 0);
4390 // Added as of MDL-63457 toggle viewability for each user.
4391 if ($classification == COURSE_TIMELINE_ALLINCLUDINGHIDDEN || ($classification == COURSE_TIMELINE_HIDDEN && $pref) ||
4392 (($classification == COURSE_TIMELINE_ALL || $classification == course_classify_for_timeline($course)) && !$pref)) {
4393 $filteredcourses[] = $course;
4394 $filtermatches++;
4397 if ($limit && $filtermatches >= $limit) {
4398 // We've found the number of requested courses. No need to continue searching.
4399 break;
4403 // Return the number of filtered courses as well as the number of courses that were searched
4404 // in order to find the matching courses. This allows the calling code to do some kind of
4405 // pagination.
4406 return [$filteredcourses, $numberofcoursesprocessed];
4410 * Search the given $courses for any that match the given $classification up to the specified
4411 * $limit.
4413 * This function will return the subset of courses that are favourites as well as the
4414 * number of courses it had to process to build that subset.
4416 * It is recommended that for larger sets of courses this function is given a Generator that loads
4417 * the courses from the database in chunks.
4419 * @param array|Traversable $courses List of courses to process
4420 * @param array $favouritecourseids Array of favourite courses.
4421 * @param int $limit Limit the number of results to this amount
4422 * @return array First value is the filtered courses, second value is the number of courses processed
4424 function course_filter_courses_by_favourites(
4425 $courses,
4426 $favouritecourseids,
4427 int $limit = 0
4428 ) : array {
4430 $filteredcourses = [];
4431 $numberofcoursesprocessed = 0;
4432 $filtermatches = 0;
4434 foreach ($courses as $course) {
4435 $numberofcoursesprocessed++;
4437 if (in_array($course->id, $favouritecourseids)) {
4438 $filteredcourses[] = $course;
4439 $filtermatches++;
4442 if ($limit && $filtermatches >= $limit) {
4443 // We've found the number of requested courses. No need to continue searching.
4444 break;
4448 // Return the number of filtered courses as well as the number of courses that were searched
4449 // in order to find the matching courses. This allows the calling code to do some kind of
4450 // pagination.
4451 return [$filteredcourses, $numberofcoursesprocessed];
4455 * Search the given $courses for any that have a $customfieldname value that matches the given
4456 * $customfieldvalue, up to the specified $limit.
4458 * This function will return the subset of courses that matches the value as well as the
4459 * number of courses it had to process to build that subset.
4461 * It is recommended that for larger sets of courses this function is given a Generator that loads
4462 * the courses from the database in chunks.
4464 * @param array|Traversable $courses List of courses to process
4465 * @param string $customfieldname the shortname of the custom field to match against
4466 * @param string $customfieldvalue the value this custom field needs to match
4467 * @param int $limit Limit the number of results to this amount
4468 * @return array First value is the filtered courses, second value is the number of courses processed
4470 function course_filter_courses_by_customfield(
4471 $courses,
4472 $customfieldname,
4473 $customfieldvalue,
4474 int $limit = 0
4475 ) : array {
4476 global $DB;
4478 if (!$courses) {
4479 return [[], 0];
4482 // Prepare the list of courses to search through.
4483 $coursesbyid = [];
4484 foreach ($courses as $course) {
4485 $coursesbyid[$course->id] = $course;
4487 if (!$coursesbyid) {
4488 return [[], 0];
4490 list($csql, $params) = $DB->get_in_or_equal(array_keys($coursesbyid), SQL_PARAMS_NAMED);
4492 // Get the id of the custom field.
4493 $sql = "
4494 SELECT f.id
4495 FROM {customfield_field} f
4496 JOIN {customfield_category} cat ON cat.id = f.categoryid
4497 WHERE f.shortname = ?
4498 AND cat.component = 'core_course'
4499 AND cat.area = 'course'
4501 $fieldid = $DB->get_field_sql($sql, [$customfieldname]);
4502 if (!$fieldid) {
4503 return [[], 0];
4506 // Get a list of courseids that match that custom field value.
4507 if ($customfieldvalue == COURSE_CUSTOMFIELD_EMPTY) {
4508 $comparevalue = $DB->sql_compare_text('cd.value');
4509 $sql = "
4510 SELECT c.id
4511 FROM {course} c
4512 LEFT JOIN {customfield_data} cd ON cd.instanceid = c.id AND cd.fieldid = :fieldid
4513 WHERE c.id $csql
4514 AND (cd.value IS NULL OR $comparevalue = '' OR $comparevalue = '0')
4516 $params['fieldid'] = $fieldid;
4517 $matchcourseids = $DB->get_fieldset_sql($sql, $params);
4518 } else {
4519 $comparevalue = $DB->sql_compare_text('value');
4520 $select = "fieldid = :fieldid AND $comparevalue = :customfieldvalue AND instanceid $csql";
4521 $params['fieldid'] = $fieldid;
4522 $params['customfieldvalue'] = $customfieldvalue;
4523 $matchcourseids = $DB->get_fieldset_select('customfield_data', 'instanceid', $select, $params);
4526 // Prepare the list of courses to return.
4527 $filteredcourses = [];
4528 $numberofcoursesprocessed = 0;
4529 $filtermatches = 0;
4531 foreach ($coursesbyid as $course) {
4532 $numberofcoursesprocessed++;
4534 if (in_array($course->id, $matchcourseids)) {
4535 $filteredcourses[] = $course;
4536 $filtermatches++;
4539 if ($limit && $filtermatches >= $limit) {
4540 // We've found the number of requested courses. No need to continue searching.
4541 break;
4545 // Return the number of filtered courses as well as the number of courses that were searched
4546 // in order to find the matching courses. This allows the calling code to do some kind of
4547 // pagination.
4548 return [$filteredcourses, $numberofcoursesprocessed];
4552 * Check module updates since a given time.
4553 * This function checks for updates in the module config, file areas, completion, grades, comments and ratings.
4555 * @param cm_info $cm course module data
4556 * @param int $from the time to check
4557 * @param array $fileareas additional file ares to check
4558 * @param array $filter if we need to filter and return only selected updates
4559 * @return stdClass object with the different updates
4560 * @since Moodle 3.2
4562 function course_check_module_updates_since($cm, $from, $fileareas = array(), $filter = array()) {
4563 global $DB, $CFG, $USER;
4565 $context = $cm->context;
4566 $mod = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
4568 $updates = new stdClass();
4569 $course = get_course($cm->course);
4570 $component = 'mod_' . $cm->modname;
4572 // Check changes in the module configuration.
4573 if (isset($mod->timemodified) and (empty($filter) or in_array('configuration', $filter))) {
4574 $updates->configuration = (object) array('updated' => false);
4575 if ($updates->configuration->updated = $mod->timemodified > $from) {
4576 $updates->configuration->timeupdated = $mod->timemodified;
4580 // Check for updates in files.
4581 if (plugin_supports('mod', $cm->modname, FEATURE_MOD_INTRO)) {
4582 $fileareas[] = 'intro';
4584 if (!empty($fileareas) and (empty($filter) or in_array('fileareas', $filter))) {
4585 $fs = get_file_storage();
4586 $files = $fs->get_area_files($context->id, $component, $fileareas, false, "filearea, timemodified DESC", false, $from);
4587 foreach ($fileareas as $filearea) {
4588 $updates->{$filearea . 'files'} = (object) array('updated' => false);
4590 foreach ($files as $file) {
4591 $updates->{$file->get_filearea() . 'files'}->updated = true;
4592 $updates->{$file->get_filearea() . 'files'}->itemids[] = $file->get_id();
4596 // Check completion.
4597 $supportcompletion = plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_HAS_RULES);
4598 $supportcompletion = $supportcompletion or plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_TRACKS_VIEWS);
4599 if ($supportcompletion and (empty($filter) or in_array('completion', $filter))) {
4600 $updates->completion = (object) array('updated' => false);
4601 $completion = new completion_info($course);
4602 // Use wholecourse to cache all the modules the first time.
4603 $completiondata = $completion->get_data($cm, true);
4604 if ($updates->completion->updated = !empty($completiondata->timemodified) && $completiondata->timemodified > $from) {
4605 $updates->completion->timemodified = $completiondata->timemodified;
4609 // Check grades.
4610 $supportgrades = plugin_supports('mod', $cm->modname, FEATURE_GRADE_HAS_GRADE);
4611 $supportgrades = $supportgrades or plugin_supports('mod', $cm->modname, FEATURE_GRADE_OUTCOMES);
4612 if ($supportgrades and (empty($filter) or (in_array('gradeitems', $filter) or in_array('outcomes', $filter)))) {
4613 require_once($CFG->libdir . '/gradelib.php');
4614 $grades = grade_get_grades($course->id, 'mod', $cm->modname, $mod->id, $USER->id);
4616 if (empty($filter) or in_array('gradeitems', $filter)) {
4617 $updates->gradeitems = (object) array('updated' => false);
4618 foreach ($grades->items as $gradeitem) {
4619 foreach ($gradeitem->grades as $grade) {
4620 if ($grade->datesubmitted > $from or $grade->dategraded > $from) {
4621 $updates->gradeitems->updated = true;
4622 $updates->gradeitems->itemids[] = $gradeitem->id;
4628 if (empty($filter) or in_array('outcomes', $filter)) {
4629 $updates->outcomes = (object) array('updated' => false);
4630 foreach ($grades->outcomes as $outcome) {
4631 foreach ($outcome->grades as $grade) {
4632 if ($grade->datesubmitted > $from or $grade->dategraded > $from) {
4633 $updates->outcomes->updated = true;
4634 $updates->outcomes->itemids[] = $outcome->id;
4641 // Check comments.
4642 if (plugin_supports('mod', $cm->modname, FEATURE_COMMENT) and (empty($filter) or in_array('comments', $filter))) {
4643 $updates->comments = (object) array('updated' => false);
4644 require_once($CFG->dirroot . '/comment/lib.php');
4645 require_once($CFG->dirroot . '/comment/locallib.php');
4646 $manager = new comment_manager();
4647 $comments = $manager->get_component_comments_since($course, $context, $component, $from, $cm);
4648 if (!empty($comments)) {
4649 $updates->comments->updated = true;
4650 $updates->comments->itemids = array_keys($comments);
4654 // Check ratings.
4655 if (plugin_supports('mod', $cm->modname, FEATURE_RATE) and (empty($filter) or in_array('ratings', $filter))) {
4656 $updates->ratings = (object) array('updated' => false);
4657 require_once($CFG->dirroot . '/rating/lib.php');
4658 $manager = new rating_manager();
4659 $ratings = $manager->get_component_ratings_since($context, $component, $from);
4660 if (!empty($ratings)) {
4661 $updates->ratings->updated = true;
4662 $updates->ratings->itemids = array_keys($ratings);
4666 return $updates;
4670 * Returns true if the user can view the participant page, false otherwise,
4672 * @param context $context The context we are checking.
4673 * @return bool
4675 function course_can_view_participants($context) {
4676 $viewparticipantscap = 'moodle/course:viewparticipants';
4677 if ($context->contextlevel == CONTEXT_SYSTEM) {
4678 $viewparticipantscap = 'moodle/site:viewparticipants';
4681 return has_any_capability([$viewparticipantscap, 'moodle/course:enrolreview'], $context);
4685 * Checks if a user can view the participant page, if not throws an exception.
4687 * @param context $context The context we are checking.
4688 * @throws required_capability_exception
4690 function course_require_view_participants($context) {
4691 if (!course_can_view_participants($context)) {
4692 $viewparticipantscap = 'moodle/course:viewparticipants';
4693 if ($context->contextlevel == CONTEXT_SYSTEM) {
4694 $viewparticipantscap = 'moodle/site:viewparticipants';
4696 throw new required_capability_exception($context, $viewparticipantscap, 'nopermissions', '');
4701 * Return whether the user can download from the specified backup file area in the given context.
4703 * @param string $filearea the backup file area. E.g. 'course', 'backup' or 'automated'.
4704 * @param \context $context
4705 * @param stdClass $user the user object. If not provided, the current user will be checked.
4706 * @return bool true if the user is allowed to download in the context, false otherwise.
4708 function can_download_from_backup_filearea($filearea, \context $context, stdClass $user = null) {
4709 $candownload = false;
4710 switch ($filearea) {
4711 case 'course':
4712 case 'backup':
4713 $candownload = has_capability('moodle/backup:downloadfile', $context, $user);
4714 break;
4715 case 'automated':
4716 // Given the automated backups may contain userinfo, we restrict access such that only users who are able to
4717 // restore with userinfo are able to download the file. Users can't create these backups, so checking 'backup:userinfo'
4718 // doesn't make sense here.
4719 $candownload = has_capability('moodle/backup:downloadfile', $context, $user) &&
4720 has_capability('moodle/restore:userinfo', $context, $user);
4721 break;
4722 default:
4723 break;
4726 return $candownload;
4730 * Get a list of hidden courses
4732 * @param int|object|null $user User override to get the filter from. Defaults to current user
4733 * @return array $ids List of hidden courses
4734 * @throws coding_exception
4736 function get_hidden_courses_on_timeline($user = null) {
4737 global $USER;
4739 if (empty($user)) {
4740 $user = $USER->id;
4743 $preferences = get_user_preferences(null, null, $user);
4744 $ids = [];
4745 foreach ($preferences as $key => $value) {
4746 if (preg_match('/block_myoverview_hidden_course_(\d)+/', $key)) {
4747 $id = preg_split('/block_myoverview_hidden_course_/', $key);
4748 $ids[] = $id[1];
4752 return $ids;
4756 * Returns a list of the most recently courses accessed by a user
4758 * @param int $userid User id from which the courses will be obtained
4759 * @param int $limit Restrict result set to this amount
4760 * @param int $offset Skip this number of records from the start of the result set
4761 * @param string|null $sort SQL string for sorting
4762 * @return array
4764 function course_get_recent_courses(int $userid = null, int $limit = 0, int $offset = 0, string $sort = null) {
4766 global $CFG, $USER, $DB;
4768 if (empty($userid)) {
4769 $userid = $USER->id;
4772 $basefields = array('id', 'idnumber', 'summary', 'summaryformat', 'startdate', 'enddate', 'category',
4773 'shortname', 'fullname', 'timeaccess', 'component', 'visible');
4775 $sort = trim($sort);
4776 if (empty($sort)) {
4777 $sort = 'timeaccess DESC';
4778 } else {
4779 $rawsorts = explode(',', $sort);
4780 $sorts = array();
4781 foreach ($rawsorts as $rawsort) {
4782 $rawsort = trim($rawsort);
4783 $sorts[] = trim($rawsort);
4785 $sort = implode(',', $sorts);
4788 $orderby = "ORDER BY $sort";
4790 $ctxfields = context_helper::get_preload_record_columns_sql('ctx');
4792 $coursefields = 'c.' .join(',', $basefields);
4794 // Ask the favourites service to give us the join SQL for favourited courses,
4795 // so we can include favourite information in the query.
4796 $usercontext = \context_user::instance($userid);
4797 $favservice = \core_favourites\service_factory::get_service_for_user_context($usercontext);
4798 list($favsql, $favparams) = $favservice->get_join_sql_by_type('core_course', 'courses', 'fav', 'ul.courseid');
4800 $sql = "SELECT $coursefields, $ctxfields
4801 FROM {course} c
4802 JOIN {context} ctx
4803 ON ctx.contextlevel = :contextlevel
4804 AND ctx.instanceid = c.id
4805 JOIN {user_lastaccess} ul
4806 ON ul.courseid = c.id
4807 $favsql
4808 WHERE ul.userid = :userid
4809 AND c.visible = :visible
4810 AND EXISTS (SELECT e.id
4811 FROM {enrol} e
4812 LEFT JOIN {user_enrolments} ue ON ue.enrolid = e.id
4813 WHERE e.courseid = c.id
4814 AND e.status = :statusenrol
4815 AND ((ue.status = :status
4816 AND ue.userid = ul.userid
4817 AND ue.timestart < :now1
4818 AND (ue.timeend = 0 OR ue.timeend > :now2)
4820 OR e.enrol = :guestenrol
4823 $orderby";
4825 $now = round(time(), -2); // Improves db caching.
4826 $params = ['userid' => $userid, 'contextlevel' => CONTEXT_COURSE, 'visible' => 1, 'status' => ENROL_USER_ACTIVE,
4827 'statusenrol' => ENROL_INSTANCE_ENABLED, 'guestenrol' => 'guest', 'now1' => $now, 'now2' => $now] + $favparams;
4829 $recentcourses = $DB->get_records_sql($sql, $params, $offset, $limit);
4831 // Filter courses if last access field is hidden.
4832 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
4834 if ($userid != $USER->id && isset($hiddenfields['lastaccess'])) {
4835 $recentcourses = array_filter($recentcourses, function($course) {
4836 context_helper::preload_from_record($course);
4837 $context = context_course::instance($course->id, IGNORE_MISSING);
4838 // If last access was a hidden field, a user requesting info about another user would need permission to view hidden
4839 // fields.
4840 return has_capability('moodle/course:viewhiddenuserfields', $context);
4844 return $recentcourses;
4848 * Calculate the course start date and offset for the given user ids.
4850 * If the course is a fixed date course then the course start date will be returned.
4851 * If the course is a relative date course then the course date will be calculated and
4852 * and offset provided.
4854 * The dates are returned as an array with the index being the user id. The array
4855 * contains the start date and start offset values for the user.
4857 * If the user is not enrolled in the course then the course start date will be returned.
4859 * If we have a course which starts on 1563244000 and 2 users, id 123 and 456, where the
4860 * former is enrolled in the course at 1563244693 and the latter is not enrolled then the
4861 * return value would look like:
4863 * '123' => [
4864 * 'start' => 1563244693,
4865 * 'startoffset' => 693
4866 * ],
4867 * '456' => [
4868 * 'start' => 1563244000,
4869 * 'startoffset' => 0
4873 * @param stdClass $course The course to fetch dates for.
4874 * @param array $userids The list of user ids to get dates for.
4875 * @return array
4877 function course_get_course_dates_for_user_ids(stdClass $course, array $userids): array {
4878 if (empty($course->relativedatesmode)) {
4879 // This course isn't set to relative dates so we can early return with the course
4880 // start date.
4881 return array_reduce($userids, function($carry, $userid) use ($course) {
4882 $carry[$userid] = [
4883 'start' => $course->startdate,
4884 'startoffset' => 0
4886 return $carry;
4887 }, []);
4890 // We're dealing with a relative dates course now so we need to calculate some dates.
4891 $cache = cache::make('core', 'course_user_dates');
4892 $dates = [];
4893 $uncacheduserids = [];
4895 // Try fetching the values from the cache so that we don't need to do a DB request.
4896 foreach ($userids as $userid) {
4897 $cachekey = "{$course->id}_{$userid}";
4898 $cachedvalue = $cache->get($cachekey);
4900 if ($cachedvalue === false) {
4901 // Looks like we haven't seen this user for this course before so we'll have
4902 // to fetch it.
4903 $uncacheduserids[] = $userid;
4904 } else {
4905 [$start, $startoffset] = $cachedvalue;
4906 $dates[$userid] = [
4907 'start' => $start,
4908 'startoffset' => $startoffset
4913 if (!empty($uncacheduserids)) {
4914 // Load the enrolments for any users we haven't seen yet. Set the "onlyactive" param
4915 // to false because it filters out users with enrolment start times in the future which
4916 // we don't want.
4917 $enrolments = enrol_get_course_users($course->id, false, $uncacheduserids);
4919 foreach ($uncacheduserids as $userid) {
4920 // Find the user enrolment that has the earliest start date.
4921 $enrolment = array_reduce(array_values($enrolments), function($carry, $enrolment) use ($userid) {
4922 // Only consider enrolments for this user if the user enrolment is active and the
4923 // enrolment method is enabled.
4924 if (
4925 $enrolment->uestatus == ENROL_USER_ACTIVE &&
4926 $enrolment->estatus == ENROL_INSTANCE_ENABLED &&
4927 $enrolment->id == $userid
4929 if (is_null($carry)) {
4930 // Haven't found an enrolment yet for this user so use the one we just found.
4931 $carry = $enrolment;
4932 } else {
4933 // We've already found an enrolment for this user so let's use which ever one
4934 // has the earliest start time.
4935 $carry = $carry->uetimestart < $enrolment->uetimestart ? $carry : $enrolment;
4939 return $carry;
4940 }, null);
4942 if ($enrolment) {
4943 // The course is in relative dates mode so we calculate the student's start
4944 // date based on their enrolment start date.
4945 $start = $course->startdate > $enrolment->uetimestart ? $course->startdate : $enrolment->uetimestart;
4946 $startoffset = $start - $course->startdate;
4947 } else {
4948 // The user is not enrolled in the course so default back to the course start date.
4949 $start = $course->startdate;
4950 $startoffset = 0;
4953 $dates[$userid] = [
4954 'start' => $start,
4955 'startoffset' => $startoffset
4958 $cachekey = "{$course->id}_{$userid}";
4959 $cache->set($cachekey, [$start, $startoffset]);
4963 return $dates;
4967 * Calculate the course start date and offset for the given user id.
4969 * If the course is a fixed date course then the course start date will be returned.
4970 * If the course is a relative date course then the course date will be calculated and
4971 * and offset provided.
4973 * The return array contains the start date and start offset values for the user.
4975 * If the user is not enrolled in the course then the course start date will be returned.
4977 * If we have a course which starts on 1563244000. If a user's enrolment starts on 1563244693
4978 * then the return would be:
4980 * 'start' => 1563244693,
4981 * 'startoffset' => 693
4984 * If the use was not enrolled then the return would be:
4986 * 'start' => 1563244000,
4987 * 'startoffset' => 0
4990 * @param stdClass $course The course to fetch dates for.
4991 * @param int $userid The user id to get dates for.
4992 * @return array
4994 function course_get_course_dates_for_user_id(stdClass $course, int $userid): array {
4995 return (course_get_course_dates_for_user_ids($course, [$userid]))[$userid];