MDL-68292 core: Remove sesskey leakage on module pages
[moodle.git] / course / lib.php
bloba834ba73222e52c14e73a1169ff04e445a5aa4bb
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Library of useful functions
20 * @copyright 1999 Martin Dougiamas http://dougiamas.com
21 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
22 * @package core_course
25 defined('MOODLE_INTERNAL') || die;
27 require_once($CFG->libdir.'/completionlib.php');
28 require_once($CFG->libdir.'/filelib.php');
29 require_once($CFG->libdir.'/datalib.php');
30 require_once($CFG->dirroot.'/course/format/lib.php');
32 define('COURSE_MAX_LOGS_PER_PAGE', 1000); // Records.
33 define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds.
35 /**
36 * Number of courses to display when summaries are included.
37 * @var int
38 * @deprecated since 2.4, use $CFG->courseswithsummarieslimit instead.
40 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10);
42 // Max courses in log dropdown before switching to optional.
43 define('COURSE_MAX_COURSES_PER_DROPDOWN', 1000);
44 // Max users in log dropdown before switching to optional.
45 define('COURSE_MAX_USERS_PER_DROPDOWN', 1000);
46 define('FRONTPAGENEWS', '0');
47 define('FRONTPAGECATEGORYNAMES', '2');
48 define('FRONTPAGECATEGORYCOMBO', '4');
49 define('FRONTPAGEENROLLEDCOURSELIST', '5');
50 define('FRONTPAGEALLCOURSELIST', '6');
51 define('FRONTPAGECOURSESEARCH', '7');
52 // Important! Replaced with $CFG->frontpagecourselimit - maximum number of courses displayed on the frontpage.
53 define('EXCELROWS', 65535);
54 define('FIRSTUSEDEXCELROW', 3);
56 define('MOD_CLASS_ACTIVITY', 0);
57 define('MOD_CLASS_RESOURCE', 1);
59 define('COURSE_TIMELINE_ALLINCLUDINGHIDDEN', 'allincludinghidden');
60 define('COURSE_TIMELINE_ALL', 'all');
61 define('COURSE_TIMELINE_PAST', 'past');
62 define('COURSE_TIMELINE_INPROGRESS', 'inprogress');
63 define('COURSE_TIMELINE_FUTURE', 'future');
64 define('COURSE_FAVOURITES', 'favourites');
65 define('COURSE_TIMELINE_HIDDEN', 'hidden');
66 define('COURSE_CUSTOMFIELD', 'customfield');
67 define('COURSE_DB_QUERY_LIMIT', 1000);
68 /** Searching for all courses that have no value for the specified custom field. */
69 define('COURSE_CUSTOMFIELD_EMPTY', -1);
71 // Course activity chooser footer default display option.
72 define('COURSE_CHOOSER_FOOTER_NONE', 'hidden');
74 function make_log_url($module, $url) {
75 switch ($module) {
76 case 'course':
77 if (strpos($url, 'report/') === 0) {
78 // there is only one report type, course reports are deprecated
79 $url = "/$url";
80 break;
82 case 'file':
83 case 'login':
84 case 'lib':
85 case 'admin':
86 case 'category':
87 case 'mnet course':
88 if (strpos($url, '../') === 0) {
89 $url = ltrim($url, '.');
90 } else {
91 $url = "/course/$url";
93 break;
94 case 'calendar':
95 $url = "/calendar/$url";
96 break;
97 case 'user':
98 case 'blog':
99 $url = "/$module/$url";
100 break;
101 case 'upload':
102 $url = $url;
103 break;
104 case 'coursetags':
105 $url = '/'.$url;
106 break;
107 case 'library':
108 case '':
109 $url = '/';
110 break;
111 case 'message':
112 $url = "/message/$url";
113 break;
114 case 'notes':
115 $url = "/notes/$url";
116 break;
117 case 'tag':
118 $url = "/tag/$url";
119 break;
120 case 'role':
121 $url = '/'.$url;
122 break;
123 case 'grade':
124 $url = "/grade/$url";
125 break;
126 default:
127 $url = "/mod/$module/$url";
128 break;
131 //now let's sanitise urls - there might be some ugly nasties:-(
132 $parts = explode('?', $url);
133 $script = array_shift($parts);
134 if (strpos($script, 'http') === 0) {
135 $script = clean_param($script, PARAM_URL);
136 } else {
137 $script = clean_param($script, PARAM_PATH);
140 $query = '';
141 if ($parts) {
142 $query = implode('', $parts);
143 $query = str_replace('&amp;', '&', $query); // both & and &amp; are stored in db :-|
144 $parts = explode('&', $query);
145 $eq = urlencode('=');
146 foreach ($parts as $key=>$part) {
147 $part = urlencode(urldecode($part));
148 $part = str_replace($eq, '=', $part);
149 $parts[$key] = $part;
151 $query = '?'.implode('&amp;', $parts);
154 return $script.$query;
158 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
159 $modname="", $modid=0, $modaction="", $groupid=0) {
160 global $CFG, $DB;
162 // It is assumed that $date is the GMT time of midnight for that day,
163 // and so the next 86400 seconds worth of logs are printed.
165 /// Setup for group handling.
167 // TODO: I don't understand group/context/etc. enough to be able to do
168 // something interesting with it here
169 // What is the context of a remote course?
171 /// If the group mode is separate, and this user does not have editing privileges,
172 /// then only the user's group can be viewed.
173 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
174 // $groupid = get_current_group($course->id);
176 /// If this course doesn't have groups, no groupid can be specified.
177 //else if (!$course->groupmode) {
178 // $groupid = 0;
181 $groupid = 0;
183 $joins = array();
184 $where = '';
186 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
187 FROM {mnet_log} l
188 LEFT JOIN {user} u ON l.userid = u.id
189 WHERE ";
190 $params = array();
192 $where .= "l.hostid = :hostid";
193 $params['hostid'] = $hostid;
195 // TODO: Is 1 really a magic number referring to the sitename?
196 if ($course != SITEID || $modid != 0) {
197 $where .= " AND l.course=:courseid";
198 $params['courseid'] = $course;
201 if ($modname) {
202 $where .= " AND l.module = :modname";
203 $params['modname'] = $modname;
206 if ('site_errors' === $modid) {
207 $where .= " AND ( l.action='error' OR l.action='infected' )";
208 } else if ($modid) {
209 //TODO: This assumes that modids are the same across sites... probably
210 //not true
211 $where .= " AND l.cmid = :modid";
212 $params['modid'] = $modid;
215 if ($modaction) {
216 $firstletter = substr($modaction, 0, 1);
217 if ($firstletter == '-') {
218 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
219 $params['modaction'] = '%'.substr($modaction, 1).'%';
220 } else {
221 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
222 $params['modaction'] = '%'.$modaction.'%';
226 if ($user) {
227 $where .= " AND l.userid = :user";
228 $params['user'] = $user;
231 if ($date) {
232 $enddate = $date + 86400;
233 $where .= " AND l.time > :date AND l.time < :enddate";
234 $params['date'] = $date;
235 $params['enddate'] = $enddate;
238 $result = array();
239 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
240 if(!empty($result['totalcount'])) {
241 $where .= " ORDER BY $order";
242 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
243 } else {
244 $result['logs'] = array();
246 return $result;
250 * Checks the integrity of the course data.
252 * In summary - compares course_sections.sequence and course_modules.section.
254 * More detailed, checks that:
255 * - course_sections.sequence contains each module id not more than once in the course
256 * - for each moduleid from course_sections.sequence the field course_modules.section
257 * refers to the same section id (this means course_sections.sequence is more
258 * important if they are different)
259 * - ($fullcheck only) each module in the course is present in one of
260 * course_sections.sequence
261 * - ($fullcheck only) removes non-existing course modules from section sequences
263 * If there are any mismatches, the changes are made and records are updated in DB.
265 * Course cache is NOT rebuilt if there are any errors!
267 * This function is used each time when course cache is being rebuilt with $fullcheck = false
268 * and in CLI script admin/cli/fix_course_sequence.php with $fullcheck = true
270 * @param int $courseid id of the course
271 * @param array $rawmods result of funciton {@link get_course_mods()} - containst
272 * the list of enabled course modules in the course. Retrieved from DB if not specified.
273 * Argument ignored in cashe of $fullcheck, the list is retrieved form DB anyway.
274 * @param array $sections records from course_sections table for this course.
275 * Retrieved from DB if not specified
276 * @param bool $fullcheck Will add orphaned modules to their sections and remove non-existing
277 * course modules from sequences. Only to be used in site maintenance mode when we are
278 * sure that another user is not in the middle of the process of moving/removing a module.
279 * @param bool $checkonly Only performs the check without updating DB, outputs all errors as debug messages.
280 * @return array array of messages with found problems. Empty output means everything is ok
282 function course_integrity_check($courseid, $rawmods = null, $sections = null, $fullcheck = false, $checkonly = false) {
283 global $DB;
284 $messages = array();
285 if ($sections === null) {
286 $sections = $DB->get_records('course_sections', array('course' => $courseid), 'section', 'id,section,sequence');
288 if ($fullcheck) {
289 // Retrieve all records from course_modules regardless of module type visibility.
290 $rawmods = $DB->get_records('course_modules', array('course' => $courseid), 'id', 'id,section');
292 if ($rawmods === null) {
293 $rawmods = get_course_mods($courseid);
295 if (!$fullcheck && (empty($sections) || empty($rawmods))) {
296 // If either of the arrays is empty, no modules are displayed anyway.
297 return true;
299 $debuggingprefix = 'Failed integrity check for course ['.$courseid.']. ';
301 // First make sure that each module id appears in section sequences only once.
302 // If it appears in several section sequences the last section wins.
303 // If it appears twice in one section sequence, the first occurence wins.
304 $modsection = array();
305 foreach ($sections as $sectionid => $section) {
306 $sections[$sectionid]->newsequence = $section->sequence;
307 if (!empty($section->sequence)) {
308 $sequence = explode(",", $section->sequence);
309 $sequenceunique = array_unique($sequence);
310 if (count($sequenceunique) != count($sequence)) {
311 // Some course module id appears in this section sequence more than once.
312 ksort($sequenceunique); // Preserve initial order of modules.
313 $sequence = array_values($sequenceunique);
314 $sections[$sectionid]->newsequence = join(',', $sequence);
315 $messages[] = $debuggingprefix.'Sequence for course section ['.
316 $sectionid.'] is "'.$sections[$sectionid]->sequence.'", must be "'.$sections[$sectionid]->newsequence.'"';
318 foreach ($sequence as $cmid) {
319 if (array_key_exists($cmid, $modsection) && isset($rawmods[$cmid])) {
320 // Some course module id appears to be in more than one section's sequences.
321 $wrongsectionid = $modsection[$cmid];
322 $sections[$wrongsectionid]->newsequence = trim(preg_replace("/,$cmid,/", ',', ','.$sections[$wrongsectionid]->newsequence. ','), ',');
323 $messages[] = $debuggingprefix.'Course module ['.$cmid.'] must be removed from sequence of section ['.
324 $wrongsectionid.'] because it is also present in sequence of section ['.$sectionid.']';
326 $modsection[$cmid] = $sectionid;
331 // Add orphaned modules to their sections if they exist or to section 0 otherwise.
332 if ($fullcheck) {
333 foreach ($rawmods as $cmid => $mod) {
334 if (!isset($modsection[$cmid])) {
335 // This is a module that is not mentioned in course_section.sequence at all.
336 // Add it to the section $mod->section or to the last available section.
337 if ($mod->section && isset($sections[$mod->section])) {
338 $modsection[$cmid] = $mod->section;
339 } else {
340 $firstsection = reset($sections);
341 $modsection[$cmid] = $firstsection->id;
343 $sections[$modsection[$cmid]]->newsequence = trim($sections[$modsection[$cmid]]->newsequence.','.$cmid, ',');
344 $messages[] = $debuggingprefix.'Course module ['.$cmid.'] is missing from sequence of section ['.
345 $modsection[$cmid].']';
348 foreach ($modsection as $cmid => $sectionid) {
349 if (!isset($rawmods[$cmid])) {
350 // Section $sectionid refers to module id that does not exist.
351 $sections[$sectionid]->newsequence = trim(preg_replace("/,$cmid,/", ',', ','.$sections[$sectionid]->newsequence.','), ',');
352 $messages[] = $debuggingprefix.'Course module ['.$cmid.
353 '] does not exist but is present in the sequence of section ['.$sectionid.']';
358 // Update changed sections.
359 if (!$checkonly && !empty($messages)) {
360 foreach ($sections as $sectionid => $section) {
361 if ($section->newsequence !== $section->sequence) {
362 $DB->update_record('course_sections', array('id' => $sectionid, 'sequence' => $section->newsequence));
367 // Now make sure that all modules point to the correct sections.
368 foreach ($rawmods as $cmid => $mod) {
369 if (isset($modsection[$cmid]) && $modsection[$cmid] != $mod->section) {
370 if (!$checkonly) {
371 $DB->update_record('course_modules', array('id' => $cmid, 'section' => $modsection[$cmid]));
373 $messages[] = $debuggingprefix.'Course module ['.$cmid.
374 '] points to section ['.$mod->section.'] instead of ['.$modsection[$cmid].']';
378 return $messages;
382 * For a given course, returns an array of course activity objects
383 * Each item in the array contains he following properties:
385 function get_array_of_activities($courseid) {
386 // cm - course module id
387 // mod - name of the module (eg forum)
388 // section - the number of the section (eg week or topic)
389 // name - the name of the instance
390 // visible - is the instance visible or not
391 // groupingid - grouping id
392 // extra - contains extra string to include in any link
393 global $CFG, $DB;
395 $course = $DB->get_record('course', array('id'=>$courseid));
397 if (empty($course)) {
398 throw new moodle_exception('courseidnotfound');
401 $mod = array();
403 $rawmods = get_course_mods($courseid);
404 if (empty($rawmods)) {
405 return $mod; // always return array
407 $courseformat = course_get_format($course);
409 if ($sections = $DB->get_records('course_sections', array('course' => $courseid),
410 'section ASC', 'id,section,sequence,visible')) {
411 // First check and correct obvious mismatches between course_sections.sequence and course_modules.section.
412 if ($errormessages = course_integrity_check($courseid, $rawmods, $sections)) {
413 debugging(join('<br>', $errormessages));
414 $rawmods = get_course_mods($courseid);
415 $sections = $DB->get_records('course_sections', array('course' => $courseid),
416 'section ASC', 'id,section,sequence,visible');
418 // Build array of activities.
419 foreach ($sections as $section) {
420 if (!empty($section->sequence)) {
421 $sequence = explode(",", $section->sequence);
422 foreach ($sequence as $seq) {
423 if (empty($rawmods[$seq])) {
424 continue;
426 // Adjust visibleoncoursepage, value in DB may not respect format availability.
427 $rawmods[$seq]->visibleoncoursepage = (!$rawmods[$seq]->visible
428 || $rawmods[$seq]->visibleoncoursepage
429 || empty($CFG->allowstealth)
430 || !$courseformat->allow_stealth_module_visibility($rawmods[$seq], $section)) ? 1 : 0;
432 // Create an object that will be cached.
433 $mod[$seq] = new stdClass();
434 $mod[$seq]->id = $rawmods[$seq]->instance;
435 $mod[$seq]->cm = $rawmods[$seq]->id;
436 $mod[$seq]->mod = $rawmods[$seq]->modname;
438 // Oh dear. Inconsistent names left here for backward compatibility.
439 $mod[$seq]->section = $section->section;
440 $mod[$seq]->sectionid = $rawmods[$seq]->section;
442 $mod[$seq]->module = $rawmods[$seq]->module;
443 $mod[$seq]->added = $rawmods[$seq]->added;
444 $mod[$seq]->score = $rawmods[$seq]->score;
445 $mod[$seq]->idnumber = $rawmods[$seq]->idnumber;
446 $mod[$seq]->visible = $rawmods[$seq]->visible;
447 $mod[$seq]->visibleoncoursepage = $rawmods[$seq]->visibleoncoursepage;
448 $mod[$seq]->visibleold = $rawmods[$seq]->visibleold;
449 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
450 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
451 $mod[$seq]->indent = $rawmods[$seq]->indent;
452 $mod[$seq]->completion = $rawmods[$seq]->completion;
453 $mod[$seq]->extra = "";
454 $mod[$seq]->completiongradeitemnumber =
455 $rawmods[$seq]->completiongradeitemnumber;
456 $mod[$seq]->completionview = $rawmods[$seq]->completionview;
457 $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected;
458 $mod[$seq]->showdescription = $rawmods[$seq]->showdescription;
459 $mod[$seq]->availability = $rawmods[$seq]->availability;
460 $mod[$seq]->deletioninprogress = $rawmods[$seq]->deletioninprogress;
462 $modname = $mod[$seq]->mod;
463 $functionname = $modname."_get_coursemodule_info";
465 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
466 continue;
469 include_once("$CFG->dirroot/mod/$modname/lib.php");
471 if ($hasfunction = function_exists($functionname)) {
472 if ($info = $functionname($rawmods[$seq])) {
473 if (!empty($info->icon)) {
474 $mod[$seq]->icon = $info->icon;
476 if (!empty($info->iconcomponent)) {
477 $mod[$seq]->iconcomponent = $info->iconcomponent;
479 if (!empty($info->name)) {
480 $mod[$seq]->name = $info->name;
482 if ($info instanceof cached_cm_info) {
483 // When using cached_cm_info you can include three new fields
484 // that aren't available for legacy code
485 if (!empty($info->content)) {
486 $mod[$seq]->content = $info->content;
488 if (!empty($info->extraclasses)) {
489 $mod[$seq]->extraclasses = $info->extraclasses;
491 if (!empty($info->iconurl)) {
492 // Convert URL to string as it's easier to store. Also serialized object contains \0 byte and can not be written to Postgres DB.
493 $url = new moodle_url($info->iconurl);
494 $mod[$seq]->iconurl = $url->out(false);
496 if (!empty($info->onclick)) {
497 $mod[$seq]->onclick = $info->onclick;
499 if (!empty($info->customdata)) {
500 $mod[$seq]->customdata = $info->customdata;
502 } else {
503 // When using a stdclass, the (horrible) deprecated ->extra field
504 // is available for BC
505 if (!empty($info->extra)) {
506 $mod[$seq]->extra = $info->extra;
511 // When there is no modname_get_coursemodule_info function,
512 // but showdescriptions is enabled, then we use the 'intro'
513 // and 'introformat' fields in the module table
514 if (!$hasfunction && $rawmods[$seq]->showdescription) {
515 if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
516 array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
517 // Set content from intro and introformat. Filters are disabled
518 // because we filter it with format_text at display time
519 $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
520 $modvalues, $rawmods[$seq]->id, false);
522 // To save making another query just below, put name in here
523 $mod[$seq]->name = $modvalues->name;
526 if (!isset($mod[$seq]->name)) {
527 $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
530 // Minimise the database size by unsetting default options when they are
531 // 'empty'. This list corresponds to code in the cm_info constructor.
532 foreach (array('idnumber', 'groupmode', 'groupingid',
533 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
534 'icon', 'iconcomponent', 'customdata', 'availability', 'completionview',
535 'completionexpected', 'score', 'showdescription', 'deletioninprogress') as $property) {
536 if (property_exists($mod[$seq], $property) &&
537 empty($mod[$seq]->{$property})) {
538 unset($mod[$seq]->{$property});
541 // Special case: this value is usually set to null, but may be 0
542 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
543 is_null($mod[$seq]->completiongradeitemnumber)) {
544 unset($mod[$seq]->completiongradeitemnumber);
550 return $mod;
554 * Returns the localised human-readable names of all used modules
556 * @param bool $plural if true returns the plural forms of the names
557 * @return array where key is the module name (component name without 'mod_') and
558 * the value is the human-readable string. Array sorted alphabetically by value
560 function get_module_types_names($plural = false) {
561 static $modnames = null;
562 global $DB, $CFG;
563 if ($modnames === null) {
564 $modnames = array(0 => array(), 1 => array());
565 if ($allmods = $DB->get_records("modules")) {
566 foreach ($allmods as $mod) {
567 if (file_exists("$CFG->dirroot/mod/$mod->name/lib.php") && $mod->visible) {
568 $modnames[0][$mod->name] = get_string("modulename", "$mod->name", null, true);
569 $modnames[1][$mod->name] = get_string("modulenameplural", "$mod->name", null, true);
574 return $modnames[(int)$plural];
578 * Set highlighted section. Only one section can be highlighted at the time.
580 * @param int $courseid course id
581 * @param int $marker highlight section with this number, 0 means remove higlightin
582 * @return void
584 function course_set_marker($courseid, $marker) {
585 global $DB, $COURSE;
586 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
587 if ($COURSE && $COURSE->id == $courseid) {
588 $COURSE->marker = $marker;
590 if (class_exists('format_base')) {
591 format_base::reset_course_cache($courseid);
593 course_modinfo::clear_instance_cache($courseid);
597 * For a given course section, marks it visible or hidden,
598 * and does the same for every activity in that section
600 * @param int $courseid course id
601 * @param int $sectionnumber The section number to adjust
602 * @param int $visibility The new visibility
603 * @return array A list of resources which were hidden in the section
605 function set_section_visible($courseid, $sectionnumber, $visibility) {
606 global $DB;
608 $resourcestotoggle = array();
609 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
610 course_update_section($courseid, $section, array('visible' => $visibility));
612 // Determine which modules are visible for AJAX update
613 $modules = !empty($section->sequence) ? explode(',', $section->sequence) : array();
614 if (!empty($modules)) {
615 list($insql, $params) = $DB->get_in_or_equal($modules);
616 $select = 'id ' . $insql . ' AND visible = ?';
617 array_push($params, $visibility);
618 if (!$visibility) {
619 $select .= ' AND visibleold = 1';
621 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
624 return $resourcestotoggle;
628 * Return the course category context for the category with id $categoryid, except
629 * that if $categoryid is 0, return the system context.
631 * @param integer $categoryid a category id or 0.
632 * @return context the corresponding context
634 function get_category_or_system_context($categoryid) {
635 if ($categoryid) {
636 return context_coursecat::instance($categoryid, IGNORE_MISSING);
637 } else {
638 return context_system::instance();
643 * Print the buttons relating to course requests.
645 * @param context $context current page context.
647 function print_course_request_buttons($context) {
648 global $CFG, $DB, $OUTPUT;
649 if (empty($CFG->enablecourserequests)) {
650 return;
652 if (course_request::can_request($context)) {
653 // Print a button to request a new course.
654 $params = [];
655 if ($context instanceof context_coursecat) {
656 $params['category'] = $context->instanceid;
658 echo $OUTPUT->single_button(new moodle_url('/course/request.php', $params),
659 get_string('requestcourse'), 'get');
661 /// Print a button to manage pending requests
662 if (has_capability('moodle/site:approvecourse', $context)) {
663 $disabled = !$DB->record_exists('course_request', array());
664 echo $OUTPUT->single_button(new moodle_url('/course/pending.php'), get_string('coursespending'), 'get', array('disabled' => $disabled));
669 * Does the user have permission to edit things in this category?
671 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
672 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
674 function can_edit_in_category($categoryid = 0) {
675 $context = get_category_or_system_context($categoryid);
676 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
679 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
681 function add_course_module($mod) {
682 global $DB;
684 $mod->added = time();
685 unset($mod->id);
687 $cmid = $DB->insert_record("course_modules", $mod);
688 rebuild_course_cache($mod->course, true);
689 return $cmid;
693 * Creates a course section and adds it to the specified position
695 * @param int|stdClass $courseorid course id or course object
696 * @param int $position position to add to, 0 means to the end. If position is greater than
697 * number of existing secitons, the section is added to the end. This will become sectionnum of the
698 * new section. All existing sections at this or bigger position will be shifted down.
699 * @param bool $skipcheck the check has already been made and we know that the section with this position does not exist
700 * @return stdClass created section object
702 function course_create_section($courseorid, $position = 0, $skipcheck = false) {
703 global $DB;
704 $courseid = is_object($courseorid) ? $courseorid->id : $courseorid;
706 // Find the last sectionnum among existing sections.
707 if ($skipcheck) {
708 $lastsection = $position - 1;
709 } else {
710 $lastsection = (int)$DB->get_field_sql('SELECT max(section) from {course_sections} WHERE course = ?', [$courseid]);
713 // First add section to the end.
714 $cw = new stdClass();
715 $cw->course = $courseid;
716 $cw->section = $lastsection + 1;
717 $cw->summary = '';
718 $cw->summaryformat = FORMAT_HTML;
719 $cw->sequence = '';
720 $cw->name = null;
721 $cw->visible = 1;
722 $cw->availability = null;
723 $cw->timemodified = time();
724 $cw->id = $DB->insert_record("course_sections", $cw);
726 // Now move it to the specified position.
727 if ($position > 0 && $position <= $lastsection) {
728 $course = is_object($courseorid) ? $courseorid : get_course($courseorid);
729 move_section_to($course, $cw->section, $position, true);
730 $cw->section = $position;
733 core\event\course_section_created::create_from_section($cw)->trigger();
735 rebuild_course_cache($courseid, true);
736 return $cw;
740 * Creates missing course section(s) and rebuilds course cache
742 * @param int|stdClass $courseorid course id or course object
743 * @param int|array $sections list of relative section numbers to create
744 * @return bool if there were any sections created
746 function course_create_sections_if_missing($courseorid, $sections) {
747 if (!is_array($sections)) {
748 $sections = array($sections);
750 $existing = array_keys(get_fast_modinfo($courseorid)->get_section_info_all());
751 if ($newsections = array_diff($sections, $existing)) {
752 foreach ($newsections as $sectionnum) {
753 course_create_section($courseorid, $sectionnum, true);
755 return true;
757 return false;
761 * Adds an existing module to the section
763 * Updates both tables {course_sections} and {course_modules}
765 * Note: This function does not use modinfo PROVIDED that the section you are
766 * adding the module to already exists. If the section does not exist, it will
767 * build modinfo if necessary and create the section.
769 * @param int|stdClass $courseorid course id or course object
770 * @param int $cmid id of the module already existing in course_modules table
771 * @param int $sectionnum relative number of the section (field course_sections.section)
772 * If section does not exist it will be created
773 * @param int|stdClass $beforemod id or object with field id corresponding to the module
774 * before which the module needs to be included. Null for inserting in the
775 * end of the section
776 * @return int The course_sections ID where the module is inserted
778 function course_add_cm_to_section($courseorid, $cmid, $sectionnum, $beforemod = null) {
779 global $DB, $COURSE;
780 if (is_object($beforemod)) {
781 $beforemod = $beforemod->id;
783 if (is_object($courseorid)) {
784 $courseid = $courseorid->id;
785 } else {
786 $courseid = $courseorid;
788 // Do not try to use modinfo here, there is no guarantee it is valid!
789 $section = $DB->get_record('course_sections',
790 array('course' => $courseid, 'section' => $sectionnum), '*', IGNORE_MISSING);
791 if (!$section) {
792 // This function call requires modinfo.
793 course_create_sections_if_missing($courseorid, $sectionnum);
794 $section = $DB->get_record('course_sections',
795 array('course' => $courseid, 'section' => $sectionnum), '*', MUST_EXIST);
798 $modarray = explode(",", trim($section->sequence));
799 if (empty($section->sequence)) {
800 $newsequence = "$cmid";
801 } else if ($beforemod && ($key = array_keys($modarray, $beforemod))) {
802 $insertarray = array($cmid, $beforemod);
803 array_splice($modarray, $key[0], 1, $insertarray);
804 $newsequence = implode(",", $modarray);
805 } else {
806 $newsequence = "$section->sequence,$cmid";
808 $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id));
809 $DB->set_field('course_modules', 'section', $section->id, array('id' => $cmid));
810 if (is_object($courseorid)) {
811 rebuild_course_cache($courseorid->id, true);
812 } else {
813 rebuild_course_cache($courseorid, true);
815 return $section->id; // Return course_sections ID that was used.
819 * Change the group mode of a course module.
821 * Note: Do not forget to trigger the event \core\event\course_module_updated as it needs
822 * to be triggered manually, refer to {@link \core\event\course_module_updated::create_from_cm()}.
824 * @param int $id course module ID.
825 * @param int $groupmode the new groupmode value.
826 * @return bool True if the $groupmode was updated.
828 function set_coursemodule_groupmode($id, $groupmode) {
829 global $DB;
830 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST);
831 if ($cm->groupmode != $groupmode) {
832 $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id));
833 rebuild_course_cache($cm->course, true);
835 return ($cm->groupmode != $groupmode);
838 function set_coursemodule_idnumber($id, $idnumber) {
839 global $DB;
840 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST);
841 if ($cm->idnumber != $idnumber) {
842 $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id));
843 rebuild_course_cache($cm->course, true);
845 return ($cm->idnumber != $idnumber);
849 * Set the visibility of a module and inherent properties.
851 * Note: Do not forget to trigger the event \core\event\course_module_updated as it needs
852 * to be triggered manually, refer to {@link \core\event\course_module_updated::create_from_cm()}.
854 * From 2.4 the parameter $prevstateoverrides has been removed, the logic it triggered
855 * has been moved to {@link set_section_visible()} which was the only place from which
856 * the parameter was used.
858 * @param int $id of the module
859 * @param int $visible state of the module
860 * @param int $visibleoncoursepage state of the module on the course page
861 * @return bool false when the module was not found, true otherwise
863 function set_coursemodule_visible($id, $visible, $visibleoncoursepage = 1) {
864 global $DB, $CFG;
865 require_once($CFG->libdir.'/gradelib.php');
866 require_once($CFG->dirroot.'/calendar/lib.php');
868 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
869 return false;
872 // Create events and propagate visibility to associated grade items if the value has changed.
873 // Only do this if it's changed to avoid accidently overwriting manual showing/hiding of student grades.
874 if ($cm->visible == $visible && $cm->visibleoncoursepage == $visibleoncoursepage) {
875 return true;
878 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
879 return false;
881 if (($cm->visible != $visible) &&
882 ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename)))) {
883 foreach($events as $event) {
884 if ($visible) {
885 $event = new calendar_event($event);
886 $event->toggle_visibility(true);
887 } else {
888 $event = new calendar_event($event);
889 $event->toggle_visibility(false);
894 // Updating visible and visibleold to keep them in sync. Only changing a section visibility will
895 // affect visibleold to allow for an original visibility restore. See set_section_visible().
896 $cminfo = new stdClass();
897 $cminfo->id = $id;
898 $cminfo->visible = $visible;
899 $cminfo->visibleoncoursepage = $visibleoncoursepage;
900 $cminfo->visibleold = $visible;
901 $DB->update_record('course_modules', $cminfo);
903 // Hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there.
904 // Note that this must be done after updating the row in course_modules, in case
905 // the modules grade_item_update function needs to access $cm->visible.
906 if ($cm->visible != $visible &&
907 plugin_supports('mod', $modulename, FEATURE_CONTROLS_GRADE_VISIBILITY) &&
908 component_callback_exists('mod_' . $modulename, 'grade_item_update')) {
909 $instance = $DB->get_record($modulename, array('id' => $cm->instance), '*', MUST_EXIST);
910 component_callback('mod_' . $modulename, 'grade_item_update', array($instance));
911 } else if ($cm->visible != $visible) {
912 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
913 if ($grade_items) {
914 foreach ($grade_items as $grade_item) {
915 $grade_item->set_hidden(!$visible);
920 rebuild_course_cache($cm->course, true);
921 return true;
925 * Changes the course module name
927 * @param int $id course module id
928 * @param string $name new value for a name
929 * @return bool whether a change was made
931 function set_coursemodule_name($id, $name) {
932 global $CFG, $DB;
933 require_once($CFG->libdir . '/gradelib.php');
935 $cm = get_coursemodule_from_id('', $id, 0, false, MUST_EXIST);
937 $module = new \stdClass();
938 $module->id = $cm->instance;
940 // Escape strings as they would be by mform.
941 if (!empty($CFG->formatstringstriptags)) {
942 $module->name = clean_param($name, PARAM_TEXT);
943 } else {
944 $module->name = clean_param($name, PARAM_CLEANHTML);
946 if ($module->name === $cm->name || strval($module->name) === '') {
947 return false;
949 if (\core_text::strlen($module->name) > 255) {
950 throw new \moodle_exception('maximumchars', 'moodle', '', 255);
953 $module->timemodified = time();
954 $DB->update_record($cm->modname, $module);
955 $cm->name = $module->name;
956 \core\event\course_module_updated::create_from_cm($cm)->trigger();
957 rebuild_course_cache($cm->course, true);
959 // Attempt to update the grade item if relevant.
960 $grademodule = $DB->get_record($cm->modname, array('id' => $cm->instance));
961 $grademodule->cmidnumber = $cm->idnumber;
962 $grademodule->modname = $cm->modname;
963 grade_update_mod_grades($grademodule);
965 // Update calendar events with the new name.
966 course_module_update_calendar_events($cm->modname, $grademodule, $cm);
968 return true;
972 * This function will handle the whole deletion process of a module. This includes calling
973 * the modules delete_instance function, deleting files, events, grades, conditional data,
974 * the data in the course_module and course_sections table and adding a module deletion
975 * event to the DB.
977 * @param int $cmid the course module id
978 * @param bool $async whether or not to try to delete the module using an adhoc task. Async also depends on a plugin hook.
979 * @throws moodle_exception
980 * @since Moodle 2.5
982 function course_delete_module($cmid, $async = false) {
983 // Check the 'course_module_background_deletion_recommended' hook first.
984 // Only use asynchronous deletion if at least one plugin returns true and if async deletion has been requested.
985 // Both are checked because plugins should not be allowed to dictate the deletion behaviour, only support/decline it.
986 // It's up to plugins to handle things like whether or not they are enabled.
987 if ($async && $pluginsfunction = get_plugins_with_function('course_module_background_deletion_recommended')) {
988 foreach ($pluginsfunction as $plugintype => $plugins) {
989 foreach ($plugins as $pluginfunction) {
990 if ($pluginfunction()) {
991 return course_module_flag_for_async_deletion($cmid);
997 global $CFG, $DB;
999 require_once($CFG->libdir.'/gradelib.php');
1000 require_once($CFG->libdir.'/questionlib.php');
1001 require_once($CFG->dirroot.'/blog/lib.php');
1002 require_once($CFG->dirroot.'/calendar/lib.php');
1004 // Get the course module.
1005 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
1006 return true;
1009 // Get the module context.
1010 $modcontext = context_module::instance($cm->id);
1012 // Get the course module name.
1013 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
1015 // Get the file location of the delete_instance function for this module.
1016 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
1018 // Include the file required to call the delete_instance function for this module.
1019 if (file_exists($modlib)) {
1020 require_once($modlib);
1021 } else {
1022 throw new moodle_exception('cannotdeletemodulemissinglib', '', '', null,
1023 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
1026 $deleteinstancefunction = $modulename . '_delete_instance';
1028 // Ensure the delete_instance function exists for this module.
1029 if (!function_exists($deleteinstancefunction)) {
1030 throw new moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
1031 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
1034 // Allow plugins to use this course module before we completely delete it.
1035 if ($pluginsfunction = get_plugins_with_function('pre_course_module_delete')) {
1036 foreach ($pluginsfunction as $plugintype => $plugins) {
1037 foreach ($plugins as $pluginfunction) {
1038 $pluginfunction($cm);
1043 question_delete_activity($cm);
1045 // Call the delete_instance function, if it returns false throw an exception.
1046 if (!$deleteinstancefunction($cm->instance)) {
1047 throw new moodle_exception('cannotdeletemoduleinstance', '', '', null,
1048 "Cannot delete the module $modulename (instance).");
1051 // Remove all module files in case modules forget to do that.
1052 $fs = get_file_storage();
1053 $fs->delete_area_files($modcontext->id);
1055 // Delete events from calendar.
1056 if ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename))) {
1057 $coursecontext = context_course::instance($cm->course);
1058 foreach($events as $event) {
1059 $event->context = $coursecontext;
1060 $calendarevent = calendar_event::load($event);
1061 $calendarevent->delete();
1065 // Delete grade items, outcome items and grades attached to modules.
1066 if ($grade_items = grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $modulename,
1067 'iteminstance' => $cm->instance, 'courseid' => $cm->course))) {
1068 foreach ($grade_items as $grade_item) {
1069 $grade_item->delete('moddelete');
1073 // Delete associated blogs and blog tag instances.
1074 blog_remove_associations_for_module($modcontext->id);
1076 // Delete completion and availability data; it is better to do this even if the
1077 // features are not turned on, in case they were turned on previously (these will be
1078 // very quick on an empty table).
1079 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
1080 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
1081 'course' => $cm->course,
1082 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
1084 // Delete all tag instances associated with the instance of this module.
1085 core_tag_tag::delete_instances('mod_' . $modulename, null, $modcontext->id);
1086 core_tag_tag::remove_all_item_tags('core', 'course_modules', $cm->id);
1088 // Notify the competency subsystem.
1089 \core_competency\api::hook_course_module_deleted($cm);
1091 // Delete the context.
1092 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
1094 // Delete the module from the course_modules table.
1095 $DB->delete_records('course_modules', array('id' => $cm->id));
1097 // Delete module from that section.
1098 if (!delete_mod_from_section($cm->id, $cm->section)) {
1099 throw new moodle_exception('cannotdeletemodulefromsection', '', '', null,
1100 "Cannot delete the module $modulename (instance) from section.");
1103 // Trigger event for course module delete action.
1104 $event = \core\event\course_module_deleted::create(array(
1105 'courseid' => $cm->course,
1106 'context' => $modcontext,
1107 'objectid' => $cm->id,
1108 'other' => array(
1109 'modulename' => $modulename,
1110 'instanceid' => $cm->instance,
1113 $event->add_record_snapshot('course_modules', $cm);
1114 $event->trigger();
1115 rebuild_course_cache($cm->course, true);
1119 * Schedule a course module for deletion in the background using an adhoc task.
1121 * This method should not be called directly. Instead, please use course_delete_module($cmid, true), to denote async deletion.
1122 * The real deletion of the module is handled by the task, which calls 'course_delete_module($cmid)'.
1124 * @param int $cmid the course module id.
1125 * @return bool whether the module was successfully scheduled for deletion.
1126 * @throws \moodle_exception
1128 function course_module_flag_for_async_deletion($cmid) {
1129 global $CFG, $DB, $USER;
1130 require_once($CFG->libdir.'/gradelib.php');
1131 require_once($CFG->libdir.'/questionlib.php');
1132 require_once($CFG->dirroot.'/blog/lib.php');
1133 require_once($CFG->dirroot.'/calendar/lib.php');
1135 // Get the course module.
1136 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
1137 return true;
1140 // We need to be reasonably certain the deletion is going to succeed before we background the process.
1141 // Make the necessary delete_instance checks, etc. before proceeding further. Throw exceptions if required.
1143 // Get the course module name.
1144 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
1146 // Get the file location of the delete_instance function for this module.
1147 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
1149 // Include the file required to call the delete_instance function for this module.
1150 if (file_exists($modlib)) {
1151 require_once($modlib);
1152 } else {
1153 throw new \moodle_exception('cannotdeletemodulemissinglib', '', '', null,
1154 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
1157 $deleteinstancefunction = $modulename . '_delete_instance';
1159 // Ensure the delete_instance function exists for this module.
1160 if (!function_exists($deleteinstancefunction)) {
1161 throw new \moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
1162 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
1165 // We are going to defer the deletion as we can't be sure how long the module's pre_delete code will run for.
1166 $cm->deletioninprogress = '1';
1167 $DB->update_record('course_modules', $cm);
1169 // Create an adhoc task for the deletion of the course module. The task takes an array of course modules for removal.
1170 $removaltask = new \core_course\task\course_delete_modules();
1171 $removaltask->set_custom_data(array(
1172 'cms' => array($cm),
1173 'userid' => $USER->id,
1174 'realuserid' => \core\session\manager::get_realuser()->id
1177 // Queue the task for the next run.
1178 \core\task\manager::queue_adhoc_task($removaltask);
1180 // Reset the course cache to hide the module.
1181 rebuild_course_cache($cm->course, true);
1185 * Checks whether the given course has any course modules scheduled for adhoc deletion.
1187 * @param int $courseid the id of the course.
1188 * @param bool $onlygradable whether to check only gradable modules or all modules.
1189 * @return bool true if the course contains any modules pending deletion, false otherwise.
1191 function course_modules_pending_deletion(int $courseid, bool $onlygradable = false) : bool {
1192 if (empty($courseid)) {
1193 return false;
1196 if ($onlygradable) {
1197 // Fetch modules with grade items.
1198 if (!$coursegradeitems = grade_item::fetch_all(['itemtype' => 'mod', 'courseid' => $courseid])) {
1199 // Return early when there is none.
1200 return false;
1204 $modinfo = get_fast_modinfo($courseid);
1205 foreach ($modinfo->get_cms() as $module) {
1206 if ($module->deletioninprogress == '1') {
1207 if ($onlygradable) {
1208 // Check if the module being deleted is in the list of course modules with grade items.
1209 foreach ($coursegradeitems as $coursegradeitem) {
1210 if ($coursegradeitem->itemmodule == $module->modname && $coursegradeitem->iteminstance == $module->instance) {
1211 // The module being deleted is within the gradable modules.
1212 return true;
1215 } else {
1216 return true;
1220 return false;
1224 * Checks whether the course module, as defined by modulename and instanceid, is scheduled for deletion within the given course.
1226 * @param int $courseid the course id.
1227 * @param string $modulename the module name. E.g. 'assign', 'book', etc.
1228 * @param int $instanceid the module instance id.
1229 * @return bool true if the course module is pending deletion, false otherwise.
1231 function course_module_instance_pending_deletion($courseid, $modulename, $instanceid) {
1232 if (empty($courseid) || empty($modulename) || empty($instanceid)) {
1233 return false;
1235 $modinfo = get_fast_modinfo($courseid);
1236 $instances = $modinfo->get_instances_of($modulename);
1237 return isset($instances[$instanceid]) && $instances[$instanceid]->deletioninprogress;
1240 function delete_mod_from_section($modid, $sectionid) {
1241 global $DB;
1243 if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
1245 $modarray = explode(",", $section->sequence);
1247 if ($key = array_keys ($modarray, $modid)) {
1248 array_splice($modarray, $key[0], 1);
1249 $newsequence = implode(",", $modarray);
1250 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
1251 rebuild_course_cache($section->course, true);
1252 return true;
1253 } else {
1254 return false;
1258 return false;
1262 * This function updates the calendar events from the information stored in the module table and the course
1263 * module table.
1265 * @param string $modulename Module name
1266 * @param stdClass $instance Module object. Either the $instance or the $cm must be supplied.
1267 * @param stdClass $cm Course module object. Either the $instance or the $cm must be supplied.
1268 * @return bool Returns true if calendar events are updated.
1269 * @since Moodle 3.3.4
1271 function course_module_update_calendar_events($modulename, $instance = null, $cm = null) {
1272 global $DB;
1274 if (isset($instance) || isset($cm)) {
1276 if (!isset($instance)) {
1277 $instance = $DB->get_record($modulename, array('id' => $cm->instance), '*', MUST_EXIST);
1279 if (!isset($cm)) {
1280 $cm = get_coursemodule_from_instance($modulename, $instance->id, $instance->course);
1282 if (!empty($cm)) {
1283 course_module_calendar_event_update_process($instance, $cm);
1285 return true;
1287 return false;
1291 * Update all instances through out the site or in a course.
1293 * @param string $modulename Module type to update.
1294 * @param integer $courseid Course id to update events. 0 for the whole site.
1295 * @return bool Returns True if the update was successful.
1296 * @since Moodle 3.3.4
1298 function course_module_bulk_update_calendar_events($modulename, $courseid = 0) {
1299 global $DB;
1301 $instances = null;
1302 if ($courseid) {
1303 if (!$instances = $DB->get_records($modulename, array('course' => $courseid))) {
1304 return false;
1306 } else {
1307 if (!$instances = $DB->get_records($modulename)) {
1308 return false;
1312 foreach ($instances as $instance) {
1313 if ($cm = get_coursemodule_from_instance($modulename, $instance->id, $instance->course)) {
1314 course_module_calendar_event_update_process($instance, $cm);
1317 return true;
1321 * Calendar events for a module instance are updated.
1323 * @param stdClass $instance Module instance object.
1324 * @param stdClass $cm Course Module object.
1325 * @since Moodle 3.3.4
1327 function course_module_calendar_event_update_process($instance, $cm) {
1328 // We need to call *_refresh_events() first because some modules delete 'old' events at the end of the code which
1329 // will remove the completion events.
1330 $refresheventsfunction = $cm->modname . '_refresh_events';
1331 if (function_exists($refresheventsfunction)) {
1332 call_user_func($refresheventsfunction, $cm->course, $instance, $cm);
1334 $completionexpected = (!empty($cm->completionexpected)) ? $cm->completionexpected : null;
1335 \core_completion\api::update_completion_date_event($cm->id, $cm->modname, $instance, $completionexpected);
1339 * Moves a section within a course, from a position to another.
1340 * Be very careful: $section and $destination refer to section number,
1341 * not id!.
1343 * @param object $course
1344 * @param int $section Section number (not id!!!)
1345 * @param int $destination
1346 * @param bool $ignorenumsections
1347 * @return boolean Result
1349 function move_section_to($course, $section, $destination, $ignorenumsections = false) {
1350 /// Moves a whole course section up and down within the course
1351 global $USER, $DB;
1353 if (!$destination && $destination != 0) {
1354 return true;
1357 // compartibility with course formats using field 'numsections'
1358 $courseformatoptions = course_get_format($course)->get_format_options();
1359 if ((!$ignorenumsections && array_key_exists('numsections', $courseformatoptions) &&
1360 ($destination > $courseformatoptions['numsections'])) || ($destination < 1)) {
1361 return false;
1364 // Get all sections for this course and re-order them (2 of them should now share the same section number)
1365 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
1366 'section ASC, id ASC', 'id, section')) {
1367 return false;
1370 $movedsections = reorder_sections($sections, $section, $destination);
1372 // Update all sections. Do this in 2 steps to avoid breaking database
1373 // uniqueness constraint
1374 $transaction = $DB->start_delegated_transaction();
1375 foreach ($movedsections as $id => $position) {
1376 if ($sections[$id] !== $position) {
1377 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
1380 foreach ($movedsections as $id => $position) {
1381 if ($sections[$id] !== $position) {
1382 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
1386 // If we move the highlighted section itself, then just highlight the destination.
1387 // Adjust the higlighted section location if we move something over it either direction.
1388 if ($section == $course->marker) {
1389 course_set_marker($course->id, $destination);
1390 } elseif ($section > $course->marker && $course->marker >= $destination) {
1391 course_set_marker($course->id, $course->marker+1);
1392 } elseif ($section < $course->marker && $course->marker <= $destination) {
1393 course_set_marker($course->id, $course->marker-1);
1396 $transaction->allow_commit();
1397 rebuild_course_cache($course->id, true);
1398 return true;
1402 * This method will delete a course section and may delete all modules inside it.
1404 * No permissions are checked here, use {@link course_can_delete_section()} to
1405 * check if section can actually be deleted.
1407 * @param int|stdClass $course
1408 * @param int|stdClass|section_info $section
1409 * @param bool $forcedeleteifnotempty if set to false section will not be deleted if it has modules in it.
1410 * @param bool $async whether or not to try to delete the section using an adhoc task. Async also depends on a plugin hook.
1411 * @return bool whether section was deleted
1413 function course_delete_section($course, $section, $forcedeleteifnotempty = true, $async = false) {
1414 global $DB;
1416 // Prepare variables.
1417 $courseid = (is_object($course)) ? $course->id : (int)$course;
1418 $sectionnum = (is_object($section)) ? $section->section : (int)$section;
1419 $section = $DB->get_record('course_sections', array('course' => $courseid, 'section' => $sectionnum));
1420 if (!$section) {
1421 // No section exists, can't proceed.
1422 return false;
1425 // Check the 'course_module_background_deletion_recommended' hook first.
1426 // Only use asynchronous deletion if at least one plugin returns true and if async deletion has been requested.
1427 // Both are checked because plugins should not be allowed to dictate the deletion behaviour, only support/decline it.
1428 // It's up to plugins to handle things like whether or not they are enabled.
1429 if ($async && $pluginsfunction = get_plugins_with_function('course_module_background_deletion_recommended')) {
1430 foreach ($pluginsfunction as $plugintype => $plugins) {
1431 foreach ($plugins as $pluginfunction) {
1432 if ($pluginfunction()) {
1433 return course_delete_section_async($section, $forcedeleteifnotempty);
1439 $format = course_get_format($course);
1440 $sectionname = $format->get_section_name($section);
1442 // Delete section.
1443 $result = $format->delete_section($section, $forcedeleteifnotempty);
1445 // Trigger an event for course section deletion.
1446 if ($result) {
1447 $context = context_course::instance($courseid);
1448 $event = \core\event\course_section_deleted::create(
1449 array(
1450 'objectid' => $section->id,
1451 'courseid' => $courseid,
1452 'context' => $context,
1453 'other' => array(
1454 'sectionnum' => $section->section,
1455 'sectionname' => $sectionname,
1459 $event->add_record_snapshot('course_sections', $section);
1460 $event->trigger();
1462 return $result;
1466 * Course section deletion, using an adhoc task for deletion of the modules it contains.
1467 * 1. Schedule all modules within the section for adhoc removal.
1468 * 2. Move all modules to course section 0.
1469 * 3. Delete the resulting empty section.
1471 * @param \stdClass $section the section to schedule for deletion.
1472 * @param bool $forcedeleteifnotempty whether to force section deletion if it contains modules.
1473 * @return bool true if the section was scheduled for deletion, false otherwise.
1475 function course_delete_section_async($section, $forcedeleteifnotempty = true) {
1476 global $DB, $USER;
1478 // Objects only, and only valid ones.
1479 if (!is_object($section) || empty($section->id)) {
1480 return false;
1483 // Does the object currently exist in the DB for removal (check for stale objects).
1484 $section = $DB->get_record('course_sections', array('id' => $section->id));
1485 if (!$section || !$section->section) {
1486 // No section exists, or the section is 0. Can't proceed.
1487 return false;
1490 // Check whether the section can be removed.
1491 if (!$forcedeleteifnotempty && (!empty($section->sequence) || !empty($section->summary))) {
1492 return false;
1495 $format = course_get_format($section->course);
1496 $sectionname = $format->get_section_name($section);
1498 // Flag those modules having no existing deletion flag. Some modules may have been scheduled for deletion manually, and we don't
1499 // want to create additional adhoc deletion tasks for these. Moving them to section 0 will suffice.
1500 $affectedmods = $DB->get_records_select('course_modules', 'course = ? AND section = ? AND deletioninprogress <> ?',
1501 [$section->course, $section->id, 1], '', 'id');
1502 $DB->set_field('course_modules', 'deletioninprogress', '1', ['course' => $section->course, 'section' => $section->id]);
1504 // Move all modules to section 0.
1505 $modules = $DB->get_records('course_modules', ['section' => $section->id], '');
1506 $sectionzero = $DB->get_record('course_sections', ['course' => $section->course, 'section' => '0']);
1507 foreach ($modules as $mod) {
1508 moveto_module($mod, $sectionzero);
1511 // Create and queue an adhoc task for the deletion of the modules.
1512 $removaltask = new \core_course\task\course_delete_modules();
1513 $data = array(
1514 'cms' => $affectedmods,
1515 'userid' => $USER->id,
1516 'realuserid' => \core\session\manager::get_realuser()->id
1518 $removaltask->set_custom_data($data);
1519 \core\task\manager::queue_adhoc_task($removaltask);
1521 // Delete the now empty section, passing in only the section number, which forces the function to fetch a new object.
1522 // The refresh is needed because the section->sequence is now stale.
1523 $result = $format->delete_section($section->section, $forcedeleteifnotempty);
1525 // Trigger an event for course section deletion.
1526 if ($result) {
1527 $context = \context_course::instance($section->course);
1528 $event = \core\event\course_section_deleted::create(
1529 array(
1530 'objectid' => $section->id,
1531 'courseid' => $section->course,
1532 'context' => $context,
1533 'other' => array(
1534 'sectionnum' => $section->section,
1535 'sectionname' => $sectionname,
1539 $event->add_record_snapshot('course_sections', $section);
1540 $event->trigger();
1542 rebuild_course_cache($section->course, true);
1544 return $result;
1548 * Updates the course section
1550 * This function does not check permissions or clean values - this has to be done prior to calling it.
1552 * @param int|stdClass $course
1553 * @param stdClass $section record from course_sections table - it will be updated with the new values
1554 * @param array|stdClass $data
1556 function course_update_section($course, $section, $data) {
1557 global $DB;
1559 $courseid = (is_object($course)) ? $course->id : (int)$course;
1561 // Some fields can not be updated using this method.
1562 $data = array_diff_key((array)$data, array('id', 'course', 'section', 'sequence'));
1563 $changevisibility = (array_key_exists('visible', $data) && (bool)$data['visible'] != (bool)$section->visible);
1564 if (array_key_exists('name', $data) && \core_text::strlen($data['name']) > 255) {
1565 throw new moodle_exception('maximumchars', 'moodle', '', 255);
1568 // Update record in the DB and course format options.
1569 $data['id'] = $section->id;
1570 $data['timemodified'] = time();
1571 $DB->update_record('course_sections', $data);
1572 rebuild_course_cache($courseid, true);
1573 course_get_format($courseid)->update_section_format_options($data);
1575 // Update fields of the $section object.
1576 foreach ($data as $key => $value) {
1577 if (property_exists($section, $key)) {
1578 $section->$key = $value;
1582 // Trigger an event for course section update.
1583 $event = \core\event\course_section_updated::create(
1584 array(
1585 'objectid' => $section->id,
1586 'courseid' => $courseid,
1587 'context' => context_course::instance($courseid),
1588 'other' => array('sectionnum' => $section->section)
1591 $event->trigger();
1593 // If section visibility was changed, hide the modules in this section too.
1594 if ($changevisibility && !empty($section->sequence)) {
1595 $modules = explode(',', $section->sequence);
1596 foreach ($modules as $moduleid) {
1597 if ($cm = get_coursemodule_from_id(null, $moduleid, $courseid)) {
1598 if ($data['visible']) {
1599 // As we unhide the section, we use the previously saved visibility stored in visibleold.
1600 set_coursemodule_visible($moduleid, $cm->visibleold, $cm->visibleoncoursepage);
1601 } else {
1602 // We hide the section, so we hide the module but we store the original state in visibleold.
1603 set_coursemodule_visible($moduleid, 0, $cm->visibleoncoursepage);
1604 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id' => $moduleid));
1606 \core\event\course_module_updated::create_from_cm($cm)->trigger();
1613 * Checks if the current user can delete a section (if course format allows it and user has proper permissions).
1615 * @param int|stdClass $course
1616 * @param int|stdClass|section_info $section
1617 * @return bool
1619 function course_can_delete_section($course, $section) {
1620 if (is_object($section)) {
1621 $section = $section->section;
1623 if (!$section) {
1624 // Not possible to delete 0-section.
1625 return false;
1627 // Course format should allow to delete sections.
1628 if (!course_get_format($course)->can_delete_section($section)) {
1629 return false;
1631 // Make sure user has capability to update course and move sections.
1632 $context = context_course::instance(is_object($course) ? $course->id : $course);
1633 if (!has_all_capabilities(array('moodle/course:movesections', 'moodle/course:update'), $context)) {
1634 return false;
1636 // Make sure user has capability to delete each activity in this section.
1637 $modinfo = get_fast_modinfo($course);
1638 if (!empty($modinfo->sections[$section])) {
1639 foreach ($modinfo->sections[$section] as $cmid) {
1640 if (!has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
1641 return false;
1645 return true;
1649 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
1650 * an original position number and a target position number, rebuilds the array so that the
1651 * move is made without any duplication of section positions.
1652 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
1653 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
1655 * @param array $sections
1656 * @param int $origin_position
1657 * @param int $target_position
1658 * @return array
1660 function reorder_sections($sections, $origin_position, $target_position) {
1661 if (!is_array($sections)) {
1662 return false;
1665 // We can't move section position 0
1666 if ($origin_position < 1) {
1667 echo "We can't move section position 0";
1668 return false;
1671 // Locate origin section in sections array
1672 if (!$origin_key = array_search($origin_position, $sections)) {
1673 echo "searched position not in sections array";
1674 return false; // searched position not in sections array
1677 // Extract origin section
1678 $origin_section = $sections[$origin_key];
1679 unset($sections[$origin_key]);
1681 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
1682 $found = false;
1683 $append_array = array();
1684 foreach ($sections as $id => $position) {
1685 if ($found) {
1686 $append_array[$id] = $position;
1687 unset($sections[$id]);
1689 if ($position == $target_position) {
1690 if ($target_position < $origin_position) {
1691 $append_array[$id] = $position;
1692 unset($sections[$id]);
1694 $found = true;
1698 // Append moved section
1699 $sections[$origin_key] = $origin_section;
1701 // Append rest of array (if applicable)
1702 if (!empty($append_array)) {
1703 foreach ($append_array as $id => $position) {
1704 $sections[$id] = $position;
1708 // Renumber positions
1709 $position = 0;
1710 foreach ($sections as $id => $p) {
1711 $sections[$id] = $position;
1712 $position++;
1715 return $sections;
1720 * Move the module object $mod to the specified $section
1721 * If $beforemod exists then that is the module
1722 * before which $modid should be inserted
1724 * @param stdClass|cm_info $mod
1725 * @param stdClass|section_info $section
1726 * @param int|stdClass $beforemod id or object with field id corresponding to the module
1727 * before which the module needs to be included. Null for inserting in the
1728 * end of the section
1729 * @return int new value for module visibility (0 or 1)
1731 function moveto_module($mod, $section, $beforemod=NULL) {
1732 global $OUTPUT, $DB;
1734 // Current module visibility state - return value of this function.
1735 $modvisible = $mod->visible;
1737 // Remove original module from original section.
1738 if (! delete_mod_from_section($mod->id, $mod->section)) {
1739 echo $OUTPUT->notification("Could not delete module from existing section");
1742 // If moving to a hidden section then hide module.
1743 if ($mod->section != $section->id) {
1744 if (!$section->visible && $mod->visible) {
1745 // Module was visible but must become hidden after moving to hidden section.
1746 $modvisible = 0;
1747 set_coursemodule_visible($mod->id, 0);
1748 // Set visibleold to 1 so module will be visible when section is made visible.
1749 $DB->set_field('course_modules', 'visibleold', 1, array('id' => $mod->id));
1751 if ($section->visible && !$mod->visible) {
1752 // Hidden module was moved to the visible section, restore the module visibility from visibleold.
1753 set_coursemodule_visible($mod->id, $mod->visibleold);
1754 $modvisible = $mod->visibleold;
1758 // Add the module into the new section.
1759 course_add_cm_to_section($section->course, $mod->id, $section->section, $beforemod);
1760 return $modvisible;
1764 * Returns the list of all editing actions that current user can perform on the module
1766 * @param cm_info $mod The module to produce editing buttons for
1767 * @param int $indent The current indenting (default -1 means no move left-right actions)
1768 * @param int $sr The section to link back to (used for creating the links)
1769 * @return array array of action_link or pix_icon objects
1771 function course_get_cm_edit_actions(cm_info $mod, $indent = -1, $sr = null) {
1772 global $COURSE, $SITE, $CFG;
1774 static $str;
1776 $coursecontext = context_course::instance($mod->course);
1777 $modcontext = context_module::instance($mod->id);
1778 $courseformat = course_get_format($mod->get_course());
1780 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
1781 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
1783 // No permission to edit anything.
1784 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
1785 return array();
1788 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
1790 if (!isset($str)) {
1791 $str = get_strings(array('delete', 'move', 'moveright', 'moveleft',
1792 'editsettings', 'duplicate', 'modhide', 'makeavailable', 'makeunavailable', 'modshow'), 'moodle');
1793 $str->assign = get_string('assignroles', 'role');
1794 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
1795 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
1796 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
1799 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
1801 if ($sr !== null) {
1802 $baseurl->param('sr', $sr);
1804 $actions = array();
1806 // Update.
1807 if ($hasmanageactivities) {
1808 $actions['update'] = new action_menu_link_secondary(
1809 new moodle_url($baseurl, array('update' => $mod->id)),
1810 new pix_icon('t/edit', '', 'moodle', array('class' => 'iconsmall')),
1811 $str->editsettings,
1812 array('class' => 'editing_update', 'data-action' => 'update')
1816 // Indent.
1817 if ($hasmanageactivities && $indent >= 0) {
1818 $indentlimits = new stdClass();
1819 $indentlimits->min = 0;
1820 $indentlimits->max = 16;
1821 if (right_to_left()) { // Exchange arrows on RTL
1822 $rightarrow = 't/left';
1823 $leftarrow = 't/right';
1824 } else {
1825 $rightarrow = 't/right';
1826 $leftarrow = 't/left';
1829 if ($indent >= $indentlimits->max) {
1830 $enabledclass = 'hidden';
1831 } else {
1832 $enabledclass = '';
1834 $actions['moveright'] = new action_menu_link_secondary(
1835 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
1836 new pix_icon($rightarrow, '', 'moodle', array('class' => 'iconsmall')),
1837 $str->moveright,
1838 array('class' => 'editing_moveright ' . $enabledclass, 'data-action' => 'moveright',
1839 'data-keepopen' => true, 'data-sectionreturn' => $sr)
1842 if ($indent <= $indentlimits->min) {
1843 $enabledclass = 'hidden';
1844 } else {
1845 $enabledclass = '';
1847 $actions['moveleft'] = new action_menu_link_secondary(
1848 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
1849 new pix_icon($leftarrow, '', 'moodle', array('class' => 'iconsmall')),
1850 $str->moveleft,
1851 array('class' => 'editing_moveleft ' . $enabledclass, 'data-action' => 'moveleft',
1852 'data-keepopen' => true, 'data-sectionreturn' => $sr)
1857 // Hide/Show/Available/Unavailable.
1858 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
1859 $allowstealth = !empty($CFG->allowstealth) && $courseformat->allow_stealth_module_visibility($mod, $mod->get_section_info());
1861 $sectionvisible = $mod->get_section_info()->visible;
1862 // The module on the course page may be in one of the following states:
1863 // - Available and displayed on the course page ($displayedoncoursepage);
1864 // - Not available and not displayed on the course page ($unavailable);
1865 // - Available but not displayed on the course page ($stealth) - this can also be a visible activity in a hidden section.
1866 $displayedoncoursepage = $mod->visible && $mod->visibleoncoursepage && $sectionvisible;
1867 $unavailable = !$mod->visible;
1868 $stealth = $mod->visible && (!$mod->visibleoncoursepage || !$sectionvisible);
1869 if ($displayedoncoursepage) {
1870 $actions['hide'] = new action_menu_link_secondary(
1871 new moodle_url($baseurl, array('hide' => $mod->id)),
1872 new pix_icon('t/hide', '', 'moodle', array('class' => 'iconsmall')),
1873 $str->modhide,
1874 array('class' => 'editing_hide', 'data-action' => 'hide')
1876 } else if (!$displayedoncoursepage && $sectionvisible) {
1877 // Offer to "show" only if the section is visible.
1878 $actions['show'] = new action_menu_link_secondary(
1879 new moodle_url($baseurl, array('show' => $mod->id)),
1880 new pix_icon('t/show', '', 'moodle', array('class' => 'iconsmall')),
1881 $str->modshow,
1882 array('class' => 'editing_show', 'data-action' => 'show')
1886 if ($stealth) {
1887 // When making the "stealth" module unavailable we perform the same action as hiding the visible module.
1888 $actions['hide'] = new action_menu_link_secondary(
1889 new moodle_url($baseurl, array('hide' => $mod->id)),
1890 new pix_icon('t/unblock', '', 'moodle', array('class' => 'iconsmall')),
1891 $str->makeunavailable,
1892 array('class' => 'editing_makeunavailable', 'data-action' => 'hide', 'data-sectionreturn' => $sr)
1894 } else if ($unavailable && (!$sectionvisible || $allowstealth) && $mod->has_view()) {
1895 // Allow to make visually hidden module available in gradebook and other reports by making it a "stealth" module.
1896 // When the section is hidden it is an equivalent of "showing" the module.
1897 // Activities without the link (i.e. labels) can not be made available but hidden on course page.
1898 $action = $sectionvisible ? 'stealth' : 'show';
1899 $actions[$action] = new action_menu_link_secondary(
1900 new moodle_url($baseurl, array($action => $mod->id)),
1901 new pix_icon('t/block', '', 'moodle', array('class' => 'iconsmall')),
1902 $str->makeavailable,
1903 array('class' => 'editing_makeavailable', 'data-action' => $action, 'data-sectionreturn' => $sr)
1908 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
1909 if (has_all_capabilities($dupecaps, $coursecontext) &&
1910 plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2) &&
1911 course_allowed_module($mod->get_course(), $mod->modname)) {
1912 $actions['duplicate'] = new action_menu_link_secondary(
1913 new moodle_url($baseurl, array('duplicate' => $mod->id)),
1914 new pix_icon('t/copy', '', 'moodle', array('class' => 'iconsmall')),
1915 $str->duplicate,
1916 array('class' => 'editing_duplicate', 'data-action' => 'duplicate', 'data-sectionreturn' => $sr)
1920 // Groupmode.
1921 if ($hasmanageactivities && !$mod->coursegroupmodeforce) {
1922 if (plugin_supports('mod', $mod->modname, FEATURE_GROUPS, false)) {
1923 if ($mod->effectivegroupmode == SEPARATEGROUPS) {
1924 $nextgroupmode = VISIBLEGROUPS;
1925 $grouptitle = $str->groupsseparate;
1926 $actionname = 'groupsseparate';
1927 $nextactionname = 'groupsvisible';
1928 $groupimage = 'i/groups';
1929 } else if ($mod->effectivegroupmode == VISIBLEGROUPS) {
1930 $nextgroupmode = NOGROUPS;
1931 $grouptitle = $str->groupsvisible;
1932 $actionname = 'groupsvisible';
1933 $nextactionname = 'groupsnone';
1934 $groupimage = 'i/groupv';
1935 } else {
1936 $nextgroupmode = SEPARATEGROUPS;
1937 $grouptitle = $str->groupsnone;
1938 $actionname = 'groupsnone';
1939 $nextactionname = 'groupsseparate';
1940 $groupimage = 'i/groupn';
1943 $actions[$actionname] = new action_menu_link_primary(
1944 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $nextgroupmode)),
1945 new pix_icon($groupimage, '', 'moodle', array('class' => 'iconsmall')),
1946 $grouptitle,
1947 array('class' => 'editing_'. $actionname, 'data-action' => $nextactionname,
1948 'aria-live' => 'assertive', 'data-sectionreturn' => $sr)
1950 } else {
1951 $actions['nogroupsupport'] = new action_menu_filler();
1955 // Assign.
1956 if (has_capability('moodle/role:assign', $modcontext)){
1957 $actions['assign'] = new action_menu_link_secondary(
1958 new moodle_url('/admin/roles/assign.php', array('contextid' => $modcontext->id)),
1959 new pix_icon('t/assignroles', '', 'moodle', array('class' => 'iconsmall')),
1960 $str->assign,
1961 array('class' => 'editing_assign', 'data-action' => 'assignroles', 'data-sectionreturn' => $sr)
1965 // Delete.
1966 if ($hasmanageactivities) {
1967 $actions['delete'] = new action_menu_link_secondary(
1968 new moodle_url($baseurl, array('delete' => $mod->id)),
1969 new pix_icon('t/delete', '', 'moodle', array('class' => 'iconsmall')),
1970 $str->delete,
1971 array('class' => 'editing_delete', 'data-action' => 'delete', 'data-sectionreturn' => $sr)
1975 return $actions;
1979 * Returns the move action.
1981 * @param cm_info $mod The module to produce a move button for
1982 * @param int $sr The section to link back to (used for creating the links)
1983 * @return The markup for the move action, or an empty string if not available.
1985 function course_get_cm_move(cm_info $mod, $sr = null) {
1986 global $OUTPUT;
1988 static $str;
1989 static $baseurl;
1991 $modcontext = context_module::instance($mod->id);
1992 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
1994 if (!isset($str)) {
1995 $str = get_strings(array('move'));
1998 if (!isset($baseurl)) {
1999 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
2001 if ($sr !== null) {
2002 $baseurl->param('sr', $sr);
2006 if ($hasmanageactivities) {
2007 $pixicon = 'i/dragdrop';
2009 if (!course_ajax_enabled($mod->get_course())) {
2010 // Override for course frontpage until we get drag/drop working there.
2011 $pixicon = 't/move';
2014 return html_writer::link(
2015 new moodle_url($baseurl, array('copy' => $mod->id)),
2016 $OUTPUT->pix_icon($pixicon, $str->move, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2017 array('class' => 'editing_move', 'data-action' => 'move', 'data-sectionreturn' => $sr)
2020 return '';
2024 * given a course object with shortname & fullname, this function will
2025 * truncate the the number of chars allowed and add ... if it was too long
2027 function course_format_name ($course,$max=100) {
2029 $context = context_course::instance($course->id);
2030 $shortname = format_string($course->shortname, true, array('context' => $context));
2031 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
2032 $str = $shortname.': '. $fullname;
2033 if (core_text::strlen($str) <= $max) {
2034 return $str;
2036 else {
2037 return core_text::substr($str,0,$max-3).'...';
2042 * Is the user allowed to add this type of module to this course?
2043 * @param object $course the course settings. Only $course->id is used.
2044 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
2045 * @param \stdClass $user the user to check, defaults to the global user if not provided.
2046 * @return bool whether the current user is allowed to add this type of module to this course.
2048 function course_allowed_module($course, $modname, \stdClass $user = null) {
2049 global $USER;
2050 $user = $user ?? $USER;
2051 if (is_numeric($modname)) {
2052 throw new coding_exception('Function course_allowed_module no longer
2053 supports numeric module ids. Please update your code to pass the module name.');
2056 $capability = 'mod/' . $modname . ':addinstance';
2057 if (!get_capability_info($capability)) {
2058 // Debug warning that the capability does not exist, but no more than once per page.
2059 static $warned = array();
2060 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
2061 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
2062 debugging('The module ' . $modname . ' does not define the standard capability ' .
2063 $capability , DEBUG_DEVELOPER);
2064 $warned[$modname] = 1;
2067 // If the capability does not exist, the module can always be added.
2068 return true;
2071 $coursecontext = context_course::instance($course->id);
2072 return has_capability($capability, $coursecontext, $user);
2076 * Efficiently moves many courses around while maintaining
2077 * sortorder in order.
2079 * @param array $courseids is an array of course ids
2080 * @param int $categoryid
2081 * @return bool success
2083 function move_courses($courseids, $categoryid) {
2084 global $DB;
2086 if (empty($courseids)) {
2087 // Nothing to do.
2088 return false;
2091 if (!$category = $DB->get_record('course_categories', array('id' => $categoryid))) {
2092 return false;
2095 $courseids = array_reverse($courseids);
2096 $newparent = context_coursecat::instance($category->id);
2097 $i = 1;
2099 list($where, $params) = $DB->get_in_or_equal($courseids);
2100 $dbcourses = $DB->get_records_select('course', 'id ' . $where, $params, '', 'id, category, shortname, fullname');
2101 foreach ($dbcourses as $dbcourse) {
2102 $course = new stdClass();
2103 $course->id = $dbcourse->id;
2104 $course->timemodified = time();
2105 $course->category = $category->id;
2106 $course->sortorder = $category->sortorder + get_max_courses_in_category() - $i++;
2107 if ($category->visible == 0) {
2108 // Hide the course when moving into hidden category, do not update the visibleold flag - we want to get
2109 // to previous state if somebody unhides the category.
2110 $course->visible = 0;
2113 $DB->update_record('course', $course);
2115 // Update context, so it can be passed to event.
2116 $context = context_course::instance($course->id);
2117 $context->update_moved($newparent);
2119 // Trigger a course updated event.
2120 $event = \core\event\course_updated::create(array(
2121 'objectid' => $course->id,
2122 'context' => context_course::instance($course->id),
2123 'other' => array('shortname' => $dbcourse->shortname,
2124 'fullname' => $dbcourse->fullname,
2125 'updatedfields' => array('category' => $category->id))
2127 $event->set_legacy_logdata(array($course->id, 'course', 'move', 'edit.php?id=' . $course->id, $course->id));
2128 $event->trigger();
2130 fix_course_sortorder();
2131 cache_helper::purge_by_event('changesincourse');
2133 return true;
2137 * Returns the display name of the given section that the course prefers
2139 * Implementation of this function is provided by course format
2140 * @see format_base::get_section_name()
2142 * @param int|stdClass $courseorid The course to get the section name for (object or just course id)
2143 * @param int|stdClass $section Section object from database or just field course_sections.section
2144 * @return string Display name that the course format prefers, e.g. "Week 2"
2146 function get_section_name($courseorid, $section) {
2147 return course_get_format($courseorid)->get_section_name($section);
2151 * Tells if current course format uses sections
2153 * @param string $format Course format ID e.g. 'weeks' $course->format
2154 * @return bool
2156 function course_format_uses_sections($format) {
2157 $course = new stdClass();
2158 $course->format = $format;
2159 return course_get_format($course)->uses_sections();
2163 * Returns the information about the ajax support in the given source format
2165 * The returned object's property (boolean)capable indicates that
2166 * the course format supports Moodle course ajax features.
2168 * @param string $format
2169 * @return stdClass
2171 function course_format_ajax_support($format) {
2172 $course = new stdClass();
2173 $course->format = $format;
2174 return course_get_format($course)->supports_ajax();
2178 * Can the current user delete this course?
2179 * Course creators have exception,
2180 * 1 day after the creation they can sill delete the course.
2181 * @param int $courseid
2182 * @return boolean
2184 function can_delete_course($courseid) {
2185 global $USER;
2187 $context = context_course::instance($courseid);
2189 if (has_capability('moodle/course:delete', $context)) {
2190 return true;
2193 // hack: now try to find out if creator created this course recently (1 day)
2194 if (!has_capability('moodle/course:create', $context)) {
2195 return false;
2198 $since = time() - 60*60*24;
2199 $course = get_course($courseid);
2201 if ($course->timecreated < $since) {
2202 return false; // Return if the course was not created in last 24 hours.
2205 $logmanger = get_log_manager();
2206 $readers = $logmanger->get_readers('\core\log\sql_reader');
2207 $reader = reset($readers);
2209 if (empty($reader)) {
2210 return false; // No log reader found.
2213 // A proper reader.
2214 $select = "userid = :userid AND courseid = :courseid AND eventname = :eventname AND timecreated > :since";
2215 $params = array('userid' => $USER->id, 'since' => $since, 'courseid' => $course->id, 'eventname' => '\core\event\course_created');
2217 return (bool)$reader->get_events_select_count($select, $params);
2221 * Save the Your name for 'Some role' strings.
2223 * @param integer $courseid the id of this course.
2224 * @param array $data the data that came from the course settings form.
2226 function save_local_role_names($courseid, $data) {
2227 global $DB;
2228 $context = context_course::instance($courseid);
2230 foreach ($data as $fieldname => $value) {
2231 if (strpos($fieldname, 'role_') !== 0) {
2232 continue;
2234 list($ignored, $roleid) = explode('_', $fieldname);
2236 // make up our mind whether we want to delete, update or insert
2237 if (!$value) {
2238 $DB->delete_records('role_names', array('contextid' => $context->id, 'roleid' => $roleid));
2240 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id, 'roleid' => $roleid))) {
2241 $rolename->name = $value;
2242 $DB->update_record('role_names', $rolename);
2244 } else {
2245 $rolename = new stdClass;
2246 $rolename->contextid = $context->id;
2247 $rolename->roleid = $roleid;
2248 $rolename->name = $value;
2249 $DB->insert_record('role_names', $rolename);
2251 // This will ensure the course contacts cache is purged..
2252 core_course_category::role_assignment_changed($roleid, $context);
2257 * Returns options to use in course overviewfiles filemanager
2259 * @param null|stdClass|core_course_list_element|int $course either object that has 'id' property or just the course id;
2260 * may be empty if course does not exist yet (course create form)
2261 * @return array|null array of options such as maxfiles, maxbytes, accepted_types, etc.
2262 * or null if overviewfiles are disabled
2264 function course_overviewfiles_options($course) {
2265 global $CFG;
2266 if (empty($CFG->courseoverviewfileslimit)) {
2267 return null;
2269 $accepted_types = preg_split('/\s*,\s*/', trim($CFG->courseoverviewfilesext), -1, PREG_SPLIT_NO_EMPTY);
2270 if (in_array('*', $accepted_types) || empty($accepted_types)) {
2271 $accepted_types = '*';
2272 } else {
2273 // Since config for $CFG->courseoverviewfilesext is a text box, human factor must be considered.
2274 // Make sure extensions are prefixed with dot unless they are valid typegroups
2275 foreach ($accepted_types as $i => $type) {
2276 if (substr($type, 0, 1) !== '.') {
2277 require_once($CFG->libdir. '/filelib.php');
2278 if (!count(file_get_typegroup('extension', $type))) {
2279 // It does not start with dot and is not a valid typegroup, this is most likely extension.
2280 $accepted_types[$i] = '.'. $type;
2281 $corrected = true;
2285 if (!empty($corrected)) {
2286 set_config('courseoverviewfilesext', join(',', $accepted_types));
2289 $options = array(
2290 'maxfiles' => $CFG->courseoverviewfileslimit,
2291 'maxbytes' => $CFG->maxbytes,
2292 'subdirs' => 0,
2293 'accepted_types' => $accepted_types
2295 if (!empty($course->id)) {
2296 $options['context'] = context_course::instance($course->id);
2297 } else if (is_int($course) && $course > 0) {
2298 $options['context'] = context_course::instance($course);
2300 return $options;
2304 * Create a course and either return a $course object
2306 * Please note this functions does not verify any access control,
2307 * the calling code is responsible for all validation (usually it is the form definition).
2309 * @param array $editoroptions course description editor options
2310 * @param object $data - all the data needed for an entry in the 'course' table
2311 * @return object new course instance
2313 function create_course($data, $editoroptions = NULL) {
2314 global $DB, $CFG;
2316 //check the categoryid - must be given for all new courses
2317 $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
2319 // Check if the shortname already exists.
2320 if (!empty($data->shortname)) {
2321 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
2322 throw new moodle_exception('shortnametaken', '', '', $data->shortname);
2326 // Check if the idnumber already exists.
2327 if (!empty($data->idnumber)) {
2328 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
2329 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber);
2333 if (empty($CFG->enablecourserelativedates)) {
2334 // Make sure we're not setting the relative dates mode when the setting is disabled.
2335 unset($data->relativedatesmode);
2338 if ($errorcode = course_validate_dates((array)$data)) {
2339 throw new moodle_exception($errorcode);
2342 // Check if timecreated is given.
2343 $data->timecreated = !empty($data->timecreated) ? $data->timecreated : time();
2344 $data->timemodified = $data->timecreated;
2346 // place at beginning of any category
2347 $data->sortorder = 0;
2349 if ($editoroptions) {
2350 // summary text is updated later, we need context to store the files first
2351 $data->summary = '';
2352 $data->summary_format = FORMAT_HTML;
2355 if (!isset($data->visible)) {
2356 // data not from form, add missing visibility info
2357 $data->visible = $category->visible;
2359 $data->visibleold = $data->visible;
2361 $newcourseid = $DB->insert_record('course', $data);
2362 $context = context_course::instance($newcourseid, MUST_EXIST);
2364 if ($editoroptions) {
2365 // Save the files used in the summary editor and store
2366 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2367 $DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid));
2368 $DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid));
2370 if ($overviewfilesoptions = course_overviewfiles_options($newcourseid)) {
2371 // Save the course overviewfiles
2372 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2375 // update course format options
2376 course_get_format($newcourseid)->update_course_format_options($data);
2378 $course = course_get_format($newcourseid)->get_course();
2380 fix_course_sortorder();
2381 // purge appropriate caches in case fix_course_sortorder() did not change anything
2382 cache_helper::purge_by_event('changesincourse');
2384 // Trigger a course created event.
2385 $event = \core\event\course_created::create(array(
2386 'objectid' => $course->id,
2387 'context' => context_course::instance($course->id),
2388 'other' => array('shortname' => $course->shortname,
2389 'fullname' => $course->fullname)
2392 $event->trigger();
2394 // Setup the blocks
2395 blocks_add_default_course_blocks($course);
2397 // Create default section and initial sections if specified (unless they've already been created earlier).
2398 // We do not want to call course_create_sections_if_missing() because to avoid creating course cache.
2399 $numsections = isset($data->numsections) ? $data->numsections : 0;
2400 $existingsections = $DB->get_fieldset_sql('SELECT section from {course_sections} WHERE course = ?', [$newcourseid]);
2401 $newsections = array_diff(range(0, $numsections), $existingsections);
2402 foreach ($newsections as $sectionnum) {
2403 course_create_section($newcourseid, $sectionnum, true);
2406 // Save any custom role names.
2407 save_local_role_names($course->id, (array)$data);
2409 // set up enrolments
2410 enrol_course_updated(true, $course, $data);
2412 // Update course tags.
2413 if (isset($data->tags)) {
2414 core_tag_tag::set_item_tags('core', 'course', $course->id, context_course::instance($course->id), $data->tags);
2417 // Save custom fields if there are any of them in the form.
2418 $handler = core_course\customfield\course_handler::create();
2419 // Make sure to set the handler's parent context first.
2420 $coursecatcontext = context_coursecat::instance($category->id);
2421 $handler->set_parent_context($coursecatcontext);
2422 // Save the custom field data.
2423 $data->id = $course->id;
2424 $handler->instance_form_save($data, true);
2426 return $course;
2430 * Update a course.
2432 * Please note this functions does not verify any access control,
2433 * the calling code is responsible for all validation (usually it is the form definition).
2435 * @param object $data - all the data needed for an entry in the 'course' table
2436 * @param array $editoroptions course description editor options
2437 * @return void
2439 function update_course($data, $editoroptions = NULL) {
2440 global $DB, $CFG;
2442 // Prevent changes on front page course.
2443 if ($data->id == SITEID) {
2444 throw new moodle_exception('invalidcourse', 'error');
2447 $oldcourse = course_get_format($data->id)->get_course();
2448 $context = context_course::instance($oldcourse->id);
2450 // Make sure we're not changing whatever the course's relativedatesmode setting is.
2451 unset($data->relativedatesmode);
2453 // Capture the updated fields for the log data.
2454 $updatedfields = [];
2455 foreach (get_object_vars($oldcourse) as $field => $value) {
2456 if ($field == 'summary_editor') {
2457 if (($data->$field)['text'] !== $value['text']) {
2458 // The summary might be very long, we don't wan't to fill up the log record with the full text.
2459 $updatedfields[$field] = '(updated)';
2461 } else if ($field == 'tags' && isset($data->tags)) {
2462 // Tags might not have the same array keys, just check the values.
2463 if (array_values($data->$field) !== array_values($value)) {
2464 $updatedfields[$field] = $data->$field;
2466 } else {
2467 if (isset($data->$field) && $data->$field != $value) {
2468 $updatedfields[$field] = $data->$field;
2473 $data->timemodified = time();
2475 if ($editoroptions) {
2476 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2478 if ($overviewfilesoptions = course_overviewfiles_options($data->id)) {
2479 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2482 // Check we don't have a duplicate shortname.
2483 if (!empty($data->shortname) && $oldcourse->shortname != $data->shortname) {
2484 if ($DB->record_exists_sql('SELECT id from {course} WHERE shortname = ? AND id <> ?', array($data->shortname, $data->id))) {
2485 throw new moodle_exception('shortnametaken', '', '', $data->shortname);
2489 // Check we don't have a duplicate idnumber.
2490 if (!empty($data->idnumber) && $oldcourse->idnumber != $data->idnumber) {
2491 if ($DB->record_exists_sql('SELECT id from {course} WHERE idnumber = ? AND id <> ?', array($data->idnumber, $data->id))) {
2492 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber);
2496 if ($errorcode = course_validate_dates((array)$data)) {
2497 throw new moodle_exception($errorcode);
2500 if (!isset($data->category) or empty($data->category)) {
2501 // prevent nulls and 0 in category field
2502 unset($data->category);
2504 $changesincoursecat = $movecat = (isset($data->category) and $oldcourse->category != $data->category);
2506 if (!isset($data->visible)) {
2507 // data not from form, add missing visibility info
2508 $data->visible = $oldcourse->visible;
2511 if ($data->visible != $oldcourse->visible) {
2512 // reset the visibleold flag when manually hiding/unhiding course
2513 $data->visibleold = $data->visible;
2514 $changesincoursecat = true;
2515 } else {
2516 if ($movecat) {
2517 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category));
2518 if (empty($newcategory->visible)) {
2519 // make sure when moving into hidden category the course is hidden automatically
2520 $data->visible = 0;
2525 // Set newsitems to 0 if format does not support announcements.
2526 if (isset($data->format)) {
2527 $newcourseformat = course_get_format((object)['format' => $data->format]);
2528 if (!$newcourseformat->supports_news()) {
2529 $data->newsitems = 0;
2533 // Update custom fields if there are any of them in the form.
2534 $handler = core_course\customfield\course_handler::create();
2535 $handler->instance_form_save($data);
2537 // Update with the new data
2538 $DB->update_record('course', $data);
2539 // make sure the modinfo cache is reset
2540 rebuild_course_cache($data->id);
2542 // update course format options with full course data
2543 course_get_format($data->id)->update_course_format_options($data, $oldcourse);
2545 $course = $DB->get_record('course', array('id'=>$data->id));
2547 if ($movecat) {
2548 $newparent = context_coursecat::instance($course->category);
2549 $context->update_moved($newparent);
2551 $fixcoursesortorder = $movecat || (isset($data->sortorder) && ($oldcourse->sortorder != $data->sortorder));
2552 if ($fixcoursesortorder) {
2553 fix_course_sortorder();
2556 // purge appropriate caches in case fix_course_sortorder() did not change anything
2557 cache_helper::purge_by_event('changesincourse');
2558 if ($changesincoursecat) {
2559 cache_helper::purge_by_event('changesincoursecat');
2562 // Test for and remove blocks which aren't appropriate anymore
2563 blocks_remove_inappropriate($course);
2565 // Save any custom role names.
2566 save_local_role_names($course->id, $data);
2568 // update enrol settings
2569 enrol_course_updated(false, $course, $data);
2571 // Update course tags.
2572 if (isset($data->tags)) {
2573 core_tag_tag::set_item_tags('core', 'course', $course->id, context_course::instance($course->id), $data->tags);
2576 // Trigger a course updated event.
2577 $event = \core\event\course_updated::create(array(
2578 'objectid' => $course->id,
2579 'context' => context_course::instance($course->id),
2580 'other' => array('shortname' => $course->shortname,
2581 'fullname' => $course->fullname,
2582 'updatedfields' => $updatedfields)
2585 $event->set_legacy_logdata(array($course->id, 'course', 'update', 'edit.php?id=' . $course->id, $course->id));
2586 $event->trigger();
2588 if ($oldcourse->format !== $course->format) {
2589 // Remove all options stored for the previous format
2590 // We assume that new course format migrated everything it needed watching trigger
2591 // 'course_updated' and in method format_XXX::update_course_format_options()
2592 $DB->delete_records('course_format_options',
2593 array('courseid' => $course->id, 'format' => $oldcourse->format));
2598 * Calculate the average number of enrolled participants per course.
2600 * This is intended for statistics purposes during the site registration. Only visible courses are taken into account.
2601 * Front page enrolments are excluded.
2603 * @param bool $onlyactive Consider only active enrolments in enabled plugins and obey the enrolment time restrictions.
2604 * @param int $lastloginsince If specified, count only users who logged in after this timestamp.
2605 * @return float
2607 function average_number_of_participants(bool $onlyactive = false, int $lastloginsince = null): float {
2608 global $DB;
2610 $params = [
2611 'siteid' => SITEID,
2614 $sql = "SELECT DISTINCT ue.userid, e.courseid
2615 FROM {user_enrolments} ue
2616 JOIN {enrol} e ON e.id = ue.enrolid
2617 JOIN {course} c ON c.id = e.courseid ";
2619 if ($onlyactive || $lastloginsince) {
2620 $sql .= "JOIN {user} u ON u.id = ue.userid ";
2623 $sql .= "WHERE e.courseid <> :siteid
2624 AND c.visible = 1 ";
2626 if ($onlyactive) {
2627 $sql .= "AND ue.status = :active
2628 AND e.status = :enabled
2629 AND ue.timestart < :now1
2630 AND (ue.timeend = 0 OR ue.timeend > :now2) ";
2632 // Same as in the enrollib - the rounding should help caching in the database.
2633 $now = round(time(), -2);
2635 $params += [
2636 'active' => ENROL_USER_ACTIVE,
2637 'enabled' => ENROL_INSTANCE_ENABLED,
2638 'now1' => $now,
2639 'now2' => $now,
2643 if ($lastloginsince) {
2644 $sql .= "AND u.lastlogin > :lastlogin ";
2645 $params['lastlogin'] = $lastloginsince;
2648 $sql = "SELECT COUNT(*)
2649 FROM ($sql) total";
2651 $enrolmenttotal = $DB->count_records_sql($sql, $params);
2653 // Get the number of visible courses (exclude the front page).
2654 $coursetotal = $DB->count_records('course', ['visible' => 1]);
2655 $coursetotal = $coursetotal - 1;
2657 if (empty($coursetotal)) {
2658 $participantaverage = 0;
2660 } else {
2661 $participantaverage = $enrolmenttotal / $coursetotal;
2664 return $participantaverage;
2668 * Average number of course modules
2669 * @return integer
2671 function average_number_of_courses_modules() {
2672 global $DB, $SITE;
2674 //count total of visible course module (except front page)
2675 $sql = 'SELECT COUNT(*) FROM (
2676 SELECT cm.course, cm.module
2677 FROM {course} c, {course_modules} cm
2678 WHERE c.id = cm.course
2679 AND c.id <> :siteid
2680 AND cm.visible = 1
2681 AND c.visible = 1) total';
2682 $params = array('siteid' => $SITE->id);
2683 $moduletotal = $DB->count_records_sql($sql, $params);
2686 //count total of visible courses (minus front page)
2687 $coursetotal = $DB->count_records('course', array('visible' => 1));
2688 $coursetotal = $coursetotal - 1 ;
2690 //average of course module
2691 if (empty($coursetotal)) {
2692 $coursemoduleaverage = 0;
2693 } else {
2694 $coursemoduleaverage = $moduletotal / $coursetotal;
2697 return $coursemoduleaverage;
2701 * This class pertains to course requests and contains methods associated with
2702 * create, approving, and removing course requests.
2704 * Please note we do not allow embedded images here because there is no context
2705 * to store them with proper access control.
2707 * @copyright 2009 Sam Hemelryk
2708 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2709 * @since Moodle 2.0
2711 * @property-read int $id
2712 * @property-read string $fullname
2713 * @property-read string $shortname
2714 * @property-read string $summary
2715 * @property-read int $summaryformat
2716 * @property-read int $summarytrust
2717 * @property-read string $reason
2718 * @property-read int $requester
2720 class course_request {
2723 * This is the stdClass that stores the properties for the course request
2724 * and is externally accessed through the __get magic method
2725 * @var stdClass
2727 protected $properties;
2730 * An array of options for the summary editor used by course request forms.
2731 * This is initially set by {@link summary_editor_options()}
2732 * @var array
2733 * @static
2735 protected static $summaryeditoroptions;
2738 * Static function to prepare the summary editor for working with a course
2739 * request.
2741 * @static
2742 * @param null|stdClass $data Optional, an object containing the default values
2743 * for the form, these may be modified when preparing the
2744 * editor so this should be called before creating the form
2745 * @return stdClass An object that can be used to set the default values for
2746 * an mforms form
2748 public static function prepare($data=null) {
2749 if ($data === null) {
2750 $data = new stdClass;
2752 $data = file_prepare_standard_editor($data, 'summary', self::summary_editor_options());
2753 return $data;
2757 * Static function to create a new course request when passed an array of properties
2758 * for it.
2760 * This function also handles saving any files that may have been used in the editor
2762 * @static
2763 * @param stdClass $data
2764 * @return course_request The newly created course request
2766 public static function create($data) {
2767 global $USER, $DB, $CFG;
2768 $data->requester = $USER->id;
2770 // Setting the default category if none set.
2771 if (empty($data->category) || !empty($CFG->lockrequestcategory)) {
2772 $data->category = $CFG->defaultrequestcategory;
2775 // Summary is a required field so copy the text over
2776 $data->summary = $data->summary_editor['text'];
2777 $data->summaryformat = $data->summary_editor['format'];
2779 $data->id = $DB->insert_record('course_request', $data);
2781 // Create a new course_request object and return it
2782 $request = new course_request($data);
2784 // Notify the admin if required.
2785 if ($users = get_users_from_config($CFG->courserequestnotify, 'moodle/site:approvecourse')) {
2787 $a = new stdClass;
2788 $a->link = "$CFG->wwwroot/course/pending.php";
2789 $a->user = fullname($USER);
2790 $subject = get_string('courserequest');
2791 $message = get_string('courserequestnotifyemail', 'admin', $a);
2792 foreach ($users as $user) {
2793 $request->notify($user, $USER, 'courserequested', $subject, $message);
2797 return $request;
2801 * Returns an array of options to use with a summary editor
2803 * @uses course_request::$summaryeditoroptions
2804 * @return array An array of options to use with the editor
2806 public static function summary_editor_options() {
2807 global $CFG;
2808 if (self::$summaryeditoroptions === null) {
2809 self::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
2811 return self::$summaryeditoroptions;
2815 * Loads the properties for this course request object. Id is required and if
2816 * only id is provided then we load the rest of the properties from the database
2818 * @param stdClass|int $properties Either an object containing properties
2819 * or the course_request id to load
2821 public function __construct($properties) {
2822 global $DB;
2823 if (empty($properties->id)) {
2824 if (empty($properties)) {
2825 throw new coding_exception('You must provide a course request id when creating a course_request object');
2827 $id = $properties;
2828 $properties = new stdClass;
2829 $properties->id = (int)$id;
2830 unset($id);
2832 if (empty($properties->requester)) {
2833 if (!($this->properties = $DB->get_record('course_request', array('id' => $properties->id)))) {
2834 print_error('unknowncourserequest');
2836 } else {
2837 $this->properties = $properties;
2839 $this->properties->collision = null;
2843 * Returns the requested property
2845 * @param string $key
2846 * @return mixed
2848 public function __get($key) {
2849 return $this->properties->$key;
2853 * Override this to ensure empty($request->blah) calls return a reliable answer...
2855 * This is required because we define the __get method
2857 * @param mixed $key
2858 * @return bool True is it not empty, false otherwise
2860 public function __isset($key) {
2861 return (!empty($this->properties->$key));
2865 * Returns the user who requested this course
2867 * Uses a static var to cache the results and cut down the number of db queries
2869 * @staticvar array $requesters An array of cached users
2870 * @return stdClass The user who requested the course
2872 public function get_requester() {
2873 global $DB;
2874 static $requesters= array();
2875 if (!array_key_exists($this->properties->requester, $requesters)) {
2876 $requesters[$this->properties->requester] = $DB->get_record('user', array('id'=>$this->properties->requester));
2878 return $requesters[$this->properties->requester];
2882 * Checks that the shortname used by the course does not conflict with any other
2883 * courses that exist
2885 * @param string|null $shortnamemark The string to append to the requests shortname
2886 * should a conflict be found
2887 * @return bool true is there is a conflict, false otherwise
2889 public function check_shortname_collision($shortnamemark = '[*]') {
2890 global $DB;
2892 if ($this->properties->collision !== null) {
2893 return $this->properties->collision;
2896 if (empty($this->properties->shortname)) {
2897 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER);
2898 $this->properties->collision = false;
2899 } else if ($DB->record_exists('course', array('shortname' => $this->properties->shortname))) {
2900 if (!empty($shortnamemark)) {
2901 $this->properties->shortname .= ' '.$shortnamemark;
2903 $this->properties->collision = true;
2904 } else {
2905 $this->properties->collision = false;
2907 return $this->properties->collision;
2911 * Checks user capability to approve a requested course
2913 * If course was requested without category for some reason (might happen if $CFG->defaultrequestcategory is
2914 * misconfigured), we check capabilities 'moodle/site:approvecourse' and 'moodle/course:changecategory'.
2916 * @return bool
2918 public function can_approve() {
2919 global $CFG;
2920 $category = null;
2921 if ($this->properties->category) {
2922 $category = core_course_category::get($this->properties->category, IGNORE_MISSING);
2923 } else if ($CFG->defaultrequestcategory) {
2924 $category = core_course_category::get($CFG->defaultrequestcategory, IGNORE_MISSING);
2926 if ($category) {
2927 return has_capability('moodle/site:approvecourse', $category->get_context());
2930 // We can not determine the context where the course should be created. The approver should have
2931 // both capabilities to approve courses and change course category in the system context.
2932 return has_all_capabilities(['moodle/site:approvecourse', 'moodle/course:changecategory'], context_system::instance());
2936 * Returns the category where this course request should be created
2938 * Note that we don't check here that user has a capability to view
2939 * hidden categories if he has capabilities 'moodle/site:approvecourse' and
2940 * 'moodle/course:changecategory'
2942 * @return core_course_category
2944 public function get_category() {
2945 global $CFG;
2946 if ($this->properties->category && ($category = core_course_category::get($this->properties->category, IGNORE_MISSING))) {
2947 return $category;
2948 } else if ($CFG->defaultrequestcategory &&
2949 ($category = core_course_category::get($CFG->defaultrequestcategory, IGNORE_MISSING))) {
2950 return $category;
2951 } else {
2952 return core_course_category::get_default();
2957 * This function approves the request turning it into a course
2959 * This function converts the course request into a course, at the same time
2960 * transferring any files used in the summary to the new course and then removing
2961 * the course request and the files associated with it.
2963 * @return int The id of the course that was created from this request
2965 public function approve() {
2966 global $CFG, $DB, $USER;
2968 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
2970 $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted'=>0), '*', MUST_EXIST);
2972 $courseconfig = get_config('moodlecourse');
2974 // Transfer appropriate settings
2975 $data = clone($this->properties);
2976 unset($data->id);
2977 unset($data->reason);
2978 unset($data->requester);
2980 // Set category
2981 $category = $this->get_category();
2982 $data->category = $category->id;
2983 // Set misc settings
2984 $data->requested = 1;
2986 // Apply course default settings
2987 $data->format = $courseconfig->format;
2988 $data->newsitems = $courseconfig->newsitems;
2989 $data->showgrades = $courseconfig->showgrades;
2990 $data->showreports = $courseconfig->showreports;
2991 $data->maxbytes = $courseconfig->maxbytes;
2992 $data->groupmode = $courseconfig->groupmode;
2993 $data->groupmodeforce = $courseconfig->groupmodeforce;
2994 $data->visible = $courseconfig->visible;
2995 $data->visibleold = $data->visible;
2996 $data->lang = $courseconfig->lang;
2997 $data->enablecompletion = $courseconfig->enablecompletion;
2998 $data->numsections = $courseconfig->numsections;
2999 $data->startdate = usergetmidnight(time());
3000 if ($courseconfig->courseenddateenabled) {
3001 $data->enddate = usergetmidnight(time()) + $courseconfig->courseduration;
3004 list($data->fullname, $data->shortname) = restore_dbops::calculate_course_names(0, $data->fullname, $data->shortname);
3006 $course = create_course($data);
3007 $context = context_course::instance($course->id, MUST_EXIST);
3009 // add enrol instances
3010 if (!$DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
3011 if ($manual = enrol_get_plugin('manual')) {
3012 $manual->add_default_instance($course);
3016 // enrol the requester as teacher if necessary
3017 if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
3018 enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid);
3021 $this->delete();
3023 $a = new stdClass();
3024 $a->name = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
3025 $a->url = $CFG->wwwroot.'/course/view.php?id=' . $course->id;
3026 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a), $course->id);
3028 return $course->id;
3032 * Reject a course request
3034 * This function rejects a course request, emailing the requesting user the
3035 * provided notice and then removing the request from the database
3037 * @param string $notice The message to display to the user
3039 public function reject($notice) {
3040 global $USER, $DB;
3041 $user = $DB->get_record('user', array('id' => $this->properties->requester), '*', MUST_EXIST);
3042 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
3043 $this->delete();
3047 * Deletes the course request and any associated files
3049 public function delete() {
3050 global $DB;
3051 $DB->delete_records('course_request', array('id' => $this->properties->id));
3055 * Send a message from one user to another using events_trigger
3057 * @param object $touser
3058 * @param object $fromuser
3059 * @param string $name
3060 * @param string $subject
3061 * @param string $message
3062 * @param int|null $courseid
3064 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message, $courseid = null) {
3065 $eventdata = new \core\message\message();
3066 $eventdata->courseid = empty($courseid) ? SITEID : $courseid;
3067 $eventdata->component = 'moodle';
3068 $eventdata->name = $name;
3069 $eventdata->userfrom = $fromuser;
3070 $eventdata->userto = $touser;
3071 $eventdata->subject = $subject;
3072 $eventdata->fullmessage = $message;
3073 $eventdata->fullmessageformat = FORMAT_PLAIN;
3074 $eventdata->fullmessagehtml = '';
3075 $eventdata->smallmessage = '';
3076 $eventdata->notification = 1;
3077 message_send($eventdata);
3081 * Checks if current user can request a course in this context
3083 * @param context $context
3084 * @return bool
3086 public static function can_request(context $context) {
3087 global $CFG;
3088 if (empty($CFG->enablecourserequests)) {
3089 return false;
3091 if (has_capability('moodle/course:create', $context)) {
3092 return false;
3095 if ($context instanceof context_system) {
3096 $defaultcontext = context_coursecat::instance($CFG->defaultrequestcategory, IGNORE_MISSING);
3097 return $defaultcontext &&
3098 has_capability('moodle/course:request', $defaultcontext);
3099 } else if ($context instanceof context_coursecat) {
3100 if (!$CFG->lockrequestcategory || $CFG->defaultrequestcategory == $context->instanceid) {
3101 return has_capability('moodle/course:request', $context);
3104 return false;
3109 * Return a list of page types
3110 * @param string $pagetype current page type
3111 * @param context $parentcontext Block's parent context
3112 * @param context $currentcontext Current context of block
3113 * @return array array of page types
3115 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
3116 if ($pagetype === 'course-index' || $pagetype === 'course-index-category') {
3117 // For courses and categories browsing pages (/course/index.php) add option to show on ANY category page
3118 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
3119 'course-index-*' => get_string('page-course-index-x', 'pagetype'),
3121 } else if ($currentcontext && (!($coursecontext = $currentcontext->get_course_context(false)) || $coursecontext->instanceid == SITEID)) {
3122 // We know for sure that despite pagetype starts with 'course-' this is not a page in course context (i.e. /course/search.php, etc.)
3123 $pagetypes = array('*' => get_string('page-x', 'pagetype'));
3124 } else {
3125 // Otherwise consider it a page inside a course even if $currentcontext is null
3126 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
3127 'course-*' => get_string('page-course-x', 'pagetype'),
3128 'course-view-*' => get_string('page-course-view-x', 'pagetype')
3131 return $pagetypes;
3135 * Determine whether course ajax should be enabled for the specified course
3137 * @param stdClass $course The course to test against
3138 * @return boolean Whether course ajax is enabled or note
3140 function course_ajax_enabled($course) {
3141 global $CFG, $PAGE, $SITE;
3143 // The user must be editing for AJAX to be included
3144 if (!$PAGE->user_is_editing()) {
3145 return false;
3148 // Check that the theme suports
3149 if (!$PAGE->theme->enablecourseajax) {
3150 return false;
3153 // Check that the course format supports ajax functionality
3154 // The site 'format' doesn't have information on course format support
3155 if ($SITE->id !== $course->id) {
3156 $courseformatajaxsupport = course_format_ajax_support($course->format);
3157 if (!$courseformatajaxsupport->capable) {
3158 return false;
3162 // All conditions have been met so course ajax should be enabled
3163 return true;
3167 * Include the relevant javascript and language strings for the resource
3168 * toolbox YUI module
3170 * @param integer $id The ID of the course being applied to
3171 * @param array $usedmodules An array containing the names of the modules in use on the page
3172 * @param array $enabledmodules An array containing the names of the enabled (visible) modules on this site
3173 * @param stdClass $config An object containing configuration parameters for ajax modules including:
3174 * * resourceurl The URL to post changes to for resource changes
3175 * * sectionurl The URL to post changes to for section changes
3176 * * pageparams Additional parameters to pass through in the post
3177 * @return bool
3179 function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) {
3180 global $CFG, $PAGE, $SITE;
3182 // Ensure that ajax should be included
3183 if (!course_ajax_enabled($course)) {
3184 return false;
3187 if (!$config) {
3188 $config = new stdClass();
3191 // The URL to use for resource changes
3192 if (!isset($config->resourceurl)) {
3193 $config->resourceurl = '/course/rest.php';
3196 // The URL to use for section changes
3197 if (!isset($config->sectionurl)) {
3198 $config->sectionurl = '/course/rest.php';
3201 // Any additional parameters which need to be included on page submission
3202 if (!isset($config->pageparams)) {
3203 $config->pageparams = array();
3206 // Include course dragdrop
3207 if (course_format_uses_sections($course->format)) {
3208 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_section_dragdrop',
3209 array(array(
3210 'courseid' => $course->id,
3211 'ajaxurl' => $config->sectionurl,
3212 'config' => $config,
3213 )), null, true);
3215 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_resource_dragdrop',
3216 array(array(
3217 'courseid' => $course->id,
3218 'ajaxurl' => $config->resourceurl,
3219 'config' => $config,
3220 )), null, true);
3223 // Require various strings for the command toolbox
3224 $PAGE->requires->strings_for_js(array(
3225 'moveleft',
3226 'deletechecktype',
3227 'deletechecktypename',
3228 'edittitle',
3229 'edittitleinstructions',
3230 'show',
3231 'hide',
3232 'highlight',
3233 'highlightoff',
3234 'groupsnone',
3235 'groupsvisible',
3236 'groupsseparate',
3237 'clicktochangeinbrackets',
3238 'markthistopic',
3239 'markedthistopic',
3240 'movesection',
3241 'movecoursemodule',
3242 'movecoursesection',
3243 'movecontent',
3244 'tocontent',
3245 'emptydragdropregion',
3246 'afterresource',
3247 'aftersection',
3248 'totopofsection',
3249 ), 'moodle');
3251 // Include section-specific strings for formats which support sections.
3252 if (course_format_uses_sections($course->format)) {
3253 $PAGE->requires->strings_for_js(array(
3254 'showfromothers',
3255 'hidefromothers',
3256 ), 'format_' . $course->format);
3259 // For confirming resource deletion we need the name of the module in question
3260 foreach ($usedmodules as $module => $modname) {
3261 $PAGE->requires->string_for_js('pluginname', $module);
3264 // Load drag and drop upload AJAX.
3265 require_once($CFG->dirroot.'/course/dnduploadlib.php');
3266 dndupload_add_to_course($course, $enabledmodules);
3268 $PAGE->requires->js_call_amd('core_course/actions', 'initCoursePage', array($course->format));
3270 return true;
3274 * Returns the sorted list of available course formats, filtered by enabled if necessary
3276 * @param bool $enabledonly return only formats that are enabled
3277 * @return array array of sorted format names
3279 function get_sorted_course_formats($enabledonly = false) {
3280 global $CFG;
3281 $formats = core_component::get_plugin_list('format');
3283 if (!empty($CFG->format_plugins_sortorder)) {
3284 $order = explode(',', $CFG->format_plugins_sortorder);
3285 $order = array_merge(array_intersect($order, array_keys($formats)),
3286 array_diff(array_keys($formats), $order));
3287 } else {
3288 $order = array_keys($formats);
3290 if (!$enabledonly) {
3291 return $order;
3293 $sortedformats = array();
3294 foreach ($order as $formatname) {
3295 if (!get_config('format_'.$formatname, 'disabled')) {
3296 $sortedformats[] = $formatname;
3299 return $sortedformats;
3303 * The URL to use for the specified course (with section)
3305 * @param int|stdClass $courseorid The course to get the section name for (either object or just course id)
3306 * @param int|stdClass $section Section object from database or just field course_sections.section
3307 * if omitted the course view page is returned
3308 * @param array $options options for view URL. At the moment core uses:
3309 * 'navigation' (bool) if true and section has no separate page, the function returns null
3310 * 'sr' (int) used by multipage formats to specify to which section to return
3311 * @return moodle_url The url of course
3313 function course_get_url($courseorid, $section = null, $options = array()) {
3314 return course_get_format($courseorid)->get_view_url($section, $options);
3318 * Create a module.
3320 * It includes:
3321 * - capability checks and other checks
3322 * - create the module from the module info
3324 * @param object $module
3325 * @return object the created module info
3326 * @throws moodle_exception if user is not allowed to perform the action or module is not allowed in this course
3328 function create_module($moduleinfo) {
3329 global $DB, $CFG;
3331 require_once($CFG->dirroot . '/course/modlib.php');
3333 // Check manadatory attributs.
3334 $mandatoryfields = array('modulename', 'course', 'section', 'visible');
3335 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
3336 $mandatoryfields[] = 'introeditor';
3338 foreach($mandatoryfields as $mandatoryfield) {
3339 if (!isset($moduleinfo->{$mandatoryfield})) {
3340 throw new moodle_exception('createmodulemissingattribut', '', '', $mandatoryfield);
3344 // Some additional checks (capability / existing instances).
3345 $course = $DB->get_record('course', array('id'=>$moduleinfo->course), '*', MUST_EXIST);
3346 list($module, $context, $cw) = can_add_moduleinfo($course, $moduleinfo->modulename, $moduleinfo->section);
3348 // Add the module.
3349 $moduleinfo->module = $module->id;
3350 $moduleinfo = add_moduleinfo($moduleinfo, $course, null);
3352 return $moduleinfo;
3356 * Update a module.
3358 * It includes:
3359 * - capability and other checks
3360 * - update the module
3362 * @param object $module
3363 * @return object the updated module info
3364 * @throws moodle_exception if current user is not allowed to update the module
3366 function update_module($moduleinfo) {
3367 global $DB, $CFG;
3369 require_once($CFG->dirroot . '/course/modlib.php');
3371 // Check the course module exists.
3372 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule, 0, false, MUST_EXIST);
3374 // Check the course exists.
3375 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
3377 // Some checks (capaibility / existing instances).
3378 list($cm, $context, $module, $data, $cw) = can_update_moduleinfo($cm);
3380 // Retrieve few information needed by update_moduleinfo.
3381 $moduleinfo->modulename = $cm->modname;
3382 if (!isset($moduleinfo->scale)) {
3383 $moduleinfo->scale = 0;
3385 $moduleinfo->type = 'mod';
3387 // Update the module.
3388 list($cm, $moduleinfo) = update_moduleinfo($cm, $moduleinfo, $course, null);
3390 return $moduleinfo;
3394 * Duplicate a module on the course for ajax.
3396 * @see mod_duplicate_module()
3397 * @param object $course The course
3398 * @param object $cm The course module to duplicate
3399 * @param int $sr The section to link back to (used for creating the links)
3400 * @throws moodle_exception if the plugin doesn't support duplication
3401 * @return Object containing:
3402 * - fullcontent: The HTML markup for the created CM
3403 * - cmid: The CMID of the newly created CM
3404 * - redirect: Whether to trigger a redirect following this change
3406 function mod_duplicate_activity($course, $cm, $sr = null) {
3407 global $PAGE;
3409 $newcm = duplicate_module($course, $cm);
3411 $resp = new stdClass();
3412 if ($newcm) {
3413 $courserenderer = $PAGE->get_renderer('core', 'course');
3414 $completioninfo = new completion_info($course);
3415 $modulehtml = $courserenderer->course_section_cm($course, $completioninfo,
3416 $newcm, null, array());
3418 $resp->fullcontent = $courserenderer->course_section_cm_list_item($course, $completioninfo, $newcm, $sr);
3419 $resp->cmid = $newcm->id;
3420 } else {
3421 // Trigger a redirect.
3422 $resp->redirect = true;
3424 return $resp;
3428 * Api to duplicate a module.
3430 * @param object $course course object.
3431 * @param object $cm course module object to be duplicated.
3432 * @since Moodle 2.8
3434 * @throws Exception
3435 * @throws coding_exception
3436 * @throws moodle_exception
3437 * @throws restore_controller_exception
3439 * @return cm_info|null cminfo object if we sucessfully duplicated the mod and found the new cm.
3441 function duplicate_module($course, $cm) {
3442 global $CFG, $DB, $USER;
3443 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
3444 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
3445 require_once($CFG->libdir . '/filelib.php');
3447 $a = new stdClass();
3448 $a->modtype = get_string('modulename', $cm->modname);
3449 $a->modname = format_string($cm->name);
3451 if (!plugin_supports('mod', $cm->modname, FEATURE_BACKUP_MOODLE2)) {
3452 throw new moodle_exception('duplicatenosupport', 'error', '', $a);
3455 // Backup the activity.
3457 $bc = new backup_controller(backup::TYPE_1ACTIVITY, $cm->id, backup::FORMAT_MOODLE,
3458 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
3460 $backupid = $bc->get_backupid();
3461 $backupbasepath = $bc->get_plan()->get_basepath();
3463 $bc->execute_plan();
3465 $bc->destroy();
3467 // Restore the backup immediately.
3469 $rc = new restore_controller($backupid, $course->id,
3470 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, backup::TARGET_CURRENT_ADDING);
3472 // Make sure that the restore_general_groups setting is always enabled when duplicating an activity.
3473 $plan = $rc->get_plan();
3474 $groupsetting = $plan->get_setting('groups');
3475 if (empty($groupsetting->get_value())) {
3476 $groupsetting->set_value(true);
3479 $cmcontext = context_module::instance($cm->id);
3480 if (!$rc->execute_precheck()) {
3481 $precheckresults = $rc->get_precheck_results();
3482 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
3483 if (empty($CFG->keeptempdirectoriesonbackup)) {
3484 fulldelete($backupbasepath);
3489 $rc->execute_plan();
3491 // Now a bit hacky part follows - we try to get the cmid of the newly
3492 // restored copy of the module.
3493 $newcmid = null;
3494 $tasks = $rc->get_plan()->get_tasks();
3495 foreach ($tasks as $task) {
3496 if (is_subclass_of($task, 'restore_activity_task')) {
3497 if ($task->get_old_contextid() == $cmcontext->id) {
3498 $newcmid = $task->get_moduleid();
3499 break;
3504 $rc->destroy();
3506 if (empty($CFG->keeptempdirectoriesonbackup)) {
3507 fulldelete($backupbasepath);
3510 // If we know the cmid of the new course module, let us move it
3511 // right below the original one. otherwise it will stay at the
3512 // end of the section.
3513 if ($newcmid) {
3514 // Proceed with activity renaming before everything else. We don't use APIs here to avoid
3515 // triggering a lot of create/update duplicated events.
3516 $newcm = get_coursemodule_from_id($cm->modname, $newcmid, $cm->course);
3517 // Add ' (copy)' to duplicates. Note we don't cleanup or validate lengths here. It comes
3518 // from original name that was valid, so the copy should be too.
3519 $newname = get_string('duplicatedmodule', 'moodle', $newcm->name);
3520 $DB->set_field($cm->modname, 'name', $newname, ['id' => $newcm->instance]);
3522 $section = $DB->get_record('course_sections', array('id' => $cm->section, 'course' => $cm->course));
3523 $modarray = explode(",", trim($section->sequence));
3524 $cmindex = array_search($cm->id, $modarray);
3525 if ($cmindex !== false && $cmindex < count($modarray) - 1) {
3526 moveto_module($newcm, $section, $modarray[$cmindex + 1]);
3529 // Update calendar events with the duplicated module.
3530 // The following line is to be removed in MDL-58906.
3531 course_module_update_calendar_events($newcm->modname, null, $newcm);
3533 // Trigger course module created event. We can trigger the event only if we know the newcmid.
3534 $newcm = get_fast_modinfo($cm->course)->get_cm($newcmid);
3535 $event = \core\event\course_module_created::create_from_cm($newcm);
3536 $event->trigger();
3539 return isset($newcm) ? $newcm : null;
3543 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3544 * Sorts by descending order of time.
3546 * @param stdClass $a First object
3547 * @param stdClass $b Second object
3548 * @return int 0,1,-1 representing the order
3550 function compare_activities_by_time_desc($a, $b) {
3551 // Make sure the activities actually have a timestamp property.
3552 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3553 return 0;
3555 // We treat instances without timestamp as if they have a timestamp of 0.
3556 if ((!property_exists($a, 'timestamp')) && (property_exists($b,'timestamp'))) {
3557 return 1;
3559 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3560 return -1;
3562 if ($a->timestamp == $b->timestamp) {
3563 return 0;
3565 return ($a->timestamp > $b->timestamp) ? -1 : 1;
3569 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3570 * Sorts by ascending order of time.
3572 * @param stdClass $a First object
3573 * @param stdClass $b Second object
3574 * @return int 0,1,-1 representing the order
3576 function compare_activities_by_time_asc($a, $b) {
3577 // Make sure the activities actually have a timestamp property.
3578 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3579 return 0;
3581 // We treat instances without timestamp as if they have a timestamp of 0.
3582 if ((!property_exists($a, 'timestamp')) && (property_exists($b, 'timestamp'))) {
3583 return -1;
3585 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3586 return 1;
3588 if ($a->timestamp == $b->timestamp) {
3589 return 0;
3591 return ($a->timestamp < $b->timestamp) ? -1 : 1;
3595 * Changes the visibility of a course.
3597 * @param int $courseid The course to change.
3598 * @param bool $show True to make it visible, false otherwise.
3599 * @return bool
3601 function course_change_visibility($courseid, $show = true) {
3602 $course = new stdClass;
3603 $course->id = $courseid;
3604 $course->visible = ($show) ? '1' : '0';
3605 $course->visibleold = $course->visible;
3606 update_course($course);
3607 return true;
3611 * Changes the course sortorder by one, moving it up or down one in respect to sort order.
3613 * @param stdClass|core_course_list_element $course
3614 * @param bool $up If set to true the course will be moved up one. Otherwise down one.
3615 * @return bool
3617 function course_change_sortorder_by_one($course, $up) {
3618 global $DB;
3619 $params = array($course->sortorder, $course->category);
3620 if ($up) {
3621 $select = 'sortorder < ? AND category = ?';
3622 $sort = 'sortorder DESC';
3623 } else {
3624 $select = 'sortorder > ? AND category = ?';
3625 $sort = 'sortorder ASC';
3627 fix_course_sortorder();
3628 $swapcourse = $DB->get_records_select('course', $select, $params, $sort, '*', 0, 1);
3629 if ($swapcourse) {
3630 $swapcourse = reset($swapcourse);
3631 $DB->set_field('course', 'sortorder', $swapcourse->sortorder, array('id' => $course->id));
3632 $DB->set_field('course', 'sortorder', $course->sortorder, array('id' => $swapcourse->id));
3633 // Finally reorder courses.
3634 fix_course_sortorder();
3635 cache_helper::purge_by_event('changesincourse');
3636 return true;
3638 return false;
3642 * Changes the sort order of courses in a category so that the first course appears after the second.
3644 * @param int|stdClass $courseorid The course to focus on.
3645 * @param int $moveaftercourseid The course to shifter after or 0 if you want it to be the first course in the category.
3646 * @return bool
3648 function course_change_sortorder_after_course($courseorid, $moveaftercourseid) {
3649 global $DB;
3651 if (!is_object($courseorid)) {
3652 $course = get_course($courseorid);
3653 } else {
3654 $course = $courseorid;
3657 if ((int)$moveaftercourseid === 0) {
3658 // We've moving the course to the start of the queue.
3659 $sql = 'SELECT sortorder
3660 FROM {course}
3661 WHERE category = :categoryid
3662 ORDER BY sortorder';
3663 $params = array(
3664 'categoryid' => $course->category
3666 $sortorder = $DB->get_field_sql($sql, $params, IGNORE_MULTIPLE);
3668 $sql = 'UPDATE {course}
3669 SET sortorder = sortorder + 1
3670 WHERE category = :categoryid
3671 AND id <> :id';
3672 $params = array(
3673 'categoryid' => $course->category,
3674 'id' => $course->id,
3676 $DB->execute($sql, $params);
3677 $DB->set_field('course', 'sortorder', $sortorder, array('id' => $course->id));
3678 } else if ($course->id === $moveaftercourseid) {
3679 // They're the same - moronic.
3680 debugging("Invalid move after course given.", DEBUG_DEVELOPER);
3681 return false;
3682 } else {
3683 // Moving this course after the given course. It could be before it could be after.
3684 $moveaftercourse = get_course($moveaftercourseid);
3685 if ($course->category !== $moveaftercourse->category) {
3686 debugging("Cannot re-order courses. The given courses do not belong to the same category.", DEBUG_DEVELOPER);
3687 return false;
3689 // Increment all courses in the same category that are ordered after the moveafter course.
3690 // This makes a space for the course we're moving.
3691 $sql = 'UPDATE {course}
3692 SET sortorder = sortorder + 1
3693 WHERE category = :categoryid
3694 AND sortorder > :sortorder';
3695 $params = array(
3696 'categoryid' => $moveaftercourse->category,
3697 'sortorder' => $moveaftercourse->sortorder
3699 $DB->execute($sql, $params);
3700 $DB->set_field('course', 'sortorder', $moveaftercourse->sortorder + 1, array('id' => $course->id));
3702 fix_course_sortorder();
3703 cache_helper::purge_by_event('changesincourse');
3704 return true;
3708 * Trigger course viewed event. This API function is used when course view actions happens,
3709 * usually in course/view.php but also in external functions.
3711 * @param stdClass $context course context object
3712 * @param int $sectionnumber section number
3713 * @since Moodle 2.9
3715 function course_view($context, $sectionnumber = 0) {
3717 $eventdata = array('context' => $context);
3719 if (!empty($sectionnumber)) {
3720 $eventdata['other']['coursesectionnumber'] = $sectionnumber;
3723 $event = \core\event\course_viewed::create($eventdata);
3724 $event->trigger();
3726 user_accesstime_log($context->instanceid);
3730 * Returns courses tagged with a specified tag.
3732 * @param core_tag_tag $tag
3733 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
3734 * are displayed on the page and the per-page limit may be bigger
3735 * @param int $fromctx context id where the link was displayed, may be used by callbacks
3736 * to display items in the same context first
3737 * @param int $ctx context id where to search for records
3738 * @param bool $rec search in subcontexts as well
3739 * @param int $page 0-based number of page being displayed
3740 * @return \core_tag\output\tagindex
3742 function course_get_tagged_courses($tag, $exclusivemode = false, $fromctx = 0, $ctx = 0, $rec = 1, $page = 0) {
3743 global $CFG, $PAGE;
3745 $perpage = $exclusivemode ? $CFG->coursesperpage : 5;
3746 $displayoptions = array(
3747 'limit' => $perpage,
3748 'offset' => $page * $perpage,
3749 'viewmoreurl' => null,
3752 $courserenderer = $PAGE->get_renderer('core', 'course');
3753 $totalcount = core_course_category::search_courses_count(array('tagid' => $tag->id, 'ctx' => $ctx, 'rec' => $rec));
3754 $content = $courserenderer->tagged_courses($tag->id, $exclusivemode, $ctx, $rec, $displayoptions);
3755 $totalpages = ceil($totalcount / $perpage);
3757 return new core_tag\output\tagindex($tag, 'core', 'course', $content,
3758 $exclusivemode, $fromctx, $ctx, $rec, $page, $totalpages);
3762 * Implements callback inplace_editable() allowing to edit values in-place
3764 * @param string $itemtype
3765 * @param int $itemid
3766 * @param mixed $newvalue
3767 * @return \core\output\inplace_editable
3769 function core_course_inplace_editable($itemtype, $itemid, $newvalue) {
3770 if ($itemtype === 'activityname') {
3771 return \core_course\output\course_module_name::update($itemid, $newvalue);
3776 * This function calculates the minimum and maximum cutoff values for the timestart of
3777 * the given event.
3779 * It will return an array with two values, the first being the minimum cutoff value and
3780 * the second being the maximum cutoff value. Either or both values can be null, which
3781 * indicates there is no minimum or maximum, respectively.
3783 * If a cutoff is required then the function must return an array containing the cutoff
3784 * timestamp and error string to display to the user if the cutoff value is violated.
3786 * A minimum and maximum cutoff return value will look like:
3788 * [1505704373, 'The date must be after this date'],
3789 * [1506741172, 'The date must be before this date']
3792 * @param calendar_event $event The calendar event to get the time range for
3793 * @param stdClass $course The course object to get the range from
3794 * @return array Returns an array with min and max date.
3796 function core_course_core_calendar_get_valid_event_timestart_range(\calendar_event $event, $course) {
3797 $mindate = null;
3798 $maxdate = null;
3800 if ($course->startdate) {
3801 $mindate = [
3802 $course->startdate,
3803 get_string('errorbeforecoursestart', 'calendar')
3807 return [$mindate, $maxdate];
3811 * Returns course modules tagged with a specified tag ready for output on tag/index.php page
3813 * This is a callback used by the tag area core/course_modules to search for course modules
3814 * tagged with a specific tag.
3816 * @param core_tag_tag $tag
3817 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
3818 * are displayed on the page and the per-page limit may be bigger
3819 * @param int $fromcontextid context id where the link was displayed, may be used by callbacks
3820 * to display items in the same context first
3821 * @param int $contextid context id where to search for records
3822 * @param bool $recursivecontext search in subcontexts as well
3823 * @param int $page 0-based number of page being displayed
3824 * @return \core_tag\output\tagindex
3826 function course_get_tagged_course_modules($tag, $exclusivemode = false, $fromcontextid = 0, $contextid = 0,
3827 $recursivecontext = 1, $page = 0) {
3828 global $OUTPUT;
3829 $perpage = $exclusivemode ? 20 : 5;
3831 // Build select query.
3832 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
3833 $query = "SELECT cm.id AS cmid, c.id AS courseid, $ctxselect
3834 FROM {course_modules} cm
3835 JOIN {tag_instance} tt ON cm.id = tt.itemid
3836 JOIN {course} c ON cm.course = c.id
3837 JOIN {context} ctx ON ctx.instanceid = cm.id AND ctx.contextlevel = :coursemodulecontextlevel
3838 WHERE tt.itemtype = :itemtype AND tt.tagid = :tagid AND tt.component = :component
3839 AND cm.deletioninprogress = 0
3840 AND c.id %COURSEFILTER% AND cm.id %ITEMFILTER%";
3842 $params = array('itemtype' => 'course_modules', 'tagid' => $tag->id, 'component' => 'core',
3843 'coursemodulecontextlevel' => CONTEXT_MODULE);
3844 if ($contextid) {
3845 $context = context::instance_by_id($contextid);
3846 $query .= $recursivecontext ? ' AND (ctx.id = :contextid OR ctx.path LIKE :path)' : ' AND ctx.id = :contextid';
3847 $params['contextid'] = $context->id;
3848 $params['path'] = $context->path.'/%';
3851 $query .= ' ORDER BY';
3852 if ($fromcontextid) {
3853 // In order-clause specify that modules from inside "fromctx" context should be returned first.
3854 $fromcontext = context::instance_by_id($fromcontextid);
3855 $query .= ' (CASE WHEN ctx.id = :fromcontextid OR ctx.path LIKE :frompath THEN 0 ELSE 1 END),';
3856 $params['fromcontextid'] = $fromcontext->id;
3857 $params['frompath'] = $fromcontext->path.'/%';
3859 $query .= ' c.sortorder, cm.id';
3860 $totalpages = $page + 1;
3862 // Use core_tag_index_builder to build and filter the list of items.
3863 // Request one item more than we need so we know if next page exists.
3864 $builder = new core_tag_index_builder('core', 'course_modules', $query, $params, $page * $perpage, $perpage + 1);
3865 while ($item = $builder->has_item_that_needs_access_check()) {
3866 context_helper::preload_from_record($item);
3867 $courseid = $item->courseid;
3868 if (!$builder->can_access_course($courseid)) {
3869 $builder->set_accessible($item, false);
3870 continue;
3872 $modinfo = get_fast_modinfo($builder->get_course($courseid));
3873 // Set accessibility of this item and all other items in the same course.
3874 $builder->walk(function ($taggeditem) use ($courseid, $modinfo, $builder) {
3875 if ($taggeditem->courseid == $courseid) {
3876 $cm = $modinfo->get_cm($taggeditem->cmid);
3877 $builder->set_accessible($taggeditem, $cm->uservisible);
3882 $items = $builder->get_items();
3883 if (count($items) > $perpage) {
3884 $totalpages = $page + 2; // We don't need exact page count, just indicate that the next page exists.
3885 array_pop($items);
3888 // Build the display contents.
3889 if ($items) {
3890 $tagfeed = new core_tag\output\tagfeed();
3891 foreach ($items as $item) {
3892 context_helper::preload_from_record($item);
3893 $course = $builder->get_course($item->courseid);
3894 $modinfo = get_fast_modinfo($course);
3895 $cm = $modinfo->get_cm($item->cmid);
3896 $courseurl = course_get_url($item->courseid, $cm->sectionnum);
3897 $cmname = $cm->get_formatted_name();
3898 if (!$exclusivemode) {
3899 $cmname = shorten_text($cmname, 100);
3901 $cmname = html_writer::link($cm->url?:$courseurl, $cmname);
3902 $coursename = format_string($course->fullname, true,
3903 array('context' => context_course::instance($item->courseid)));
3904 $coursename = html_writer::link($courseurl, $coursename);
3905 $icon = html_writer::empty_tag('img', array('src' => $cm->get_icon_url()));
3906 $tagfeed->add($icon, $cmname, $coursename);
3909 $content = $OUTPUT->render_from_template('core_tag/tagfeed',
3910 $tagfeed->export_for_template($OUTPUT));
3912 return new core_tag\output\tagindex($tag, 'core', 'course_modules', $content,
3913 $exclusivemode, $fromcontextid, $contextid, $recursivecontext, $page, $totalpages);
3918 * Return an object with the list of navigation options in a course that are avaialable or not for the current user.
3919 * This function also handles the frontpage course.
3921 * @param stdClass $context context object (it can be a course context or the system context for frontpage settings)
3922 * @param stdClass $course the course where the settings are being rendered
3923 * @return stdClass the navigation options in a course and their availability status
3924 * @since Moodle 3.2
3926 function course_get_user_navigation_options($context, $course = null) {
3927 global $CFG;
3929 $isloggedin = isloggedin();
3930 $isguestuser = isguestuser();
3931 $isfrontpage = $context->contextlevel == CONTEXT_SYSTEM;
3933 if ($isfrontpage) {
3934 $sitecontext = $context;
3935 } else {
3936 $sitecontext = context_system::instance();
3939 // Sets defaults for all options.
3940 $options = (object) [
3941 'badges' => false,
3942 'blogs' => false,
3943 'calendar' => false,
3944 'competencies' => false,
3945 'grades' => false,
3946 'notes' => false,
3947 'participants' => false,
3948 'search' => false,
3949 'tags' => false,
3952 $options->blogs = !empty($CFG->enableblogs) &&
3953 ($CFG->bloglevel == BLOG_GLOBAL_LEVEL ||
3954 ($CFG->bloglevel == BLOG_SITE_LEVEL and ($isloggedin and !$isguestuser)))
3955 && has_capability('moodle/blog:view', $sitecontext);
3957 $options->notes = !empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $context);
3959 // Frontpage settings?
3960 if ($isfrontpage) {
3961 // We are on the front page, so make sure we use the proper capability (site:viewparticipants).
3962 $options->participants = course_can_view_participants($sitecontext);
3963 $options->badges = !empty($CFG->enablebadges) && has_capability('moodle/badges:viewbadges', $sitecontext);
3964 $options->tags = !empty($CFG->usetags) && $isloggedin;
3965 $options->search = !empty($CFG->enableglobalsearch) && has_capability('moodle/search:query', $sitecontext);
3966 $options->calendar = $isloggedin;
3967 } else {
3968 // We are in a course, so make sure we use the proper capability (course:viewparticipants).
3969 $options->participants = course_can_view_participants($context);
3970 $options->badges = !empty($CFG->enablebadges) && !empty($CFG->badges_allowcoursebadges) &&
3971 has_capability('moodle/badges:viewbadges', $context);
3972 // Add view grade report is permitted.
3973 $grades = false;
3975 if (has_capability('moodle/grade:viewall', $context)) {
3976 $grades = true;
3977 } else if (!empty($course->showgrades)) {
3978 $reports = core_component::get_plugin_list('gradereport');
3979 if (is_array($reports) && count($reports) > 0) { // Get all installed reports.
3980 arsort($reports); // User is last, we want to test it first.
3981 foreach ($reports as $plugin => $plugindir) {
3982 if (has_capability('gradereport/'.$plugin.':view', $context)) {
3983 // Stop when the first visible plugin is found.
3984 $grades = true;
3985 break;
3990 $options->grades = $grades;
3993 if (\core_competency\api::is_enabled()) {
3994 $capabilities = array('moodle/competency:coursecompetencyview', 'moodle/competency:coursecompetencymanage');
3995 $options->competencies = has_any_capability($capabilities, $context);
3997 return $options;
4001 * Return an object with the list of administration options in a course that are available or not for the current user.
4002 * This function also handles the frontpage settings.
4004 * @param stdClass $course course object (for frontpage it should be a clone of $SITE)
4005 * @param stdClass $context context object (course context)
4006 * @return stdClass the administration options in a course and their availability status
4007 * @since Moodle 3.2
4009 function course_get_user_administration_options($course, $context) {
4010 global $CFG;
4011 $isfrontpage = $course->id == SITEID;
4012 $completionenabled = $CFG->enablecompletion && $course->enablecompletion;
4013 $hascompletiontabs = count(core_completion\manager::get_available_completion_tabs($course, $context)) > 0;
4014 $options = new stdClass;
4015 $options->update = has_capability('moodle/course:update', $context);
4016 $options->editcompletion = $CFG->enablecompletion &&
4017 $course->enablecompletion &&
4018 ($options->update || $hascompletiontabs);
4019 $options->filters = has_capability('moodle/filter:manage', $context) &&
4020 count(filter_get_available_in_context($context)) > 0;
4021 $options->reports = has_capability('moodle/site:viewreports', $context);
4022 $options->backup = has_capability('moodle/backup:backupcourse', $context);
4023 $options->restore = has_capability('moodle/restore:restorecourse', $context);
4024 $options->copy = \core_course\management\helper::can_copy_course($course->id);
4025 $options->files = ($course->legacyfiles == 2 && has_capability('moodle/course:managefiles', $context));
4027 if (!$isfrontpage) {
4028 $options->tags = has_capability('moodle/course:tag', $context);
4029 $options->gradebook = has_capability('moodle/grade:manage', $context);
4030 $options->outcomes = !empty($CFG->enableoutcomes) && has_capability('moodle/course:update', $context);
4031 $options->badges = !empty($CFG->enablebadges);
4032 $options->import = has_capability('moodle/restore:restoretargetimport', $context);
4033 $options->reset = has_capability('moodle/course:reset', $context);
4034 $options->roles = has_capability('moodle/role:switchroles', $context);
4035 } else {
4036 // Set default options to false.
4037 $listofoptions = array('tags', 'gradebook', 'outcomes', 'badges', 'import', 'publish', 'reset', 'roles', 'grades');
4039 foreach ($listofoptions as $option) {
4040 $options->$option = false;
4044 return $options;
4048 * Validates course start and end dates.
4050 * Checks that the end course date is not greater than the start course date.
4052 * $coursedata['startdate'] or $coursedata['enddate'] may not be set, it depends on the form and user input.
4054 * @param array $coursedata May contain startdate and enddate timestamps, depends on the user input.
4055 * @return mixed False if everything alright, error codes otherwise.
4057 function course_validate_dates($coursedata) {
4059 // If both start and end dates are set end date should be later than the start date.
4060 if (!empty($coursedata['startdate']) && !empty($coursedata['enddate']) &&
4061 ($coursedata['enddate'] < $coursedata['startdate'])) {
4062 return 'enddatebeforestartdate';
4065 // If start date is not set end date can not be set.
4066 if (empty($coursedata['startdate']) && !empty($coursedata['enddate'])) {
4067 return 'nostartdatenoenddate';
4070 return false;
4074 * Check for course updates in the given context level instances (only modules supported right Now)
4076 * @param stdClass $course course object
4077 * @param array $tocheck instances to check for updates
4078 * @param array $filter check only for updates in these areas
4079 * @return array list of warnings and instances with updates information
4080 * @since Moodle 3.2
4082 function course_check_updates($course, $tocheck, $filter = array()) {
4083 global $CFG, $DB;
4085 $instances = array();
4086 $warnings = array();
4087 $modulescallbacksupport = array();
4088 $modinfo = get_fast_modinfo($course);
4090 $supportedplugins = get_plugin_list_with_function('mod', 'check_updates_since');
4092 // Check instances.
4093 foreach ($tocheck as $instance) {
4094 if ($instance['contextlevel'] == 'module') {
4095 // Check module visibility.
4096 try {
4097 $cm = $modinfo->get_cm($instance['id']);
4098 } catch (Exception $e) {
4099 $warnings[] = array(
4100 'item' => 'module',
4101 'itemid' => $instance['id'],
4102 'warningcode' => 'cmidnotincourse',
4103 'message' => 'This module id does not belong to this course.'
4105 continue;
4108 if (!$cm->uservisible) {
4109 $warnings[] = array(
4110 'item' => 'module',
4111 'itemid' => $instance['id'],
4112 'warningcode' => 'nonuservisible',
4113 'message' => 'You don\'t have access to this module.'
4115 continue;
4117 if (empty($supportedplugins['mod_' . $cm->modname])) {
4118 $warnings[] = array(
4119 'item' => 'module',
4120 'itemid' => $instance['id'],
4121 'warningcode' => 'missingcallback',
4122 'message' => 'This module does not implement the check_updates_since callback: ' . $instance['contextlevel'],
4124 continue;
4126 // Retrieve the module instance.
4127 $instances[] = array(
4128 'contextlevel' => $instance['contextlevel'],
4129 'id' => $instance['id'],
4130 'updates' => call_user_func($cm->modname . '_check_updates_since', $cm, $instance['since'], $filter)
4133 } else {
4134 $warnings[] = array(
4135 'item' => 'contextlevel',
4136 'itemid' => $instance['id'],
4137 'warningcode' => 'contextlevelnotsupported',
4138 'message' => 'Context level not yet supported ' . $instance['contextlevel'],
4142 return array($instances, $warnings);
4146 * This function classifies a course as past, in progress or future.
4148 * This function may incur a DB hit to calculate course completion.
4149 * @param stdClass $course Course record
4150 * @param stdClass $user User record (optional - defaults to $USER).
4151 * @param completion_info $completioninfo Completion record for the user (optional - will be fetched if required).
4152 * @return string (one of COURSE_TIMELINE_FUTURE, COURSE_TIMELINE_INPROGRESS or COURSE_TIMELINE_PAST)
4154 function course_classify_for_timeline($course, $user = null, $completioninfo = null) {
4155 global $USER;
4157 if ($user == null) {
4158 $user = $USER;
4161 $today = time();
4162 // End date past.
4163 if (!empty($course->enddate) && (course_classify_end_date($course) < $today)) {
4164 return COURSE_TIMELINE_PAST;
4167 if ($completioninfo == null) {
4168 $completioninfo = new completion_info($course);
4171 // Course was completed.
4172 if ($completioninfo->is_enabled() && $completioninfo->is_course_complete($user->id)) {
4173 return COURSE_TIMELINE_PAST;
4176 // Start date not reached.
4177 if (!empty($course->startdate) && (course_classify_start_date($course) > $today)) {
4178 return COURSE_TIMELINE_FUTURE;
4181 // Everything else is in progress.
4182 return COURSE_TIMELINE_INPROGRESS;
4186 * This function calculates the end date to use for display classification purposes,
4187 * incorporating the grace period, if any.
4189 * @param stdClass $course The course record.
4190 * @return int The new enddate.
4192 function course_classify_end_date($course) {
4193 global $CFG;
4194 $coursegraceperiodafter = (empty($CFG->coursegraceperiodafter)) ? 0 : $CFG->coursegraceperiodafter;
4195 $enddate = (new \DateTimeImmutable())->setTimestamp($course->enddate)->modify("+{$coursegraceperiodafter} days");
4196 return $enddate->getTimestamp();
4200 * This function calculates the start date to use for display classification purposes,
4201 * incorporating the grace period, if any.
4203 * @param stdClass $course The course record.
4204 * @return int The new startdate.
4206 function course_classify_start_date($course) {
4207 global $CFG;
4208 $coursegraceperiodbefore = (empty($CFG->coursegraceperiodbefore)) ? 0 : $CFG->coursegraceperiodbefore;
4209 $startdate = (new \DateTimeImmutable())->setTimestamp($course->startdate)->modify("-{$coursegraceperiodbefore} days");
4210 return $startdate->getTimestamp();
4214 * Group a list of courses into either past, future, or in progress.
4216 * The return value will be an array indexed by the COURSE_TIMELINE_* constants
4217 * with each value being an array of courses in that group.
4218 * E.g.
4220 * COURSE_TIMELINE_PAST => [... list of past courses ...],
4221 * COURSE_TIMELINE_FUTURE => [],
4222 * COURSE_TIMELINE_INPROGRESS => []
4225 * @param array $courses List of courses to be grouped.
4226 * @return array
4228 function course_classify_courses_for_timeline(array $courses) {
4229 return array_reduce($courses, function($carry, $course) {
4230 $classification = course_classify_for_timeline($course);
4231 array_push($carry[$classification], $course);
4233 return $carry;
4234 }, [
4235 COURSE_TIMELINE_PAST => [],
4236 COURSE_TIMELINE_FUTURE => [],
4237 COURSE_TIMELINE_INPROGRESS => []
4242 * Get the list of enrolled courses for the current user.
4244 * This function returns a Generator. The courses will be loaded from the database
4245 * in chunks rather than a single query.
4247 * @param int $limit Restrict result set to this amount
4248 * @param int $offset Skip this number of records from the start of the result set
4249 * @param string|null $sort SQL string for sorting
4250 * @param string|null $fields SQL string for fields to be returned
4251 * @param int $dbquerylimit The number of records to load per DB request
4252 * @param array $includecourses courses ids to be restricted
4253 * @param array $hiddencourses courses ids to be excluded
4254 * @return Generator
4256 function course_get_enrolled_courses_for_logged_in_user(
4257 int $limit = 0,
4258 int $offset = 0,
4259 string $sort = null,
4260 string $fields = null,
4261 int $dbquerylimit = COURSE_DB_QUERY_LIMIT,
4262 array $includecourses = [],
4263 array $hiddencourses = []
4264 ) : Generator {
4266 $haslimit = !empty($limit);
4267 $recordsloaded = 0;
4268 $querylimit = (!$haslimit || $limit > $dbquerylimit) ? $dbquerylimit : $limit;
4270 while ($courses = enrol_get_my_courses($fields, $sort, $querylimit, $includecourses, false, $offset, $hiddencourses)) {
4271 yield from $courses;
4273 $recordsloaded += $querylimit;
4275 if (count($courses) < $querylimit) {
4276 break;
4278 if ($haslimit && $recordsloaded >= $limit) {
4279 break;
4282 $offset += $querylimit;
4287 * Search the given $courses for any that match the given $classification up to the specified
4288 * $limit.
4290 * This function will return the subset of courses that match the classification as well as the
4291 * number of courses it had to process to build that subset.
4293 * It is recommended that for larger sets of courses this function is given a Generator that loads
4294 * the courses from the database in chunks.
4296 * @param array|Traversable $courses List of courses to process
4297 * @param string $classification One of the COURSE_TIMELINE_* constants
4298 * @param int $limit Limit the number of results to this amount
4299 * @return array First value is the filtered courses, second value is the number of courses processed
4301 function course_filter_courses_by_timeline_classification(
4302 $courses,
4303 string $classification,
4304 int $limit = 0
4305 ) : array {
4307 if (!in_array($classification,
4308 [COURSE_TIMELINE_ALLINCLUDINGHIDDEN, COURSE_TIMELINE_ALL, COURSE_TIMELINE_PAST, COURSE_TIMELINE_INPROGRESS,
4309 COURSE_TIMELINE_FUTURE, COURSE_TIMELINE_HIDDEN])) {
4310 $message = 'Classification must be one of COURSE_TIMELINE_ALLINCLUDINGHIDDEN, COURSE_TIMELINE_ALL, COURSE_TIMELINE_PAST, '
4311 . 'COURSE_TIMELINE_INPROGRESS or COURSE_TIMELINE_FUTURE';
4312 throw new moodle_exception($message);
4315 $filteredcourses = [];
4316 $numberofcoursesprocessed = 0;
4317 $filtermatches = 0;
4319 foreach ($courses as $course) {
4320 $numberofcoursesprocessed++;
4321 $pref = get_user_preferences('block_myoverview_hidden_course_' . $course->id, 0);
4323 // Added as of MDL-63457 toggle viewability for each user.
4324 if ($classification == COURSE_TIMELINE_ALLINCLUDINGHIDDEN || ($classification == COURSE_TIMELINE_HIDDEN && $pref) ||
4325 (($classification == COURSE_TIMELINE_ALL || $classification == course_classify_for_timeline($course)) && !$pref)) {
4326 $filteredcourses[] = $course;
4327 $filtermatches++;
4330 if ($limit && $filtermatches >= $limit) {
4331 // We've found the number of requested courses. No need to continue searching.
4332 break;
4336 // Return the number of filtered courses as well as the number of courses that were searched
4337 // in order to find the matching courses. This allows the calling code to do some kind of
4338 // pagination.
4339 return [$filteredcourses, $numberofcoursesprocessed];
4343 * Search the given $courses for any that match the given $classification up to the specified
4344 * $limit.
4346 * This function will return the subset of courses that are favourites as well as the
4347 * number of courses it had to process to build that subset.
4349 * It is recommended that for larger sets of courses this function is given a Generator that loads
4350 * the courses from the database in chunks.
4352 * @param array|Traversable $courses List of courses to process
4353 * @param array $favouritecourseids Array of favourite courses.
4354 * @param int $limit Limit the number of results to this amount
4355 * @return array First value is the filtered courses, second value is the number of courses processed
4357 function course_filter_courses_by_favourites(
4358 $courses,
4359 $favouritecourseids,
4360 int $limit = 0
4361 ) : array {
4363 $filteredcourses = [];
4364 $numberofcoursesprocessed = 0;
4365 $filtermatches = 0;
4367 foreach ($courses as $course) {
4368 $numberofcoursesprocessed++;
4370 if (in_array($course->id, $favouritecourseids)) {
4371 $filteredcourses[] = $course;
4372 $filtermatches++;
4375 if ($limit && $filtermatches >= $limit) {
4376 // We've found the number of requested courses. No need to continue searching.
4377 break;
4381 // Return the number of filtered courses as well as the number of courses that were searched
4382 // in order to find the matching courses. This allows the calling code to do some kind of
4383 // pagination.
4384 return [$filteredcourses, $numberofcoursesprocessed];
4388 * Search the given $courses for any that have a $customfieldname value that matches the given
4389 * $customfieldvalue, up to the specified $limit.
4391 * This function will return the subset of courses that matches the value as well as the
4392 * number of courses it had to process to build that subset.
4394 * It is recommended that for larger sets of courses this function is given a Generator that loads
4395 * the courses from the database in chunks.
4397 * @param array|Traversable $courses List of courses to process
4398 * @param string $customfieldname the shortname of the custom field to match against
4399 * @param string $customfieldvalue the value this custom field needs to match
4400 * @param int $limit Limit the number of results to this amount
4401 * @return array First value is the filtered courses, second value is the number of courses processed
4403 function course_filter_courses_by_customfield(
4404 $courses,
4405 $customfieldname,
4406 $customfieldvalue,
4407 int $limit = 0
4408 ) : array {
4409 global $DB;
4411 if (!$courses) {
4412 return [[], 0];
4415 // Prepare the list of courses to search through.
4416 $coursesbyid = [];
4417 foreach ($courses as $course) {
4418 $coursesbyid[$course->id] = $course;
4420 if (!$coursesbyid) {
4421 return [[], 0];
4423 list($csql, $params) = $DB->get_in_or_equal(array_keys($coursesbyid), SQL_PARAMS_NAMED);
4425 // Get the id of the custom field.
4426 $sql = "
4427 SELECT f.id
4428 FROM {customfield_field} f
4429 JOIN {customfield_category} cat ON cat.id = f.categoryid
4430 WHERE f.shortname = ?
4431 AND cat.component = 'core_course'
4432 AND cat.area = 'course'
4434 $fieldid = $DB->get_field_sql($sql, [$customfieldname]);
4435 if (!$fieldid) {
4436 return [[], 0];
4439 // Get a list of courseids that match that custom field value.
4440 if ($customfieldvalue == COURSE_CUSTOMFIELD_EMPTY) {
4441 $comparevalue = $DB->sql_compare_text('cd.value');
4442 $sql = "
4443 SELECT c.id
4444 FROM {course} c
4445 LEFT JOIN {customfield_data} cd ON cd.instanceid = c.id AND cd.fieldid = :fieldid
4446 WHERE c.id $csql
4447 AND (cd.value IS NULL OR $comparevalue = '' OR $comparevalue = '0')
4449 $params['fieldid'] = $fieldid;
4450 $matchcourseids = $DB->get_fieldset_sql($sql, $params);
4451 } else {
4452 $comparevalue = $DB->sql_compare_text('value');
4453 $select = "fieldid = :fieldid AND $comparevalue = :customfieldvalue AND instanceid $csql";
4454 $params['fieldid'] = $fieldid;
4455 $params['customfieldvalue'] = $customfieldvalue;
4456 $matchcourseids = $DB->get_fieldset_select('customfield_data', 'instanceid', $select, $params);
4459 // Prepare the list of courses to return.
4460 $filteredcourses = [];
4461 $numberofcoursesprocessed = 0;
4462 $filtermatches = 0;
4464 foreach ($coursesbyid as $course) {
4465 $numberofcoursesprocessed++;
4467 if (in_array($course->id, $matchcourseids)) {
4468 $filteredcourses[] = $course;
4469 $filtermatches++;
4472 if ($limit && $filtermatches >= $limit) {
4473 // We've found the number of requested courses. No need to continue searching.
4474 break;
4478 // Return the number of filtered courses as well as the number of courses that were searched
4479 // in order to find the matching courses. This allows the calling code to do some kind of
4480 // pagination.
4481 return [$filteredcourses, $numberofcoursesprocessed];
4485 * Check module updates since a given time.
4486 * This function checks for updates in the module config, file areas, completion, grades, comments and ratings.
4488 * @param cm_info $cm course module data
4489 * @param int $from the time to check
4490 * @param array $fileareas additional file ares to check
4491 * @param array $filter if we need to filter and return only selected updates
4492 * @return stdClass object with the different updates
4493 * @since Moodle 3.2
4495 function course_check_module_updates_since($cm, $from, $fileareas = array(), $filter = array()) {
4496 global $DB, $CFG, $USER;
4498 $context = $cm->context;
4499 $mod = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
4501 $updates = new stdClass();
4502 $course = get_course($cm->course);
4503 $component = 'mod_' . $cm->modname;
4505 // Check changes in the module configuration.
4506 if (isset($mod->timemodified) and (empty($filter) or in_array('configuration', $filter))) {
4507 $updates->configuration = (object) array('updated' => false);
4508 if ($updates->configuration->updated = $mod->timemodified > $from) {
4509 $updates->configuration->timeupdated = $mod->timemodified;
4513 // Check for updates in files.
4514 if (plugin_supports('mod', $cm->modname, FEATURE_MOD_INTRO)) {
4515 $fileareas[] = 'intro';
4517 if (!empty($fileareas) and (empty($filter) or in_array('fileareas', $filter))) {
4518 $fs = get_file_storage();
4519 $files = $fs->get_area_files($context->id, $component, $fileareas, false, "filearea, timemodified DESC", false, $from);
4520 foreach ($fileareas as $filearea) {
4521 $updates->{$filearea . 'files'} = (object) array('updated' => false);
4523 foreach ($files as $file) {
4524 $updates->{$file->get_filearea() . 'files'}->updated = true;
4525 $updates->{$file->get_filearea() . 'files'}->itemids[] = $file->get_id();
4529 // Check completion.
4530 $supportcompletion = plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_HAS_RULES);
4531 $supportcompletion = $supportcompletion or plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_TRACKS_VIEWS);
4532 if ($supportcompletion and (empty($filter) or in_array('completion', $filter))) {
4533 $updates->completion = (object) array('updated' => false);
4534 $completion = new completion_info($course);
4535 // Use wholecourse to cache all the modules the first time.
4536 $completiondata = $completion->get_data($cm, true);
4537 if ($updates->completion->updated = !empty($completiondata->timemodified) && $completiondata->timemodified > $from) {
4538 $updates->completion->timemodified = $completiondata->timemodified;
4542 // Check grades.
4543 $supportgrades = plugin_supports('mod', $cm->modname, FEATURE_GRADE_HAS_GRADE);
4544 $supportgrades = $supportgrades or plugin_supports('mod', $cm->modname, FEATURE_GRADE_OUTCOMES);
4545 if ($supportgrades and (empty($filter) or (in_array('gradeitems', $filter) or in_array('outcomes', $filter)))) {
4546 require_once($CFG->libdir . '/gradelib.php');
4547 $grades = grade_get_grades($course->id, 'mod', $cm->modname, $mod->id, $USER->id);
4549 if (empty($filter) or in_array('gradeitems', $filter)) {
4550 $updates->gradeitems = (object) array('updated' => false);
4551 foreach ($grades->items as $gradeitem) {
4552 foreach ($gradeitem->grades as $grade) {
4553 if ($grade->datesubmitted > $from or $grade->dategraded > $from) {
4554 $updates->gradeitems->updated = true;
4555 $updates->gradeitems->itemids[] = $gradeitem->id;
4561 if (empty($filter) or in_array('outcomes', $filter)) {
4562 $updates->outcomes = (object) array('updated' => false);
4563 foreach ($grades->outcomes as $outcome) {
4564 foreach ($outcome->grades as $grade) {
4565 if ($grade->datesubmitted > $from or $grade->dategraded > $from) {
4566 $updates->outcomes->updated = true;
4567 $updates->outcomes->itemids[] = $outcome->id;
4574 // Check comments.
4575 if (plugin_supports('mod', $cm->modname, FEATURE_COMMENT) and (empty($filter) or in_array('comments', $filter))) {
4576 $updates->comments = (object) array('updated' => false);
4577 require_once($CFG->dirroot . '/comment/lib.php');
4578 require_once($CFG->dirroot . '/comment/locallib.php');
4579 $manager = new comment_manager();
4580 $comments = $manager->get_component_comments_since($course, $context, $component, $from, $cm);
4581 if (!empty($comments)) {
4582 $updates->comments->updated = true;
4583 $updates->comments->itemids = array_keys($comments);
4587 // Check ratings.
4588 if (plugin_supports('mod', $cm->modname, FEATURE_RATE) and (empty($filter) or in_array('ratings', $filter))) {
4589 $updates->ratings = (object) array('updated' => false);
4590 require_once($CFG->dirroot . '/rating/lib.php');
4591 $manager = new rating_manager();
4592 $ratings = $manager->get_component_ratings_since($context, $component, $from);
4593 if (!empty($ratings)) {
4594 $updates->ratings->updated = true;
4595 $updates->ratings->itemids = array_keys($ratings);
4599 return $updates;
4603 * Returns true if the user can view the participant page, false otherwise,
4605 * @param context $context The context we are checking.
4606 * @return bool
4608 function course_can_view_participants($context) {
4609 $viewparticipantscap = 'moodle/course:viewparticipants';
4610 if ($context->contextlevel == CONTEXT_SYSTEM) {
4611 $viewparticipantscap = 'moodle/site:viewparticipants';
4614 return has_any_capability([$viewparticipantscap, 'moodle/course:enrolreview'], $context);
4618 * Checks if a user can view the participant page, if not throws an exception.
4620 * @param context $context The context we are checking.
4621 * @throws required_capability_exception
4623 function course_require_view_participants($context) {
4624 if (!course_can_view_participants($context)) {
4625 $viewparticipantscap = 'moodle/course:viewparticipants';
4626 if ($context->contextlevel == CONTEXT_SYSTEM) {
4627 $viewparticipantscap = 'moodle/site:viewparticipants';
4629 throw new required_capability_exception($context, $viewparticipantscap, 'nopermissions', '');
4634 * Return whether the user can download from the specified backup file area in the given context.
4636 * @param string $filearea the backup file area. E.g. 'course', 'backup' or 'automated'.
4637 * @param \context $context
4638 * @param stdClass $user the user object. If not provided, the current user will be checked.
4639 * @return bool true if the user is allowed to download in the context, false otherwise.
4641 function can_download_from_backup_filearea($filearea, \context $context, stdClass $user = null) {
4642 $candownload = false;
4643 switch ($filearea) {
4644 case 'course':
4645 case 'backup':
4646 $candownload = has_capability('moodle/backup:downloadfile', $context, $user);
4647 break;
4648 case 'automated':
4649 // Given the automated backups may contain userinfo, we restrict access such that only users who are able to
4650 // restore with userinfo are able to download the file. Users can't create these backups, so checking 'backup:userinfo'
4651 // doesn't make sense here.
4652 $candownload = has_capability('moodle/backup:downloadfile', $context, $user) &&
4653 has_capability('moodle/restore:userinfo', $context, $user);
4654 break;
4655 default:
4656 break;
4659 return $candownload;
4663 * Get a list of hidden courses
4665 * @param int|object|null $user User override to get the filter from. Defaults to current user
4666 * @return array $ids List of hidden courses
4667 * @throws coding_exception
4669 function get_hidden_courses_on_timeline($user = null) {
4670 global $USER;
4672 if (empty($user)) {
4673 $user = $USER->id;
4676 $preferences = get_user_preferences(null, null, $user);
4677 $ids = [];
4678 foreach ($preferences as $key => $value) {
4679 if (preg_match('/block_myoverview_hidden_course_(\d)+/', $key)) {
4680 $id = preg_split('/block_myoverview_hidden_course_/', $key);
4681 $ids[] = $id[1];
4685 return $ids;
4689 * Returns a list of the most recently courses accessed by a user
4691 * @param int $userid User id from which the courses will be obtained
4692 * @param int $limit Restrict result set to this amount
4693 * @param int $offset Skip this number of records from the start of the result set
4694 * @param string|null $sort SQL string for sorting
4695 * @return array
4697 function course_get_recent_courses(int $userid = null, int $limit = 0, int $offset = 0, string $sort = null) {
4699 global $CFG, $USER, $DB;
4701 if (empty($userid)) {
4702 $userid = $USER->id;
4705 $basefields = array('id', 'idnumber', 'summary', 'summaryformat', 'startdate', 'enddate', 'category',
4706 'shortname', 'fullname', 'timeaccess', 'component', 'visible');
4708 $sort = trim($sort);
4709 if (empty($sort)) {
4710 $sort = 'timeaccess DESC';
4711 } else {
4712 $rawsorts = explode(',', $sort);
4713 $sorts = array();
4714 foreach ($rawsorts as $rawsort) {
4715 $rawsort = trim($rawsort);
4716 $sorts[] = trim($rawsort);
4718 $sort = implode(',', $sorts);
4721 $orderby = "ORDER BY $sort";
4723 $ctxfields = context_helper::get_preload_record_columns_sql('ctx');
4725 $coursefields = 'c.' .join(',', $basefields);
4727 // Ask the favourites service to give us the join SQL for favourited courses,
4728 // so we can include favourite information in the query.
4729 $usercontext = \context_user::instance($userid);
4730 $favservice = \core_favourites\service_factory::get_service_for_user_context($usercontext);
4731 list($favsql, $favparams) = $favservice->get_join_sql_by_type('core_course', 'courses', 'fav', 'ul.courseid');
4733 $sql = "SELECT $coursefields, $ctxfields
4734 FROM {course} c
4735 JOIN {context} ctx
4736 ON ctx.contextlevel = :contextlevel
4737 AND ctx.instanceid = c.id
4738 JOIN {user_lastaccess} ul
4739 ON ul.courseid = c.id
4740 $favsql
4741 WHERE ul.userid = :userid
4742 AND c.visible = :visible
4743 AND EXISTS (SELECT e.id
4744 FROM {enrol} e
4745 LEFT JOIN {user_enrolments} ue ON ue.enrolid = e.id
4746 WHERE e.courseid = c.id
4747 AND e.status = :statusenrol
4748 AND ((ue.status = :status
4749 AND ue.userid = ul.userid
4750 AND ue.timestart < :now1
4751 AND (ue.timeend = 0 OR ue.timeend > :now2)
4753 OR e.enrol = :guestenrol
4756 $orderby";
4758 $now = round(time(), -2); // Improves db caching.
4759 $params = ['userid' => $userid, 'contextlevel' => CONTEXT_COURSE, 'visible' => 1, 'status' => ENROL_USER_ACTIVE,
4760 'statusenrol' => ENROL_INSTANCE_ENABLED, 'guestenrol' => 'guest', 'now1' => $now, 'now2' => $now] + $favparams;
4762 $recentcourses = $DB->get_records_sql($sql, $params, $offset, $limit);
4764 // Filter courses if last access field is hidden.
4765 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
4767 if ($userid != $USER->id && isset($hiddenfields['lastaccess'])) {
4768 $recentcourses = array_filter($recentcourses, function($course) {
4769 context_helper::preload_from_record($course);
4770 $context = context_course::instance($course->id, IGNORE_MISSING);
4771 // If last access was a hidden field, a user requesting info about another user would need permission to view hidden
4772 // fields.
4773 return has_capability('moodle/course:viewhiddenuserfields', $context);
4777 return $recentcourses;
4781 * Calculate the course start date and offset for the given user ids.
4783 * If the course is a fixed date course then the course start date will be returned.
4784 * If the course is a relative date course then the course date will be calculated and
4785 * and offset provided.
4787 * The dates are returned as an array with the index being the user id. The array
4788 * contains the start date and start offset values for the user.
4790 * If the user is not enrolled in the course then the course start date will be returned.
4792 * If we have a course which starts on 1563244000 and 2 users, id 123 and 456, where the
4793 * former is enrolled in the course at 1563244693 and the latter is not enrolled then the
4794 * return value would look like:
4796 * '123' => [
4797 * 'start' => 1563244693,
4798 * 'startoffset' => 693
4799 * ],
4800 * '456' => [
4801 * 'start' => 1563244000,
4802 * 'startoffset' => 0
4806 * @param stdClass $course The course to fetch dates for.
4807 * @param array $userids The list of user ids to get dates for.
4808 * @return array
4810 function course_get_course_dates_for_user_ids(stdClass $course, array $userids): array {
4811 if (empty($course->relativedatesmode)) {
4812 // This course isn't set to relative dates so we can early return with the course
4813 // start date.
4814 return array_reduce($userids, function($carry, $userid) use ($course) {
4815 $carry[$userid] = [
4816 'start' => $course->startdate,
4817 'startoffset' => 0
4819 return $carry;
4820 }, []);
4823 // We're dealing with a relative dates course now so we need to calculate some dates.
4824 $cache = cache::make('core', 'course_user_dates');
4825 $dates = [];
4826 $uncacheduserids = [];
4828 // Try fetching the values from the cache so that we don't need to do a DB request.
4829 foreach ($userids as $userid) {
4830 $cachekey = "{$course->id}_{$userid}";
4831 $cachedvalue = $cache->get($cachekey);
4833 if ($cachedvalue === false) {
4834 // Looks like we haven't seen this user for this course before so we'll have
4835 // to fetch it.
4836 $uncacheduserids[] = $userid;
4837 } else {
4838 [$start, $startoffset] = $cachedvalue;
4839 $dates[$userid] = [
4840 'start' => $start,
4841 'startoffset' => $startoffset
4846 if (!empty($uncacheduserids)) {
4847 // Load the enrolments for any users we haven't seen yet. Set the "onlyactive" param
4848 // to false because it filters out users with enrolment start times in the future which
4849 // we don't want.
4850 $enrolments = enrol_get_course_users($course->id, false, $uncacheduserids);
4852 foreach ($uncacheduserids as $userid) {
4853 // Find the user enrolment that has the earliest start date.
4854 $enrolment = array_reduce(array_values($enrolments), function($carry, $enrolment) use ($userid) {
4855 // Only consider enrolments for this user if the user enrolment is active and the
4856 // enrolment method is enabled.
4857 if (
4858 $enrolment->uestatus == ENROL_USER_ACTIVE &&
4859 $enrolment->estatus == ENROL_INSTANCE_ENABLED &&
4860 $enrolment->id == $userid
4862 if (is_null($carry)) {
4863 // Haven't found an enrolment yet for this user so use the one we just found.
4864 $carry = $enrolment;
4865 } else {
4866 // We've already found an enrolment for this user so let's use which ever one
4867 // has the earliest start time.
4868 $carry = $carry->uetimestart < $enrolment->uetimestart ? $carry : $enrolment;
4872 return $carry;
4873 }, null);
4875 if ($enrolment) {
4876 // The course is in relative dates mode so we calculate the student's start
4877 // date based on their enrolment start date.
4878 $start = $course->startdate > $enrolment->uetimestart ? $course->startdate : $enrolment->uetimestart;
4879 $startoffset = $start - $course->startdate;
4880 } else {
4881 // The user is not enrolled in the course so default back to the course start date.
4882 $start = $course->startdate;
4883 $startoffset = 0;
4886 $dates[$userid] = [
4887 'start' => $start,
4888 'startoffset' => $startoffset
4891 $cachekey = "{$course->id}_{$userid}";
4892 $cache->set($cachekey, [$start, $startoffset]);
4896 return $dates;
4900 * Calculate the course start date and offset for the given user id.
4902 * If the course is a fixed date course then the course start date will be returned.
4903 * If the course is a relative date course then the course date will be calculated and
4904 * and offset provided.
4906 * The return array contains the start date and start offset values for the user.
4908 * If the user is not enrolled in the course then the course start date will be returned.
4910 * If we have a course which starts on 1563244000. If a user's enrolment starts on 1563244693
4911 * then the return would be:
4913 * 'start' => 1563244693,
4914 * 'startoffset' => 693
4917 * If the use was not enrolled then the return would be:
4919 * 'start' => 1563244000,
4920 * 'startoffset' => 0
4923 * @param stdClass $course The course to fetch dates for.
4924 * @param int $userid The user id to get dates for.
4925 * @return array
4927 function course_get_course_dates_for_user_id(stdClass $course, int $userid): array {
4928 return (course_get_course_dates_for_user_ids($course, [$userid]))[$userid];
4932 * Renders the course copy form for the modal on the course management screen.
4934 * @param array $args
4935 * @return string $o Form HTML.
4937 function course_output_fragment_new_base_form($args) {
4939 $serialiseddata = json_decode($args['jsonformdata'], true);
4940 $formdata = [];
4941 if (!empty($serialiseddata)) {
4942 parse_str($serialiseddata, $formdata);
4945 $context = context_course::instance($args['courseid']);
4946 $copycaps = \core_course\management\helper::get_course_copy_capabilities();
4947 require_all_capabilities($copycaps, $context);
4949 $course = get_course($args['courseid']);
4950 $mform = new \core_backup\output\copy_form(
4951 null,
4952 array('course' => $course, 'returnto' => '', 'returnurl' => ''),
4953 'post', '', ['class' => 'ignoredirty'], true, $formdata);
4955 if (!empty($serialiseddata)) {
4956 // If we were passed non-empty form data we want the mform to call validation functions and show errors.
4957 $mform->is_validated();
4960 ob_start();
4961 $mform->display();
4962 $o = ob_get_contents();
4963 ob_end_clean();
4965 return $o;