MDL-73863 course: Add tertiary navigation in completion pages
[moodle.git] / course / lib.php
blobb986431a508778393ee7b54faaa527e4dc35db58
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Library of useful functions
20 * @copyright 1999 Martin Dougiamas http://dougiamas.com
21 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
22 * @package core_course
25 defined('MOODLE_INTERNAL') || die;
27 use core_courseformat\base as course_format;
29 require_once($CFG->libdir.'/completionlib.php');
30 require_once($CFG->libdir.'/filelib.php');
31 require_once($CFG->libdir.'/datalib.php');
32 require_once($CFG->dirroot.'/course/format/lib.php');
34 define('COURSE_MAX_LOGS_PER_PAGE', 1000); // Records.
35 define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds.
37 /**
38 * Number of courses to display when summaries are included.
39 * @var int
40 * @deprecated since 2.4, use $CFG->courseswithsummarieslimit instead.
42 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10);
44 // Max courses in log dropdown before switching to optional.
45 define('COURSE_MAX_COURSES_PER_DROPDOWN', 1000);
46 // Max users in log dropdown before switching to optional.
47 define('COURSE_MAX_USERS_PER_DROPDOWN', 1000);
48 define('FRONTPAGENEWS', '0');
49 define('FRONTPAGECATEGORYNAMES', '2');
50 define('FRONTPAGECATEGORYCOMBO', '4');
51 define('FRONTPAGEENROLLEDCOURSELIST', '5');
52 define('FRONTPAGEALLCOURSELIST', '6');
53 define('FRONTPAGECOURSESEARCH', '7');
54 // Important! Replaced with $CFG->frontpagecourselimit - maximum number of courses displayed on the frontpage.
55 define('EXCELROWS', 65535);
56 define('FIRSTUSEDEXCELROW', 3);
58 define('MOD_CLASS_ACTIVITY', 0);
59 define('MOD_CLASS_RESOURCE', 1);
61 define('COURSE_TIMELINE_ALLINCLUDINGHIDDEN', 'allincludinghidden');
62 define('COURSE_TIMELINE_ALL', 'all');
63 define('COURSE_TIMELINE_PAST', 'past');
64 define('COURSE_TIMELINE_INPROGRESS', 'inprogress');
65 define('COURSE_TIMELINE_FUTURE', 'future');
66 define('COURSE_TIMELINE_SEARCH', 'search');
67 define('COURSE_FAVOURITES', 'favourites');
68 define('COURSE_TIMELINE_HIDDEN', 'hidden');
69 define('COURSE_CUSTOMFIELD', 'customfield');
70 define('COURSE_DB_QUERY_LIMIT', 1000);
71 /** Searching for all courses that have no value for the specified custom field. */
72 define('COURSE_CUSTOMFIELD_EMPTY', -1);
74 // Course activity chooser footer default display option.
75 define('COURSE_CHOOSER_FOOTER_NONE', 'hidden');
77 // Download course content options.
78 define('DOWNLOAD_COURSE_CONTENT_DISABLED', 0);
79 define('DOWNLOAD_COURSE_CONTENT_ENABLED', 1);
80 define('DOWNLOAD_COURSE_CONTENT_SITE_DEFAULT', 2);
82 function make_log_url($module, $url) {
83 switch ($module) {
84 case 'course':
85 if (strpos($url, 'report/') === 0) {
86 // there is only one report type, course reports are deprecated
87 $url = "/$url";
88 break;
90 case 'file':
91 case 'login':
92 case 'lib':
93 case 'admin':
94 case 'category':
95 case 'mnet course':
96 if (strpos($url, '../') === 0) {
97 $url = ltrim($url, '.');
98 } else {
99 $url = "/course/$url";
101 break;
102 case 'calendar':
103 $url = "/calendar/$url";
104 break;
105 case 'user':
106 case 'blog':
107 $url = "/$module/$url";
108 break;
109 case 'upload':
110 $url = $url;
111 break;
112 case 'coursetags':
113 $url = '/'.$url;
114 break;
115 case 'library':
116 case '':
117 $url = '/';
118 break;
119 case 'message':
120 $url = "/message/$url";
121 break;
122 case 'notes':
123 $url = "/notes/$url";
124 break;
125 case 'tag':
126 $url = "/tag/$url";
127 break;
128 case 'role':
129 $url = '/'.$url;
130 break;
131 case 'grade':
132 $url = "/grade/$url";
133 break;
134 default:
135 $url = "/mod/$module/$url";
136 break;
139 //now let's sanitise urls - there might be some ugly nasties:-(
140 $parts = explode('?', $url);
141 $script = array_shift($parts);
142 if (strpos($script, 'http') === 0) {
143 $script = clean_param($script, PARAM_URL);
144 } else {
145 $script = clean_param($script, PARAM_PATH);
148 $query = '';
149 if ($parts) {
150 $query = implode('', $parts);
151 $query = str_replace('&amp;', '&', $query); // both & and &amp; are stored in db :-|
152 $parts = explode('&', $query);
153 $eq = urlencode('=');
154 foreach ($parts as $key=>$part) {
155 $part = urlencode(urldecode($part));
156 $part = str_replace($eq, '=', $part);
157 $parts[$key] = $part;
159 $query = '?'.implode('&amp;', $parts);
162 return $script.$query;
166 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
167 $modname="", $modid=0, $modaction="", $groupid=0) {
168 global $CFG, $DB;
170 // It is assumed that $date is the GMT time of midnight for that day,
171 // and so the next 86400 seconds worth of logs are printed.
173 /// Setup for group handling.
175 // TODO: I don't understand group/context/etc. enough to be able to do
176 // something interesting with it here
177 // What is the context of a remote course?
179 /// If the group mode is separate, and this user does not have editing privileges,
180 /// then only the user's group can be viewed.
181 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
182 // $groupid = get_current_group($course->id);
184 /// If this course doesn't have groups, no groupid can be specified.
185 //else if (!$course->groupmode) {
186 // $groupid = 0;
189 $groupid = 0;
191 $joins = array();
192 $where = '';
194 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
195 FROM {mnet_log} l
196 LEFT JOIN {user} u ON l.userid = u.id
197 WHERE ";
198 $params = array();
200 $where .= "l.hostid = :hostid";
201 $params['hostid'] = $hostid;
203 // TODO: Is 1 really a magic number referring to the sitename?
204 if ($course != SITEID || $modid != 0) {
205 $where .= " AND l.course=:courseid";
206 $params['courseid'] = $course;
209 if ($modname) {
210 $where .= " AND l.module = :modname";
211 $params['modname'] = $modname;
214 if ('site_errors' === $modid) {
215 $where .= " AND ( l.action='error' OR l.action='infected' )";
216 } else if ($modid) {
217 //TODO: This assumes that modids are the same across sites... probably
218 //not true
219 $where .= " AND l.cmid = :modid";
220 $params['modid'] = $modid;
223 if ($modaction) {
224 $firstletter = substr($modaction, 0, 1);
225 if ($firstletter == '-') {
226 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
227 $params['modaction'] = '%'.substr($modaction, 1).'%';
228 } else {
229 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
230 $params['modaction'] = '%'.$modaction.'%';
234 if ($user) {
235 $where .= " AND l.userid = :user";
236 $params['user'] = $user;
239 if ($date) {
240 $enddate = $date + 86400;
241 $where .= " AND l.time > :date AND l.time < :enddate";
242 $params['date'] = $date;
243 $params['enddate'] = $enddate;
246 $result = array();
247 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
248 if(!empty($result['totalcount'])) {
249 $where .= " ORDER BY $order";
250 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
251 } else {
252 $result['logs'] = array();
254 return $result;
258 * Checks the integrity of the course data.
260 * In summary - compares course_sections.sequence and course_modules.section.
262 * More detailed, checks that:
263 * - course_sections.sequence contains each module id not more than once in the course
264 * - for each moduleid from course_sections.sequence the field course_modules.section
265 * refers to the same section id (this means course_sections.sequence is more
266 * important if they are different)
267 * - ($fullcheck only) each module in the course is present in one of
268 * course_sections.sequence
269 * - ($fullcheck only) removes non-existing course modules from section sequences
271 * If there are any mismatches, the changes are made and records are updated in DB.
273 * Course cache is NOT rebuilt if there are any errors!
275 * This function is used each time when course cache is being rebuilt with $fullcheck = false
276 * and in CLI script admin/cli/fix_course_sequence.php with $fullcheck = true
278 * @param int $courseid id of the course
279 * @param array $rawmods result of funciton {@link get_course_mods()} - containst
280 * the list of enabled course modules in the course. Retrieved from DB if not specified.
281 * Argument ignored in cashe of $fullcheck, the list is retrieved form DB anyway.
282 * @param array $sections records from course_sections table for this course.
283 * Retrieved from DB if not specified
284 * @param bool $fullcheck Will add orphaned modules to their sections and remove non-existing
285 * course modules from sequences. Only to be used in site maintenance mode when we are
286 * sure that another user is not in the middle of the process of moving/removing a module.
287 * @param bool $checkonly Only performs the check without updating DB, outputs all errors as debug messages.
288 * @return array array of messages with found problems. Empty output means everything is ok
290 function course_integrity_check($courseid, $rawmods = null, $sections = null, $fullcheck = false, $checkonly = false) {
291 global $DB;
292 $messages = array();
293 if ($sections === null) {
294 $sections = $DB->get_records('course_sections', array('course' => $courseid), 'section', 'id,section,sequence');
296 if ($fullcheck) {
297 // Retrieve all records from course_modules regardless of module type visibility.
298 $rawmods = $DB->get_records('course_modules', array('course' => $courseid), 'id', 'id,section');
300 if ($rawmods === null) {
301 $rawmods = get_course_mods($courseid);
303 if (!$fullcheck && (empty($sections) || empty($rawmods))) {
304 // If either of the arrays is empty, no modules are displayed anyway.
305 return true;
307 $debuggingprefix = 'Failed integrity check for course ['.$courseid.']. ';
309 // First make sure that each module id appears in section sequences only once.
310 // If it appears in several section sequences the last section wins.
311 // If it appears twice in one section sequence, the first occurence wins.
312 $modsection = array();
313 foreach ($sections as $sectionid => $section) {
314 $sections[$sectionid]->newsequence = $section->sequence;
315 if (!empty($section->sequence)) {
316 $sequence = explode(",", $section->sequence);
317 $sequenceunique = array_unique($sequence);
318 if (count($sequenceunique) != count($sequence)) {
319 // Some course module id appears in this section sequence more than once.
320 ksort($sequenceunique); // Preserve initial order of modules.
321 $sequence = array_values($sequenceunique);
322 $sections[$sectionid]->newsequence = join(',', $sequence);
323 $messages[] = $debuggingprefix.'Sequence for course section ['.
324 $sectionid.'] is "'.$sections[$sectionid]->sequence.'", must be "'.$sections[$sectionid]->newsequence.'"';
326 foreach ($sequence as $cmid) {
327 if (array_key_exists($cmid, $modsection) && isset($rawmods[$cmid])) {
328 // Some course module id appears to be in more than one section's sequences.
329 $wrongsectionid = $modsection[$cmid];
330 $sections[$wrongsectionid]->newsequence = trim(preg_replace("/,$cmid,/", ',', ','.$sections[$wrongsectionid]->newsequence. ','), ',');
331 $messages[] = $debuggingprefix.'Course module ['.$cmid.'] must be removed from sequence of section ['.
332 $wrongsectionid.'] because it is also present in sequence of section ['.$sectionid.']';
334 $modsection[$cmid] = $sectionid;
339 // Add orphaned modules to their sections if they exist or to section 0 otherwise.
340 if ($fullcheck) {
341 foreach ($rawmods as $cmid => $mod) {
342 if (!isset($modsection[$cmid])) {
343 // This is a module that is not mentioned in course_section.sequence at all.
344 // Add it to the section $mod->section or to the last available section.
345 if ($mod->section && isset($sections[$mod->section])) {
346 $modsection[$cmid] = $mod->section;
347 } else {
348 $firstsection = reset($sections);
349 $modsection[$cmid] = $firstsection->id;
351 $sections[$modsection[$cmid]]->newsequence = trim($sections[$modsection[$cmid]]->newsequence.','.$cmid, ',');
352 $messages[] = $debuggingprefix.'Course module ['.$cmid.'] is missing from sequence of section ['.
353 $modsection[$cmid].']';
356 foreach ($modsection as $cmid => $sectionid) {
357 if (!isset($rawmods[$cmid])) {
358 // Section $sectionid refers to module id that does not exist.
359 $sections[$sectionid]->newsequence = trim(preg_replace("/,$cmid,/", ',', ','.$sections[$sectionid]->newsequence.','), ',');
360 $messages[] = $debuggingprefix.'Course module ['.$cmid.
361 '] does not exist but is present in the sequence of section ['.$sectionid.']';
366 // Update changed sections.
367 if (!$checkonly && !empty($messages)) {
368 foreach ($sections as $sectionid => $section) {
369 if ($section->newsequence !== $section->sequence) {
370 $DB->update_record('course_sections', array('id' => $sectionid, 'sequence' => $section->newsequence));
375 // Now make sure that all modules point to the correct sections.
376 foreach ($rawmods as $cmid => $mod) {
377 if (isset($modsection[$cmid]) && $modsection[$cmid] != $mod->section) {
378 if (!$checkonly) {
379 $DB->update_record('course_modules', array('id' => $cmid, 'section' => $modsection[$cmid]));
381 $messages[] = $debuggingprefix.'Course module ['.$cmid.
382 '] points to section ['.$mod->section.'] instead of ['.$modsection[$cmid].']';
386 return $messages;
390 * For a given course, returns an array of course activity objects
391 * Each item in the array contains he following properties:
393 function get_array_of_activities($courseid) {
394 // cm - course module id
395 // mod - name of the module (eg forum)
396 // section - the number of the section (eg week or topic)
397 // name - the name of the instance
398 // visible - is the instance visible or not
399 // groupingid - grouping id
400 // extra - contains extra string to include in any link
401 global $CFG, $DB;
403 $course = $DB->get_record('course', array('id'=>$courseid));
405 if (empty($course)) {
406 throw new moodle_exception('courseidnotfound');
409 $mod = array();
411 $rawmods = get_course_mods($courseid);
412 if (empty($rawmods)) {
413 return $mod; // always return array
415 $courseformat = course_get_format($course);
417 if ($sections = $DB->get_records('course_sections', array('course' => $courseid),
418 'section ASC', 'id,section,sequence,visible')) {
419 // First check and correct obvious mismatches between course_sections.sequence and course_modules.section.
420 if ($errormessages = course_integrity_check($courseid, $rawmods, $sections)) {
421 debugging(join('<br>', $errormessages));
422 $rawmods = get_course_mods($courseid);
423 $sections = $DB->get_records('course_sections', array('course' => $courseid),
424 'section ASC', 'id,section,sequence,visible');
426 // Build array of activities.
427 foreach ($sections as $section) {
428 if (!empty($section->sequence)) {
429 $sequence = explode(",", $section->sequence);
430 foreach ($sequence as $seq) {
431 if (empty($rawmods[$seq])) {
432 continue;
434 // Adjust visibleoncoursepage, value in DB may not respect format availability.
435 $rawmods[$seq]->visibleoncoursepage = (!$rawmods[$seq]->visible
436 || $rawmods[$seq]->visibleoncoursepage
437 || empty($CFG->allowstealth)
438 || !$courseformat->allow_stealth_module_visibility($rawmods[$seq], $section)) ? 1 : 0;
440 // Create an object that will be cached.
441 $mod[$seq] = new stdClass();
442 $mod[$seq]->id = $rawmods[$seq]->instance;
443 $mod[$seq]->cm = $rawmods[$seq]->id;
444 $mod[$seq]->mod = $rawmods[$seq]->modname;
446 // Oh dear. Inconsistent names left here for backward compatibility.
447 $mod[$seq]->section = $section->section;
448 $mod[$seq]->sectionid = $rawmods[$seq]->section;
450 $mod[$seq]->module = $rawmods[$seq]->module;
451 $mod[$seq]->added = $rawmods[$seq]->added;
452 $mod[$seq]->score = $rawmods[$seq]->score;
453 $mod[$seq]->idnumber = $rawmods[$seq]->idnumber;
454 $mod[$seq]->visible = $rawmods[$seq]->visible;
455 $mod[$seq]->visibleoncoursepage = $rawmods[$seq]->visibleoncoursepage;
456 $mod[$seq]->visibleold = $rawmods[$seq]->visibleold;
457 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
458 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
459 $mod[$seq]->indent = $rawmods[$seq]->indent;
460 $mod[$seq]->completion = $rawmods[$seq]->completion;
461 $mod[$seq]->extra = "";
462 $mod[$seq]->completiongradeitemnumber =
463 $rawmods[$seq]->completiongradeitemnumber;
464 $mod[$seq]->completionpassgrade = $rawmods[$seq]->completionpassgrade;
465 $mod[$seq]->completionview = $rawmods[$seq]->completionview;
466 $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected;
467 $mod[$seq]->showdescription = $rawmods[$seq]->showdescription;
468 $mod[$seq]->availability = $rawmods[$seq]->availability;
469 $mod[$seq]->deletioninprogress = $rawmods[$seq]->deletioninprogress;
470 $mod[$seq]->downloadcontent = $rawmods[$seq]->downloadcontent;
471 $modname = $mod[$seq]->mod;
472 $functionname = $modname."_get_coursemodule_info";
474 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
475 continue;
478 include_once("$CFG->dirroot/mod/$modname/lib.php");
480 if ($hasfunction = function_exists($functionname)) {
481 if ($info = $functionname($rawmods[$seq])) {
482 if (!empty($info->icon)) {
483 $mod[$seq]->icon = $info->icon;
485 if (!empty($info->iconcomponent)) {
486 $mod[$seq]->iconcomponent = $info->iconcomponent;
488 if (!empty($info->name)) {
489 $mod[$seq]->name = $info->name;
491 if ($info instanceof cached_cm_info) {
492 // When using cached_cm_info you can include three new fields
493 // that aren't available for legacy code
494 if (!empty($info->content)) {
495 $mod[$seq]->content = $info->content;
497 if (!empty($info->extraclasses)) {
498 $mod[$seq]->extraclasses = $info->extraclasses;
500 if (!empty($info->iconurl)) {
501 // Convert URL to string as it's easier to store. Also serialized object contains \0 byte and can not be written to Postgres DB.
502 $url = new moodle_url($info->iconurl);
503 $mod[$seq]->iconurl = $url->out(false);
505 if (!empty($info->onclick)) {
506 $mod[$seq]->onclick = $info->onclick;
508 if (!empty($info->customdata)) {
509 $mod[$seq]->customdata = $info->customdata;
511 } else {
512 // When using a stdclass, the (horrible) deprecated ->extra field
513 // is available for BC
514 if (!empty($info->extra)) {
515 $mod[$seq]->extra = $info->extra;
520 // When there is no modname_get_coursemodule_info function,
521 // but showdescriptions is enabled, then we use the 'intro'
522 // and 'introformat' fields in the module table
523 if (!$hasfunction && $rawmods[$seq]->showdescription) {
524 if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
525 array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
526 // Set content from intro and introformat. Filters are disabled
527 // because we filter it with format_text at display time
528 $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
529 $modvalues, $rawmods[$seq]->id, false);
531 // To save making another query just below, put name in here
532 $mod[$seq]->name = $modvalues->name;
535 if (!isset($mod[$seq]->name)) {
536 $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
539 // Minimise the database size by unsetting default options when they are
540 // 'empty'. This list corresponds to code in the cm_info constructor.
541 foreach (array('idnumber', 'groupmode', 'groupingid',
542 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
543 'icon', 'iconcomponent', 'customdata', 'availability', 'completionview',
544 'completionexpected', 'score', 'showdescription', 'deletioninprogress') as $property) {
545 if (property_exists($mod[$seq], $property) &&
546 empty($mod[$seq]->{$property})) {
547 unset($mod[$seq]->{$property});
550 // Special case: this value is usually set to null, but may be 0
551 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
552 is_null($mod[$seq]->completiongradeitemnumber)) {
553 unset($mod[$seq]->completiongradeitemnumber);
559 return $mod;
563 * Returns the localised human-readable names of all used modules
565 * @param bool $plural if true returns the plural forms of the names
566 * @return array where key is the module name (component name without 'mod_') and
567 * the value is the human-readable string. Array sorted alphabetically by value
569 function get_module_types_names($plural = false) {
570 static $modnames = null;
571 global $DB, $CFG;
572 if ($modnames === null) {
573 $modnames = array(0 => array(), 1 => array());
574 if ($allmods = $DB->get_records("modules")) {
575 foreach ($allmods as $mod) {
576 if (file_exists("$CFG->dirroot/mod/$mod->name/lib.php") && $mod->visible) {
577 $modnames[0][$mod->name] = get_string("modulename", "$mod->name", null, true);
578 $modnames[1][$mod->name] = get_string("modulenameplural", "$mod->name", null, true);
583 return $modnames[(int)$plural];
587 * Set highlighted section. Only one section can be highlighted at the time.
589 * @param int $courseid course id
590 * @param int $marker highlight section with this number, 0 means remove higlightin
591 * @return void
593 function course_set_marker($courseid, $marker) {
594 global $DB, $COURSE;
595 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
596 if ($COURSE && $COURSE->id == $courseid) {
597 $COURSE->marker = $marker;
599 core_courseformat\base::reset_course_cache($courseid);
600 course_modinfo::clear_instance_cache($courseid);
604 * For a given course section, marks it visible or hidden,
605 * and does the same for every activity in that section
607 * @param int $courseid course id
608 * @param int $sectionnumber The section number to adjust
609 * @param int $visibility The new visibility
610 * @return array A list of resources which were hidden in the section
612 function set_section_visible($courseid, $sectionnumber, $visibility) {
613 global $DB;
615 $resourcestotoggle = array();
616 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
617 course_update_section($courseid, $section, array('visible' => $visibility));
619 // Determine which modules are visible for AJAX update
620 $modules = !empty($section->sequence) ? explode(',', $section->sequence) : array();
621 if (!empty($modules)) {
622 list($insql, $params) = $DB->get_in_or_equal($modules);
623 $select = 'id ' . $insql . ' AND visible = ?';
624 array_push($params, $visibility);
625 if (!$visibility) {
626 $select .= ' AND visibleold = 1';
628 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
631 return $resourcestotoggle;
635 * Return the course category context for the category with id $categoryid, except
636 * that if $categoryid is 0, return the system context.
638 * @param integer $categoryid a category id or 0.
639 * @return context the corresponding context
641 function get_category_or_system_context($categoryid) {
642 if ($categoryid) {
643 return context_coursecat::instance($categoryid, IGNORE_MISSING);
644 } else {
645 return context_system::instance();
650 * Print the buttons relating to course requests.
652 * @param context $context current page context.
653 * @deprecated since Moodle 4.0
654 * @todo Final deprecation MDL-73976
656 function print_course_request_buttons($context) {
657 global $CFG, $DB, $OUTPUT;
658 debugging("print_course_request_buttons() is deprecated. " .
659 "This is replaced with the category_action_bar tertiary navigation.", DEBUG_DEVELOPER);
660 if (empty($CFG->enablecourserequests)) {
661 return;
663 if (course_request::can_request($context)) {
664 // Print a button to request a new course.
665 $params = [];
666 if ($context instanceof context_coursecat) {
667 $params['category'] = $context->instanceid;
669 echo $OUTPUT->single_button(new moodle_url('/course/request.php', $params),
670 get_string('requestcourse'), 'get');
672 /// Print a button to manage pending requests
673 if (has_capability('moodle/site:approvecourse', $context)) {
674 $disabled = !$DB->record_exists('course_request', array());
675 echo $OUTPUT->single_button(new moodle_url('/course/pending.php'), get_string('coursespending'), 'get', array('disabled' => $disabled));
680 * Does the user have permission to edit things in this category?
682 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
683 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
685 function can_edit_in_category($categoryid = 0) {
686 $context = get_category_or_system_context($categoryid);
687 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
690 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
692 function add_course_module($mod) {
693 global $DB;
695 $mod->added = time();
696 unset($mod->id);
698 $cmid = $DB->insert_record("course_modules", $mod);
699 rebuild_course_cache($mod->course, true);
700 return $cmid;
704 * Creates a course section and adds it to the specified position
706 * @param int|stdClass $courseorid course id or course object
707 * @param int $position position to add to, 0 means to the end. If position is greater than
708 * number of existing secitons, the section is added to the end. This will become sectionnum of the
709 * new section. All existing sections at this or bigger position will be shifted down.
710 * @param bool $skipcheck the check has already been made and we know that the section with this position does not exist
711 * @return stdClass created section object
713 function course_create_section($courseorid, $position = 0, $skipcheck = false) {
714 global $DB;
715 $courseid = is_object($courseorid) ? $courseorid->id : $courseorid;
717 // Find the last sectionnum among existing sections.
718 if ($skipcheck) {
719 $lastsection = $position - 1;
720 } else {
721 $lastsection = (int)$DB->get_field_sql('SELECT max(section) from {course_sections} WHERE course = ?', [$courseid]);
724 // First add section to the end.
725 $cw = new stdClass();
726 $cw->course = $courseid;
727 $cw->section = $lastsection + 1;
728 $cw->summary = '';
729 $cw->summaryformat = FORMAT_HTML;
730 $cw->sequence = '';
731 $cw->name = null;
732 $cw->visible = 1;
733 $cw->availability = null;
734 $cw->timemodified = time();
735 $cw->id = $DB->insert_record("course_sections", $cw);
737 // Now move it to the specified position.
738 if ($position > 0 && $position <= $lastsection) {
739 $course = is_object($courseorid) ? $courseorid : get_course($courseorid);
740 move_section_to($course, $cw->section, $position, true);
741 $cw->section = $position;
744 core\event\course_section_created::create_from_section($cw)->trigger();
746 rebuild_course_cache($courseid, true);
747 return $cw;
751 * Creates missing course section(s) and rebuilds course cache
753 * @param int|stdClass $courseorid course id or course object
754 * @param int|array $sections list of relative section numbers to create
755 * @return bool if there were any sections created
757 function course_create_sections_if_missing($courseorid, $sections) {
758 if (!is_array($sections)) {
759 $sections = array($sections);
761 $existing = array_keys(get_fast_modinfo($courseorid)->get_section_info_all());
762 if ($newsections = array_diff($sections, $existing)) {
763 foreach ($newsections as $sectionnum) {
764 course_create_section($courseorid, $sectionnum, true);
766 return true;
768 return false;
772 * Adds an existing module to the section
774 * Updates both tables {course_sections} and {course_modules}
776 * Note: This function does not use modinfo PROVIDED that the section you are
777 * adding the module to already exists. If the section does not exist, it will
778 * build modinfo if necessary and create the section.
780 * @param int|stdClass $courseorid course id or course object
781 * @param int $cmid id of the module already existing in course_modules table
782 * @param int $sectionnum relative number of the section (field course_sections.section)
783 * If section does not exist it will be created
784 * @param int|stdClass $beforemod id or object with field id corresponding to the module
785 * before which the module needs to be included. Null for inserting in the
786 * end of the section
787 * @return int The course_sections ID where the module is inserted
789 function course_add_cm_to_section($courseorid, $cmid, $sectionnum, $beforemod = null) {
790 global $DB, $COURSE;
791 if (is_object($beforemod)) {
792 $beforemod = $beforemod->id;
794 if (is_object($courseorid)) {
795 $courseid = $courseorid->id;
796 } else {
797 $courseid = $courseorid;
799 // Do not try to use modinfo here, there is no guarantee it is valid!
800 $section = $DB->get_record('course_sections',
801 array('course' => $courseid, 'section' => $sectionnum), '*', IGNORE_MISSING);
802 if (!$section) {
803 // This function call requires modinfo.
804 course_create_sections_if_missing($courseorid, $sectionnum);
805 $section = $DB->get_record('course_sections',
806 array('course' => $courseid, 'section' => $sectionnum), '*', MUST_EXIST);
809 $modarray = explode(",", trim($section->sequence));
810 if (empty($section->sequence)) {
811 $newsequence = "$cmid";
812 } else if ($beforemod && ($key = array_keys($modarray, $beforemod))) {
813 $insertarray = array($cmid, $beforemod);
814 array_splice($modarray, $key[0], 1, $insertarray);
815 $newsequence = implode(",", $modarray);
816 } else {
817 $newsequence = "$section->sequence,$cmid";
819 $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id));
820 $DB->set_field('course_modules', 'section', $section->id, array('id' => $cmid));
821 if (is_object($courseorid)) {
822 rebuild_course_cache($courseorid->id, true);
823 } else {
824 rebuild_course_cache($courseorid, true);
826 return $section->id; // Return course_sections ID that was used.
830 * Change the group mode of a course module.
832 * Note: Do not forget to trigger the event \core\event\course_module_updated as it needs
833 * to be triggered manually, refer to {@link \core\event\course_module_updated::create_from_cm()}.
835 * @param int $id course module ID.
836 * @param int $groupmode the new groupmode value.
837 * @return bool True if the $groupmode was updated.
839 function set_coursemodule_groupmode($id, $groupmode) {
840 global $DB;
841 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST);
842 if ($cm->groupmode != $groupmode) {
843 $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id));
844 rebuild_course_cache($cm->course, true);
846 return ($cm->groupmode != $groupmode);
849 function set_coursemodule_idnumber($id, $idnumber) {
850 global $DB;
851 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST);
852 if ($cm->idnumber != $idnumber) {
853 $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id));
854 rebuild_course_cache($cm->course, true);
856 return ($cm->idnumber != $idnumber);
860 * Set downloadcontent value to course module.
862 * @param int $id The id of the module.
863 * @param bool $downloadcontent Whether the module can be downloaded when download course content is enabled.
864 * @return bool True if downloadcontent has been updated, false otherwise.
866 function set_downloadcontent(int $id, bool $downloadcontent): bool {
867 global $DB;
868 $cm = $DB->get_record('course_modules', ['id' => $id], 'id, course, downloadcontent', MUST_EXIST);
869 if ($cm->downloadcontent != $downloadcontent) {
870 $DB->set_field('course_modules', 'downloadcontent', $downloadcontent, ['id' => $cm->id]);
871 rebuild_course_cache($cm->course, true);
873 return ($cm->downloadcontent != $downloadcontent);
877 * Set the visibility of a module and inherent properties.
879 * Note: Do not forget to trigger the event \core\event\course_module_updated as it needs
880 * to be triggered manually, refer to {@link \core\event\course_module_updated::create_from_cm()}.
882 * From 2.4 the parameter $prevstateoverrides has been removed, the logic it triggered
883 * has been moved to {@link set_section_visible()} which was the only place from which
884 * the parameter was used.
886 * @param int $id of the module
887 * @param int $visible state of the module
888 * @param int $visibleoncoursepage state of the module on the course page
889 * @return bool false when the module was not found, true otherwise
891 function set_coursemodule_visible($id, $visible, $visibleoncoursepage = 1) {
892 global $DB, $CFG;
893 require_once($CFG->libdir.'/gradelib.php');
894 require_once($CFG->dirroot.'/calendar/lib.php');
896 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
897 return false;
900 // Create events and propagate visibility to associated grade items if the value has changed.
901 // Only do this if it's changed to avoid accidently overwriting manual showing/hiding of student grades.
902 if ($cm->visible == $visible && $cm->visibleoncoursepage == $visibleoncoursepage) {
903 return true;
906 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
907 return false;
909 if (($cm->visible != $visible) &&
910 ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename)))) {
911 foreach($events as $event) {
912 if ($visible) {
913 $event = new calendar_event($event);
914 $event->toggle_visibility(true);
915 } else {
916 $event = new calendar_event($event);
917 $event->toggle_visibility(false);
922 // Updating visible and visibleold to keep them in sync. Only changing a section visibility will
923 // affect visibleold to allow for an original visibility restore. See set_section_visible().
924 $cminfo = new stdClass();
925 $cminfo->id = $id;
926 $cminfo->visible = $visible;
927 $cminfo->visibleoncoursepage = $visibleoncoursepage;
928 $cminfo->visibleold = $visible;
929 $DB->update_record('course_modules', $cminfo);
931 // Hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there.
932 // Note that this must be done after updating the row in course_modules, in case
933 // the modules grade_item_update function needs to access $cm->visible.
934 if ($cm->visible != $visible &&
935 plugin_supports('mod', $modulename, FEATURE_CONTROLS_GRADE_VISIBILITY) &&
936 component_callback_exists('mod_' . $modulename, 'grade_item_update')) {
937 $instance = $DB->get_record($modulename, array('id' => $cm->instance), '*', MUST_EXIST);
938 component_callback('mod_' . $modulename, 'grade_item_update', array($instance));
939 } else if ($cm->visible != $visible) {
940 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
941 if ($grade_items) {
942 foreach ($grade_items as $grade_item) {
943 $grade_item->set_hidden(!$visible);
948 rebuild_course_cache($cm->course, true);
949 return true;
953 * Changes the course module name
955 * @param int $id course module id
956 * @param string $name new value for a name
957 * @return bool whether a change was made
959 function set_coursemodule_name($id, $name) {
960 global $CFG, $DB;
961 require_once($CFG->libdir . '/gradelib.php');
963 $cm = get_coursemodule_from_id('', $id, 0, false, MUST_EXIST);
965 $module = new \stdClass();
966 $module->id = $cm->instance;
968 // Escape strings as they would be by mform.
969 if (!empty($CFG->formatstringstriptags)) {
970 $module->name = clean_param($name, PARAM_TEXT);
971 } else {
972 $module->name = clean_param($name, PARAM_CLEANHTML);
974 if ($module->name === $cm->name || strval($module->name) === '') {
975 return false;
977 if (\core_text::strlen($module->name) > 255) {
978 throw new \moodle_exception('maximumchars', 'moodle', '', 255);
981 $module->timemodified = time();
982 $DB->update_record($cm->modname, $module);
983 $cm->name = $module->name;
984 \core\event\course_module_updated::create_from_cm($cm)->trigger();
985 rebuild_course_cache($cm->course, true);
987 // Attempt to update the grade item if relevant.
988 $grademodule = $DB->get_record($cm->modname, array('id' => $cm->instance));
989 $grademodule->cmidnumber = $cm->idnumber;
990 $grademodule->modname = $cm->modname;
991 grade_update_mod_grades($grademodule);
993 // Update calendar events with the new name.
994 course_module_update_calendar_events($cm->modname, $grademodule, $cm);
996 return true;
1000 * This function will handle the whole deletion process of a module. This includes calling
1001 * the modules delete_instance function, deleting files, events, grades, conditional data,
1002 * the data in the course_module and course_sections table and adding a module deletion
1003 * event to the DB.
1005 * @param int $cmid the course module id
1006 * @param bool $async whether or not to try to delete the module using an adhoc task. Async also depends on a plugin hook.
1007 * @throws moodle_exception
1008 * @since Moodle 2.5
1010 function course_delete_module($cmid, $async = false) {
1011 // Check the 'course_module_background_deletion_recommended' hook first.
1012 // Only use asynchronous deletion if at least one plugin returns true and if async deletion has been requested.
1013 // Both are checked because plugins should not be allowed to dictate the deletion behaviour, only support/decline it.
1014 // It's up to plugins to handle things like whether or not they are enabled.
1015 if ($async && $pluginsfunction = get_plugins_with_function('course_module_background_deletion_recommended')) {
1016 foreach ($pluginsfunction as $plugintype => $plugins) {
1017 foreach ($plugins as $pluginfunction) {
1018 if ($pluginfunction()) {
1019 return course_module_flag_for_async_deletion($cmid);
1025 global $CFG, $DB;
1027 require_once($CFG->libdir.'/gradelib.php');
1028 require_once($CFG->libdir.'/questionlib.php');
1029 require_once($CFG->dirroot.'/blog/lib.php');
1030 require_once($CFG->dirroot.'/calendar/lib.php');
1032 // Get the course module.
1033 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
1034 return true;
1037 // Get the module context.
1038 $modcontext = context_module::instance($cm->id);
1040 // Get the course module name.
1041 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
1043 // Get the file location of the delete_instance function for this module.
1044 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
1046 // Include the file required to call the delete_instance function for this module.
1047 if (file_exists($modlib)) {
1048 require_once($modlib);
1049 } else {
1050 throw new moodle_exception('cannotdeletemodulemissinglib', '', '', null,
1051 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
1054 $deleteinstancefunction = $modulename . '_delete_instance';
1056 // Ensure the delete_instance function exists for this module.
1057 if (!function_exists($deleteinstancefunction)) {
1058 throw new moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
1059 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
1062 // Allow plugins to use this course module before we completely delete it.
1063 if ($pluginsfunction = get_plugins_with_function('pre_course_module_delete')) {
1064 foreach ($pluginsfunction as $plugintype => $plugins) {
1065 foreach ($plugins as $pluginfunction) {
1066 $pluginfunction($cm);
1071 // Call the delete_instance function, if it returns false throw an exception.
1072 if (!$deleteinstancefunction($cm->instance)) {
1073 throw new moodle_exception('cannotdeletemoduleinstance', '', '', null,
1074 "Cannot delete the module $modulename (instance).");
1077 question_delete_activity($cm);
1079 // Remove all module files in case modules forget to do that.
1080 $fs = get_file_storage();
1081 $fs->delete_area_files($modcontext->id);
1083 // Delete events from calendar.
1084 if ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename))) {
1085 $coursecontext = context_course::instance($cm->course);
1086 foreach($events as $event) {
1087 $event->context = $coursecontext;
1088 $calendarevent = calendar_event::load($event);
1089 $calendarevent->delete();
1093 // Delete grade items, outcome items and grades attached to modules.
1094 if ($grade_items = grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $modulename,
1095 'iteminstance' => $cm->instance, 'courseid' => $cm->course))) {
1096 foreach ($grade_items as $grade_item) {
1097 $grade_item->delete('moddelete');
1101 // Delete associated blogs and blog tag instances.
1102 blog_remove_associations_for_module($modcontext->id);
1104 // Delete completion and availability data; it is better to do this even if the
1105 // features are not turned on, in case they were turned on previously (these will be
1106 // very quick on an empty table).
1107 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
1108 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
1109 'course' => $cm->course,
1110 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
1112 // Delete all tag instances associated with the instance of this module.
1113 core_tag_tag::delete_instances('mod_' . $modulename, null, $modcontext->id);
1114 core_tag_tag::remove_all_item_tags('core', 'course_modules', $cm->id);
1116 // Notify the competency subsystem.
1117 \core_competency\api::hook_course_module_deleted($cm);
1119 // Delete the context.
1120 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
1122 // Delete the module from the course_modules table.
1123 $DB->delete_records('course_modules', array('id' => $cm->id));
1125 // Delete module from that section.
1126 if (!delete_mod_from_section($cm->id, $cm->section)) {
1127 throw new moodle_exception('cannotdeletemodulefromsection', '', '', null,
1128 "Cannot delete the module $modulename (instance) from section.");
1131 // Trigger event for course module delete action.
1132 $event = \core\event\course_module_deleted::create(array(
1133 'courseid' => $cm->course,
1134 'context' => $modcontext,
1135 'objectid' => $cm->id,
1136 'other' => array(
1137 'modulename' => $modulename,
1138 'instanceid' => $cm->instance,
1141 $event->add_record_snapshot('course_modules', $cm);
1142 $event->trigger();
1143 rebuild_course_cache($cm->course, true);
1147 * Schedule a course module for deletion in the background using an adhoc task.
1149 * This method should not be called directly. Instead, please use course_delete_module($cmid, true), to denote async deletion.
1150 * The real deletion of the module is handled by the task, which calls 'course_delete_module($cmid)'.
1152 * @param int $cmid the course module id.
1153 * @return bool whether the module was successfully scheduled for deletion.
1154 * @throws \moodle_exception
1156 function course_module_flag_for_async_deletion($cmid) {
1157 global $CFG, $DB, $USER;
1158 require_once($CFG->libdir.'/gradelib.php');
1159 require_once($CFG->libdir.'/questionlib.php');
1160 require_once($CFG->dirroot.'/blog/lib.php');
1161 require_once($CFG->dirroot.'/calendar/lib.php');
1163 // Get the course module.
1164 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
1165 return true;
1168 // We need to be reasonably certain the deletion is going to succeed before we background the process.
1169 // Make the necessary delete_instance checks, etc. before proceeding further. Throw exceptions if required.
1171 // Get the course module name.
1172 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
1174 // Get the file location of the delete_instance function for this module.
1175 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
1177 // Include the file required to call the delete_instance function for this module.
1178 if (file_exists($modlib)) {
1179 require_once($modlib);
1180 } else {
1181 throw new \moodle_exception('cannotdeletemodulemissinglib', '', '', null,
1182 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
1185 $deleteinstancefunction = $modulename . '_delete_instance';
1187 // Ensure the delete_instance function exists for this module.
1188 if (!function_exists($deleteinstancefunction)) {
1189 throw new \moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
1190 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
1193 // We are going to defer the deletion as we can't be sure how long the module's pre_delete code will run for.
1194 $cm->deletioninprogress = '1';
1195 $DB->update_record('course_modules', $cm);
1197 // Create an adhoc task for the deletion of the course module. The task takes an array of course modules for removal.
1198 $removaltask = new \core_course\task\course_delete_modules();
1199 $removaltask->set_custom_data(array(
1200 'cms' => array($cm),
1201 'userid' => $USER->id,
1202 'realuserid' => \core\session\manager::get_realuser()->id
1205 // Queue the task for the next run.
1206 \core\task\manager::queue_adhoc_task($removaltask);
1208 // Reset the course cache to hide the module.
1209 rebuild_course_cache($cm->course, true);
1213 * Checks whether the given course has any course modules scheduled for adhoc deletion.
1215 * @param int $courseid the id of the course.
1216 * @param bool $onlygradable whether to check only gradable modules or all modules.
1217 * @return bool true if the course contains any modules pending deletion, false otherwise.
1219 function course_modules_pending_deletion(int $courseid, bool $onlygradable = false) : bool {
1220 if (empty($courseid)) {
1221 return false;
1224 if ($onlygradable) {
1225 // Fetch modules with grade items.
1226 if (!$coursegradeitems = grade_item::fetch_all(['itemtype' => 'mod', 'courseid' => $courseid])) {
1227 // Return early when there is none.
1228 return false;
1232 $modinfo = get_fast_modinfo($courseid);
1233 foreach ($modinfo->get_cms() as $module) {
1234 if ($module->deletioninprogress == '1') {
1235 if ($onlygradable) {
1236 // Check if the module being deleted is in the list of course modules with grade items.
1237 foreach ($coursegradeitems as $coursegradeitem) {
1238 if ($coursegradeitem->itemmodule == $module->modname && $coursegradeitem->iteminstance == $module->instance) {
1239 // The module being deleted is within the gradable modules.
1240 return true;
1243 } else {
1244 return true;
1248 return false;
1252 * Checks whether the course module, as defined by modulename and instanceid, is scheduled for deletion within the given course.
1254 * @param int $courseid the course id.
1255 * @param string $modulename the module name. E.g. 'assign', 'book', etc.
1256 * @param int $instanceid the module instance id.
1257 * @return bool true if the course module is pending deletion, false otherwise.
1259 function course_module_instance_pending_deletion($courseid, $modulename, $instanceid) {
1260 if (empty($courseid) || empty($modulename) || empty($instanceid)) {
1261 return false;
1263 $modinfo = get_fast_modinfo($courseid);
1264 $instances = $modinfo->get_instances_of($modulename);
1265 return isset($instances[$instanceid]) && $instances[$instanceid]->deletioninprogress;
1268 function delete_mod_from_section($modid, $sectionid) {
1269 global $DB;
1271 if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
1273 $modarray = explode(",", $section->sequence);
1275 if ($key = array_keys ($modarray, $modid)) {
1276 array_splice($modarray, $key[0], 1);
1277 $newsequence = implode(",", $modarray);
1278 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
1279 rebuild_course_cache($section->course, true);
1280 return true;
1281 } else {
1282 return false;
1286 return false;
1290 * This function updates the calendar events from the information stored in the module table and the course
1291 * module table.
1293 * @param string $modulename Module name
1294 * @param stdClass $instance Module object. Either the $instance or the $cm must be supplied.
1295 * @param stdClass $cm Course module object. Either the $instance or the $cm must be supplied.
1296 * @return bool Returns true if calendar events are updated.
1297 * @since Moodle 3.3.4
1299 function course_module_update_calendar_events($modulename, $instance = null, $cm = null) {
1300 global $DB;
1302 if (isset($instance) || isset($cm)) {
1304 if (!isset($instance)) {
1305 $instance = $DB->get_record($modulename, array('id' => $cm->instance), '*', MUST_EXIST);
1307 if (!isset($cm)) {
1308 $cm = get_coursemodule_from_instance($modulename, $instance->id, $instance->course);
1310 if (!empty($cm)) {
1311 course_module_calendar_event_update_process($instance, $cm);
1313 return true;
1315 return false;
1319 * Update all instances through out the site or in a course.
1321 * @param string $modulename Module type to update.
1322 * @param integer $courseid Course id to update events. 0 for the whole site.
1323 * @return bool Returns True if the update was successful.
1324 * @since Moodle 3.3.4
1326 function course_module_bulk_update_calendar_events($modulename, $courseid = 0) {
1327 global $DB;
1329 $instances = null;
1330 if ($courseid) {
1331 if (!$instances = $DB->get_records($modulename, array('course' => $courseid))) {
1332 return false;
1334 } else {
1335 if (!$instances = $DB->get_records($modulename)) {
1336 return false;
1340 foreach ($instances as $instance) {
1341 if ($cm = get_coursemodule_from_instance($modulename, $instance->id, $instance->course)) {
1342 course_module_calendar_event_update_process($instance, $cm);
1345 return true;
1349 * Calendar events for a module instance are updated.
1351 * @param stdClass $instance Module instance object.
1352 * @param stdClass $cm Course Module object.
1353 * @since Moodle 3.3.4
1355 function course_module_calendar_event_update_process($instance, $cm) {
1356 // We need to call *_refresh_events() first because some modules delete 'old' events at the end of the code which
1357 // will remove the completion events.
1358 $refresheventsfunction = $cm->modname . '_refresh_events';
1359 if (function_exists($refresheventsfunction)) {
1360 call_user_func($refresheventsfunction, $cm->course, $instance, $cm);
1362 $completionexpected = (!empty($cm->completionexpected)) ? $cm->completionexpected : null;
1363 \core_completion\api::update_completion_date_event($cm->id, $cm->modname, $instance, $completionexpected);
1367 * Moves a section within a course, from a position to another.
1368 * Be very careful: $section and $destination refer to section number,
1369 * not id!.
1371 * @param object $course
1372 * @param int $section Section number (not id!!!)
1373 * @param int $destination
1374 * @param bool $ignorenumsections
1375 * @return boolean Result
1377 function move_section_to($course, $section, $destination, $ignorenumsections = false) {
1378 /// Moves a whole course section up and down within the course
1379 global $USER, $DB;
1381 if (!$destination && $destination != 0) {
1382 return true;
1385 // compartibility with course formats using field 'numsections'
1386 $courseformatoptions = course_get_format($course)->get_format_options();
1387 if ((!$ignorenumsections && array_key_exists('numsections', $courseformatoptions) &&
1388 ($destination > $courseformatoptions['numsections'])) || ($destination < 1)) {
1389 return false;
1392 // Get all sections for this course and re-order them (2 of them should now share the same section number)
1393 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
1394 'section ASC, id ASC', 'id, section')) {
1395 return false;
1398 $movedsections = reorder_sections($sections, $section, $destination);
1400 // Update all sections. Do this in 2 steps to avoid breaking database
1401 // uniqueness constraint
1402 $transaction = $DB->start_delegated_transaction();
1403 foreach ($movedsections as $id => $position) {
1404 if ($sections[$id] !== $position) {
1405 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
1408 foreach ($movedsections as $id => $position) {
1409 if ($sections[$id] !== $position) {
1410 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
1414 // If we move the highlighted section itself, then just highlight the destination.
1415 // Adjust the higlighted section location if we move something over it either direction.
1416 if ($section == $course->marker) {
1417 course_set_marker($course->id, $destination);
1418 } elseif ($section > $course->marker && $course->marker >= $destination) {
1419 course_set_marker($course->id, $course->marker+1);
1420 } elseif ($section < $course->marker && $course->marker <= $destination) {
1421 course_set_marker($course->id, $course->marker-1);
1424 $transaction->allow_commit();
1425 rebuild_course_cache($course->id, true);
1426 return true;
1430 * This method will delete a course section and may delete all modules inside it.
1432 * No permissions are checked here, use {@link course_can_delete_section()} to
1433 * check if section can actually be deleted.
1435 * @param int|stdClass $course
1436 * @param int|stdClass|section_info $section
1437 * @param bool $forcedeleteifnotempty if set to false section will not be deleted if it has modules in it.
1438 * @param bool $async whether or not to try to delete the section using an adhoc task. Async also depends on a plugin hook.
1439 * @return bool whether section was deleted
1441 function course_delete_section($course, $section, $forcedeleteifnotempty = true, $async = false) {
1442 global $DB;
1444 // Prepare variables.
1445 $courseid = (is_object($course)) ? $course->id : (int)$course;
1446 $sectionnum = (is_object($section)) ? $section->section : (int)$section;
1447 $section = $DB->get_record('course_sections', array('course' => $courseid, 'section' => $sectionnum));
1448 if (!$section) {
1449 // No section exists, can't proceed.
1450 return false;
1453 // Check the 'course_module_background_deletion_recommended' hook first.
1454 // Only use asynchronous deletion if at least one plugin returns true and if async deletion has been requested.
1455 // Both are checked because plugins should not be allowed to dictate the deletion behaviour, only support/decline it.
1456 // It's up to plugins to handle things like whether or not they are enabled.
1457 if ($async && $pluginsfunction = get_plugins_with_function('course_module_background_deletion_recommended')) {
1458 foreach ($pluginsfunction as $plugintype => $plugins) {
1459 foreach ($plugins as $pluginfunction) {
1460 if ($pluginfunction()) {
1461 return course_delete_section_async($section, $forcedeleteifnotempty);
1467 $format = course_get_format($course);
1468 $sectionname = $format->get_section_name($section);
1470 // Delete section.
1471 $result = $format->delete_section($section, $forcedeleteifnotempty);
1473 // Trigger an event for course section deletion.
1474 if ($result) {
1475 $context = context_course::instance($courseid);
1476 $event = \core\event\course_section_deleted::create(
1477 array(
1478 'objectid' => $section->id,
1479 'courseid' => $courseid,
1480 'context' => $context,
1481 'other' => array(
1482 'sectionnum' => $section->section,
1483 'sectionname' => $sectionname,
1487 $event->add_record_snapshot('course_sections', $section);
1488 $event->trigger();
1490 return $result;
1494 * Course section deletion, using an adhoc task for deletion of the modules it contains.
1495 * 1. Schedule all modules within the section for adhoc removal.
1496 * 2. Move all modules to course section 0.
1497 * 3. Delete the resulting empty section.
1499 * @param \stdClass $section the section to schedule for deletion.
1500 * @param bool $forcedeleteifnotempty whether to force section deletion if it contains modules.
1501 * @return bool true if the section was scheduled for deletion, false otherwise.
1503 function course_delete_section_async($section, $forcedeleteifnotempty = true) {
1504 global $DB, $USER;
1506 // Objects only, and only valid ones.
1507 if (!is_object($section) || empty($section->id)) {
1508 return false;
1511 // Does the object currently exist in the DB for removal (check for stale objects).
1512 $section = $DB->get_record('course_sections', array('id' => $section->id));
1513 if (!$section || !$section->section) {
1514 // No section exists, or the section is 0. Can't proceed.
1515 return false;
1518 // Check whether the section can be removed.
1519 if (!$forcedeleteifnotempty && (!empty($section->sequence) || !empty($section->summary))) {
1520 return false;
1523 $format = course_get_format($section->course);
1524 $sectionname = $format->get_section_name($section);
1526 // Flag those modules having no existing deletion flag. Some modules may have been scheduled for deletion manually, and we don't
1527 // want to create additional adhoc deletion tasks for these. Moving them to section 0 will suffice.
1528 $affectedmods = $DB->get_records_select('course_modules', 'course = ? AND section = ? AND deletioninprogress <> ?',
1529 [$section->course, $section->id, 1], '', 'id');
1530 $DB->set_field('course_modules', 'deletioninprogress', '1', ['course' => $section->course, 'section' => $section->id]);
1532 // Move all modules to section 0.
1533 $modules = $DB->get_records('course_modules', ['section' => $section->id], '');
1534 $sectionzero = $DB->get_record('course_sections', ['course' => $section->course, 'section' => '0']);
1535 foreach ($modules as $mod) {
1536 moveto_module($mod, $sectionzero);
1539 // Create and queue an adhoc task for the deletion of the modules.
1540 $removaltask = new \core_course\task\course_delete_modules();
1541 $data = array(
1542 'cms' => $affectedmods,
1543 'userid' => $USER->id,
1544 'realuserid' => \core\session\manager::get_realuser()->id
1546 $removaltask->set_custom_data($data);
1547 \core\task\manager::queue_adhoc_task($removaltask);
1549 // Delete the now empty section, passing in only the section number, which forces the function to fetch a new object.
1550 // The refresh is needed because the section->sequence is now stale.
1551 $result = $format->delete_section($section->section, $forcedeleteifnotempty);
1553 // Trigger an event for course section deletion.
1554 if ($result) {
1555 $context = \context_course::instance($section->course);
1556 $event = \core\event\course_section_deleted::create(
1557 array(
1558 'objectid' => $section->id,
1559 'courseid' => $section->course,
1560 'context' => $context,
1561 'other' => array(
1562 'sectionnum' => $section->section,
1563 'sectionname' => $sectionname,
1567 $event->add_record_snapshot('course_sections', $section);
1568 $event->trigger();
1570 rebuild_course_cache($section->course, true);
1572 return $result;
1576 * Updates the course section
1578 * This function does not check permissions or clean values - this has to be done prior to calling it.
1580 * @param int|stdClass $course
1581 * @param stdClass $section record from course_sections table - it will be updated with the new values
1582 * @param array|stdClass $data
1584 function course_update_section($course, $section, $data) {
1585 global $DB;
1587 $courseid = (is_object($course)) ? $course->id : (int)$course;
1589 // Some fields can not be updated using this method.
1590 $data = array_diff_key((array)$data, array('id', 'course', 'section', 'sequence'));
1591 $changevisibility = (array_key_exists('visible', $data) && (bool)$data['visible'] != (bool)$section->visible);
1592 if (array_key_exists('name', $data) && \core_text::strlen($data['name']) > 255) {
1593 throw new moodle_exception('maximumchars', 'moodle', '', 255);
1596 // Update record in the DB and course format options.
1597 $data['id'] = $section->id;
1598 $data['timemodified'] = time();
1599 $DB->update_record('course_sections', $data);
1600 rebuild_course_cache($courseid, true);
1601 course_get_format($courseid)->update_section_format_options($data);
1603 // Update fields of the $section object.
1604 foreach ($data as $key => $value) {
1605 if (property_exists($section, $key)) {
1606 $section->$key = $value;
1610 // Trigger an event for course section update.
1611 $event = \core\event\course_section_updated::create(
1612 array(
1613 'objectid' => $section->id,
1614 'courseid' => $courseid,
1615 'context' => context_course::instance($courseid),
1616 'other' => array('sectionnum' => $section->section)
1619 $event->trigger();
1621 // If section visibility was changed, hide the modules in this section too.
1622 if ($changevisibility && !empty($section->sequence)) {
1623 $modules = explode(',', $section->sequence);
1624 foreach ($modules as $moduleid) {
1625 if ($cm = get_coursemodule_from_id(null, $moduleid, $courseid)) {
1626 if ($data['visible']) {
1627 // As we unhide the section, we use the previously saved visibility stored in visibleold.
1628 set_coursemodule_visible($moduleid, $cm->visibleold, $cm->visibleoncoursepage);
1629 } else {
1630 // We hide the section, so we hide the module but we store the original state in visibleold.
1631 set_coursemodule_visible($moduleid, 0, $cm->visibleoncoursepage);
1632 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id' => $moduleid));
1634 \core\event\course_module_updated::create_from_cm($cm)->trigger();
1641 * Checks if the current user can delete a section (if course format allows it and user has proper permissions).
1643 * @param int|stdClass $course
1644 * @param int|stdClass|section_info $section
1645 * @return bool
1647 function course_can_delete_section($course, $section) {
1648 if (is_object($section)) {
1649 $section = $section->section;
1651 if (!$section) {
1652 // Not possible to delete 0-section.
1653 return false;
1655 // Course format should allow to delete sections.
1656 if (!course_get_format($course)->can_delete_section($section)) {
1657 return false;
1659 // Make sure user has capability to update course and move sections.
1660 $context = context_course::instance(is_object($course) ? $course->id : $course);
1661 if (!has_all_capabilities(array('moodle/course:movesections', 'moodle/course:update'), $context)) {
1662 return false;
1664 // Make sure user has capability to delete each activity in this section.
1665 $modinfo = get_fast_modinfo($course);
1666 if (!empty($modinfo->sections[$section])) {
1667 foreach ($modinfo->sections[$section] as $cmid) {
1668 if (!has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
1669 return false;
1673 return true;
1677 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
1678 * an original position number and a target position number, rebuilds the array so that the
1679 * move is made without any duplication of section positions.
1680 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
1681 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
1683 * @param array $sections
1684 * @param int $origin_position
1685 * @param int $target_position
1686 * @return array
1688 function reorder_sections($sections, $origin_position, $target_position) {
1689 if (!is_array($sections)) {
1690 return false;
1693 // We can't move section position 0
1694 if ($origin_position < 1) {
1695 echo "We can't move section position 0";
1696 return false;
1699 // Locate origin section in sections array
1700 if (!$origin_key = array_search($origin_position, $sections)) {
1701 echo "searched position not in sections array";
1702 return false; // searched position not in sections array
1705 // Extract origin section
1706 $origin_section = $sections[$origin_key];
1707 unset($sections[$origin_key]);
1709 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
1710 $found = false;
1711 $append_array = array();
1712 foreach ($sections as $id => $position) {
1713 if ($found) {
1714 $append_array[$id] = $position;
1715 unset($sections[$id]);
1717 if ($position == $target_position) {
1718 if ($target_position < $origin_position) {
1719 $append_array[$id] = $position;
1720 unset($sections[$id]);
1722 $found = true;
1726 // Append moved section
1727 $sections[$origin_key] = $origin_section;
1729 // Append rest of array (if applicable)
1730 if (!empty($append_array)) {
1731 foreach ($append_array as $id => $position) {
1732 $sections[$id] = $position;
1736 // Renumber positions
1737 $position = 0;
1738 foreach ($sections as $id => $p) {
1739 $sections[$id] = $position;
1740 $position++;
1743 return $sections;
1748 * Move the module object $mod to the specified $section
1749 * If $beforemod exists then that is the module
1750 * before which $modid should be inserted
1752 * @param stdClass|cm_info $mod
1753 * @param stdClass|section_info $section
1754 * @param int|stdClass $beforemod id or object with field id corresponding to the module
1755 * before which the module needs to be included. Null for inserting in the
1756 * end of the section
1757 * @return int new value for module visibility (0 or 1)
1759 function moveto_module($mod, $section, $beforemod=NULL) {
1760 global $OUTPUT, $DB;
1762 // Current module visibility state - return value of this function.
1763 $modvisible = $mod->visible;
1765 // Remove original module from original section.
1766 if (! delete_mod_from_section($mod->id, $mod->section)) {
1767 echo $OUTPUT->notification("Could not delete module from existing section");
1770 // Add the module into the new section.
1771 course_add_cm_to_section($section->course, $mod->id, $section->section, $beforemod);
1773 // If moving to a hidden section then hide module.
1774 if ($mod->section != $section->id) {
1775 if (!$section->visible && $mod->visible) {
1776 // Module was visible but must become hidden after moving to hidden section.
1777 $modvisible = 0;
1778 set_coursemodule_visible($mod->id, 0);
1779 // Set visibleold to 1 so module will be visible when section is made visible.
1780 $DB->set_field('course_modules', 'visibleold', 1, array('id' => $mod->id));
1782 if ($section->visible && !$mod->visible) {
1783 // Hidden module was moved to the visible section, restore the module visibility from visibleold.
1784 set_coursemodule_visible($mod->id, $mod->visibleold);
1785 $modvisible = $mod->visibleold;
1789 return $modvisible;
1793 * Returns the list of all editing actions that current user can perform on the module
1795 * @param cm_info $mod The module to produce editing buttons for
1796 * @param int $indent The current indenting (default -1 means no move left-right actions)
1797 * @param int $sr The section to link back to (used for creating the links)
1798 * @return array array of action_link or pix_icon objects
1800 function course_get_cm_edit_actions(cm_info $mod, $indent = -1, $sr = null) {
1801 global $COURSE, $SITE, $CFG;
1803 static $str;
1805 $coursecontext = context_course::instance($mod->course);
1806 $modcontext = context_module::instance($mod->id);
1807 $courseformat = course_get_format($mod->get_course());
1809 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
1810 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
1812 // No permission to edit anything.
1813 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
1814 return array();
1817 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
1819 if (!isset($str)) {
1820 $str = get_strings(array('delete', 'move', 'moveright', 'moveleft',
1821 'editsettings', 'duplicate', 'modhide', 'makeavailable', 'makeunavailable', 'modshow'), 'moodle');
1822 $str->assign = get_string('assignroles', 'role');
1823 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
1824 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
1825 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
1828 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
1830 if ($sr !== null) {
1831 $baseurl->param('sr', $sr);
1833 $actions = array();
1835 // Update.
1836 if ($hasmanageactivities) {
1837 $actions['update'] = new action_menu_link_secondary(
1838 new moodle_url($baseurl, array('update' => $mod->id)),
1839 new pix_icon('t/edit', '', 'moodle', array('class' => 'iconsmall')),
1840 $str->editsettings,
1841 array('class' => 'editing_update', 'data-action' => 'update')
1845 // Move (only for component compatible formats).
1846 if ($courseformat->supports_components()) {
1847 $actions['move'] = new action_menu_link_secondary(
1848 new moodle_url($baseurl, [
1849 'sesskey' => sesskey(),
1850 'copy' => $mod->id,
1852 new pix_icon('i/dragdrop', '', 'moodle', ['class' => 'iconsmall']),
1853 $str->move,
1855 'class' => 'editing_movecm',
1856 'data-action' => 'moveCm',
1857 'data-id' => $mod->id,
1862 // Indent.
1863 if ($hasmanageactivities && $indent >= 0) {
1864 $indentlimits = new stdClass();
1865 $indentlimits->min = 0;
1866 $indentlimits->max = 16;
1867 if (right_to_left()) { // Exchange arrows on RTL
1868 $rightarrow = 't/left';
1869 $leftarrow = 't/right';
1870 } else {
1871 $rightarrow = 't/right';
1872 $leftarrow = 't/left';
1875 if ($indent >= $indentlimits->max) {
1876 $enabledclass = 'hidden';
1877 } else {
1878 $enabledclass = '';
1880 $actions['moveright'] = new action_menu_link_secondary(
1881 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
1882 new pix_icon($rightarrow, '', 'moodle', array('class' => 'iconsmall')),
1883 $str->moveright,
1884 array('class' => 'editing_moveright ' . $enabledclass, 'data-action' => 'moveright',
1885 'data-keepopen' => true, 'data-sectionreturn' => $sr)
1888 if ($indent <= $indentlimits->min) {
1889 $enabledclass = 'hidden';
1890 } else {
1891 $enabledclass = '';
1893 $actions['moveleft'] = new action_menu_link_secondary(
1894 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
1895 new pix_icon($leftarrow, '', 'moodle', array('class' => 'iconsmall')),
1896 $str->moveleft,
1897 array('class' => 'editing_moveleft ' . $enabledclass, 'data-action' => 'moveleft',
1898 'data-keepopen' => true, 'data-sectionreturn' => $sr)
1903 // Hide/Show/Available/Unavailable.
1904 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
1905 $allowstealth = !empty($CFG->allowstealth) && $courseformat->allow_stealth_module_visibility($mod, $mod->get_section_info());
1907 $sectionvisible = $mod->get_section_info()->visible;
1908 // The module on the course page may be in one of the following states:
1909 // - Available and displayed on the course page ($displayedoncoursepage);
1910 // - Not available and not displayed on the course page ($unavailable);
1911 // - Available but not displayed on the course page ($stealth) - this can also be a visible activity in a hidden section.
1912 $displayedoncoursepage = $mod->visible && $mod->visibleoncoursepage && $sectionvisible;
1913 $unavailable = !$mod->visible;
1914 $stealth = $mod->visible && (!$mod->visibleoncoursepage || !$sectionvisible);
1915 if ($displayedoncoursepage) {
1916 $actions['hide'] = new action_menu_link_secondary(
1917 new moodle_url($baseurl, array('hide' => $mod->id)),
1918 new pix_icon('t/hide', '', 'moodle', array('class' => 'iconsmall')),
1919 $str->modhide,
1920 array('class' => 'editing_hide', 'data-action' => 'hide')
1922 } else if (!$displayedoncoursepage && $sectionvisible) {
1923 // Offer to "show" only if the section is visible.
1924 $actions['show'] = new action_menu_link_secondary(
1925 new moodle_url($baseurl, array('show' => $mod->id)),
1926 new pix_icon('t/show', '', 'moodle', array('class' => 'iconsmall')),
1927 $str->modshow,
1928 array('class' => 'editing_show', 'data-action' => 'show')
1932 if ($stealth) {
1933 // When making the "stealth" module unavailable we perform the same action as hiding the visible module.
1934 $actions['hide'] = new action_menu_link_secondary(
1935 new moodle_url($baseurl, array('hide' => $mod->id)),
1936 new pix_icon('t/unblock', '', 'moodle', array('class' => 'iconsmall')),
1937 $str->makeunavailable,
1938 array('class' => 'editing_makeunavailable', 'data-action' => 'hide', 'data-sectionreturn' => $sr)
1940 } else if ($unavailable && (!$sectionvisible || $allowstealth) && $mod->has_view()) {
1941 // Allow to make visually hidden module available in gradebook and other reports by making it a "stealth" module.
1942 // When the section is hidden it is an equivalent of "showing" the module.
1943 // Activities without the link (i.e. labels) can not be made available but hidden on course page.
1944 $action = $sectionvisible ? 'stealth' : 'show';
1945 $actions[$action] = new action_menu_link_secondary(
1946 new moodle_url($baseurl, array($action => $mod->id)),
1947 new pix_icon('t/block', '', 'moodle', array('class' => 'iconsmall')),
1948 $str->makeavailable,
1949 array('class' => 'editing_makeavailable', 'data-action' => $action, 'data-sectionreturn' => $sr)
1954 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
1955 if (has_all_capabilities($dupecaps, $coursecontext) &&
1956 plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2) &&
1957 course_allowed_module($mod->get_course(), $mod->modname)) {
1958 $actions['duplicate'] = new action_menu_link_secondary(
1959 new moodle_url($baseurl, array('duplicate' => $mod->id)),
1960 new pix_icon('t/copy', '', 'moodle', array('class' => 'iconsmall')),
1961 $str->duplicate,
1962 array('class' => 'editing_duplicate', 'data-action' => 'duplicate', 'data-sectionreturn' => $sr)
1966 // Assign.
1967 if (has_capability('moodle/role:assign', $modcontext)){
1968 $actions['assign'] = new action_menu_link_secondary(
1969 new moodle_url('/admin/roles/assign.php', array('contextid' => $modcontext->id)),
1970 new pix_icon('t/assignroles', '', 'moodle', array('class' => 'iconsmall')),
1971 $str->assign,
1972 array('class' => 'editing_assign', 'data-action' => 'assignroles', 'data-sectionreturn' => $sr)
1976 // Delete.
1977 if ($hasmanageactivities) {
1978 $actions['delete'] = new action_menu_link_secondary(
1979 new moodle_url($baseurl, array('delete' => $mod->id)),
1980 new pix_icon('t/delete', '', 'moodle', array('class' => 'iconsmall')),
1981 $str->delete,
1982 array('class' => 'editing_delete', 'data-action' => 'delete', 'data-sectionreturn' => $sr)
1986 return $actions;
1990 * Returns the move action.
1992 * @param cm_info $mod The module to produce a move button for
1993 * @param int $sr The section to link back to (used for creating the links)
1994 * @return The markup for the move action, or an empty string if not available.
1996 function course_get_cm_move(cm_info $mod, $sr = null) {
1997 global $OUTPUT;
1999 static $str;
2000 static $baseurl;
2002 $modcontext = context_module::instance($mod->id);
2003 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
2005 if (!isset($str)) {
2006 $str = get_strings(array('move'));
2009 if (!isset($baseurl)) {
2010 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
2012 if ($sr !== null) {
2013 $baseurl->param('sr', $sr);
2017 if ($hasmanageactivities) {
2018 $pixicon = 'i/dragdrop';
2020 if (!course_ajax_enabled($mod->get_course())) {
2021 // Override for course frontpage until we get drag/drop working there.
2022 $pixicon = 't/move';
2025 $attributes = [
2026 'class' => 'editing_move',
2027 'data-action' => 'move',
2028 'data-sectionreturn' => $sr,
2029 'title' => $str->move,
2030 'aria-label' => $str->move,
2032 return html_writer::link(
2033 new moodle_url($baseurl, ['copy' => $mod->id]),
2034 $OUTPUT->pix_icon($pixicon, '', 'moodle', ['class' => 'iconsmall']),
2035 $attributes
2038 return '';
2042 * given a course object with shortname & fullname, this function will
2043 * truncate the the number of chars allowed and add ... if it was too long
2045 function course_format_name ($course,$max=100) {
2047 $context = context_course::instance($course->id);
2048 $shortname = format_string($course->shortname, true, array('context' => $context));
2049 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
2050 $str = $shortname.': '. $fullname;
2051 if (core_text::strlen($str) <= $max) {
2052 return $str;
2054 else {
2055 return core_text::substr($str,0,$max-3).'...';
2060 * Is the user allowed to add this type of module to this course?
2061 * @param object $course the course settings. Only $course->id is used.
2062 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
2063 * @param \stdClass $user the user to check, defaults to the global user if not provided.
2064 * @return bool whether the current user is allowed to add this type of module to this course.
2066 function course_allowed_module($course, $modname, \stdClass $user = null) {
2067 global $USER;
2068 $user = $user ?? $USER;
2069 if (is_numeric($modname)) {
2070 throw new coding_exception('Function course_allowed_module no longer
2071 supports numeric module ids. Please update your code to pass the module name.');
2074 $capability = 'mod/' . $modname . ':addinstance';
2075 if (!get_capability_info($capability)) {
2076 // Debug warning that the capability does not exist, but no more than once per page.
2077 static $warned = array();
2078 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
2079 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
2080 debugging('The module ' . $modname . ' does not define the standard capability ' .
2081 $capability , DEBUG_DEVELOPER);
2082 $warned[$modname] = 1;
2085 // If the capability does not exist, the module can always be added.
2086 return true;
2089 $coursecontext = context_course::instance($course->id);
2090 return has_capability($capability, $coursecontext, $user);
2094 * Efficiently moves many courses around while maintaining
2095 * sortorder in order.
2097 * @param array $courseids is an array of course ids
2098 * @param int $categoryid
2099 * @return bool success
2101 function move_courses($courseids, $categoryid) {
2102 global $DB;
2104 if (empty($courseids)) {
2105 // Nothing to do.
2106 return false;
2109 if (!$category = $DB->get_record('course_categories', array('id' => $categoryid))) {
2110 return false;
2113 $courseids = array_reverse($courseids);
2114 $newparent = context_coursecat::instance($category->id);
2115 $i = 1;
2117 list($where, $params) = $DB->get_in_or_equal($courseids);
2118 $dbcourses = $DB->get_records_select('course', 'id ' . $where, $params, '', 'id, category, shortname, fullname');
2119 foreach ($dbcourses as $dbcourse) {
2120 $course = new stdClass();
2121 $course->id = $dbcourse->id;
2122 $course->timemodified = time();
2123 $course->category = $category->id;
2124 $course->sortorder = $category->sortorder + get_max_courses_in_category() - $i++;
2125 if ($category->visible == 0) {
2126 // Hide the course when moving into hidden category, do not update the visibleold flag - we want to get
2127 // to previous state if somebody unhides the category.
2128 $course->visible = 0;
2131 $DB->update_record('course', $course);
2133 // Update context, so it can be passed to event.
2134 $context = context_course::instance($course->id);
2135 $context->update_moved($newparent);
2137 // Trigger a course updated event.
2138 $event = \core\event\course_updated::create(array(
2139 'objectid' => $course->id,
2140 'context' => context_course::instance($course->id),
2141 'other' => array('shortname' => $dbcourse->shortname,
2142 'fullname' => $dbcourse->fullname,
2143 'updatedfields' => array('category' => $category->id))
2145 $event->set_legacy_logdata(array($course->id, 'course', 'move', 'edit.php?id=' . $course->id, $course->id));
2146 $event->trigger();
2148 fix_course_sortorder();
2149 cache_helper::purge_by_event('changesincourse');
2151 return true;
2155 * Returns the display name of the given section that the course prefers
2157 * Implementation of this function is provided by course format
2158 * @see core_courseformat\base::get_section_name()
2160 * @param int|stdClass $courseorid The course to get the section name for (object or just course id)
2161 * @param int|stdClass $section Section object from database or just field course_sections.section
2162 * @return string Display name that the course format prefers, e.g. "Week 2"
2164 function get_section_name($courseorid, $section) {
2165 return course_get_format($courseorid)->get_section_name($section);
2169 * Tells if current course format uses sections
2171 * @param string $format Course format ID e.g. 'weeks' $course->format
2172 * @return bool
2174 function course_format_uses_sections($format) {
2175 $course = new stdClass();
2176 $course->format = $format;
2177 return course_get_format($course)->uses_sections();
2181 * Returns the information about the ajax support in the given source format
2183 * The returned object's property (boolean)capable indicates that
2184 * the course format supports Moodle course ajax features.
2186 * @param string $format
2187 * @return stdClass
2189 function course_format_ajax_support($format) {
2190 $course = new stdClass();
2191 $course->format = $format;
2192 return course_get_format($course)->supports_ajax();
2196 * Can the current user delete this course?
2197 * Course creators have exception,
2198 * 1 day after the creation they can sill delete the course.
2199 * @param int $courseid
2200 * @return boolean
2202 function can_delete_course($courseid) {
2203 global $USER;
2205 $context = context_course::instance($courseid);
2207 if (has_capability('moodle/course:delete', $context)) {
2208 return true;
2211 // hack: now try to find out if creator created this course recently (1 day)
2212 if (!has_capability('moodle/course:create', $context)) {
2213 return false;
2216 $since = time() - 60*60*24;
2217 $course = get_course($courseid);
2219 if ($course->timecreated < $since) {
2220 return false; // Return if the course was not created in last 24 hours.
2223 $logmanger = get_log_manager();
2224 $readers = $logmanger->get_readers('\core\log\sql_reader');
2225 $reader = reset($readers);
2227 if (empty($reader)) {
2228 return false; // No log reader found.
2231 // A proper reader.
2232 $select = "userid = :userid AND courseid = :courseid AND eventname = :eventname AND timecreated > :since";
2233 $params = array('userid' => $USER->id, 'since' => $since, 'courseid' => $course->id, 'eventname' => '\core\event\course_created');
2235 return (bool)$reader->get_events_select_count($select, $params);
2239 * Save the Your name for 'Some role' strings.
2241 * @param integer $courseid the id of this course.
2242 * @param array $data the data that came from the course settings form.
2244 function save_local_role_names($courseid, $data) {
2245 global $DB;
2246 $context = context_course::instance($courseid);
2248 foreach ($data as $fieldname => $value) {
2249 if (strpos($fieldname, 'role_') !== 0) {
2250 continue;
2252 list($ignored, $roleid) = explode('_', $fieldname);
2254 // make up our mind whether we want to delete, update or insert
2255 if (!$value) {
2256 $DB->delete_records('role_names', array('contextid' => $context->id, 'roleid' => $roleid));
2258 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id, 'roleid' => $roleid))) {
2259 $rolename->name = $value;
2260 $DB->update_record('role_names', $rolename);
2262 } else {
2263 $rolename = new stdClass;
2264 $rolename->contextid = $context->id;
2265 $rolename->roleid = $roleid;
2266 $rolename->name = $value;
2267 $DB->insert_record('role_names', $rolename);
2269 // This will ensure the course contacts cache is purged..
2270 core_course_category::role_assignment_changed($roleid, $context);
2275 * Returns options to use in course overviewfiles filemanager
2277 * @param null|stdClass|core_course_list_element|int $course either object that has 'id' property or just the course id;
2278 * may be empty if course does not exist yet (course create form)
2279 * @return array|null array of options such as maxfiles, maxbytes, accepted_types, etc.
2280 * or null if overviewfiles are disabled
2282 function course_overviewfiles_options($course) {
2283 global $CFG;
2284 if (empty($CFG->courseoverviewfileslimit)) {
2285 return null;
2288 // Create accepted file types based on config value, falling back to default all.
2289 $acceptedtypes = (new \core_form\filetypes_util)->normalize_file_types($CFG->courseoverviewfilesext);
2290 if (in_array('*', $acceptedtypes) || empty($acceptedtypes)) {
2291 $acceptedtypes = '*';
2294 $options = array(
2295 'maxfiles' => $CFG->courseoverviewfileslimit,
2296 'maxbytes' => $CFG->maxbytes,
2297 'subdirs' => 0,
2298 'accepted_types' => $acceptedtypes
2300 if (!empty($course->id)) {
2301 $options['context'] = context_course::instance($course->id);
2302 } else if (is_int($course) && $course > 0) {
2303 $options['context'] = context_course::instance($course);
2305 return $options;
2309 * Create a course and either return a $course object
2311 * Please note this functions does not verify any access control,
2312 * the calling code is responsible for all validation (usually it is the form definition).
2314 * @param array $editoroptions course description editor options
2315 * @param object $data - all the data needed for an entry in the 'course' table
2316 * @return object new course instance
2318 function create_course($data, $editoroptions = NULL) {
2319 global $DB, $CFG;
2321 //check the categoryid - must be given for all new courses
2322 $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
2324 // Check if the shortname already exists.
2325 if (!empty($data->shortname)) {
2326 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
2327 throw new moodle_exception('shortnametaken', '', '', $data->shortname);
2331 // Check if the idnumber already exists.
2332 if (!empty($data->idnumber)) {
2333 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
2334 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber);
2338 if (empty($CFG->enablecourserelativedates)) {
2339 // Make sure we're not setting the relative dates mode when the setting is disabled.
2340 unset($data->relativedatesmode);
2343 if ($errorcode = course_validate_dates((array)$data)) {
2344 throw new moodle_exception($errorcode);
2347 // Check if timecreated is given.
2348 $data->timecreated = !empty($data->timecreated) ? $data->timecreated : time();
2349 $data->timemodified = $data->timecreated;
2351 // place at beginning of any category
2352 $data->sortorder = 0;
2354 if ($editoroptions) {
2355 // summary text is updated later, we need context to store the files first
2356 $data->summary = '';
2357 $data->summary_format = FORMAT_HTML;
2360 // Get default completion settings as a fallback in case the enablecompletion field is not set.
2361 $courseconfig = get_config('moodlecourse');
2362 $defaultcompletion = !empty($CFG->enablecompletion) ? $courseconfig->enablecompletion : COMPLETION_DISABLED;
2363 $enablecompletion = $data->enablecompletion ?? $defaultcompletion;
2364 // Unset showcompletionconditions when completion tracking is not enabled for the course.
2365 if ($enablecompletion == COMPLETION_DISABLED) {
2366 unset($data->showcompletionconditions);
2367 } else if (!isset($data->showcompletionconditions)) {
2368 // Show completion conditions should have a default value when completion is enabled. Set it to the site defaults.
2369 // This scenario can happen when a course is created through data generators or through a web service.
2370 $data->showcompletionconditions = $courseconfig->showcompletionconditions;
2373 if (!isset($data->visible)) {
2374 // data not from form, add missing visibility info
2375 $data->visible = $category->visible;
2377 $data->visibleold = $data->visible;
2379 $newcourseid = $DB->insert_record('course', $data);
2380 $context = context_course::instance($newcourseid, MUST_EXIST);
2382 if ($editoroptions) {
2383 // Save the files used in the summary editor and store
2384 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2385 $DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid));
2386 $DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid));
2388 if ($overviewfilesoptions = course_overviewfiles_options($newcourseid)) {
2389 // Save the course overviewfiles
2390 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2393 // update course format options
2394 course_get_format($newcourseid)->update_course_format_options($data);
2396 $course = course_get_format($newcourseid)->get_course();
2398 fix_course_sortorder();
2399 // purge appropriate caches in case fix_course_sortorder() did not change anything
2400 cache_helper::purge_by_event('changesincourse');
2402 // Trigger a course created event.
2403 $event = \core\event\course_created::create(array(
2404 'objectid' => $course->id,
2405 'context' => context_course::instance($course->id),
2406 'other' => array('shortname' => $course->shortname,
2407 'fullname' => $course->fullname)
2410 $event->trigger();
2412 // Setup the blocks
2413 blocks_add_default_course_blocks($course);
2415 // Create default section and initial sections if specified (unless they've already been created earlier).
2416 // We do not want to call course_create_sections_if_missing() because to avoid creating course cache.
2417 $numsections = isset($data->numsections) ? $data->numsections : 0;
2418 $existingsections = $DB->get_fieldset_sql('SELECT section from {course_sections} WHERE course = ?', [$newcourseid]);
2419 $newsections = array_diff(range(0, $numsections), $existingsections);
2420 foreach ($newsections as $sectionnum) {
2421 course_create_section($newcourseid, $sectionnum, true);
2424 // Save any custom role names.
2425 save_local_role_names($course->id, (array)$data);
2427 // set up enrolments
2428 enrol_course_updated(true, $course, $data);
2430 // Update course tags.
2431 if (isset($data->tags)) {
2432 core_tag_tag::set_item_tags('core', 'course', $course->id, context_course::instance($course->id), $data->tags);
2435 // Save custom fields if there are any of them in the form.
2436 $handler = core_course\customfield\course_handler::create();
2437 // Make sure to set the handler's parent context first.
2438 $coursecatcontext = context_coursecat::instance($category->id);
2439 $handler->set_parent_context($coursecatcontext);
2440 // Save the custom field data.
2441 $data->id = $course->id;
2442 $handler->instance_form_save($data, true);
2444 return $course;
2448 * Update a course.
2450 * Please note this functions does not verify any access control,
2451 * the calling code is responsible for all validation (usually it is the form definition).
2453 * @param object $data - all the data needed for an entry in the 'course' table
2454 * @param array $editoroptions course description editor options
2455 * @return void
2457 function update_course($data, $editoroptions = NULL) {
2458 global $DB, $CFG;
2460 // Prevent changes on front page course.
2461 if ($data->id == SITEID) {
2462 throw new moodle_exception('invalidcourse', 'error');
2465 $oldcourse = course_get_format($data->id)->get_course();
2466 $context = context_course::instance($oldcourse->id);
2468 // Make sure we're not changing whatever the course's relativedatesmode setting is.
2469 unset($data->relativedatesmode);
2471 // Capture the updated fields for the log data.
2472 $updatedfields = [];
2473 foreach (get_object_vars($oldcourse) as $field => $value) {
2474 if ($field == 'summary_editor') {
2475 if (($data->$field)['text'] !== $value['text']) {
2476 // The summary might be very long, we don't wan't to fill up the log record with the full text.
2477 $updatedfields[$field] = '(updated)';
2479 } else if ($field == 'tags' && isset($data->tags)) {
2480 // Tags might not have the same array keys, just check the values.
2481 if (array_values($data->$field) !== array_values($value)) {
2482 $updatedfields[$field] = $data->$field;
2484 } else {
2485 if (isset($data->$field) && $data->$field != $value) {
2486 $updatedfields[$field] = $data->$field;
2491 $data->timemodified = time();
2493 if ($editoroptions) {
2494 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2496 if ($overviewfilesoptions = course_overviewfiles_options($data->id)) {
2497 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2500 // Check we don't have a duplicate shortname.
2501 if (!empty($data->shortname) && $oldcourse->shortname != $data->shortname) {
2502 if ($DB->record_exists_sql('SELECT id from {course} WHERE shortname = ? AND id <> ?', array($data->shortname, $data->id))) {
2503 throw new moodle_exception('shortnametaken', '', '', $data->shortname);
2507 // Check we don't have a duplicate idnumber.
2508 if (!empty($data->idnumber) && $oldcourse->idnumber != $data->idnumber) {
2509 if ($DB->record_exists_sql('SELECT id from {course} WHERE idnumber = ? AND id <> ?', array($data->idnumber, $data->id))) {
2510 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber);
2514 if ($errorcode = course_validate_dates((array)$data)) {
2515 throw new moodle_exception($errorcode);
2518 if (!isset($data->category) or empty($data->category)) {
2519 // prevent nulls and 0 in category field
2520 unset($data->category);
2522 $changesincoursecat = $movecat = (isset($data->category) and $oldcourse->category != $data->category);
2524 if (!isset($data->visible)) {
2525 // data not from form, add missing visibility info
2526 $data->visible = $oldcourse->visible;
2529 if ($data->visible != $oldcourse->visible) {
2530 // reset the visibleold flag when manually hiding/unhiding course
2531 $data->visibleold = $data->visible;
2532 $changesincoursecat = true;
2533 } else {
2534 if ($movecat) {
2535 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category));
2536 if (empty($newcategory->visible)) {
2537 // make sure when moving into hidden category the course is hidden automatically
2538 $data->visible = 0;
2543 // Set newsitems to 0 if format does not support announcements.
2544 if (isset($data->format)) {
2545 $newcourseformat = course_get_format((object)['format' => $data->format]);
2546 if (!$newcourseformat->supports_news()) {
2547 $data->newsitems = 0;
2551 // Set showcompletionconditions to null when completion tracking has been disabled for the course.
2552 if (isset($data->enablecompletion) && $data->enablecompletion == COMPLETION_DISABLED) {
2553 $data->showcompletionconditions = null;
2556 // Update custom fields if there are any of them in the form.
2557 $handler = core_course\customfield\course_handler::create();
2558 $handler->instance_form_save($data);
2560 // Update with the new data
2561 $DB->update_record('course', $data);
2562 // make sure the modinfo cache is reset
2563 rebuild_course_cache($data->id);
2565 // Purge course image cache in case if course image has been updated.
2566 \cache::make('core', 'course_image')->delete($data->id);
2568 // update course format options with full course data
2569 course_get_format($data->id)->update_course_format_options($data, $oldcourse);
2571 $course = $DB->get_record('course', array('id'=>$data->id));
2573 if ($movecat) {
2574 $newparent = context_coursecat::instance($course->category);
2575 $context->update_moved($newparent);
2577 $fixcoursesortorder = $movecat || (isset($data->sortorder) && ($oldcourse->sortorder != $data->sortorder));
2578 if ($fixcoursesortorder) {
2579 fix_course_sortorder();
2582 // purge appropriate caches in case fix_course_sortorder() did not change anything
2583 cache_helper::purge_by_event('changesincourse');
2584 if ($changesincoursecat) {
2585 cache_helper::purge_by_event('changesincoursecat');
2588 // Test for and remove blocks which aren't appropriate anymore
2589 blocks_remove_inappropriate($course);
2591 // Save any custom role names.
2592 save_local_role_names($course->id, $data);
2594 // update enrol settings
2595 enrol_course_updated(false, $course, $data);
2597 // Update course tags.
2598 if (isset($data->tags)) {
2599 core_tag_tag::set_item_tags('core', 'course', $course->id, context_course::instance($course->id), $data->tags);
2602 // Trigger a course updated event.
2603 $event = \core\event\course_updated::create(array(
2604 'objectid' => $course->id,
2605 'context' => context_course::instance($course->id),
2606 'other' => array('shortname' => $course->shortname,
2607 'fullname' => $course->fullname,
2608 'updatedfields' => $updatedfields)
2611 $event->set_legacy_logdata(array($course->id, 'course', 'update', 'edit.php?id=' . $course->id, $course->id));
2612 $event->trigger();
2614 if ($oldcourse->format !== $course->format) {
2615 // Remove all options stored for the previous format
2616 // We assume that new course format migrated everything it needed watching trigger
2617 // 'course_updated' and in method format_XXX::update_course_format_options()
2618 $DB->delete_records('course_format_options',
2619 array('courseid' => $course->id, 'format' => $oldcourse->format));
2624 * Calculate the average number of enrolled participants per course.
2626 * This is intended for statistics purposes during the site registration. Only visible courses are taken into account.
2627 * Front page enrolments are excluded.
2629 * @param bool $onlyactive Consider only active enrolments in enabled plugins and obey the enrolment time restrictions.
2630 * @param int $lastloginsince If specified, count only users who logged in after this timestamp.
2631 * @return float
2633 function average_number_of_participants(bool $onlyactive = false, int $lastloginsince = null): float {
2634 global $DB;
2636 $params = [
2637 'siteid' => SITEID,
2640 $sql = "SELECT DISTINCT ue.userid, e.courseid
2641 FROM {user_enrolments} ue
2642 JOIN {enrol} e ON e.id = ue.enrolid
2643 JOIN {course} c ON c.id = e.courseid ";
2645 if ($onlyactive || $lastloginsince) {
2646 $sql .= "JOIN {user} u ON u.id = ue.userid ";
2649 $sql .= "WHERE e.courseid <> :siteid
2650 AND c.visible = 1 ";
2652 if ($onlyactive) {
2653 $sql .= "AND ue.status = :active
2654 AND e.status = :enabled
2655 AND ue.timestart < :now1
2656 AND (ue.timeend = 0 OR ue.timeend > :now2) ";
2658 // Same as in the enrollib - the rounding should help caching in the database.
2659 $now = round(time(), -2);
2661 $params += [
2662 'active' => ENROL_USER_ACTIVE,
2663 'enabled' => ENROL_INSTANCE_ENABLED,
2664 'now1' => $now,
2665 'now2' => $now,
2669 if ($lastloginsince) {
2670 $sql .= "AND u.lastlogin > :lastlogin ";
2671 $params['lastlogin'] = $lastloginsince;
2674 $sql = "SELECT COUNT(*)
2675 FROM ($sql) total";
2677 $enrolmenttotal = $DB->count_records_sql($sql, $params);
2679 // Get the number of visible courses (exclude the front page).
2680 $coursetotal = $DB->count_records('course', ['visible' => 1]);
2681 $coursetotal = $coursetotal - 1;
2683 if (empty($coursetotal)) {
2684 $participantaverage = 0;
2686 } else {
2687 $participantaverage = $enrolmenttotal / $coursetotal;
2690 return $participantaverage;
2694 * Average number of course modules
2695 * @return integer
2697 function average_number_of_courses_modules() {
2698 global $DB, $SITE;
2700 //count total of visible course module (except front page)
2701 $sql = 'SELECT COUNT(*) FROM (
2702 SELECT cm.course, cm.module
2703 FROM {course} c, {course_modules} cm
2704 WHERE c.id = cm.course
2705 AND c.id <> :siteid
2706 AND cm.visible = 1
2707 AND c.visible = 1) total';
2708 $params = array('siteid' => $SITE->id);
2709 $moduletotal = $DB->count_records_sql($sql, $params);
2712 //count total of visible courses (minus front page)
2713 $coursetotal = $DB->count_records('course', array('visible' => 1));
2714 $coursetotal = $coursetotal - 1 ;
2716 //average of course module
2717 if (empty($coursetotal)) {
2718 $coursemoduleaverage = 0;
2719 } else {
2720 $coursemoduleaverage = $moduletotal / $coursetotal;
2723 return $coursemoduleaverage;
2727 * This class pertains to course requests and contains methods associated with
2728 * create, approving, and removing course requests.
2730 * Please note we do not allow embedded images here because there is no context
2731 * to store them with proper access control.
2733 * @copyright 2009 Sam Hemelryk
2734 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2735 * @since Moodle 2.0
2737 * @property-read int $id
2738 * @property-read string $fullname
2739 * @property-read string $shortname
2740 * @property-read string $summary
2741 * @property-read int $summaryformat
2742 * @property-read int $summarytrust
2743 * @property-read string $reason
2744 * @property-read int $requester
2746 class course_request {
2749 * This is the stdClass that stores the properties for the course request
2750 * and is externally accessed through the __get magic method
2751 * @var stdClass
2753 protected $properties;
2756 * An array of options for the summary editor used by course request forms.
2757 * This is initially set by {@link summary_editor_options()}
2758 * @var array
2759 * @static
2761 protected static $summaryeditoroptions;
2764 * Static function to prepare the summary editor for working with a course
2765 * request.
2767 * @static
2768 * @param null|stdClass $data Optional, an object containing the default values
2769 * for the form, these may be modified when preparing the
2770 * editor so this should be called before creating the form
2771 * @return stdClass An object that can be used to set the default values for
2772 * an mforms form
2774 public static function prepare($data=null) {
2775 if ($data === null) {
2776 $data = new stdClass;
2778 $data = file_prepare_standard_editor($data, 'summary', self::summary_editor_options());
2779 return $data;
2783 * Static function to create a new course request when passed an array of properties
2784 * for it.
2786 * This function also handles saving any files that may have been used in the editor
2788 * @static
2789 * @param stdClass $data
2790 * @return course_request The newly created course request
2792 public static function create($data) {
2793 global $USER, $DB, $CFG;
2794 $data->requester = $USER->id;
2796 // Setting the default category if none set.
2797 if (empty($data->category) || !empty($CFG->lockrequestcategory)) {
2798 $data->category = $CFG->defaultrequestcategory;
2801 // Summary is a required field so copy the text over
2802 $data->summary = $data->summary_editor['text'];
2803 $data->summaryformat = $data->summary_editor['format'];
2805 $data->id = $DB->insert_record('course_request', $data);
2807 // Create a new course_request object and return it
2808 $request = new course_request($data);
2810 // Notify the admin if required.
2811 if ($users = get_users_from_config($CFG->courserequestnotify, 'moodle/site:approvecourse')) {
2813 $a = new stdClass;
2814 $a->link = "$CFG->wwwroot/course/pending.php";
2815 $a->user = fullname($USER);
2816 $subject = get_string('courserequest');
2817 $message = get_string('courserequestnotifyemail', 'admin', $a);
2818 foreach ($users as $user) {
2819 $request->notify($user, $USER, 'courserequested', $subject, $message);
2823 return $request;
2827 * Returns an array of options to use with a summary editor
2829 * @uses course_request::$summaryeditoroptions
2830 * @return array An array of options to use with the editor
2832 public static function summary_editor_options() {
2833 global $CFG;
2834 if (self::$summaryeditoroptions === null) {
2835 self::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
2837 return self::$summaryeditoroptions;
2841 * Loads the properties for this course request object. Id is required and if
2842 * only id is provided then we load the rest of the properties from the database
2844 * @param stdClass|int $properties Either an object containing properties
2845 * or the course_request id to load
2847 public function __construct($properties) {
2848 global $DB;
2849 if (empty($properties->id)) {
2850 if (empty($properties)) {
2851 throw new coding_exception('You must provide a course request id when creating a course_request object');
2853 $id = $properties;
2854 $properties = new stdClass;
2855 $properties->id = (int)$id;
2856 unset($id);
2858 if (empty($properties->requester)) {
2859 if (!($this->properties = $DB->get_record('course_request', array('id' => $properties->id)))) {
2860 print_error('unknowncourserequest');
2862 } else {
2863 $this->properties = $properties;
2865 $this->properties->collision = null;
2869 * Returns the requested property
2871 * @param string $key
2872 * @return mixed
2874 public function __get($key) {
2875 return $this->properties->$key;
2879 * Override this to ensure empty($request->blah) calls return a reliable answer...
2881 * This is required because we define the __get method
2883 * @param mixed $key
2884 * @return bool True is it not empty, false otherwise
2886 public function __isset($key) {
2887 return (!empty($this->properties->$key));
2891 * Returns the user who requested this course
2893 * Uses a static var to cache the results and cut down the number of db queries
2895 * @staticvar array $requesters An array of cached users
2896 * @return stdClass The user who requested the course
2898 public function get_requester() {
2899 global $DB;
2900 static $requesters= array();
2901 if (!array_key_exists($this->properties->requester, $requesters)) {
2902 $requesters[$this->properties->requester] = $DB->get_record('user', array('id'=>$this->properties->requester));
2904 return $requesters[$this->properties->requester];
2908 * Checks that the shortname used by the course does not conflict with any other
2909 * courses that exist
2911 * @param string|null $shortnamemark The string to append to the requests shortname
2912 * should a conflict be found
2913 * @return bool true is there is a conflict, false otherwise
2915 public function check_shortname_collision($shortnamemark = '[*]') {
2916 global $DB;
2918 if ($this->properties->collision !== null) {
2919 return $this->properties->collision;
2922 if (empty($this->properties->shortname)) {
2923 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER);
2924 $this->properties->collision = false;
2925 } else if ($DB->record_exists('course', array('shortname' => $this->properties->shortname))) {
2926 if (!empty($shortnamemark)) {
2927 $this->properties->shortname .= ' '.$shortnamemark;
2929 $this->properties->collision = true;
2930 } else {
2931 $this->properties->collision = false;
2933 return $this->properties->collision;
2937 * Checks user capability to approve a requested course
2939 * If course was requested without category for some reason (might happen if $CFG->defaultrequestcategory is
2940 * misconfigured), we check capabilities 'moodle/site:approvecourse' and 'moodle/course:changecategory'.
2942 * @return bool
2944 public function can_approve() {
2945 global $CFG;
2946 $category = null;
2947 if ($this->properties->category) {
2948 $category = core_course_category::get($this->properties->category, IGNORE_MISSING);
2949 } else if ($CFG->defaultrequestcategory) {
2950 $category = core_course_category::get($CFG->defaultrequestcategory, IGNORE_MISSING);
2952 if ($category) {
2953 return has_capability('moodle/site:approvecourse', $category->get_context());
2956 // We can not determine the context where the course should be created. The approver should have
2957 // both capabilities to approve courses and change course category in the system context.
2958 return has_all_capabilities(['moodle/site:approvecourse', 'moodle/course:changecategory'], context_system::instance());
2962 * Returns the category where this course request should be created
2964 * Note that we don't check here that user has a capability to view
2965 * hidden categories if he has capabilities 'moodle/site:approvecourse' and
2966 * 'moodle/course:changecategory'
2968 * @return core_course_category
2970 public function get_category() {
2971 global $CFG;
2972 if ($this->properties->category && ($category = core_course_category::get($this->properties->category, IGNORE_MISSING))) {
2973 return $category;
2974 } else if ($CFG->defaultrequestcategory &&
2975 ($category = core_course_category::get($CFG->defaultrequestcategory, IGNORE_MISSING))) {
2976 return $category;
2977 } else {
2978 return core_course_category::get_default();
2983 * This function approves the request turning it into a course
2985 * This function converts the course request into a course, at the same time
2986 * transferring any files used in the summary to the new course and then removing
2987 * the course request and the files associated with it.
2989 * @return int The id of the course that was created from this request
2991 public function approve() {
2992 global $CFG, $DB, $USER;
2994 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
2996 $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted'=>0), '*', MUST_EXIST);
2998 $courseconfig = get_config('moodlecourse');
3000 // Transfer appropriate settings
3001 $data = clone($this->properties);
3002 unset($data->id);
3003 unset($data->reason);
3004 unset($data->requester);
3006 // Set category
3007 $category = $this->get_category();
3008 $data->category = $category->id;
3009 // Set misc settings
3010 $data->requested = 1;
3012 // Apply course default settings
3013 $data->format = $courseconfig->format;
3014 $data->newsitems = $courseconfig->newsitems;
3015 $data->showgrades = $courseconfig->showgrades;
3016 $data->showreports = $courseconfig->showreports;
3017 $data->maxbytes = $courseconfig->maxbytes;
3018 $data->groupmode = $courseconfig->groupmode;
3019 $data->groupmodeforce = $courseconfig->groupmodeforce;
3020 $data->visible = $courseconfig->visible;
3021 $data->visibleold = $data->visible;
3022 $data->lang = $courseconfig->lang;
3023 $data->enablecompletion = $courseconfig->enablecompletion;
3024 $data->numsections = $courseconfig->numsections;
3025 $data->startdate = usergetmidnight(time());
3026 if ($courseconfig->courseenddateenabled) {
3027 $data->enddate = usergetmidnight(time()) + $courseconfig->courseduration;
3030 list($data->fullname, $data->shortname) = restore_dbops::calculate_course_names(0, $data->fullname, $data->shortname);
3032 $course = create_course($data);
3033 $context = context_course::instance($course->id, MUST_EXIST);
3035 // add enrol instances
3036 if (!$DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
3037 if ($manual = enrol_get_plugin('manual')) {
3038 $manual->add_default_instance($course);
3042 // enrol the requester as teacher if necessary
3043 if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
3044 enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid);
3047 $this->delete();
3049 $a = new stdClass();
3050 $a->name = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
3051 $a->url = $CFG->wwwroot.'/course/view.php?id=' . $course->id;
3052 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a), $course->id);
3054 return $course->id;
3058 * Reject a course request
3060 * This function rejects a course request, emailing the requesting user the
3061 * provided notice and then removing the request from the database
3063 * @param string $notice The message to display to the user
3065 public function reject($notice) {
3066 global $USER, $DB;
3067 $user = $DB->get_record('user', array('id' => $this->properties->requester), '*', MUST_EXIST);
3068 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
3069 $this->delete();
3073 * Deletes the course request and any associated files
3075 public function delete() {
3076 global $DB;
3077 $DB->delete_records('course_request', array('id' => $this->properties->id));
3081 * Send a message from one user to another using events_trigger
3083 * @param object $touser
3084 * @param object $fromuser
3085 * @param string $name
3086 * @param string $subject
3087 * @param string $message
3088 * @param int|null $courseid
3090 protected function notify($touser, $fromuser, $name, $subject, $message, $courseid = null) {
3091 $eventdata = new \core\message\message();
3092 $eventdata->courseid = empty($courseid) ? SITEID : $courseid;
3093 $eventdata->component = 'moodle';
3094 $eventdata->name = $name;
3095 $eventdata->userfrom = $fromuser;
3096 $eventdata->userto = $touser;
3097 $eventdata->subject = $subject;
3098 $eventdata->fullmessage = $message;
3099 $eventdata->fullmessageformat = FORMAT_PLAIN;
3100 $eventdata->fullmessagehtml = '';
3101 $eventdata->smallmessage = '';
3102 $eventdata->notification = 1;
3103 message_send($eventdata);
3107 * Checks if current user can request a course in this context
3109 * @param context $context
3110 * @return bool
3112 public static function can_request(context $context) {
3113 global $CFG;
3114 if (empty($CFG->enablecourserequests)) {
3115 return false;
3117 if (has_capability('moodle/course:create', $context)) {
3118 return false;
3121 if ($context instanceof context_system) {
3122 $defaultcontext = context_coursecat::instance($CFG->defaultrequestcategory, IGNORE_MISSING);
3123 return $defaultcontext &&
3124 has_capability('moodle/course:request', $defaultcontext);
3125 } else if ($context instanceof context_coursecat) {
3126 if (!$CFG->lockrequestcategory || $CFG->defaultrequestcategory == $context->instanceid) {
3127 return has_capability('moodle/course:request', $context);
3130 return false;
3135 * Return a list of page types
3136 * @param string $pagetype current page type
3137 * @param context $parentcontext Block's parent context
3138 * @param context $currentcontext Current context of block
3139 * @return array array of page types
3141 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
3142 if ($pagetype === 'course-index' || $pagetype === 'course-index-category') {
3143 // For courses and categories browsing pages (/course/index.php) add option to show on ANY category page
3144 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
3145 'course-index-*' => get_string('page-course-index-x', 'pagetype'),
3147 } else if ($currentcontext && (!($coursecontext = $currentcontext->get_course_context(false)) || $coursecontext->instanceid == SITEID)) {
3148 // We know for sure that despite pagetype starts with 'course-' this is not a page in course context (i.e. /course/search.php, etc.)
3149 $pagetypes = array('*' => get_string('page-x', 'pagetype'));
3150 } else {
3151 // Otherwise consider it a page inside a course even if $currentcontext is null
3152 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
3153 'course-*' => get_string('page-course-x', 'pagetype'),
3154 'course-view-*' => get_string('page-course-view-x', 'pagetype')
3157 return $pagetypes;
3161 * Determine whether course ajax should be enabled for the specified course
3163 * @param stdClass $course The course to test against
3164 * @return boolean Whether course ajax is enabled or note
3166 function course_ajax_enabled($course) {
3167 global $CFG, $PAGE, $SITE;
3169 // The user must be editing for AJAX to be included
3170 if (!$PAGE->user_is_editing()) {
3171 return false;
3174 // Check that the theme suports
3175 if (!$PAGE->theme->enablecourseajax) {
3176 return false;
3179 // Check that the course format supports ajax functionality
3180 // The site 'format' doesn't have information on course format support
3181 if ($SITE->id !== $course->id) {
3182 $courseformatajaxsupport = course_format_ajax_support($course->format);
3183 if (!$courseformatajaxsupport->capable) {
3184 return false;
3188 // All conditions have been met so course ajax should be enabled
3189 return true;
3193 * Include the relevant javascript and language strings for the resource
3194 * toolbox YUI module
3196 * @param integer $id The ID of the course being applied to
3197 * @param array $usedmodules An array containing the names of the modules in use on the page
3198 * @param array $enabledmodules An array containing the names of the enabled (visible) modules on this site
3199 * @param stdClass $config An object containing configuration parameters for ajax modules including:
3200 * * resourceurl The URL to post changes to for resource changes
3201 * * sectionurl The URL to post changes to for section changes
3202 * * pageparams Additional parameters to pass through in the post
3203 * @return bool
3205 function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) {
3206 global $CFG, $PAGE, $SITE;
3208 // Init the course editor module to support UI components.
3209 $format = course_get_format($course);
3210 include_course_editor($format);
3212 // Ensure that ajax should be included
3213 if (!course_ajax_enabled($course)) {
3214 return false;
3217 // Component based formats don't use YUI drag and drop anymore.
3218 if (!$format->supports_components() && course_format_uses_sections($course->format)) {
3220 if (!$config) {
3221 $config = new stdClass();
3224 // The URL to use for resource changes.
3225 if (!isset($config->resourceurl)) {
3226 $config->resourceurl = '/course/rest.php';
3229 // The URL to use for section changes.
3230 if (!isset($config->sectionurl)) {
3231 $config->sectionurl = '/course/rest.php';
3234 // Any additional parameters which need to be included on page submission.
3235 if (!isset($config->pageparams)) {
3236 $config->pageparams = array();
3239 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_section_dragdrop',
3240 array(array(
3241 'courseid' => $course->id,
3242 'ajaxurl' => $config->sectionurl,
3243 'config' => $config,
3244 )), null, true);
3246 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_resource_dragdrop',
3247 array(array(
3248 'courseid' => $course->id,
3249 'ajaxurl' => $config->resourceurl,
3250 'config' => $config,
3251 )), null, true);
3254 // Require various strings for the command toolbox
3255 $PAGE->requires->strings_for_js(array(
3256 'moveleft',
3257 'deletechecktype',
3258 'deletechecktypename',
3259 'edittitle',
3260 'edittitleinstructions',
3261 'show',
3262 'hide',
3263 'highlight',
3264 'highlightoff',
3265 'groupsnone',
3266 'groupsvisible',
3267 'groupsseparate',
3268 'clicktochangeinbrackets',
3269 'markthistopic',
3270 'markedthistopic',
3271 'movesection',
3272 'movecoursemodule',
3273 'movecoursesection',
3274 'movecontent',
3275 'tocontent',
3276 'emptydragdropregion',
3277 'afterresource',
3278 'aftersection',
3279 'totopofsection',
3280 ), 'moodle');
3282 // Include section-specific strings for formats which support sections.
3283 if (course_format_uses_sections($course->format)) {
3284 $PAGE->requires->strings_for_js(array(
3285 'showfromothers',
3286 'hidefromothers',
3287 ), 'format_' . $course->format);
3290 // For confirming resource deletion we need the name of the module in question
3291 foreach ($usedmodules as $module => $modname) {
3292 $PAGE->requires->string_for_js('pluginname', $module);
3295 // Load drag and drop upload AJAX.
3296 require_once($CFG->dirroot.'/course/dnduploadlib.php');
3297 dndupload_add_to_course($course, $enabledmodules);
3299 $PAGE->requires->js_call_amd('core_course/actions', 'initCoursePage', array($course->format));
3301 return true;
3305 * Include and configure the course editor modules.
3307 * @param course_format $format the course format instance.
3309 function include_course_editor(course_format $format) {
3310 global $PAGE, $SITE;
3312 $course = $format->get_course();
3314 if ($SITE->id === $course->id) {
3315 return;
3318 $statekey = course_format::session_cache($course);
3320 // Edition mode and some format specs must be passed to the init method.
3321 $setup = (object)[
3322 'editing' => $format->show_editor(),
3323 'supportscomponents' => $format->supports_components(),
3324 'statekey' => $statekey,
3326 // All the new editor elements will be loaded after the course is presented and
3327 // the initial course state will be generated using core_course_get_state webservice.
3328 $PAGE->requires->js_call_amd('core_courseformat/courseeditor', 'setViewFormat', [$course->id, $setup]);
3332 * Returns the sorted list of available course formats, filtered by enabled if necessary
3334 * @param bool $enabledonly return only formats that are enabled
3335 * @return array array of sorted format names
3337 function get_sorted_course_formats($enabledonly = false) {
3338 global $CFG;
3339 $formats = core_component::get_plugin_list('format');
3341 if (!empty($CFG->format_plugins_sortorder)) {
3342 $order = explode(',', $CFG->format_plugins_sortorder);
3343 $order = array_merge(array_intersect($order, array_keys($formats)),
3344 array_diff(array_keys($formats), $order));
3345 } else {
3346 $order = array_keys($formats);
3348 if (!$enabledonly) {
3349 return $order;
3351 $sortedformats = array();
3352 foreach ($order as $formatname) {
3353 if (!get_config('format_'.$formatname, 'disabled')) {
3354 $sortedformats[] = $formatname;
3357 return $sortedformats;
3361 * The URL to use for the specified course (with section)
3363 * @param int|stdClass $courseorid The course to get the section name for (either object or just course id)
3364 * @param int|stdClass $section Section object from database or just field course_sections.section
3365 * if omitted the course view page is returned
3366 * @param array $options options for view URL. At the moment core uses:
3367 * 'navigation' (bool) if true and section has no separate page, the function returns null
3368 * 'sr' (int) used by multipage formats to specify to which section to return
3369 * @return moodle_url The url of course
3371 function course_get_url($courseorid, $section = null, $options = array()) {
3372 return course_get_format($courseorid)->get_view_url($section, $options);
3376 * Create a module.
3378 * It includes:
3379 * - capability checks and other checks
3380 * - create the module from the module info
3382 * @param object $module
3383 * @return object the created module info
3384 * @throws moodle_exception if user is not allowed to perform the action or module is not allowed in this course
3386 function create_module($moduleinfo) {
3387 global $DB, $CFG;
3389 require_once($CFG->dirroot . '/course/modlib.php');
3391 // Check manadatory attributs.
3392 $mandatoryfields = array('modulename', 'course', 'section', 'visible');
3393 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
3394 $mandatoryfields[] = 'introeditor';
3396 foreach($mandatoryfields as $mandatoryfield) {
3397 if (!isset($moduleinfo->{$mandatoryfield})) {
3398 throw new moodle_exception('createmodulemissingattribut', '', '', $mandatoryfield);
3402 // Some additional checks (capability / existing instances).
3403 $course = $DB->get_record('course', array('id'=>$moduleinfo->course), '*', MUST_EXIST);
3404 list($module, $context, $cw) = can_add_moduleinfo($course, $moduleinfo->modulename, $moduleinfo->section);
3406 // Add the module.
3407 $moduleinfo->module = $module->id;
3408 $moduleinfo = add_moduleinfo($moduleinfo, $course, null);
3410 return $moduleinfo;
3414 * Update a module.
3416 * It includes:
3417 * - capability and other checks
3418 * - update the module
3420 * @param object $module
3421 * @return object the updated module info
3422 * @throws moodle_exception if current user is not allowed to update the module
3424 function update_module($moduleinfo) {
3425 global $DB, $CFG;
3427 require_once($CFG->dirroot . '/course/modlib.php');
3429 // Check the course module exists.
3430 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule, 0, false, MUST_EXIST);
3432 // Check the course exists.
3433 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
3435 // Some checks (capaibility / existing instances).
3436 list($cm, $context, $module, $data, $cw) = can_update_moduleinfo($cm);
3438 // Retrieve few information needed by update_moduleinfo.
3439 $moduleinfo->modulename = $cm->modname;
3440 if (!isset($moduleinfo->scale)) {
3441 $moduleinfo->scale = 0;
3443 $moduleinfo->type = 'mod';
3445 // Update the module.
3446 list($cm, $moduleinfo) = update_moduleinfo($cm, $moduleinfo, $course, null);
3448 return $moduleinfo;
3452 * Duplicate a module on the course for ajax.
3454 * @see mod_duplicate_module()
3455 * @param object $course The course
3456 * @param object $cm The course module to duplicate
3457 * @param int $sr The section to link back to (used for creating the links)
3458 * @throws moodle_exception if the plugin doesn't support duplication
3459 * @return Object containing:
3460 * - fullcontent: The HTML markup for the created CM
3461 * - cmid: The CMID of the newly created CM
3462 * - redirect: Whether to trigger a redirect following this change
3464 function mod_duplicate_activity($course, $cm, $sr = null) {
3465 global $PAGE;
3467 $newcm = duplicate_module($course, $cm);
3469 $resp = new stdClass();
3470 if ($newcm) {
3472 $format = course_get_format($course);
3473 $renderer = $format->get_renderer($PAGE);
3474 $modinfo = $format->get_modinfo();
3475 $section = $modinfo->get_section_info($newcm->sectionnum);
3477 // Get the new element html content.
3478 $resp->fullcontent = $renderer->course_section_updated_cm_item($format, $section, $newcm);
3480 $resp->cmid = $newcm->id;
3481 } else {
3482 // Trigger a redirect.
3483 $resp->redirect = true;
3485 return $resp;
3489 * Api to duplicate a module.
3491 * @param object $course course object.
3492 * @param object $cm course module object to be duplicated.
3493 * @since Moodle 2.8
3495 * @throws Exception
3496 * @throws coding_exception
3497 * @throws moodle_exception
3498 * @throws restore_controller_exception
3500 * @return cm_info|null cminfo object if we sucessfully duplicated the mod and found the new cm.
3502 function duplicate_module($course, $cm) {
3503 global $CFG, $DB, $USER;
3504 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
3505 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
3506 require_once($CFG->libdir . '/filelib.php');
3508 $a = new stdClass();
3509 $a->modtype = get_string('modulename', $cm->modname);
3510 $a->modname = format_string($cm->name);
3512 if (!plugin_supports('mod', $cm->modname, FEATURE_BACKUP_MOODLE2)) {
3513 throw new moodle_exception('duplicatenosupport', 'error', '', $a);
3516 // Backup the activity.
3518 $bc = new backup_controller(backup::TYPE_1ACTIVITY, $cm->id, backup::FORMAT_MOODLE,
3519 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
3521 $backupid = $bc->get_backupid();
3522 $backupbasepath = $bc->get_plan()->get_basepath();
3524 $bc->execute_plan();
3526 $bc->destroy();
3528 // Restore the backup immediately.
3530 $rc = new restore_controller($backupid, $course->id,
3531 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, backup::TARGET_CURRENT_ADDING);
3533 // Make sure that the restore_general_groups setting is always enabled when duplicating an activity.
3534 $plan = $rc->get_plan();
3535 $groupsetting = $plan->get_setting('groups');
3536 if (empty($groupsetting->get_value())) {
3537 $groupsetting->set_value(true);
3540 $cmcontext = context_module::instance($cm->id);
3541 if (!$rc->execute_precheck()) {
3542 $precheckresults = $rc->get_precheck_results();
3543 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
3544 if (empty($CFG->keeptempdirectoriesonbackup)) {
3545 fulldelete($backupbasepath);
3550 $rc->execute_plan();
3552 // Now a bit hacky part follows - we try to get the cmid of the newly
3553 // restored copy of the module.
3554 $newcmid = null;
3555 $tasks = $rc->get_plan()->get_tasks();
3556 foreach ($tasks as $task) {
3557 if (is_subclass_of($task, 'restore_activity_task')) {
3558 if ($task->get_old_contextid() == $cmcontext->id) {
3559 $newcmid = $task->get_moduleid();
3560 break;
3565 $rc->destroy();
3567 if (empty($CFG->keeptempdirectoriesonbackup)) {
3568 fulldelete($backupbasepath);
3571 // If we know the cmid of the new course module, let us move it
3572 // right below the original one. otherwise it will stay at the
3573 // end of the section.
3574 if ($newcmid) {
3575 // Proceed with activity renaming before everything else. We don't use APIs here to avoid
3576 // triggering a lot of create/update duplicated events.
3577 $newcm = get_coursemodule_from_id($cm->modname, $newcmid, $cm->course);
3578 // Add ' (copy)' to duplicates. Note we don't cleanup or validate lengths here. It comes
3579 // from original name that was valid, so the copy should be too.
3580 $newname = get_string('duplicatedmodule', 'moodle', $newcm->name);
3581 $DB->set_field($cm->modname, 'name', $newname, ['id' => $newcm->instance]);
3583 $section = $DB->get_record('course_sections', array('id' => $cm->section, 'course' => $cm->course));
3584 $modarray = explode(",", trim($section->sequence));
3585 $cmindex = array_search($cm->id, $modarray);
3586 if ($cmindex !== false && $cmindex < count($modarray) - 1) {
3587 moveto_module($newcm, $section, $modarray[$cmindex + 1]);
3590 // Update calendar events with the duplicated module.
3591 // The following line is to be removed in MDL-58906.
3592 course_module_update_calendar_events($newcm->modname, null, $newcm);
3594 // Trigger course module created event. We can trigger the event only if we know the newcmid.
3595 $newcm = get_fast_modinfo($cm->course)->get_cm($newcmid);
3596 $event = \core\event\course_module_created::create_from_cm($newcm);
3597 $event->trigger();
3600 return isset($newcm) ? $newcm : null;
3604 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3605 * Sorts by descending order of time.
3607 * @param stdClass $a First object
3608 * @param stdClass $b Second object
3609 * @return int 0,1,-1 representing the order
3611 function compare_activities_by_time_desc($a, $b) {
3612 // Make sure the activities actually have a timestamp property.
3613 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3614 return 0;
3616 // We treat instances without timestamp as if they have a timestamp of 0.
3617 if ((!property_exists($a, 'timestamp')) && (property_exists($b,'timestamp'))) {
3618 return 1;
3620 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3621 return -1;
3623 if ($a->timestamp == $b->timestamp) {
3624 return 0;
3626 return ($a->timestamp > $b->timestamp) ? -1 : 1;
3630 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3631 * Sorts by ascending order of time.
3633 * @param stdClass $a First object
3634 * @param stdClass $b Second object
3635 * @return int 0,1,-1 representing the order
3637 function compare_activities_by_time_asc($a, $b) {
3638 // Make sure the activities actually have a timestamp property.
3639 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3640 return 0;
3642 // We treat instances without timestamp as if they have a timestamp of 0.
3643 if ((!property_exists($a, 'timestamp')) && (property_exists($b, 'timestamp'))) {
3644 return -1;
3646 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3647 return 1;
3649 if ($a->timestamp == $b->timestamp) {
3650 return 0;
3652 return ($a->timestamp < $b->timestamp) ? -1 : 1;
3656 * Changes the visibility of a course.
3658 * @param int $courseid The course to change.
3659 * @param bool $show True to make it visible, false otherwise.
3660 * @return bool
3662 function course_change_visibility($courseid, $show = true) {
3663 $course = new stdClass;
3664 $course->id = $courseid;
3665 $course->visible = ($show) ? '1' : '0';
3666 $course->visibleold = $course->visible;
3667 update_course($course);
3668 return true;
3672 * Changes the course sortorder by one, moving it up or down one in respect to sort order.
3674 * @param stdClass|core_course_list_element $course
3675 * @param bool $up If set to true the course will be moved up one. Otherwise down one.
3676 * @return bool
3678 function course_change_sortorder_by_one($course, $up) {
3679 global $DB;
3680 $params = array($course->sortorder, $course->category);
3681 if ($up) {
3682 $select = 'sortorder < ? AND category = ?';
3683 $sort = 'sortorder DESC';
3684 } else {
3685 $select = 'sortorder > ? AND category = ?';
3686 $sort = 'sortorder ASC';
3688 fix_course_sortorder();
3689 $swapcourse = $DB->get_records_select('course', $select, $params, $sort, '*', 0, 1);
3690 if ($swapcourse) {
3691 $swapcourse = reset($swapcourse);
3692 $DB->set_field('course', 'sortorder', $swapcourse->sortorder, array('id' => $course->id));
3693 $DB->set_field('course', 'sortorder', $course->sortorder, array('id' => $swapcourse->id));
3694 // Finally reorder courses.
3695 fix_course_sortorder();
3696 cache_helper::purge_by_event('changesincourse');
3697 return true;
3699 return false;
3703 * Changes the sort order of courses in a category so that the first course appears after the second.
3705 * @param int|stdClass $courseorid The course to focus on.
3706 * @param int $moveaftercourseid The course to shifter after or 0 if you want it to be the first course in the category.
3707 * @return bool
3709 function course_change_sortorder_after_course($courseorid, $moveaftercourseid) {
3710 global $DB;
3712 if (!is_object($courseorid)) {
3713 $course = get_course($courseorid);
3714 } else {
3715 $course = $courseorid;
3718 if ((int)$moveaftercourseid === 0) {
3719 // We've moving the course to the start of the queue.
3720 $sql = 'SELECT sortorder
3721 FROM {course}
3722 WHERE category = :categoryid
3723 ORDER BY sortorder';
3724 $params = array(
3725 'categoryid' => $course->category
3727 $sortorder = $DB->get_field_sql($sql, $params, IGNORE_MULTIPLE);
3729 $sql = 'UPDATE {course}
3730 SET sortorder = sortorder + 1
3731 WHERE category = :categoryid
3732 AND id <> :id';
3733 $params = array(
3734 'categoryid' => $course->category,
3735 'id' => $course->id,
3737 $DB->execute($sql, $params);
3738 $DB->set_field('course', 'sortorder', $sortorder, array('id' => $course->id));
3739 } else if ($course->id === $moveaftercourseid) {
3740 // They're the same - moronic.
3741 debugging("Invalid move after course given.", DEBUG_DEVELOPER);
3742 return false;
3743 } else {
3744 // Moving this course after the given course. It could be before it could be after.
3745 $moveaftercourse = get_course($moveaftercourseid);
3746 if ($course->category !== $moveaftercourse->category) {
3747 debugging("Cannot re-order courses. The given courses do not belong to the same category.", DEBUG_DEVELOPER);
3748 return false;
3750 // Increment all courses in the same category that are ordered after the moveafter course.
3751 // This makes a space for the course we're moving.
3752 $sql = 'UPDATE {course}
3753 SET sortorder = sortorder + 1
3754 WHERE category = :categoryid
3755 AND sortorder > :sortorder';
3756 $params = array(
3757 'categoryid' => $moveaftercourse->category,
3758 'sortorder' => $moveaftercourse->sortorder
3760 $DB->execute($sql, $params);
3761 $DB->set_field('course', 'sortorder', $moveaftercourse->sortorder + 1, array('id' => $course->id));
3763 fix_course_sortorder();
3764 cache_helper::purge_by_event('changesincourse');
3765 return true;
3769 * Trigger course viewed event. This API function is used when course view actions happens,
3770 * usually in course/view.php but also in external functions.
3772 * @param stdClass $context course context object
3773 * @param int $sectionnumber section number
3774 * @since Moodle 2.9
3776 function course_view($context, $sectionnumber = 0) {
3778 $eventdata = array('context' => $context);
3780 if (!empty($sectionnumber)) {
3781 $eventdata['other']['coursesectionnumber'] = $sectionnumber;
3784 $event = \core\event\course_viewed::create($eventdata);
3785 $event->trigger();
3787 user_accesstime_log($context->instanceid);
3791 * Returns courses tagged with a specified tag.
3793 * @param core_tag_tag $tag
3794 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
3795 * are displayed on the page and the per-page limit may be bigger
3796 * @param int $fromctx context id where the link was displayed, may be used by callbacks
3797 * to display items in the same context first
3798 * @param int $ctx context id where to search for records
3799 * @param bool $rec search in subcontexts as well
3800 * @param int $page 0-based number of page being displayed
3801 * @return \core_tag\output\tagindex
3803 function course_get_tagged_courses($tag, $exclusivemode = false, $fromctx = 0, $ctx = 0, $rec = 1, $page = 0) {
3804 global $CFG, $PAGE;
3806 $perpage = $exclusivemode ? $CFG->coursesperpage : 5;
3807 $displayoptions = array(
3808 'limit' => $perpage,
3809 'offset' => $page * $perpage,
3810 'viewmoreurl' => null,
3813 $courserenderer = $PAGE->get_renderer('core', 'course');
3814 $totalcount = core_course_category::search_courses_count(array('tagid' => $tag->id, 'ctx' => $ctx, 'rec' => $rec));
3815 $content = $courserenderer->tagged_courses($tag->id, $exclusivemode, $ctx, $rec, $displayoptions);
3816 $totalpages = ceil($totalcount / $perpage);
3818 return new core_tag\output\tagindex($tag, 'core', 'course', $content,
3819 $exclusivemode, $fromctx, $ctx, $rec, $page, $totalpages);
3823 * Implements callback inplace_editable() allowing to edit values in-place
3825 * @param string $itemtype
3826 * @param int $itemid
3827 * @param mixed $newvalue
3828 * @return \core\output\inplace_editable
3830 function core_course_inplace_editable($itemtype, $itemid, $newvalue) {
3831 if ($itemtype === 'activityname') {
3832 return \core_courseformat\output\local\content\cm\cmname::update($itemid, $newvalue);
3837 * This function calculates the minimum and maximum cutoff values for the timestart of
3838 * the given event.
3840 * It will return an array with two values, the first being the minimum cutoff value and
3841 * the second being the maximum cutoff value. Either or both values can be null, which
3842 * indicates there is no minimum or maximum, respectively.
3844 * If a cutoff is required then the function must return an array containing the cutoff
3845 * timestamp and error string to display to the user if the cutoff value is violated.
3847 * A minimum and maximum cutoff return value will look like:
3849 * [1505704373, 'The date must be after this date'],
3850 * [1506741172, 'The date must be before this date']
3853 * @param calendar_event $event The calendar event to get the time range for
3854 * @param stdClass $course The course object to get the range from
3855 * @return array Returns an array with min and max date.
3857 function core_course_core_calendar_get_valid_event_timestart_range(\calendar_event $event, $course) {
3858 $mindate = null;
3859 $maxdate = null;
3861 if ($course->startdate) {
3862 $mindate = [
3863 $course->startdate,
3864 get_string('errorbeforecoursestart', 'calendar')
3868 return [$mindate, $maxdate];
3872 * Render the message drawer to be included in the top of the body of each page.
3874 * @return string HTML
3876 function core_course_drawer(): string {
3877 global $PAGE;
3879 // Only add course index on non-site course pages.
3880 if (!$PAGE->course || $PAGE->course->id == SITEID) {
3881 return '';
3884 // Show course index to users can access the course only.
3885 if (!can_access_course($PAGE->course)) {
3886 return '';
3889 $format = course_get_format($PAGE->course);
3890 $renderer = $format->get_renderer($PAGE);
3891 if (method_exists($renderer, 'course_index_drawer')) {
3892 return $renderer->course_index_drawer($format);
3895 return '';
3899 * Returns course modules tagged with a specified tag ready for output on tag/index.php page
3901 * This is a callback used by the tag area core/course_modules to search for course modules
3902 * tagged with a specific tag.
3904 * @param core_tag_tag $tag
3905 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
3906 * are displayed on the page and the per-page limit may be bigger
3907 * @param int $fromcontextid context id where the link was displayed, may be used by callbacks
3908 * to display items in the same context first
3909 * @param int $contextid context id where to search for records
3910 * @param bool $recursivecontext search in subcontexts as well
3911 * @param int $page 0-based number of page being displayed
3912 * @return \core_tag\output\tagindex
3914 function course_get_tagged_course_modules($tag, $exclusivemode = false, $fromcontextid = 0, $contextid = 0,
3915 $recursivecontext = 1, $page = 0) {
3916 global $OUTPUT;
3917 $perpage = $exclusivemode ? 20 : 5;
3919 // Build select query.
3920 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
3921 $query = "SELECT cm.id AS cmid, c.id AS courseid, $ctxselect
3922 FROM {course_modules} cm
3923 JOIN {tag_instance} tt ON cm.id = tt.itemid
3924 JOIN {course} c ON cm.course = c.id
3925 JOIN {context} ctx ON ctx.instanceid = cm.id AND ctx.contextlevel = :coursemodulecontextlevel
3926 WHERE tt.itemtype = :itemtype AND tt.tagid = :tagid AND tt.component = :component
3927 AND cm.deletioninprogress = 0
3928 AND c.id %COURSEFILTER% AND cm.id %ITEMFILTER%";
3930 $params = array('itemtype' => 'course_modules', 'tagid' => $tag->id, 'component' => 'core',
3931 'coursemodulecontextlevel' => CONTEXT_MODULE);
3932 if ($contextid) {
3933 $context = context::instance_by_id($contextid);
3934 $query .= $recursivecontext ? ' AND (ctx.id = :contextid OR ctx.path LIKE :path)' : ' AND ctx.id = :contextid';
3935 $params['contextid'] = $context->id;
3936 $params['path'] = $context->path.'/%';
3939 $query .= ' ORDER BY';
3940 if ($fromcontextid) {
3941 // In order-clause specify that modules from inside "fromctx" context should be returned first.
3942 $fromcontext = context::instance_by_id($fromcontextid);
3943 $query .= ' (CASE WHEN ctx.id = :fromcontextid OR ctx.path LIKE :frompath THEN 0 ELSE 1 END),';
3944 $params['fromcontextid'] = $fromcontext->id;
3945 $params['frompath'] = $fromcontext->path.'/%';
3947 $query .= ' c.sortorder, cm.id';
3948 $totalpages = $page + 1;
3950 // Use core_tag_index_builder to build and filter the list of items.
3951 // Request one item more than we need so we know if next page exists.
3952 $builder = new core_tag_index_builder('core', 'course_modules', $query, $params, $page * $perpage, $perpage + 1);
3953 while ($item = $builder->has_item_that_needs_access_check()) {
3954 context_helper::preload_from_record($item);
3955 $courseid = $item->courseid;
3956 if (!$builder->can_access_course($courseid)) {
3957 $builder->set_accessible($item, false);
3958 continue;
3960 $modinfo = get_fast_modinfo($builder->get_course($courseid));
3961 // Set accessibility of this item and all other items in the same course.
3962 $builder->walk(function ($taggeditem) use ($courseid, $modinfo, $builder) {
3963 if ($taggeditem->courseid == $courseid) {
3964 $cm = $modinfo->get_cm($taggeditem->cmid);
3965 $builder->set_accessible($taggeditem, $cm->uservisible);
3970 $items = $builder->get_items();
3971 if (count($items) > $perpage) {
3972 $totalpages = $page + 2; // We don't need exact page count, just indicate that the next page exists.
3973 array_pop($items);
3976 // Build the display contents.
3977 if ($items) {
3978 $tagfeed = new core_tag\output\tagfeed();
3979 foreach ($items as $item) {
3980 context_helper::preload_from_record($item);
3981 $course = $builder->get_course($item->courseid);
3982 $modinfo = get_fast_modinfo($course);
3983 $cm = $modinfo->get_cm($item->cmid);
3984 $courseurl = course_get_url($item->courseid, $cm->sectionnum);
3985 $cmname = $cm->get_formatted_name();
3986 if (!$exclusivemode) {
3987 $cmname = shorten_text($cmname, 100);
3989 $cmname = html_writer::link($cm->url?:$courseurl, $cmname);
3990 $coursename = format_string($course->fullname, true,
3991 array('context' => context_course::instance($item->courseid)));
3992 $coursename = html_writer::link($courseurl, $coursename);
3993 $icon = html_writer::empty_tag('img', array('src' => $cm->get_icon_url()));
3994 $tagfeed->add($icon, $cmname, $coursename);
3997 $content = $OUTPUT->render_from_template('core_tag/tagfeed',
3998 $tagfeed->export_for_template($OUTPUT));
4000 return new core_tag\output\tagindex($tag, 'core', 'course_modules', $content,
4001 $exclusivemode, $fromcontextid, $contextid, $recursivecontext, $page, $totalpages);
4006 * Return an object with the list of navigation options in a course that are avaialable or not for the current user.
4007 * This function also handles the frontpage course.
4009 * @param stdClass $context context object (it can be a course context or the system context for frontpage settings)
4010 * @param stdClass $course the course where the settings are being rendered
4011 * @return stdClass the navigation options in a course and their availability status
4012 * @since Moodle 3.2
4014 function course_get_user_navigation_options($context, $course = null) {
4015 global $CFG, $USER;
4017 $isloggedin = isloggedin();
4018 $isguestuser = isguestuser();
4019 $isfrontpage = $context->contextlevel == CONTEXT_SYSTEM;
4021 if ($isfrontpage) {
4022 $sitecontext = $context;
4023 } else {
4024 $sitecontext = context_system::instance();
4027 // Sets defaults for all options.
4028 $options = (object) [
4029 'badges' => false,
4030 'blogs' => false,
4031 'competencies' => false,
4032 'grades' => false,
4033 'notes' => false,
4034 'participants' => false,
4035 'search' => false,
4036 'tags' => false,
4039 $options->blogs = !empty($CFG->enableblogs) &&
4040 ($CFG->bloglevel == BLOG_GLOBAL_LEVEL ||
4041 ($CFG->bloglevel == BLOG_SITE_LEVEL and ($isloggedin and !$isguestuser)))
4042 && has_capability('moodle/blog:view', $sitecontext);
4044 $options->notes = !empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $context);
4046 // Frontpage settings?
4047 if ($isfrontpage) {
4048 // We are on the front page, so make sure we use the proper capability (site:viewparticipants).
4049 $options->participants = course_can_view_participants($sitecontext);
4050 $options->badges = !empty($CFG->enablebadges) && has_capability('moodle/badges:viewbadges', $sitecontext);
4051 $options->tags = !empty($CFG->usetags) && $isloggedin;
4052 $options->search = !empty($CFG->enableglobalsearch) && has_capability('moodle/search:query', $sitecontext);
4053 } else {
4054 // We are in a course, so make sure we use the proper capability (course:viewparticipants).
4055 $options->participants = course_can_view_participants($context);
4057 // Only display badges if they are enabled and the current user can manage them or if they can view them and have,
4058 // at least, one available badge.
4059 if (!empty($CFG->enablebadges) && !empty($CFG->badges_allowcoursebadges)) {
4060 $canmanage = has_any_capability([
4061 'moodle/badges:createbadge',
4062 'moodle/badges:awardbadge',
4063 'moodle/badges:configurecriteria',
4064 'moodle/badges:configuremessages',
4065 'moodle/badges:configuredetails',
4066 'moodle/badges:deletebadge',
4068 $context
4070 $totalbadges = [];
4071 $canview = false;
4072 if (!$canmanage) {
4073 // This only needs to be calculated if the user can't manage badges (to improve performance).
4074 $canview = has_capability('moodle/badges:viewbadges', $context);
4075 if ($canview) {
4076 require_once($CFG->dirroot.'/lib/badgeslib.php');
4077 if (is_null($course)) {
4078 $totalbadges = count(badges_get_badges(BADGE_TYPE_SITE, 0, '', '', 0, 0, $USER->id));
4079 } else {
4080 $totalbadges = count(badges_get_badges(BADGE_TYPE_COURSE, $course->id, '', '', 0, 0, $USER->id));
4085 $options->badges = ($canmanage || ($canview && $totalbadges > 0));
4087 // Add view grade report is permitted.
4088 $grades = false;
4090 if (has_capability('moodle/grade:viewall', $context)) {
4091 $grades = true;
4092 } else if (!empty($course->showgrades)) {
4093 $reports = core_component::get_plugin_list('gradereport');
4094 if (is_array($reports) && count($reports) > 0) { // Get all installed reports.
4095 arsort($reports); // User is last, we want to test it first.
4096 foreach ($reports as $plugin => $plugindir) {
4097 if (has_capability('gradereport/'.$plugin.':view', $context)) {
4098 // Stop when the first visible plugin is found.
4099 $grades = true;
4100 break;
4105 $options->grades = $grades;
4108 if (\core_competency\api::is_enabled()) {
4109 $capabilities = array('moodle/competency:coursecompetencyview', 'moodle/competency:coursecompetencymanage');
4110 $options->competencies = has_any_capability($capabilities, $context);
4112 return $options;
4116 * Return an object with the list of administration options in a course that are available or not for the current user.
4117 * This function also handles the frontpage settings.
4119 * @param stdClass $course course object (for frontpage it should be a clone of $SITE)
4120 * @param stdClass $context context object (course context)
4121 * @return stdClass the administration options in a course and their availability status
4122 * @since Moodle 3.2
4124 function course_get_user_administration_options($course, $context) {
4125 global $CFG;
4126 $isfrontpage = $course->id == SITEID;
4127 $completionenabled = $CFG->enablecompletion && $course->enablecompletion;
4128 $hascompletionoptions = count(core_completion\manager::get_available_completion_options($course->id)) > 0;
4129 $options = new stdClass;
4130 $options->update = has_capability('moodle/course:update', $context);
4131 $options->editcompletion = $CFG->enablecompletion && $course->enablecompletion &&
4132 ($options->update || $hascompletionoptions);
4133 $options->filters = has_capability('moodle/filter:manage', $context) &&
4134 count(filter_get_available_in_context($context)) > 0;
4135 $options->reports = has_capability('moodle/site:viewreports', $context);
4136 $options->backup = has_capability('moodle/backup:backupcourse', $context);
4137 $options->restore = has_capability('moodle/restore:restorecourse', $context);
4138 $options->copy = \core_course\management\helper::can_copy_course($course->id);
4139 $options->files = ($course->legacyfiles == 2 && has_capability('moodle/course:managefiles', $context));
4141 if (!$isfrontpage) {
4142 $options->tags = has_capability('moodle/course:tag', $context);
4143 $options->gradebook = has_capability('moodle/grade:manage', $context);
4144 $options->outcomes = !empty($CFG->enableoutcomes) && has_capability('moodle/course:update', $context);
4145 $options->badges = !empty($CFG->enablebadges);
4146 $options->import = has_capability('moodle/restore:restoretargetimport', $context);
4147 $options->reset = has_capability('moodle/course:reset', $context);
4148 $options->roles = has_capability('moodle/role:switchroles', $context);
4149 } else {
4150 // Set default options to false.
4151 $listofoptions = array('tags', 'gradebook', 'outcomes', 'badges', 'import', 'publish', 'reset', 'roles', 'grades');
4153 foreach ($listofoptions as $option) {
4154 $options->$option = false;
4158 return $options;
4162 * Validates course start and end dates.
4164 * Checks that the end course date is not greater than the start course date.
4166 * $coursedata['startdate'] or $coursedata['enddate'] may not be set, it depends on the form and user input.
4168 * @param array $coursedata May contain startdate and enddate timestamps, depends on the user input.
4169 * @return mixed False if everything alright, error codes otherwise.
4171 function course_validate_dates($coursedata) {
4173 // If both start and end dates are set end date should be later than the start date.
4174 if (!empty($coursedata['startdate']) && !empty($coursedata['enddate']) &&
4175 ($coursedata['enddate'] < $coursedata['startdate'])) {
4176 return 'enddatebeforestartdate';
4179 // If start date is not set end date can not be set.
4180 if (empty($coursedata['startdate']) && !empty($coursedata['enddate'])) {
4181 return 'nostartdatenoenddate';
4184 return false;
4188 * Check for course updates in the given context level instances (only modules supported right Now)
4190 * @param stdClass $course course object
4191 * @param array $tocheck instances to check for updates
4192 * @param array $filter check only for updates in these areas
4193 * @return array list of warnings and instances with updates information
4194 * @since Moodle 3.2
4196 function course_check_updates($course, $tocheck, $filter = array()) {
4197 global $CFG, $DB;
4199 $instances = array();
4200 $warnings = array();
4201 $modulescallbacksupport = array();
4202 $modinfo = get_fast_modinfo($course);
4204 $supportedplugins = get_plugin_list_with_function('mod', 'check_updates_since');
4206 // Check instances.
4207 foreach ($tocheck as $instance) {
4208 if ($instance['contextlevel'] == 'module') {
4209 // Check module visibility.
4210 try {
4211 $cm = $modinfo->get_cm($instance['id']);
4212 } catch (Exception $e) {
4213 $warnings[] = array(
4214 'item' => 'module',
4215 'itemid' => $instance['id'],
4216 'warningcode' => 'cmidnotincourse',
4217 'message' => 'This module id does not belong to this course.'
4219 continue;
4222 if (!$cm->uservisible) {
4223 $warnings[] = array(
4224 'item' => 'module',
4225 'itemid' => $instance['id'],
4226 'warningcode' => 'nonuservisible',
4227 'message' => 'You don\'t have access to this module.'
4229 continue;
4231 if (empty($supportedplugins['mod_' . $cm->modname])) {
4232 $warnings[] = array(
4233 'item' => 'module',
4234 'itemid' => $instance['id'],
4235 'warningcode' => 'missingcallback',
4236 'message' => 'This module does not implement the check_updates_since callback: ' . $instance['contextlevel'],
4238 continue;
4240 // Retrieve the module instance.
4241 $instances[] = array(
4242 'contextlevel' => $instance['contextlevel'],
4243 'id' => $instance['id'],
4244 'updates' => call_user_func($cm->modname . '_check_updates_since', $cm, $instance['since'], $filter)
4247 } else {
4248 $warnings[] = array(
4249 'item' => 'contextlevel',
4250 'itemid' => $instance['id'],
4251 'warningcode' => 'contextlevelnotsupported',
4252 'message' => 'Context level not yet supported ' . $instance['contextlevel'],
4256 return array($instances, $warnings);
4260 * This function classifies a course as past, in progress or future.
4262 * This function may incur a DB hit to calculate course completion.
4263 * @param stdClass $course Course record
4264 * @param stdClass $user User record (optional - defaults to $USER).
4265 * @param completion_info $completioninfo Completion record for the user (optional - will be fetched if required).
4266 * @return string (one of COURSE_TIMELINE_FUTURE, COURSE_TIMELINE_INPROGRESS or COURSE_TIMELINE_PAST)
4268 function course_classify_for_timeline($course, $user = null, $completioninfo = null) {
4269 global $USER;
4271 if ($user == null) {
4272 $user = $USER;
4275 $today = time();
4276 // End date past.
4277 if (!empty($course->enddate) && (course_classify_end_date($course) < $today)) {
4278 return COURSE_TIMELINE_PAST;
4281 if ($completioninfo == null) {
4282 $completioninfo = new completion_info($course);
4285 // Course was completed.
4286 if ($completioninfo->is_enabled() && $completioninfo->is_course_complete($user->id)) {
4287 return COURSE_TIMELINE_PAST;
4290 // Start date not reached.
4291 if (!empty($course->startdate) && (course_classify_start_date($course) > $today)) {
4292 return COURSE_TIMELINE_FUTURE;
4295 // Everything else is in progress.
4296 return COURSE_TIMELINE_INPROGRESS;
4300 * This function calculates the end date to use for display classification purposes,
4301 * incorporating the grace period, if any.
4303 * @param stdClass $course The course record.
4304 * @return int The new enddate.
4306 function course_classify_end_date($course) {
4307 global $CFG;
4308 $coursegraceperiodafter = (empty($CFG->coursegraceperiodafter)) ? 0 : $CFG->coursegraceperiodafter;
4309 $enddate = (new \DateTimeImmutable())->setTimestamp($course->enddate)->modify("+{$coursegraceperiodafter} days");
4310 return $enddate->getTimestamp();
4314 * This function calculates the start date to use for display classification purposes,
4315 * incorporating the grace period, if any.
4317 * @param stdClass $course The course record.
4318 * @return int The new startdate.
4320 function course_classify_start_date($course) {
4321 global $CFG;
4322 $coursegraceperiodbefore = (empty($CFG->coursegraceperiodbefore)) ? 0 : $CFG->coursegraceperiodbefore;
4323 $startdate = (new \DateTimeImmutable())->setTimestamp($course->startdate)->modify("-{$coursegraceperiodbefore} days");
4324 return $startdate->getTimestamp();
4328 * Group a list of courses into either past, future, or in progress.
4330 * The return value will be an array indexed by the COURSE_TIMELINE_* constants
4331 * with each value being an array of courses in that group.
4332 * E.g.
4334 * COURSE_TIMELINE_PAST => [... list of past courses ...],
4335 * COURSE_TIMELINE_FUTURE => [],
4336 * COURSE_TIMELINE_INPROGRESS => []
4339 * @param array $courses List of courses to be grouped.
4340 * @return array
4342 function course_classify_courses_for_timeline(array $courses) {
4343 return array_reduce($courses, function($carry, $course) {
4344 $classification = course_classify_for_timeline($course);
4345 array_push($carry[$classification], $course);
4347 return $carry;
4348 }, [
4349 COURSE_TIMELINE_PAST => [],
4350 COURSE_TIMELINE_FUTURE => [],
4351 COURSE_TIMELINE_INPROGRESS => []
4356 * Get the list of enrolled courses for the current user.
4358 * This function returns a Generator. The courses will be loaded from the database
4359 * in chunks rather than a single query.
4361 * @param int $limit Restrict result set to this amount
4362 * @param int $offset Skip this number of records from the start of the result set
4363 * @param string|null $sort SQL string for sorting
4364 * @param string|null $fields SQL string for fields to be returned
4365 * @param int $dbquerylimit The number of records to load per DB request
4366 * @param array $includecourses courses ids to be restricted
4367 * @param array $hiddencourses courses ids to be excluded
4368 * @return Generator
4370 function course_get_enrolled_courses_for_logged_in_user(
4371 int $limit = 0,
4372 int $offset = 0,
4373 string $sort = null,
4374 string $fields = null,
4375 int $dbquerylimit = COURSE_DB_QUERY_LIMIT,
4376 array $includecourses = [],
4377 array $hiddencourses = []
4378 ) : Generator {
4380 $haslimit = !empty($limit);
4381 $recordsloaded = 0;
4382 $querylimit = (!$haslimit || $limit > $dbquerylimit) ? $dbquerylimit : $limit;
4384 while ($courses = enrol_get_my_courses($fields, $sort, $querylimit, $includecourses, false, $offset, $hiddencourses)) {
4385 yield from $courses;
4387 $recordsloaded += $querylimit;
4389 if (count($courses) < $querylimit) {
4390 break;
4392 if ($haslimit && $recordsloaded >= $limit) {
4393 break;
4396 $offset += $querylimit;
4401 * Get the list of enrolled courses the current user searched for.
4403 * This function returns a Generator. The courses will be loaded from the database
4404 * in chunks rather than a single query.
4406 * @param int $limit Restrict result set to this amount
4407 * @param int $offset Skip this number of records from the start of the result set
4408 * @param string|null $sort SQL string for sorting
4409 * @param string|null $fields SQL string for fields to be returned
4410 * @param int $dbquerylimit The number of records to load per DB request
4411 * @param array $searchcriteria contains search criteria
4412 * @param array $options display options, same as in get_courses() except 'recursive' is ignored -
4413 * search is always category-independent
4414 * @return Generator
4416 function course_get_enrolled_courses_for_logged_in_user_from_search(
4417 int $limit = 0,
4418 int $offset = 0,
4419 string $sort = null,
4420 string $fields = null,
4421 int $dbquerylimit = COURSE_DB_QUERY_LIMIT,
4422 array $searchcriteria = [],
4423 array $options = []
4424 ) : Generator {
4426 $haslimit = !empty($limit);
4427 $recordsloaded = 0;
4428 $querylimit = (!$haslimit || $limit > $dbquerylimit) ? $dbquerylimit : $limit;
4429 $ids = core_course_category::search_courses($searchcriteria, $options);
4431 // If no courses were found matching the criteria return back.
4432 if (empty($ids)) {
4433 return;
4436 while ($courses = enrol_get_my_courses($fields, $sort, $querylimit, $ids, false, $offset)) {
4437 yield from $courses;
4439 $recordsloaded += $querylimit;
4441 if (count($courses) < $querylimit) {
4442 break;
4444 if ($haslimit && $recordsloaded >= $limit) {
4445 break;
4448 $offset += $querylimit;
4453 * Search the given $courses for any that match the given $classification up to the specified
4454 * $limit.
4456 * This function will return the subset of courses that match the classification as well as the
4457 * number of courses it had to process to build that subset.
4459 * It is recommended that for larger sets of courses this function is given a Generator that loads
4460 * the courses from the database in chunks.
4462 * @param array|Traversable $courses List of courses to process
4463 * @param string $classification One of the COURSE_TIMELINE_* constants
4464 * @param int $limit Limit the number of results to this amount
4465 * @return array First value is the filtered courses, second value is the number of courses processed
4467 function course_filter_courses_by_timeline_classification(
4468 $courses,
4469 string $classification,
4470 int $limit = 0
4471 ) : array {
4473 if (!in_array($classification,
4474 [COURSE_TIMELINE_ALLINCLUDINGHIDDEN, COURSE_TIMELINE_ALL, COURSE_TIMELINE_PAST, COURSE_TIMELINE_INPROGRESS,
4475 COURSE_TIMELINE_FUTURE, COURSE_TIMELINE_HIDDEN, COURSE_TIMELINE_SEARCH])) {
4476 $message = 'Classification must be one of COURSE_TIMELINE_ALLINCLUDINGHIDDEN, COURSE_TIMELINE_ALL, COURSE_TIMELINE_PAST, '
4477 . 'COURSE_TIMELINE_INPROGRESS, COURSE_TIMELINE_SEARCH or COURSE_TIMELINE_FUTURE';
4478 throw new moodle_exception($message);
4481 $filteredcourses = [];
4482 $numberofcoursesprocessed = 0;
4483 $filtermatches = 0;
4485 foreach ($courses as $course) {
4486 $numberofcoursesprocessed++;
4487 $pref = get_user_preferences('block_myoverview_hidden_course_' . $course->id, 0);
4489 // Added as of MDL-63457 toggle viewability for each user.
4490 if ($classification == COURSE_TIMELINE_ALLINCLUDINGHIDDEN || ($classification == COURSE_TIMELINE_HIDDEN && $pref) ||
4491 $classification == COURSE_TIMELINE_SEARCH||
4492 (($classification == COURSE_TIMELINE_ALL || $classification == course_classify_for_timeline($course)) && !$pref)) {
4493 $filteredcourses[] = $course;
4494 $filtermatches++;
4497 if ($limit && $filtermatches >= $limit) {
4498 // We've found the number of requested courses. No need to continue searching.
4499 break;
4503 // Return the number of filtered courses as well as the number of courses that were searched
4504 // in order to find the matching courses. This allows the calling code to do some kind of
4505 // pagination.
4506 return [$filteredcourses, $numberofcoursesprocessed];
4510 * Search the given $courses for any that match the given $classification up to the specified
4511 * $limit.
4513 * This function will return the subset of courses that are favourites as well as the
4514 * number of courses it had to process to build that subset.
4516 * It is recommended that for larger sets of courses this function is given a Generator that loads
4517 * the courses from the database in chunks.
4519 * @param array|Traversable $courses List of courses to process
4520 * @param array $favouritecourseids Array of favourite courses.
4521 * @param int $limit Limit the number of results to this amount
4522 * @return array First value is the filtered courses, second value is the number of courses processed
4524 function course_filter_courses_by_favourites(
4525 $courses,
4526 $favouritecourseids,
4527 int $limit = 0
4528 ) : array {
4530 $filteredcourses = [];
4531 $numberofcoursesprocessed = 0;
4532 $filtermatches = 0;
4534 foreach ($courses as $course) {
4535 $numberofcoursesprocessed++;
4537 if (in_array($course->id, $favouritecourseids)) {
4538 $filteredcourses[] = $course;
4539 $filtermatches++;
4542 if ($limit && $filtermatches >= $limit) {
4543 // We've found the number of requested courses. No need to continue searching.
4544 break;
4548 // Return the number of filtered courses as well as the number of courses that were searched
4549 // in order to find the matching courses. This allows the calling code to do some kind of
4550 // pagination.
4551 return [$filteredcourses, $numberofcoursesprocessed];
4555 * Search the given $courses for any that have a $customfieldname value that matches the given
4556 * $customfieldvalue, up to the specified $limit.
4558 * This function will return the subset of courses that matches the value as well as the
4559 * number of courses it had to process to build that subset.
4561 * It is recommended that for larger sets of courses this function is given a Generator that loads
4562 * the courses from the database in chunks.
4564 * @param array|Traversable $courses List of courses to process
4565 * @param string $customfieldname the shortname of the custom field to match against
4566 * @param string $customfieldvalue the value this custom field needs to match
4567 * @param int $limit Limit the number of results to this amount
4568 * @return array First value is the filtered courses, second value is the number of courses processed
4570 function course_filter_courses_by_customfield(
4571 $courses,
4572 $customfieldname,
4573 $customfieldvalue,
4574 int $limit = 0
4575 ) : array {
4576 global $DB;
4578 if (!$courses) {
4579 return [[], 0];
4582 // Prepare the list of courses to search through.
4583 $coursesbyid = [];
4584 foreach ($courses as $course) {
4585 $coursesbyid[$course->id] = $course;
4587 if (!$coursesbyid) {
4588 return [[], 0];
4590 list($csql, $params) = $DB->get_in_or_equal(array_keys($coursesbyid), SQL_PARAMS_NAMED);
4592 // Get the id of the custom field.
4593 $sql = "
4594 SELECT f.id
4595 FROM {customfield_field} f
4596 JOIN {customfield_category} cat ON cat.id = f.categoryid
4597 WHERE f.shortname = ?
4598 AND cat.component = 'core_course'
4599 AND cat.area = 'course'
4601 $fieldid = $DB->get_field_sql($sql, [$customfieldname]);
4602 if (!$fieldid) {
4603 return [[], 0];
4606 // Get a list of courseids that match that custom field value.
4607 if ($customfieldvalue == COURSE_CUSTOMFIELD_EMPTY) {
4608 $comparevalue = $DB->sql_compare_text('cd.value');
4609 $sql = "
4610 SELECT c.id
4611 FROM {course} c
4612 LEFT JOIN {customfield_data} cd ON cd.instanceid = c.id AND cd.fieldid = :fieldid
4613 WHERE c.id $csql
4614 AND (cd.value IS NULL OR $comparevalue = '' OR $comparevalue = '0')
4616 $params['fieldid'] = $fieldid;
4617 $matchcourseids = $DB->get_fieldset_sql($sql, $params);
4618 } else {
4619 $comparevalue = $DB->sql_compare_text('value');
4620 $select = "fieldid = :fieldid AND $comparevalue = :customfieldvalue AND instanceid $csql";
4621 $params['fieldid'] = $fieldid;
4622 $params['customfieldvalue'] = $customfieldvalue;
4623 $matchcourseids = $DB->get_fieldset_select('customfield_data', 'instanceid', $select, $params);
4626 // Prepare the list of courses to return.
4627 $filteredcourses = [];
4628 $numberofcoursesprocessed = 0;
4629 $filtermatches = 0;
4631 foreach ($coursesbyid as $course) {
4632 $numberofcoursesprocessed++;
4634 if (in_array($course->id, $matchcourseids)) {
4635 $filteredcourses[] = $course;
4636 $filtermatches++;
4639 if ($limit && $filtermatches >= $limit) {
4640 // We've found the number of requested courses. No need to continue searching.
4641 break;
4645 // Return the number of filtered courses as well as the number of courses that were searched
4646 // in order to find the matching courses. This allows the calling code to do some kind of
4647 // pagination.
4648 return [$filteredcourses, $numberofcoursesprocessed];
4652 * Check module updates since a given time.
4653 * This function checks for updates in the module config, file areas, completion, grades, comments and ratings.
4655 * @param cm_info $cm course module data
4656 * @param int $from the time to check
4657 * @param array $fileareas additional file ares to check
4658 * @param array $filter if we need to filter and return only selected updates
4659 * @return stdClass object with the different updates
4660 * @since Moodle 3.2
4662 function course_check_module_updates_since($cm, $from, $fileareas = array(), $filter = array()) {
4663 global $DB, $CFG, $USER;
4665 $context = $cm->context;
4666 $mod = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
4668 $updates = new stdClass();
4669 $course = get_course($cm->course);
4670 $component = 'mod_' . $cm->modname;
4672 // Check changes in the module configuration.
4673 if (isset($mod->timemodified) and (empty($filter) or in_array('configuration', $filter))) {
4674 $updates->configuration = (object) array('updated' => false);
4675 if ($updates->configuration->updated = $mod->timemodified > $from) {
4676 $updates->configuration->timeupdated = $mod->timemodified;
4680 // Check for updates in files.
4681 if (plugin_supports('mod', $cm->modname, FEATURE_MOD_INTRO)) {
4682 $fileareas[] = 'intro';
4684 if (!empty($fileareas) and (empty($filter) or in_array('fileareas', $filter))) {
4685 $fs = get_file_storage();
4686 $files = $fs->get_area_files($context->id, $component, $fileareas, false, "filearea, timemodified DESC", false, $from);
4687 foreach ($fileareas as $filearea) {
4688 $updates->{$filearea . 'files'} = (object) array('updated' => false);
4690 foreach ($files as $file) {
4691 $updates->{$file->get_filearea() . 'files'}->updated = true;
4692 $updates->{$file->get_filearea() . 'files'}->itemids[] = $file->get_id();
4696 // Check completion.
4697 $supportcompletion = plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_HAS_RULES);
4698 $supportcompletion = $supportcompletion or plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_TRACKS_VIEWS);
4699 if ($supportcompletion and (empty($filter) or in_array('completion', $filter))) {
4700 $updates->completion = (object) array('updated' => false);
4701 $completion = new completion_info($course);
4702 // Use wholecourse to cache all the modules the first time.
4703 $completiondata = $completion->get_data($cm, true);
4704 if ($updates->completion->updated = !empty($completiondata->timemodified) && $completiondata->timemodified > $from) {
4705 $updates->completion->timemodified = $completiondata->timemodified;
4709 // Check grades.
4710 $supportgrades = plugin_supports('mod', $cm->modname, FEATURE_GRADE_HAS_GRADE);
4711 $supportgrades = $supportgrades or plugin_supports('mod', $cm->modname, FEATURE_GRADE_OUTCOMES);
4712 if ($supportgrades and (empty($filter) or (in_array('gradeitems', $filter) or in_array('outcomes', $filter)))) {
4713 require_once($CFG->libdir . '/gradelib.php');
4714 $grades = grade_get_grades($course->id, 'mod', $cm->modname, $mod->id, $USER->id);
4716 if (empty($filter) or in_array('gradeitems', $filter)) {
4717 $updates->gradeitems = (object) array('updated' => false);
4718 foreach ($grades->items as $gradeitem) {
4719 foreach ($gradeitem->grades as $grade) {
4720 if ($grade->datesubmitted > $from or $grade->dategraded > $from) {
4721 $updates->gradeitems->updated = true;
4722 $updates->gradeitems->itemids[] = $gradeitem->id;
4728 if (empty($filter) or in_array('outcomes', $filter)) {
4729 $updates->outcomes = (object) array('updated' => false);
4730 foreach ($grades->outcomes as $outcome) {
4731 foreach ($outcome->grades as $grade) {
4732 if ($grade->datesubmitted > $from or $grade->dategraded > $from) {
4733 $updates->outcomes->updated = true;
4734 $updates->outcomes->itemids[] = $outcome->id;
4741 // Check comments.
4742 if (plugin_supports('mod', $cm->modname, FEATURE_COMMENT) and (empty($filter) or in_array('comments', $filter))) {
4743 $updates->comments = (object) array('updated' => false);
4744 require_once($CFG->dirroot . '/comment/lib.php');
4745 require_once($CFG->dirroot . '/comment/locallib.php');
4746 $manager = new comment_manager();
4747 $comments = $manager->get_component_comments_since($course, $context, $component, $from, $cm);
4748 if (!empty($comments)) {
4749 $updates->comments->updated = true;
4750 $updates->comments->itemids = array_keys($comments);
4754 // Check ratings.
4755 if (plugin_supports('mod', $cm->modname, FEATURE_RATE) and (empty($filter) or in_array('ratings', $filter))) {
4756 $updates->ratings = (object) array('updated' => false);
4757 require_once($CFG->dirroot . '/rating/lib.php');
4758 $manager = new rating_manager();
4759 $ratings = $manager->get_component_ratings_since($context, $component, $from);
4760 if (!empty($ratings)) {
4761 $updates->ratings->updated = true;
4762 $updates->ratings->itemids = array_keys($ratings);
4766 return $updates;
4770 * Returns true if the user can view the participant page, false otherwise,
4772 * @param context $context The context we are checking.
4773 * @return bool
4775 function course_can_view_participants($context) {
4776 $viewparticipantscap = 'moodle/course:viewparticipants';
4777 if ($context->contextlevel == CONTEXT_SYSTEM) {
4778 $viewparticipantscap = 'moodle/site:viewparticipants';
4781 return has_any_capability([$viewparticipantscap, 'moodle/course:enrolreview'], $context);
4785 * Checks if a user can view the participant page, if not throws an exception.
4787 * @param context $context The context we are checking.
4788 * @throws required_capability_exception
4790 function course_require_view_participants($context) {
4791 if (!course_can_view_participants($context)) {
4792 $viewparticipantscap = 'moodle/course:viewparticipants';
4793 if ($context->contextlevel == CONTEXT_SYSTEM) {
4794 $viewparticipantscap = 'moodle/site:viewparticipants';
4796 throw new required_capability_exception($context, $viewparticipantscap, 'nopermissions', '');
4801 * Return whether the user can download from the specified backup file area in the given context.
4803 * @param string $filearea the backup file area. E.g. 'course', 'backup' or 'automated'.
4804 * @param \context $context
4805 * @param stdClass $user the user object. If not provided, the current user will be checked.
4806 * @return bool true if the user is allowed to download in the context, false otherwise.
4808 function can_download_from_backup_filearea($filearea, \context $context, stdClass $user = null) {
4809 $candownload = false;
4810 switch ($filearea) {
4811 case 'course':
4812 case 'backup':
4813 $candownload = has_capability('moodle/backup:downloadfile', $context, $user);
4814 break;
4815 case 'automated':
4816 // Given the automated backups may contain userinfo, we restrict access such that only users who are able to
4817 // restore with userinfo are able to download the file. Users can't create these backups, so checking 'backup:userinfo'
4818 // doesn't make sense here.
4819 $candownload = has_capability('moodle/backup:downloadfile', $context, $user) &&
4820 has_capability('moodle/restore:userinfo', $context, $user);
4821 break;
4822 default:
4823 break;
4826 return $candownload;
4830 * Get a list of hidden courses
4832 * @param int|object|null $user User override to get the filter from. Defaults to current user
4833 * @return array $ids List of hidden courses
4834 * @throws coding_exception
4836 function get_hidden_courses_on_timeline($user = null) {
4837 global $USER;
4839 if (empty($user)) {
4840 $user = $USER->id;
4843 $preferences = get_user_preferences(null, null, $user);
4844 $ids = [];
4845 foreach ($preferences as $key => $value) {
4846 if (preg_match('/block_myoverview_hidden_course_(\d)+/', $key)) {
4847 $id = preg_split('/block_myoverview_hidden_course_/', $key);
4848 $ids[] = $id[1];
4852 return $ids;
4856 * Returns a list of the most recently courses accessed by a user
4858 * @param int $userid User id from which the courses will be obtained
4859 * @param int $limit Restrict result set to this amount
4860 * @param int $offset Skip this number of records from the start of the result set
4861 * @param string|null $sort SQL string for sorting
4862 * @return array
4864 function course_get_recent_courses(int $userid = null, int $limit = 0, int $offset = 0, string $sort = null) {
4866 global $CFG, $USER, $DB;
4868 if (empty($userid)) {
4869 $userid = $USER->id;
4872 $basefields = [
4873 'id', 'idnumber', 'summary', 'summaryformat', 'startdate', 'enddate', 'category',
4874 'shortname', 'fullname', 'timeaccess', 'component', 'visible',
4875 'showactivitydates', 'showcompletionconditions',
4878 if (empty($sort)) {
4879 $sort = 'timeaccess DESC';
4880 } else {
4881 // The SQL string for sorting can define sorting by multiple columns.
4882 $rawsorts = explode(',', $sort);
4883 $sorts = array();
4884 // Validate and trim the sort parameters in the SQL string for sorting.
4885 foreach ($rawsorts as $rawsort) {
4886 $sort = trim($rawsort);
4887 $sortparams = explode(' ', $sort);
4888 // A valid sort statement can not have more than 2 params (ex. 'summary desc' or 'timeaccess').
4889 if (count($sortparams) > 2) {
4890 throw new invalid_parameter_exception(
4891 'Invalid structure of the sort parameter, allowed structure: fieldname [ASC|DESC].');
4893 $sortfield = trim($sortparams[0]);
4894 // Validate the value which defines the field to sort by.
4895 if (!in_array($sortfield, $basefields)) {
4896 throw new invalid_parameter_exception('Invalid field in the sort parameter, allowed fields: ' .
4897 implode(', ', $basefields) . '.');
4899 $sortdirection = isset($sortparams[1]) ? trim($sortparams[1]) : '';
4900 // Validate the value which defines the sort direction (if present).
4901 $allowedsortdirections = ['asc', 'desc'];
4902 if (!empty($sortdirection) && !in_array(strtolower($sortdirection), $allowedsortdirections)) {
4903 throw new invalid_parameter_exception('Invalid sort direction in the sort parameter, allowed values: ' .
4904 implode(', ', $allowedsortdirections) . '.');
4906 $sorts[] = $sort;
4908 $sort = implode(',', $sorts);
4911 $ctxfields = context_helper::get_preload_record_columns_sql('ctx');
4913 $coursefields = 'c.' . join(',', $basefields);
4915 // Ask the favourites service to give us the join SQL for favourited courses,
4916 // so we can include favourite information in the query.
4917 $usercontext = \context_user::instance($userid);
4918 $favservice = \core_favourites\service_factory::get_service_for_user_context($usercontext);
4919 list($favsql, $favparams) = $favservice->get_join_sql_by_type('core_course', 'courses', 'fav', 'ul.courseid');
4921 $sql = "SELECT $coursefields, $ctxfields
4922 FROM {course} c
4923 JOIN {context} ctx
4924 ON ctx.contextlevel = :contextlevel
4925 AND ctx.instanceid = c.id
4926 JOIN {user_lastaccess} ul
4927 ON ul.courseid = c.id
4928 $favsql
4929 LEFT JOIN {enrol} eg ON eg.courseid = c.id AND eg.status = :statusenrolg AND eg.enrol = :guestenrol
4930 WHERE ul.userid = :userid
4931 AND c.visible = :visible
4932 AND (eg.id IS NOT NULL
4933 OR EXISTS (SELECT e.id
4934 FROM {enrol} e
4935 JOIN {user_enrolments} ue ON ue.enrolid = e.id
4936 WHERE e.courseid = c.id
4937 AND e.status = :statusenrol
4938 AND ue.status = :status
4939 AND ue.userid = :userid2
4940 AND ue.timestart < :now1
4941 AND (ue.timeend = 0 OR ue.timeend > :now2)
4943 ORDER BY $sort";
4945 $now = round(time(), -2); // Improves db caching.
4946 $params = ['userid' => $userid, 'contextlevel' => CONTEXT_COURSE, 'visible' => 1, 'status' => ENROL_USER_ACTIVE,
4947 'statusenrol' => ENROL_INSTANCE_ENABLED, 'guestenrol' => 'guest', 'now1' => $now, 'now2' => $now,
4948 'userid2' => $userid, 'statusenrolg' => ENROL_INSTANCE_ENABLED] + $favparams;
4950 $recentcourses = $DB->get_records_sql($sql, $params, $offset, $limit);
4952 // Filter courses if last access field is hidden.
4953 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
4955 if ($userid != $USER->id && isset($hiddenfields['lastaccess'])) {
4956 $recentcourses = array_filter($recentcourses, function($course) {
4957 context_helper::preload_from_record($course);
4958 $context = context_course::instance($course->id, IGNORE_MISSING);
4959 // If last access was a hidden field, a user requesting info about another user would need permission to view hidden
4960 // fields.
4961 return has_capability('moodle/course:viewhiddenuserfields', $context);
4965 return $recentcourses;
4969 * Calculate the course start date and offset for the given user ids.
4971 * If the course is a fixed date course then the course start date will be returned.
4972 * If the course is a relative date course then the course date will be calculated and
4973 * and offset provided.
4975 * The dates are returned as an array with the index being the user id. The array
4976 * contains the start date and start offset values for the user.
4978 * If the user is not enrolled in the course then the course start date will be returned.
4980 * If we have a course which starts on 1563244000 and 2 users, id 123 and 456, where the
4981 * former is enrolled in the course at 1563244693 and the latter is not enrolled then the
4982 * return value would look like:
4984 * '123' => [
4985 * 'start' => 1563244693,
4986 * 'startoffset' => 693
4987 * ],
4988 * '456' => [
4989 * 'start' => 1563244000,
4990 * 'startoffset' => 0
4994 * @param stdClass $course The course to fetch dates for.
4995 * @param array $userids The list of user ids to get dates for.
4996 * @return array
4998 function course_get_course_dates_for_user_ids(stdClass $course, array $userids): array {
4999 if (empty($course->relativedatesmode)) {
5000 // This course isn't set to relative dates so we can early return with the course
5001 // start date.
5002 return array_reduce($userids, function($carry, $userid) use ($course) {
5003 $carry[$userid] = [
5004 'start' => $course->startdate,
5005 'startoffset' => 0
5007 return $carry;
5008 }, []);
5011 // We're dealing with a relative dates course now so we need to calculate some dates.
5012 $cache = cache::make('core', 'course_user_dates');
5013 $dates = [];
5014 $uncacheduserids = [];
5016 // Try fetching the values from the cache so that we don't need to do a DB request.
5017 foreach ($userids as $userid) {
5018 $cachekey = "{$course->id}_{$userid}";
5019 $cachedvalue = $cache->get($cachekey);
5021 if ($cachedvalue === false) {
5022 // Looks like we haven't seen this user for this course before so we'll have
5023 // to fetch it.
5024 $uncacheduserids[] = $userid;
5025 } else {
5026 [$start, $startoffset] = $cachedvalue;
5027 $dates[$userid] = [
5028 'start' => $start,
5029 'startoffset' => $startoffset
5034 if (!empty($uncacheduserids)) {
5035 // Load the enrolments for any users we haven't seen yet. Set the "onlyactive" param
5036 // to false because it filters out users with enrolment start times in the future which
5037 // we don't want.
5038 $enrolments = enrol_get_course_users($course->id, false, $uncacheduserids);
5040 foreach ($uncacheduserids as $userid) {
5041 // Find the user enrolment that has the earliest start date.
5042 $enrolment = array_reduce(array_values($enrolments), function($carry, $enrolment) use ($userid) {
5043 // Only consider enrolments for this user if the user enrolment is active and the
5044 // enrolment method is enabled.
5045 if (
5046 $enrolment->uestatus == ENROL_USER_ACTIVE &&
5047 $enrolment->estatus == ENROL_INSTANCE_ENABLED &&
5048 $enrolment->id == $userid
5050 if (is_null($carry)) {
5051 // Haven't found an enrolment yet for this user so use the one we just found.
5052 $carry = $enrolment;
5053 } else {
5054 // We've already found an enrolment for this user so let's use which ever one
5055 // has the earliest start time.
5056 $carry = $carry->uetimestart < $enrolment->uetimestart ? $carry : $enrolment;
5060 return $carry;
5061 }, null);
5063 if ($enrolment) {
5064 // The course is in relative dates mode so we calculate the student's start
5065 // date based on their enrolment start date.
5066 $start = $course->startdate > $enrolment->uetimestart ? $course->startdate : $enrolment->uetimestart;
5067 $startoffset = $start - $course->startdate;
5068 } else {
5069 // The user is not enrolled in the course so default back to the course start date.
5070 $start = $course->startdate;
5071 $startoffset = 0;
5074 $dates[$userid] = [
5075 'start' => $start,
5076 'startoffset' => $startoffset
5079 $cachekey = "{$course->id}_{$userid}";
5080 $cache->set($cachekey, [$start, $startoffset]);
5084 return $dates;
5088 * Calculate the course start date and offset for the given user id.
5090 * If the course is a fixed date course then the course start date will be returned.
5091 * If the course is a relative date course then the course date will be calculated and
5092 * and offset provided.
5094 * The return array contains the start date and start offset values for the user.
5096 * If the user is not enrolled in the course then the course start date will be returned.
5098 * If we have a course which starts on 1563244000. If a user's enrolment starts on 1563244693
5099 * then the return would be:
5101 * 'start' => 1563244693,
5102 * 'startoffset' => 693
5105 * If the use was not enrolled then the return would be:
5107 * 'start' => 1563244000,
5108 * 'startoffset' => 0
5111 * @param stdClass $course The course to fetch dates for.
5112 * @param int $userid The user id to get dates for.
5113 * @return array
5115 function course_get_course_dates_for_user_id(stdClass $course, int $userid): array {
5116 return (course_get_course_dates_for_user_ids($course, [$userid]))[$userid];
5120 * Renders the course copy form for the modal on the course management screen.
5122 * @param array $args
5123 * @return string $o Form HTML.
5125 function course_output_fragment_new_base_form($args) {
5127 $serialiseddata = json_decode($args['jsonformdata'], true);
5128 $formdata = [];
5129 if (!empty($serialiseddata)) {
5130 parse_str($serialiseddata, $formdata);
5133 $context = context_course::instance($args['courseid']);
5134 $copycaps = \core_course\management\helper::get_course_copy_capabilities();
5135 require_all_capabilities($copycaps, $context);
5137 $course = get_course($args['courseid']);
5138 $mform = new \core_backup\output\copy_form(
5139 null,
5140 array('course' => $course, 'returnto' => '', 'returnurl' => ''),
5141 'post', '', ['class' => 'ignoredirty'], true, $formdata);
5143 if (!empty($serialiseddata)) {
5144 // If we were passed non-empty form data we want the mform to call validation functions and show errors.
5145 $mform->is_validated();
5148 ob_start();
5149 $mform->display();
5150 $o = ob_get_contents();
5151 ob_end_clean();
5153 return $o;