Merge branch 'MDL-63303_master-deleteduserfix' of https://github.com/markn86/moodle
[moodle.git] / course / lib.php
bloba409cf1965eceb1ebb4b1db1f112bd7e3d42023f
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_ALL', 'all');
60 define('COURSE_TIMELINE_PAST', 'past');
61 define('COURSE_TIMELINE_INPROGRESS', 'inprogress');
62 define('COURSE_TIMELINE_FUTURE', 'future');
63 define('COURSE_FAVOURITES', 'favourites');
64 define('COURSE_TIMELINE_HIDDEN', 'hidden');
65 define('COURSE_DB_QUERY_LIMIT', 1000);
67 function make_log_url($module, $url) {
68 switch ($module) {
69 case 'course':
70 if (strpos($url, 'report/') === 0) {
71 // there is only one report type, course reports are deprecated
72 $url = "/$url";
73 break;
75 case 'file':
76 case 'login':
77 case 'lib':
78 case 'admin':
79 case 'category':
80 case 'mnet course':
81 if (strpos($url, '../') === 0) {
82 $url = ltrim($url, '.');
83 } else {
84 $url = "/course/$url";
86 break;
87 case 'calendar':
88 $url = "/calendar/$url";
89 break;
90 case 'user':
91 case 'blog':
92 $url = "/$module/$url";
93 break;
94 case 'upload':
95 $url = $url;
96 break;
97 case 'coursetags':
98 $url = '/'.$url;
99 break;
100 case 'library':
101 case '':
102 $url = '/';
103 break;
104 case 'message':
105 $url = "/message/$url";
106 break;
107 case 'notes':
108 $url = "/notes/$url";
109 break;
110 case 'tag':
111 $url = "/tag/$url";
112 break;
113 case 'role':
114 $url = '/'.$url;
115 break;
116 case 'grade':
117 $url = "/grade/$url";
118 break;
119 default:
120 $url = "/mod/$module/$url";
121 break;
124 //now let's sanitise urls - there might be some ugly nasties:-(
125 $parts = explode('?', $url);
126 $script = array_shift($parts);
127 if (strpos($script, 'http') === 0) {
128 $script = clean_param($script, PARAM_URL);
129 } else {
130 $script = clean_param($script, PARAM_PATH);
133 $query = '';
134 if ($parts) {
135 $query = implode('', $parts);
136 $query = str_replace('&amp;', '&', $query); // both & and &amp; are stored in db :-|
137 $parts = explode('&', $query);
138 $eq = urlencode('=');
139 foreach ($parts as $key=>$part) {
140 $part = urlencode(urldecode($part));
141 $part = str_replace($eq, '=', $part);
142 $parts[$key] = $part;
144 $query = '?'.implode('&amp;', $parts);
147 return $script.$query;
151 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
152 $modname="", $modid=0, $modaction="", $groupid=0) {
153 global $CFG, $DB;
155 // It is assumed that $date is the GMT time of midnight for that day,
156 // and so the next 86400 seconds worth of logs are printed.
158 /// Setup for group handling.
160 // TODO: I don't understand group/context/etc. enough to be able to do
161 // something interesting with it here
162 // What is the context of a remote course?
164 /// If the group mode is separate, and this user does not have editing privileges,
165 /// then only the user's group can be viewed.
166 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
167 // $groupid = get_current_group($course->id);
169 /// If this course doesn't have groups, no groupid can be specified.
170 //else if (!$course->groupmode) {
171 // $groupid = 0;
174 $groupid = 0;
176 $joins = array();
177 $where = '';
179 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
180 FROM {mnet_log} l
181 LEFT JOIN {user} u ON l.userid = u.id
182 WHERE ";
183 $params = array();
185 $where .= "l.hostid = :hostid";
186 $params['hostid'] = $hostid;
188 // TODO: Is 1 really a magic number referring to the sitename?
189 if ($course != SITEID || $modid != 0) {
190 $where .= " AND l.course=:courseid";
191 $params['courseid'] = $course;
194 if ($modname) {
195 $where .= " AND l.module = :modname";
196 $params['modname'] = $modname;
199 if ('site_errors' === $modid) {
200 $where .= " AND ( l.action='error' OR l.action='infected' )";
201 } else if ($modid) {
202 //TODO: This assumes that modids are the same across sites... probably
203 //not true
204 $where .= " AND l.cmid = :modid";
205 $params['modid'] = $modid;
208 if ($modaction) {
209 $firstletter = substr($modaction, 0, 1);
210 if ($firstletter == '-') {
211 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
212 $params['modaction'] = '%'.substr($modaction, 1).'%';
213 } else {
214 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
215 $params['modaction'] = '%'.$modaction.'%';
219 if ($user) {
220 $where .= " AND l.userid = :user";
221 $params['user'] = $user;
224 if ($date) {
225 $enddate = $date + 86400;
226 $where .= " AND l.time > :date AND l.time < :enddate";
227 $params['date'] = $date;
228 $params['enddate'] = $enddate;
231 $result = array();
232 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
233 if(!empty($result['totalcount'])) {
234 $where .= " ORDER BY $order";
235 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
236 } else {
237 $result['logs'] = array();
239 return $result;
243 * Checks the integrity of the course data.
245 * In summary - compares course_sections.sequence and course_modules.section.
247 * More detailed, checks that:
248 * - course_sections.sequence contains each module id not more than once in the course
249 * - for each moduleid from course_sections.sequence the field course_modules.section
250 * refers to the same section id (this means course_sections.sequence is more
251 * important if they are different)
252 * - ($fullcheck only) each module in the course is present in one of
253 * course_sections.sequence
254 * - ($fullcheck only) removes non-existing course modules from section sequences
256 * If there are any mismatches, the changes are made and records are updated in DB.
258 * Course cache is NOT rebuilt if there are any errors!
260 * This function is used each time when course cache is being rebuilt with $fullcheck = false
261 * and in CLI script admin/cli/fix_course_sequence.php with $fullcheck = true
263 * @param int $courseid id of the course
264 * @param array $rawmods result of funciton {@link get_course_mods()} - containst
265 * the list of enabled course modules in the course. Retrieved from DB if not specified.
266 * Argument ignored in cashe of $fullcheck, the list is retrieved form DB anyway.
267 * @param array $sections records from course_sections table for this course.
268 * Retrieved from DB if not specified
269 * @param bool $fullcheck Will add orphaned modules to their sections and remove non-existing
270 * course modules from sequences. Only to be used in site maintenance mode when we are
271 * sure that another user is not in the middle of the process of moving/removing a module.
272 * @param bool $checkonly Only performs the check without updating DB, outputs all errors as debug messages.
273 * @return array array of messages with found problems. Empty output means everything is ok
275 function course_integrity_check($courseid, $rawmods = null, $sections = null, $fullcheck = false, $checkonly = false) {
276 global $DB;
277 $messages = array();
278 if ($sections === null) {
279 $sections = $DB->get_records('course_sections', array('course' => $courseid), 'section', 'id,section,sequence');
281 if ($fullcheck) {
282 // Retrieve all records from course_modules regardless of module type visibility.
283 $rawmods = $DB->get_records('course_modules', array('course' => $courseid), 'id', 'id,section');
285 if ($rawmods === null) {
286 $rawmods = get_course_mods($courseid);
288 if (!$fullcheck && (empty($sections) || empty($rawmods))) {
289 // If either of the arrays is empty, no modules are displayed anyway.
290 return true;
292 $debuggingprefix = 'Failed integrity check for course ['.$courseid.']. ';
294 // First make sure that each module id appears in section sequences only once.
295 // If it appears in several section sequences the last section wins.
296 // If it appears twice in one section sequence, the first occurence wins.
297 $modsection = array();
298 foreach ($sections as $sectionid => $section) {
299 $sections[$sectionid]->newsequence = $section->sequence;
300 if (!empty($section->sequence)) {
301 $sequence = explode(",", $section->sequence);
302 $sequenceunique = array_unique($sequence);
303 if (count($sequenceunique) != count($sequence)) {
304 // Some course module id appears in this section sequence more than once.
305 ksort($sequenceunique); // Preserve initial order of modules.
306 $sequence = array_values($sequenceunique);
307 $sections[$sectionid]->newsequence = join(',', $sequence);
308 $messages[] = $debuggingprefix.'Sequence for course section ['.
309 $sectionid.'] is "'.$sections[$sectionid]->sequence.'", must be "'.$sections[$sectionid]->newsequence.'"';
311 foreach ($sequence as $cmid) {
312 if (array_key_exists($cmid, $modsection) && isset($rawmods[$cmid])) {
313 // Some course module id appears to be in more than one section's sequences.
314 $wrongsectionid = $modsection[$cmid];
315 $sections[$wrongsectionid]->newsequence = trim(preg_replace("/,$cmid,/", ',', ','.$sections[$wrongsectionid]->newsequence. ','), ',');
316 $messages[] = $debuggingprefix.'Course module ['.$cmid.'] must be removed from sequence of section ['.
317 $wrongsectionid.'] because it is also present in sequence of section ['.$sectionid.']';
319 $modsection[$cmid] = $sectionid;
324 // Add orphaned modules to their sections if they exist or to section 0 otherwise.
325 if ($fullcheck) {
326 foreach ($rawmods as $cmid => $mod) {
327 if (!isset($modsection[$cmid])) {
328 // This is a module that is not mentioned in course_section.sequence at all.
329 // Add it to the section $mod->section or to the last available section.
330 if ($mod->section && isset($sections[$mod->section])) {
331 $modsection[$cmid] = $mod->section;
332 } else {
333 $firstsection = reset($sections);
334 $modsection[$cmid] = $firstsection->id;
336 $sections[$modsection[$cmid]]->newsequence = trim($sections[$modsection[$cmid]]->newsequence.','.$cmid, ',');
337 $messages[] = $debuggingprefix.'Course module ['.$cmid.'] is missing from sequence of section ['.
338 $modsection[$cmid].']';
341 foreach ($modsection as $cmid => $sectionid) {
342 if (!isset($rawmods[$cmid])) {
343 // Section $sectionid refers to module id that does not exist.
344 $sections[$sectionid]->newsequence = trim(preg_replace("/,$cmid,/", ',', ','.$sections[$sectionid]->newsequence.','), ',');
345 $messages[] = $debuggingprefix.'Course module ['.$cmid.
346 '] does not exist but is present in the sequence of section ['.$sectionid.']';
351 // Update changed sections.
352 if (!$checkonly && !empty($messages)) {
353 foreach ($sections as $sectionid => $section) {
354 if ($section->newsequence !== $section->sequence) {
355 $DB->update_record('course_sections', array('id' => $sectionid, 'sequence' => $section->newsequence));
360 // Now make sure that all modules point to the correct sections.
361 foreach ($rawmods as $cmid => $mod) {
362 if (isset($modsection[$cmid]) && $modsection[$cmid] != $mod->section) {
363 if (!$checkonly) {
364 $DB->update_record('course_modules', array('id' => $cmid, 'section' => $modsection[$cmid]));
366 $messages[] = $debuggingprefix.'Course module ['.$cmid.
367 '] points to section ['.$mod->section.'] instead of ['.$modsection[$cmid].']';
371 return $messages;
375 * For a given course, returns an array of course activity objects
376 * Each item in the array contains he following properties:
378 function get_array_of_activities($courseid) {
379 // cm - course module id
380 // mod - name of the module (eg forum)
381 // section - the number of the section (eg week or topic)
382 // name - the name of the instance
383 // visible - is the instance visible or not
384 // groupingid - grouping id
385 // extra - contains extra string to include in any link
386 global $CFG, $DB;
388 $course = $DB->get_record('course', array('id'=>$courseid));
390 if (empty($course)) {
391 throw new moodle_exception('courseidnotfound');
394 $mod = array();
396 $rawmods = get_course_mods($courseid);
397 if (empty($rawmods)) {
398 return $mod; // always return array
400 $courseformat = course_get_format($course);
402 if ($sections = $DB->get_records('course_sections', array('course' => $courseid),
403 'section ASC', 'id,section,sequence,visible')) {
404 // First check and correct obvious mismatches between course_sections.sequence and course_modules.section.
405 if ($errormessages = course_integrity_check($courseid, $rawmods, $sections)) {
406 debugging(join('<br>', $errormessages));
407 $rawmods = get_course_mods($courseid);
408 $sections = $DB->get_records('course_sections', array('course' => $courseid),
409 'section ASC', 'id,section,sequence,visible');
411 // Build array of activities.
412 foreach ($sections as $section) {
413 if (!empty($section->sequence)) {
414 $sequence = explode(",", $section->sequence);
415 foreach ($sequence as $seq) {
416 if (empty($rawmods[$seq])) {
417 continue;
419 // Adjust visibleoncoursepage, value in DB may not respect format availability.
420 $rawmods[$seq]->visibleoncoursepage = (!$rawmods[$seq]->visible
421 || $rawmods[$seq]->visibleoncoursepage
422 || empty($CFG->allowstealth)
423 || !$courseformat->allow_stealth_module_visibility($rawmods[$seq], $section)) ? 1 : 0;
425 // Create an object that will be cached.
426 $mod[$seq] = new stdClass();
427 $mod[$seq]->id = $rawmods[$seq]->instance;
428 $mod[$seq]->cm = $rawmods[$seq]->id;
429 $mod[$seq]->mod = $rawmods[$seq]->modname;
431 // Oh dear. Inconsistent names left here for backward compatibility.
432 $mod[$seq]->section = $section->section;
433 $mod[$seq]->sectionid = $rawmods[$seq]->section;
435 $mod[$seq]->module = $rawmods[$seq]->module;
436 $mod[$seq]->added = $rawmods[$seq]->added;
437 $mod[$seq]->score = $rawmods[$seq]->score;
438 $mod[$seq]->idnumber = $rawmods[$seq]->idnumber;
439 $mod[$seq]->visible = $rawmods[$seq]->visible;
440 $mod[$seq]->visibleoncoursepage = $rawmods[$seq]->visibleoncoursepage;
441 $mod[$seq]->visibleold = $rawmods[$seq]->visibleold;
442 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
443 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
444 $mod[$seq]->indent = $rawmods[$seq]->indent;
445 $mod[$seq]->completion = $rawmods[$seq]->completion;
446 $mod[$seq]->extra = "";
447 $mod[$seq]->completiongradeitemnumber =
448 $rawmods[$seq]->completiongradeitemnumber;
449 $mod[$seq]->completionview = $rawmods[$seq]->completionview;
450 $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected;
451 $mod[$seq]->showdescription = $rawmods[$seq]->showdescription;
452 $mod[$seq]->availability = $rawmods[$seq]->availability;
453 $mod[$seq]->deletioninprogress = $rawmods[$seq]->deletioninprogress;
455 $modname = $mod[$seq]->mod;
456 $functionname = $modname."_get_coursemodule_info";
458 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
459 continue;
462 include_once("$CFG->dirroot/mod/$modname/lib.php");
464 if ($hasfunction = function_exists($functionname)) {
465 if ($info = $functionname($rawmods[$seq])) {
466 if (!empty($info->icon)) {
467 $mod[$seq]->icon = $info->icon;
469 if (!empty($info->iconcomponent)) {
470 $mod[$seq]->iconcomponent = $info->iconcomponent;
472 if (!empty($info->name)) {
473 $mod[$seq]->name = $info->name;
475 if ($info instanceof cached_cm_info) {
476 // When using cached_cm_info you can include three new fields
477 // that aren't available for legacy code
478 if (!empty($info->content)) {
479 $mod[$seq]->content = $info->content;
481 if (!empty($info->extraclasses)) {
482 $mod[$seq]->extraclasses = $info->extraclasses;
484 if (!empty($info->iconurl)) {
485 // Convert URL to string as it's easier to store. Also serialized object contains \0 byte and can not be written to Postgres DB.
486 $url = new moodle_url($info->iconurl);
487 $mod[$seq]->iconurl = $url->out(false);
489 if (!empty($info->onclick)) {
490 $mod[$seq]->onclick = $info->onclick;
492 if (!empty($info->customdata)) {
493 $mod[$seq]->customdata = $info->customdata;
495 } else {
496 // When using a stdclass, the (horrible) deprecated ->extra field
497 // is available for BC
498 if (!empty($info->extra)) {
499 $mod[$seq]->extra = $info->extra;
504 // When there is no modname_get_coursemodule_info function,
505 // but showdescriptions is enabled, then we use the 'intro'
506 // and 'introformat' fields in the module table
507 if (!$hasfunction && $rawmods[$seq]->showdescription) {
508 if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
509 array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
510 // Set content from intro and introformat. Filters are disabled
511 // because we filter it with format_text at display time
512 $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
513 $modvalues, $rawmods[$seq]->id, false);
515 // To save making another query just below, put name in here
516 $mod[$seq]->name = $modvalues->name;
519 if (!isset($mod[$seq]->name)) {
520 $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
523 // Minimise the database size by unsetting default options when they are
524 // 'empty'. This list corresponds to code in the cm_info constructor.
525 foreach (array('idnumber', 'groupmode', 'groupingid',
526 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
527 'icon', 'iconcomponent', 'customdata', 'availability', 'completionview',
528 'completionexpected', 'score', 'showdescription', 'deletioninprogress') as $property) {
529 if (property_exists($mod[$seq], $property) &&
530 empty($mod[$seq]->{$property})) {
531 unset($mod[$seq]->{$property});
534 // Special case: this value is usually set to null, but may be 0
535 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
536 is_null($mod[$seq]->completiongradeitemnumber)) {
537 unset($mod[$seq]->completiongradeitemnumber);
543 return $mod;
547 * Returns the localised human-readable names of all used modules
549 * @param bool $plural if true returns the plural forms of the names
550 * @return array where key is the module name (component name without 'mod_') and
551 * the value is the human-readable string. Array sorted alphabetically by value
553 function get_module_types_names($plural = false) {
554 static $modnames = null;
555 global $DB, $CFG;
556 if ($modnames === null) {
557 $modnames = array(0 => array(), 1 => array());
558 if ($allmods = $DB->get_records("modules")) {
559 foreach ($allmods as $mod) {
560 if (file_exists("$CFG->dirroot/mod/$mod->name/lib.php") && $mod->visible) {
561 $modnames[0][$mod->name] = get_string("modulename", "$mod->name");
562 $modnames[1][$mod->name] = get_string("modulenameplural", "$mod->name");
565 core_collator::asort($modnames[0]);
566 core_collator::asort($modnames[1]);
569 return $modnames[(int)$plural];
573 * Set highlighted section. Only one section can be highlighted at the time.
575 * @param int $courseid course id
576 * @param int $marker highlight section with this number, 0 means remove higlightin
577 * @return void
579 function course_set_marker($courseid, $marker) {
580 global $DB, $COURSE;
581 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
582 if ($COURSE && $COURSE->id == $courseid) {
583 $COURSE->marker = $marker;
585 if (class_exists('format_base')) {
586 format_base::reset_course_cache($courseid);
588 course_modinfo::clear_instance_cache($courseid);
592 * For a given course section, marks it visible or hidden,
593 * and does the same for every activity in that section
595 * @param int $courseid course id
596 * @param int $sectionnumber The section number to adjust
597 * @param int $visibility The new visibility
598 * @return array A list of resources which were hidden in the section
600 function set_section_visible($courseid, $sectionnumber, $visibility) {
601 global $DB;
603 $resourcestotoggle = array();
604 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
605 course_update_section($courseid, $section, array('visible' => $visibility));
607 // Determine which modules are visible for AJAX update
608 $modules = !empty($section->sequence) ? explode(',', $section->sequence) : array();
609 if (!empty($modules)) {
610 list($insql, $params) = $DB->get_in_or_equal($modules);
611 $select = 'id ' . $insql . ' AND visible = ?';
612 array_push($params, $visibility);
613 if (!$visibility) {
614 $select .= ' AND visibleold = 1';
616 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
619 return $resourcestotoggle;
623 * Retrieve all metadata for the requested modules
625 * @param object $course The Course
626 * @param array $modnames An array containing the list of modules and their
627 * names
628 * @param int $sectionreturn The section to return to
629 * @return array A list of stdClass objects containing metadata about each
630 * module
632 function get_module_metadata($course, $modnames, $sectionreturn = null) {
633 global $OUTPUT;
635 // get_module_metadata will be called once per section on the page and courses may show
636 // different modules to one another
637 static $modlist = array();
638 if (!isset($modlist[$course->id])) {
639 $modlist[$course->id] = array();
642 $return = array();
643 $urlbase = new moodle_url('/course/mod.php', array('id' => $course->id, 'sesskey' => sesskey()));
644 if ($sectionreturn !== null) {
645 $urlbase->param('sr', $sectionreturn);
647 foreach($modnames as $modname => $modnamestr) {
648 if (!course_allowed_module($course, $modname)) {
649 continue;
651 if (isset($modlist[$course->id][$modname])) {
652 // This module is already cached
653 $return += $modlist[$course->id][$modname];
654 continue;
656 $modlist[$course->id][$modname] = array();
658 // Create an object for a default representation of this module type in the activity chooser. It will be used
659 // if module does not implement callback get_shortcuts() and it will also be passed to the callback if it exists.
660 $defaultmodule = new stdClass();
661 $defaultmodule->title = $modnamestr;
662 $defaultmodule->name = $modname;
663 $defaultmodule->link = new moodle_url($urlbase, array('add' => $modname));
664 $defaultmodule->icon = $OUTPUT->pix_icon('icon', '', $defaultmodule->name, array('class' => 'icon'));
665 $sm = get_string_manager();
666 if ($sm->string_exists('modulename_help', $modname)) {
667 $defaultmodule->help = get_string('modulename_help', $modname);
668 if ($sm->string_exists('modulename_link', $modname)) { // Link to further info in Moodle docs.
669 $link = get_string('modulename_link', $modname);
670 $linktext = get_string('morehelp');
671 $defaultmodule->help .= html_writer::tag('div',
672 $OUTPUT->doc_link($link, $linktext, true), array('class' => 'helpdoclink'));
675 $defaultmodule->archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
677 // Each module can implement callback modulename_get_shortcuts() in its lib.php and return the list
678 // of elements to be added to activity chooser.
679 $items = component_callback($modname, 'get_shortcuts', array($defaultmodule), null);
680 if ($items !== null) {
681 foreach ($items as $item) {
682 // Add all items to the return array. All items must have different links, use them as a key in the return array.
683 if (!isset($item->archetype)) {
684 $item->archetype = $defaultmodule->archetype;
686 if (!isset($item->icon)) {
687 $item->icon = $defaultmodule->icon;
689 // If plugin returned the only one item with the same link as default item - cache it as $modname,
690 // otherwise append the link url to the module name.
691 $item->name = (count($items) == 1 &&
692 $item->link->out() === $defaultmodule->link->out()) ? $modname : $modname . ':' . $item->link;
694 // If the module provides the helptext property, append it to the help text to match the look and feel
695 // of the default course modules.
696 if (isset($item->help) && isset($item->helplink)) {
697 $linktext = get_string('morehelp');
698 $item->help .= html_writer::tag('div',
699 $OUTPUT->doc_link($item->helplink, $linktext, true), array('class' => 'helpdoclink'));
701 $modlist[$course->id][$modname][$item->name] = $item;
703 $return += $modlist[$course->id][$modname];
704 // If get_shortcuts() callback is defined, the default module action is not added.
705 // It is a responsibility of the callback to add it to the return value unless it is not needed.
706 continue;
709 // The callback get_shortcuts() was not found, use the default item for the activity chooser.
710 $modlist[$course->id][$modname][$modname] = $defaultmodule;
711 $return[$modname] = $defaultmodule;
714 core_collator::asort_objects_by_property($return, 'title');
715 return $return;
719 * Return the course category context for the category with id $categoryid, except
720 * that if $categoryid is 0, return the system context.
722 * @param integer $categoryid a category id or 0.
723 * @return context the corresponding context
725 function get_category_or_system_context($categoryid) {
726 if ($categoryid) {
727 return context_coursecat::instance($categoryid, IGNORE_MISSING);
728 } else {
729 return context_system::instance();
734 * Returns full course categories trees to be used in html_writer::select()
736 * Calls {@link core_course_category::make_categories_list()} to build the tree and
737 * adds whitespace to denote nesting
739 * @return array array mapping course category id to the display name
741 function make_categories_options() {
742 $cats = core_course_category::make_categories_list('', 0, ' / ');
743 foreach ($cats as $key => $value) {
744 // Prefix the value with the number of spaces equal to category depth (number of separators in the value).
745 $cats[$key] = str_repeat('&nbsp;', substr_count($value, ' / ')). $value;
747 return $cats;
751 * Print the buttons relating to course requests.
753 * @param object $context current page context.
755 function print_course_request_buttons($context) {
756 global $CFG, $DB, $OUTPUT;
757 if (empty($CFG->enablecourserequests)) {
758 return;
760 if (!has_capability('moodle/course:create', $context) && has_capability('moodle/course:request', $context)) {
761 /// Print a button to request a new course
762 echo $OUTPUT->single_button(new moodle_url('/course/request.php'), get_string('requestcourse'), 'get');
764 /// Print a button to manage pending requests
765 if ($context->contextlevel == CONTEXT_SYSTEM && has_capability('moodle/site:approvecourse', $context)) {
766 $disabled = !$DB->record_exists('course_request', array());
767 echo $OUTPUT->single_button(new moodle_url('/course/pending.php'), get_string('coursespending'), 'get', array('disabled' => $disabled));
772 * Does the user have permission to edit things in this category?
774 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
775 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
777 function can_edit_in_category($categoryid = 0) {
778 $context = get_category_or_system_context($categoryid);
779 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
782 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
784 function add_course_module($mod) {
785 global $DB;
787 $mod->added = time();
788 unset($mod->id);
790 $cmid = $DB->insert_record("course_modules", $mod);
791 rebuild_course_cache($mod->course, true);
792 return $cmid;
796 * Creates a course section and adds it to the specified position
798 * @param int|stdClass $courseorid course id or course object
799 * @param int $position position to add to, 0 means to the end. If position is greater than
800 * number of existing secitons, the section is added to the end. This will become sectionnum of the
801 * new section. All existing sections at this or bigger position will be shifted down.
802 * @param bool $skipcheck the check has already been made and we know that the section with this position does not exist
803 * @return stdClass created section object
805 function course_create_section($courseorid, $position = 0, $skipcheck = false) {
806 global $DB;
807 $courseid = is_object($courseorid) ? $courseorid->id : $courseorid;
809 // Find the last sectionnum among existing sections.
810 if ($skipcheck) {
811 $lastsection = $position - 1;
812 } else {
813 $lastsection = (int)$DB->get_field_sql('SELECT max(section) from {course_sections} WHERE course = ?', [$courseid]);
816 // First add section to the end.
817 $cw = new stdClass();
818 $cw->course = $courseid;
819 $cw->section = $lastsection + 1;
820 $cw->summary = '';
821 $cw->summaryformat = FORMAT_HTML;
822 $cw->sequence = '';
823 $cw->name = null;
824 $cw->visible = 1;
825 $cw->availability = null;
826 $cw->timemodified = time();
827 $cw->id = $DB->insert_record("course_sections", $cw);
829 // Now move it to the specified position.
830 if ($position > 0 && $position <= $lastsection) {
831 $course = is_object($courseorid) ? $courseorid : get_course($courseorid);
832 move_section_to($course, $cw->section, $position, true);
833 $cw->section = $position;
836 core\event\course_section_created::create_from_section($cw)->trigger();
838 rebuild_course_cache($courseid, true);
839 return $cw;
843 * Creates missing course section(s) and rebuilds course cache
845 * @param int|stdClass $courseorid course id or course object
846 * @param int|array $sections list of relative section numbers to create
847 * @return bool if there were any sections created
849 function course_create_sections_if_missing($courseorid, $sections) {
850 if (!is_array($sections)) {
851 $sections = array($sections);
853 $existing = array_keys(get_fast_modinfo($courseorid)->get_section_info_all());
854 if ($newsections = array_diff($sections, $existing)) {
855 foreach ($newsections as $sectionnum) {
856 course_create_section($courseorid, $sectionnum, true);
858 return true;
860 return false;
864 * Adds an existing module to the section
866 * Updates both tables {course_sections} and {course_modules}
868 * Note: This function does not use modinfo PROVIDED that the section you are
869 * adding the module to already exists. If the section does not exist, it will
870 * build modinfo if necessary and create the section.
872 * @param int|stdClass $courseorid course id or course object
873 * @param int $cmid id of the module already existing in course_modules table
874 * @param int $sectionnum relative number of the section (field course_sections.section)
875 * If section does not exist it will be created
876 * @param int|stdClass $beforemod id or object with field id corresponding to the module
877 * before which the module needs to be included. Null for inserting in the
878 * end of the section
879 * @return int The course_sections ID where the module is inserted
881 function course_add_cm_to_section($courseorid, $cmid, $sectionnum, $beforemod = null) {
882 global $DB, $COURSE;
883 if (is_object($beforemod)) {
884 $beforemod = $beforemod->id;
886 if (is_object($courseorid)) {
887 $courseid = $courseorid->id;
888 } else {
889 $courseid = $courseorid;
891 // Do not try to use modinfo here, there is no guarantee it is valid!
892 $section = $DB->get_record('course_sections',
893 array('course' => $courseid, 'section' => $sectionnum), '*', IGNORE_MISSING);
894 if (!$section) {
895 // This function call requires modinfo.
896 course_create_sections_if_missing($courseorid, $sectionnum);
897 $section = $DB->get_record('course_sections',
898 array('course' => $courseid, 'section' => $sectionnum), '*', MUST_EXIST);
901 $modarray = explode(",", trim($section->sequence));
902 if (empty($section->sequence)) {
903 $newsequence = "$cmid";
904 } else if ($beforemod && ($key = array_keys($modarray, $beforemod))) {
905 $insertarray = array($cmid, $beforemod);
906 array_splice($modarray, $key[0], 1, $insertarray);
907 $newsequence = implode(",", $modarray);
908 } else {
909 $newsequence = "$section->sequence,$cmid";
911 $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id));
912 $DB->set_field('course_modules', 'section', $section->id, array('id' => $cmid));
913 if (is_object($courseorid)) {
914 rebuild_course_cache($courseorid->id, true);
915 } else {
916 rebuild_course_cache($courseorid, true);
918 return $section->id; // Return course_sections ID that was used.
922 * Change the group mode of a course module.
924 * Note: Do not forget to trigger the event \core\event\course_module_updated as it needs
925 * to be triggered manually, refer to {@link \core\event\course_module_updated::create_from_cm()}.
927 * @param int $id course module ID.
928 * @param int $groupmode the new groupmode value.
929 * @return bool True if the $groupmode was updated.
931 function set_coursemodule_groupmode($id, $groupmode) {
932 global $DB;
933 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST);
934 if ($cm->groupmode != $groupmode) {
935 $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id));
936 rebuild_course_cache($cm->course, true);
938 return ($cm->groupmode != $groupmode);
941 function set_coursemodule_idnumber($id, $idnumber) {
942 global $DB;
943 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST);
944 if ($cm->idnumber != $idnumber) {
945 $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id));
946 rebuild_course_cache($cm->course, true);
948 return ($cm->idnumber != $idnumber);
952 * Set the visibility of a module and inherent properties.
954 * Note: Do not forget to trigger the event \core\event\course_module_updated as it needs
955 * to be triggered manually, refer to {@link \core\event\course_module_updated::create_from_cm()}.
957 * From 2.4 the parameter $prevstateoverrides has been removed, the logic it triggered
958 * has been moved to {@link set_section_visible()} which was the only place from which
959 * the parameter was used.
961 * @param int $id of the module
962 * @param int $visible state of the module
963 * @param int $visibleoncoursepage state of the module on the course page
964 * @return bool false when the module was not found, true otherwise
966 function set_coursemodule_visible($id, $visible, $visibleoncoursepage = 1) {
967 global $DB, $CFG;
968 require_once($CFG->libdir.'/gradelib.php');
969 require_once($CFG->dirroot.'/calendar/lib.php');
971 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
972 return false;
975 // Create events and propagate visibility to associated grade items if the value has changed.
976 // Only do this if it's changed to avoid accidently overwriting manual showing/hiding of student grades.
977 if ($cm->visible == $visible && $cm->visibleoncoursepage == $visibleoncoursepage) {
978 return true;
981 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
982 return false;
984 if (($cm->visible != $visible) &&
985 ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename)))) {
986 foreach($events as $event) {
987 if ($visible) {
988 $event = new calendar_event($event);
989 $event->toggle_visibility(true);
990 } else {
991 $event = new calendar_event($event);
992 $event->toggle_visibility(false);
997 // Updating visible and visibleold to keep them in sync. Only changing a section visibility will
998 // affect visibleold to allow for an original visibility restore. See set_section_visible().
999 $cminfo = new stdClass();
1000 $cminfo->id = $id;
1001 $cminfo->visible = $visible;
1002 $cminfo->visibleoncoursepage = $visibleoncoursepage;
1003 $cminfo->visibleold = $visible;
1004 $DB->update_record('course_modules', $cminfo);
1006 // Hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there.
1007 // Note that this must be done after updating the row in course_modules, in case
1008 // the modules grade_item_update function needs to access $cm->visible.
1009 if ($cm->visible != $visible &&
1010 plugin_supports('mod', $modulename, FEATURE_CONTROLS_GRADE_VISIBILITY) &&
1011 component_callback_exists('mod_' . $modulename, 'grade_item_update')) {
1012 $instance = $DB->get_record($modulename, array('id' => $cm->instance), '*', MUST_EXIST);
1013 component_callback('mod_' . $modulename, 'grade_item_update', array($instance));
1014 } else if ($cm->visible != $visible) {
1015 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
1016 if ($grade_items) {
1017 foreach ($grade_items as $grade_item) {
1018 $grade_item->set_hidden(!$visible);
1023 rebuild_course_cache($cm->course, true);
1024 return true;
1028 * Changes the course module name
1030 * @param int $id course module id
1031 * @param string $name new value for a name
1032 * @return bool whether a change was made
1034 function set_coursemodule_name($id, $name) {
1035 global $CFG, $DB;
1036 require_once($CFG->libdir . '/gradelib.php');
1038 $cm = get_coursemodule_from_id('', $id, 0, false, MUST_EXIST);
1040 $module = new \stdClass();
1041 $module->id = $cm->instance;
1043 // Escape strings as they would be by mform.
1044 if (!empty($CFG->formatstringstriptags)) {
1045 $module->name = clean_param($name, PARAM_TEXT);
1046 } else {
1047 $module->name = clean_param($name, PARAM_CLEANHTML);
1049 if ($module->name === $cm->name || strval($module->name) === '') {
1050 return false;
1052 if (\core_text::strlen($module->name) > 255) {
1053 throw new \moodle_exception('maximumchars', 'moodle', '', 255);
1056 $module->timemodified = time();
1057 $DB->update_record($cm->modname, $module);
1058 $cm->name = $module->name;
1059 \core\event\course_module_updated::create_from_cm($cm)->trigger();
1060 rebuild_course_cache($cm->course, true);
1062 // Attempt to update the grade item if relevant.
1063 $grademodule = $DB->get_record($cm->modname, array('id' => $cm->instance));
1064 $grademodule->cmidnumber = $cm->idnumber;
1065 $grademodule->modname = $cm->modname;
1066 grade_update_mod_grades($grademodule);
1068 // Update calendar events with the new name.
1069 course_module_update_calendar_events($cm->modname, $grademodule, $cm);
1071 return true;
1075 * This function will handle the whole deletion process of a module. This includes calling
1076 * the modules delete_instance function, deleting files, events, grades, conditional data,
1077 * the data in the course_module and course_sections table and adding a module deletion
1078 * event to the DB.
1080 * @param int $cmid the course module id
1081 * @param bool $async whether or not to try to delete the module using an adhoc task. Async also depends on a plugin hook.
1082 * @throws moodle_exception
1083 * @since Moodle 2.5
1085 function course_delete_module($cmid, $async = false) {
1086 // Check the 'course_module_background_deletion_recommended' hook first.
1087 // Only use asynchronous deletion if at least one plugin returns true and if async deletion has been requested.
1088 // Both are checked because plugins should not be allowed to dictate the deletion behaviour, only support/decline it.
1089 // It's up to plugins to handle things like whether or not they are enabled.
1090 if ($async && $pluginsfunction = get_plugins_with_function('course_module_background_deletion_recommended')) {
1091 foreach ($pluginsfunction as $plugintype => $plugins) {
1092 foreach ($plugins as $pluginfunction) {
1093 if ($pluginfunction()) {
1094 return course_module_flag_for_async_deletion($cmid);
1100 global $CFG, $DB;
1102 require_once($CFG->libdir.'/gradelib.php');
1103 require_once($CFG->libdir.'/questionlib.php');
1104 require_once($CFG->dirroot.'/blog/lib.php');
1105 require_once($CFG->dirroot.'/calendar/lib.php');
1107 // Get the course module.
1108 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
1109 return true;
1112 // Get the module context.
1113 $modcontext = context_module::instance($cm->id);
1115 // Get the course module name.
1116 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
1118 // Get the file location of the delete_instance function for this module.
1119 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
1121 // Include the file required to call the delete_instance function for this module.
1122 if (file_exists($modlib)) {
1123 require_once($modlib);
1124 } else {
1125 throw new moodle_exception('cannotdeletemodulemissinglib', '', '', null,
1126 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
1129 $deleteinstancefunction = $modulename . '_delete_instance';
1131 // Ensure the delete_instance function exists for this module.
1132 if (!function_exists($deleteinstancefunction)) {
1133 throw new moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
1134 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
1137 // Allow plugins to use this course module before we completely delete it.
1138 if ($pluginsfunction = get_plugins_with_function('pre_course_module_delete')) {
1139 foreach ($pluginsfunction as $plugintype => $plugins) {
1140 foreach ($plugins as $pluginfunction) {
1141 $pluginfunction($cm);
1146 // Delete activity context questions and question categories.
1147 question_delete_activity($cm);
1149 // Call the delete_instance function, if it returns false throw an exception.
1150 if (!$deleteinstancefunction($cm->instance)) {
1151 throw new moodle_exception('cannotdeletemoduleinstance', '', '', null,
1152 "Cannot delete the module $modulename (instance).");
1155 // Remove all module files in case modules forget to do that.
1156 $fs = get_file_storage();
1157 $fs->delete_area_files($modcontext->id);
1159 // Delete events from calendar.
1160 if ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename))) {
1161 $coursecontext = context_course::instance($cm->course);
1162 foreach($events as $event) {
1163 $event->context = $coursecontext;
1164 $calendarevent = calendar_event::load($event);
1165 $calendarevent->delete();
1169 // Delete grade items, outcome items and grades attached to modules.
1170 if ($grade_items = grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $modulename,
1171 'iteminstance' => $cm->instance, 'courseid' => $cm->course))) {
1172 foreach ($grade_items as $grade_item) {
1173 $grade_item->delete('moddelete');
1177 // Delete associated blogs and blog tag instances.
1178 blog_remove_associations_for_module($modcontext->id);
1180 // Delete completion and availability data; it is better to do this even if the
1181 // features are not turned on, in case they were turned on previously (these will be
1182 // very quick on an empty table).
1183 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
1184 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
1185 'course' => $cm->course,
1186 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
1188 // Delete all tag instances associated with the instance of this module.
1189 core_tag_tag::delete_instances('mod_' . $modulename, null, $modcontext->id);
1190 core_tag_tag::remove_all_item_tags('core', 'course_modules', $cm->id);
1192 // Notify the competency subsystem.
1193 \core_competency\api::hook_course_module_deleted($cm);
1195 // Delete the context.
1196 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
1198 // Delete the module from the course_modules table.
1199 $DB->delete_records('course_modules', array('id' => $cm->id));
1201 // Delete module from that section.
1202 if (!delete_mod_from_section($cm->id, $cm->section)) {
1203 throw new moodle_exception('cannotdeletemodulefromsection', '', '', null,
1204 "Cannot delete the module $modulename (instance) from section.");
1207 // Trigger event for course module delete action.
1208 $event = \core\event\course_module_deleted::create(array(
1209 'courseid' => $cm->course,
1210 'context' => $modcontext,
1211 'objectid' => $cm->id,
1212 'other' => array(
1213 'modulename' => $modulename,
1214 'instanceid' => $cm->instance,
1217 $event->add_record_snapshot('course_modules', $cm);
1218 $event->trigger();
1219 rebuild_course_cache($cm->course, true);
1223 * Schedule a course module for deletion in the background using an adhoc task.
1225 * This method should not be called directly. Instead, please use course_delete_module($cmid, true), to denote async deletion.
1226 * The real deletion of the module is handled by the task, which calls 'course_delete_module($cmid)'.
1228 * @param int $cmid the course module id.
1229 * @return bool whether the module was successfully scheduled for deletion.
1230 * @throws \moodle_exception
1232 function course_module_flag_for_async_deletion($cmid) {
1233 global $CFG, $DB, $USER;
1234 require_once($CFG->libdir.'/gradelib.php');
1235 require_once($CFG->libdir.'/questionlib.php');
1236 require_once($CFG->dirroot.'/blog/lib.php');
1237 require_once($CFG->dirroot.'/calendar/lib.php');
1239 // Get the course module.
1240 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
1241 return true;
1244 // We need to be reasonably certain the deletion is going to succeed before we background the process.
1245 // Make the necessary delete_instance checks, etc. before proceeding further. Throw exceptions if required.
1247 // Get the course module name.
1248 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
1250 // Get the file location of the delete_instance function for this module.
1251 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
1253 // Include the file required to call the delete_instance function for this module.
1254 if (file_exists($modlib)) {
1255 require_once($modlib);
1256 } else {
1257 throw new \moodle_exception('cannotdeletemodulemissinglib', '', '', null,
1258 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
1261 $deleteinstancefunction = $modulename . '_delete_instance';
1263 // Ensure the delete_instance function exists for this module.
1264 if (!function_exists($deleteinstancefunction)) {
1265 throw new \moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
1266 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
1269 // We are going to defer the deletion as we can't be sure how long the module's pre_delete code will run for.
1270 $cm->deletioninprogress = '1';
1271 $DB->update_record('course_modules', $cm);
1273 // Create an adhoc task for the deletion of the course module. The task takes an array of course modules for removal.
1274 $removaltask = new \core_course\task\course_delete_modules();
1275 $removaltask->set_custom_data(array(
1276 'cms' => array($cm),
1277 'userid' => $USER->id,
1278 'realuserid' => \core\session\manager::get_realuser()->id
1281 // Queue the task for the next run.
1282 \core\task\manager::queue_adhoc_task($removaltask);
1284 // Reset the course cache to hide the module.
1285 rebuild_course_cache($cm->course, true);
1289 * Checks whether the given course has any course modules scheduled for adhoc deletion.
1291 * @param int $courseid the id of the course.
1292 * @return bool true if the course contains any modules pending deletion, false otherwise.
1294 function course_modules_pending_deletion($courseid) {
1295 if (empty($courseid)) {
1296 return false;
1298 $modinfo = get_fast_modinfo($courseid);
1299 foreach ($modinfo->get_cms() as $module) {
1300 if ($module->deletioninprogress == '1') {
1301 return true;
1304 return false;
1308 * Checks whether the course module, as defined by modulename and instanceid, is scheduled for deletion within the given course.
1310 * @param int $courseid the course id.
1311 * @param string $modulename the module name. E.g. 'assign', 'book', etc.
1312 * @param int $instanceid the module instance id.
1313 * @return bool true if the course module is pending deletion, false otherwise.
1315 function course_module_instance_pending_deletion($courseid, $modulename, $instanceid) {
1316 if (empty($courseid) || empty($modulename) || empty($instanceid)) {
1317 return false;
1319 $modinfo = get_fast_modinfo($courseid);
1320 $instances = $modinfo->get_instances_of($modulename);
1321 return isset($instances[$instanceid]) && $instances[$instanceid]->deletioninprogress;
1324 function delete_mod_from_section($modid, $sectionid) {
1325 global $DB;
1327 if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
1329 $modarray = explode(",", $section->sequence);
1331 if ($key = array_keys ($modarray, $modid)) {
1332 array_splice($modarray, $key[0], 1);
1333 $newsequence = implode(",", $modarray);
1334 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
1335 rebuild_course_cache($section->course, true);
1336 return true;
1337 } else {
1338 return false;
1342 return false;
1346 * This function updates the calendar events from the information stored in the module table and the course
1347 * module table.
1349 * @param string $modulename Module name
1350 * @param stdClass $instance Module object. Either the $instance or the $cm must be supplied.
1351 * @param stdClass $cm Course module object. Either the $instance or the $cm must be supplied.
1352 * @return bool Returns true if calendar events are updated.
1353 * @since Moodle 3.3.4
1355 function course_module_update_calendar_events($modulename, $instance = null, $cm = null) {
1356 global $DB;
1358 if (isset($instance) || isset($cm)) {
1360 if (!isset($instance)) {
1361 $instance = $DB->get_record($modulename, array('id' => $cm->instance), '*', MUST_EXIST);
1363 if (!isset($cm)) {
1364 $cm = get_coursemodule_from_instance($modulename, $instance->id, $instance->course);
1366 if (!empty($cm)) {
1367 course_module_calendar_event_update_process($instance, $cm);
1369 return true;
1371 return false;
1375 * Update all instances through out the site or in a course.
1377 * @param string $modulename Module type to update.
1378 * @param integer $courseid Course id to update events. 0 for the whole site.
1379 * @return bool Returns True if the update was successful.
1380 * @since Moodle 3.3.4
1382 function course_module_bulk_update_calendar_events($modulename, $courseid = 0) {
1383 global $DB;
1385 $instances = null;
1386 if ($courseid) {
1387 if (!$instances = $DB->get_records($modulename, array('course' => $courseid))) {
1388 return false;
1390 } else {
1391 if (!$instances = $DB->get_records($modulename)) {
1392 return false;
1396 foreach ($instances as $instance) {
1397 if ($cm = get_coursemodule_from_instance($modulename, $instance->id, $instance->course)) {
1398 course_module_calendar_event_update_process($instance, $cm);
1401 return true;
1405 * Calendar events for a module instance are updated.
1407 * @param stdClass $instance Module instance object.
1408 * @param stdClass $cm Course Module object.
1409 * @since Moodle 3.3.4
1411 function course_module_calendar_event_update_process($instance, $cm) {
1412 // We need to call *_refresh_events() first because some modules delete 'old' events at the end of the code which
1413 // will remove the completion events.
1414 $refresheventsfunction = $cm->modname . '_refresh_events';
1415 if (function_exists($refresheventsfunction)) {
1416 call_user_func($refresheventsfunction, $cm->course, $instance, $cm);
1418 $completionexpected = (!empty($cm->completionexpected)) ? $cm->completionexpected : null;
1419 \core_completion\api::update_completion_date_event($cm->id, $cm->modname, $instance, $completionexpected);
1423 * Moves a section within a course, from a position to another.
1424 * Be very careful: $section and $destination refer to section number,
1425 * not id!.
1427 * @param object $course
1428 * @param int $section Section number (not id!!!)
1429 * @param int $destination
1430 * @param bool $ignorenumsections
1431 * @return boolean Result
1433 function move_section_to($course, $section, $destination, $ignorenumsections = false) {
1434 /// Moves a whole course section up and down within the course
1435 global $USER, $DB;
1437 if (!$destination && $destination != 0) {
1438 return true;
1441 // compartibility with course formats using field 'numsections'
1442 $courseformatoptions = course_get_format($course)->get_format_options();
1443 if ((!$ignorenumsections && array_key_exists('numsections', $courseformatoptions) &&
1444 ($destination > $courseformatoptions['numsections'])) || ($destination < 1)) {
1445 return false;
1448 // Get all sections for this course and re-order them (2 of them should now share the same section number)
1449 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
1450 'section ASC, id ASC', 'id, section')) {
1451 return false;
1454 $movedsections = reorder_sections($sections, $section, $destination);
1456 // Update all sections. Do this in 2 steps to avoid breaking database
1457 // uniqueness constraint
1458 $transaction = $DB->start_delegated_transaction();
1459 foreach ($movedsections as $id => $position) {
1460 if ($sections[$id] !== $position) {
1461 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
1464 foreach ($movedsections as $id => $position) {
1465 if ($sections[$id] !== $position) {
1466 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
1470 // If we move the highlighted section itself, then just highlight the destination.
1471 // Adjust the higlighted section location if we move something over it either direction.
1472 if ($section == $course->marker) {
1473 course_set_marker($course->id, $destination);
1474 } elseif ($section > $course->marker && $course->marker >= $destination) {
1475 course_set_marker($course->id, $course->marker+1);
1476 } elseif ($section < $course->marker && $course->marker <= $destination) {
1477 course_set_marker($course->id, $course->marker-1);
1480 $transaction->allow_commit();
1481 rebuild_course_cache($course->id, true);
1482 return true;
1486 * This method will delete a course section and may delete all modules inside it.
1488 * No permissions are checked here, use {@link course_can_delete_section()} to
1489 * check if section can actually be deleted.
1491 * @param int|stdClass $course
1492 * @param int|stdClass|section_info $section
1493 * @param bool $forcedeleteifnotempty if set to false section will not be deleted if it has modules in it.
1494 * @param bool $async whether or not to try to delete the section using an adhoc task. Async also depends on a plugin hook.
1495 * @return bool whether section was deleted
1497 function course_delete_section($course, $section, $forcedeleteifnotempty = true, $async = false) {
1498 global $DB;
1500 // Prepare variables.
1501 $courseid = (is_object($course)) ? $course->id : (int)$course;
1502 $sectionnum = (is_object($section)) ? $section->section : (int)$section;
1503 $section = $DB->get_record('course_sections', array('course' => $courseid, 'section' => $sectionnum));
1504 if (!$section) {
1505 // No section exists, can't proceed.
1506 return false;
1509 // Check the 'course_module_background_deletion_recommended' hook first.
1510 // Only use asynchronous deletion if at least one plugin returns true and if async deletion has been requested.
1511 // Both are checked because plugins should not be allowed to dictate the deletion behaviour, only support/decline it.
1512 // It's up to plugins to handle things like whether or not they are enabled.
1513 if ($async && $pluginsfunction = get_plugins_with_function('course_module_background_deletion_recommended')) {
1514 foreach ($pluginsfunction as $plugintype => $plugins) {
1515 foreach ($plugins as $pluginfunction) {
1516 if ($pluginfunction()) {
1517 return course_delete_section_async($section, $forcedeleteifnotempty);
1523 $format = course_get_format($course);
1524 $sectionname = $format->get_section_name($section);
1526 // Delete section.
1527 $result = $format->delete_section($section, $forcedeleteifnotempty);
1529 // Trigger an event for course section deletion.
1530 if ($result) {
1531 $context = context_course::instance($courseid);
1532 $event = \core\event\course_section_deleted::create(
1533 array(
1534 'objectid' => $section->id,
1535 'courseid' => $courseid,
1536 'context' => $context,
1537 'other' => array(
1538 'sectionnum' => $section->section,
1539 'sectionname' => $sectionname,
1543 $event->add_record_snapshot('course_sections', $section);
1544 $event->trigger();
1546 return $result;
1550 * Course section deletion, using an adhoc task for deletion of the modules it contains.
1551 * 1. Schedule all modules within the section for adhoc removal.
1552 * 2. Move all modules to course section 0.
1553 * 3. Delete the resulting empty section.
1555 * @param \stdClass $section the section to schedule for deletion.
1556 * @param bool $forcedeleteifnotempty whether to force section deletion if it contains modules.
1557 * @return bool true if the section was scheduled for deletion, false otherwise.
1559 function course_delete_section_async($section, $forcedeleteifnotempty = true) {
1560 global $DB, $USER;
1562 // Objects only, and only valid ones.
1563 if (!is_object($section) || empty($section->id)) {
1564 return false;
1567 // Does the object currently exist in the DB for removal (check for stale objects).
1568 $section = $DB->get_record('course_sections', array('id' => $section->id));
1569 if (!$section || !$section->section) {
1570 // No section exists, or the section is 0. Can't proceed.
1571 return false;
1574 // Check whether the section can be removed.
1575 if (!$forcedeleteifnotempty && (!empty($section->sequence) || !empty($section->summary))) {
1576 return false;
1579 $format = course_get_format($section->course);
1580 $sectionname = $format->get_section_name($section);
1582 // Flag those modules having no existing deletion flag. Some modules may have been scheduled for deletion manually, and we don't
1583 // want to create additional adhoc deletion tasks for these. Moving them to section 0 will suffice.
1584 $affectedmods = $DB->get_records_select('course_modules', 'course = ? AND section = ? AND deletioninprogress <> ?',
1585 [$section->course, $section->id, 1], '', 'id');
1586 $DB->set_field('course_modules', 'deletioninprogress', '1', ['course' => $section->course, 'section' => $section->id]);
1588 // Move all modules to section 0.
1589 $modules = $DB->get_records('course_modules', ['section' => $section->id], '');
1590 $sectionzero = $DB->get_record('course_sections', ['course' => $section->course, 'section' => '0']);
1591 foreach ($modules as $mod) {
1592 moveto_module($mod, $sectionzero);
1595 // Create and queue an adhoc task for the deletion of the modules.
1596 $removaltask = new \core_course\task\course_delete_modules();
1597 $data = array(
1598 'cms' => $affectedmods,
1599 'userid' => $USER->id,
1600 'realuserid' => \core\session\manager::get_realuser()->id
1602 $removaltask->set_custom_data($data);
1603 \core\task\manager::queue_adhoc_task($removaltask);
1605 // Delete the now empty section, passing in only the section number, which forces the function to fetch a new object.
1606 // The refresh is needed because the section->sequence is now stale.
1607 $result = $format->delete_section($section->section, $forcedeleteifnotempty);
1609 // Trigger an event for course section deletion.
1610 if ($result) {
1611 $context = \context_course::instance($section->course);
1612 $event = \core\event\course_section_deleted::create(
1613 array(
1614 'objectid' => $section->id,
1615 'courseid' => $section->course,
1616 'context' => $context,
1617 'other' => array(
1618 'sectionnum' => $section->section,
1619 'sectionname' => $sectionname,
1623 $event->add_record_snapshot('course_sections', $section);
1624 $event->trigger();
1626 rebuild_course_cache($section->course, true);
1628 return $result;
1632 * Updates the course section
1634 * This function does not check permissions or clean values - this has to be done prior to calling it.
1636 * @param int|stdClass $course
1637 * @param stdClass $section record from course_sections table - it will be updated with the new values
1638 * @param array|stdClass $data
1640 function course_update_section($course, $section, $data) {
1641 global $DB;
1643 $courseid = (is_object($course)) ? $course->id : (int)$course;
1645 // Some fields can not be updated using this method.
1646 $data = array_diff_key((array)$data, array('id', 'course', 'section', 'sequence'));
1647 $changevisibility = (array_key_exists('visible', $data) && (bool)$data['visible'] != (bool)$section->visible);
1648 if (array_key_exists('name', $data) && \core_text::strlen($data['name']) > 255) {
1649 throw new moodle_exception('maximumchars', 'moodle', '', 255);
1652 // Update record in the DB and course format options.
1653 $data['id'] = $section->id;
1654 $data['timemodified'] = time();
1655 $DB->update_record('course_sections', $data);
1656 rebuild_course_cache($courseid, true);
1657 course_get_format($courseid)->update_section_format_options($data);
1659 // Update fields of the $section object.
1660 foreach ($data as $key => $value) {
1661 if (property_exists($section, $key)) {
1662 $section->$key = $value;
1666 // Trigger an event for course section update.
1667 $event = \core\event\course_section_updated::create(
1668 array(
1669 'objectid' => $section->id,
1670 'courseid' => $courseid,
1671 'context' => context_course::instance($courseid),
1672 'other' => array('sectionnum' => $section->section)
1675 $event->trigger();
1677 // If section visibility was changed, hide the modules in this section too.
1678 if ($changevisibility && !empty($section->sequence)) {
1679 $modules = explode(',', $section->sequence);
1680 foreach ($modules as $moduleid) {
1681 if ($cm = get_coursemodule_from_id(null, $moduleid, $courseid)) {
1682 if ($data['visible']) {
1683 // As we unhide the section, we use the previously saved visibility stored in visibleold.
1684 set_coursemodule_visible($moduleid, $cm->visibleold, $cm->visibleoncoursepage);
1685 } else {
1686 // We hide the section, so we hide the module but we store the original state in visibleold.
1687 set_coursemodule_visible($moduleid, 0, $cm->visibleoncoursepage);
1688 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id' => $moduleid));
1690 \core\event\course_module_updated::create_from_cm($cm)->trigger();
1697 * Checks if the current user can delete a section (if course format allows it and user has proper permissions).
1699 * @param int|stdClass $course
1700 * @param int|stdClass|section_info $section
1701 * @return bool
1703 function course_can_delete_section($course, $section) {
1704 if (is_object($section)) {
1705 $section = $section->section;
1707 if (!$section) {
1708 // Not possible to delete 0-section.
1709 return false;
1711 // Course format should allow to delete sections.
1712 if (!course_get_format($course)->can_delete_section($section)) {
1713 return false;
1715 // Make sure user has capability to update course and move sections.
1716 $context = context_course::instance(is_object($course) ? $course->id : $course);
1717 if (!has_all_capabilities(array('moodle/course:movesections', 'moodle/course:update'), $context)) {
1718 return false;
1720 // Make sure user has capability to delete each activity in this section.
1721 $modinfo = get_fast_modinfo($course);
1722 if (!empty($modinfo->sections[$section])) {
1723 foreach ($modinfo->sections[$section] as $cmid) {
1724 if (!has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
1725 return false;
1729 return true;
1733 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
1734 * an original position number and a target position number, rebuilds the array so that the
1735 * move is made without any duplication of section positions.
1736 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
1737 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
1739 * @param array $sections
1740 * @param int $origin_position
1741 * @param int $target_position
1742 * @return array
1744 function reorder_sections($sections, $origin_position, $target_position) {
1745 if (!is_array($sections)) {
1746 return false;
1749 // We can't move section position 0
1750 if ($origin_position < 1) {
1751 echo "We can't move section position 0";
1752 return false;
1755 // Locate origin section in sections array
1756 if (!$origin_key = array_search($origin_position, $sections)) {
1757 echo "searched position not in sections array";
1758 return false; // searched position not in sections array
1761 // Extract origin section
1762 $origin_section = $sections[$origin_key];
1763 unset($sections[$origin_key]);
1765 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
1766 $found = false;
1767 $append_array = array();
1768 foreach ($sections as $id => $position) {
1769 if ($found) {
1770 $append_array[$id] = $position;
1771 unset($sections[$id]);
1773 if ($position == $target_position) {
1774 if ($target_position < $origin_position) {
1775 $append_array[$id] = $position;
1776 unset($sections[$id]);
1778 $found = true;
1782 // Append moved section
1783 $sections[$origin_key] = $origin_section;
1785 // Append rest of array (if applicable)
1786 if (!empty($append_array)) {
1787 foreach ($append_array as $id => $position) {
1788 $sections[$id] = $position;
1792 // Renumber positions
1793 $position = 0;
1794 foreach ($sections as $id => $p) {
1795 $sections[$id] = $position;
1796 $position++;
1799 return $sections;
1804 * Move the module object $mod to the specified $section
1805 * If $beforemod exists then that is the module
1806 * before which $modid should be inserted
1808 * @param stdClass|cm_info $mod
1809 * @param stdClass|section_info $section
1810 * @param int|stdClass $beforemod id or object with field id corresponding to the module
1811 * before which the module needs to be included. Null for inserting in the
1812 * end of the section
1813 * @return int new value for module visibility (0 or 1)
1815 function moveto_module($mod, $section, $beforemod=NULL) {
1816 global $OUTPUT, $DB;
1818 // Current module visibility state - return value of this function.
1819 $modvisible = $mod->visible;
1821 // Remove original module from original section.
1822 if (! delete_mod_from_section($mod->id, $mod->section)) {
1823 echo $OUTPUT->notification("Could not delete module from existing section");
1826 // If moving to a hidden section then hide module.
1827 if ($mod->section != $section->id) {
1828 if (!$section->visible && $mod->visible) {
1829 // Module was visible but must become hidden after moving to hidden section.
1830 $modvisible = 0;
1831 set_coursemodule_visible($mod->id, 0);
1832 // Set visibleold to 1 so module will be visible when section is made visible.
1833 $DB->set_field('course_modules', 'visibleold', 1, array('id' => $mod->id));
1835 if ($section->visible && !$mod->visible) {
1836 // Hidden module was moved to the visible section, restore the module visibility from visibleold.
1837 set_coursemodule_visible($mod->id, $mod->visibleold);
1838 $modvisible = $mod->visibleold;
1842 // Add the module into the new section.
1843 course_add_cm_to_section($section->course, $mod->id, $section->section, $beforemod);
1844 return $modvisible;
1848 * Returns the list of all editing actions that current user can perform on the module
1850 * @param cm_info $mod The module to produce editing buttons for
1851 * @param int $indent The current indenting (default -1 means no move left-right actions)
1852 * @param int $sr The section to link back to (used for creating the links)
1853 * @return array array of action_link or pix_icon objects
1855 function course_get_cm_edit_actions(cm_info $mod, $indent = -1, $sr = null) {
1856 global $COURSE, $SITE, $CFG;
1858 static $str;
1860 $coursecontext = context_course::instance($mod->course);
1861 $modcontext = context_module::instance($mod->id);
1862 $courseformat = course_get_format($mod->get_course());
1864 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
1865 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
1867 // No permission to edit anything.
1868 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
1869 return array();
1872 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
1874 if (!isset($str)) {
1875 $str = get_strings(array('delete', 'move', 'moveright', 'moveleft',
1876 'editsettings', 'duplicate', 'modhide', 'makeavailable', 'makeunavailable', 'modshow'), 'moodle');
1877 $str->assign = get_string('assignroles', 'role');
1878 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
1879 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
1880 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
1883 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
1885 if ($sr !== null) {
1886 $baseurl->param('sr', $sr);
1888 $actions = array();
1890 // Update.
1891 if ($hasmanageactivities) {
1892 $actions['update'] = new action_menu_link_secondary(
1893 new moodle_url($baseurl, array('update' => $mod->id)),
1894 new pix_icon('t/edit', $str->editsettings, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1895 $str->editsettings,
1896 array('class' => 'editing_update', 'data-action' => 'update')
1900 // Indent.
1901 if ($hasmanageactivities && $indent >= 0) {
1902 $indentlimits = new stdClass();
1903 $indentlimits->min = 0;
1904 $indentlimits->max = 16;
1905 if (right_to_left()) { // Exchange arrows on RTL
1906 $rightarrow = 't/left';
1907 $leftarrow = 't/right';
1908 } else {
1909 $rightarrow = 't/right';
1910 $leftarrow = 't/left';
1913 if ($indent >= $indentlimits->max) {
1914 $enabledclass = 'hidden';
1915 } else {
1916 $enabledclass = '';
1918 $actions['moveright'] = new action_menu_link_secondary(
1919 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
1920 new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1921 $str->moveright,
1922 array('class' => 'editing_moveright ' . $enabledclass, 'data-action' => 'moveright',
1923 'data-keepopen' => true, 'data-sectionreturn' => $sr)
1926 if ($indent <= $indentlimits->min) {
1927 $enabledclass = 'hidden';
1928 } else {
1929 $enabledclass = '';
1931 $actions['moveleft'] = new action_menu_link_secondary(
1932 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
1933 new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1934 $str->moveleft,
1935 array('class' => 'editing_moveleft ' . $enabledclass, 'data-action' => 'moveleft',
1936 'data-keepopen' => true, 'data-sectionreturn' => $sr)
1941 // Hide/Show/Available/Unavailable.
1942 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
1943 $allowstealth = !empty($CFG->allowstealth) && $courseformat->allow_stealth_module_visibility($mod, $mod->get_section_info());
1945 $sectionvisible = $mod->get_section_info()->visible;
1946 // The module on the course page may be in one of the following states:
1947 // - Available and displayed on the course page ($displayedoncoursepage);
1948 // - Not available and not displayed on the course page ($unavailable);
1949 // - Available but not displayed on the course page ($stealth) - this can also be a visible activity in a hidden section.
1950 $displayedoncoursepage = $mod->visible && $mod->visibleoncoursepage && $sectionvisible;
1951 $unavailable = !$mod->visible;
1952 $stealth = $mod->visible && (!$mod->visibleoncoursepage || !$sectionvisible);
1953 if ($displayedoncoursepage) {
1954 $actions['hide'] = new action_menu_link_secondary(
1955 new moodle_url($baseurl, array('hide' => $mod->id)),
1956 new pix_icon('t/hide', $str->modhide, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1957 $str->modhide,
1958 array('class' => 'editing_hide', 'data-action' => 'hide')
1960 } else if (!$displayedoncoursepage && $sectionvisible) {
1961 // Offer to "show" only if the section is visible.
1962 $actions['show'] = new action_menu_link_secondary(
1963 new moodle_url($baseurl, array('show' => $mod->id)),
1964 new pix_icon('t/show', $str->modshow, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1965 $str->modshow,
1966 array('class' => 'editing_show', 'data-action' => 'show')
1970 if ($stealth) {
1971 // When making the "stealth" module unavailable we perform the same action as hiding the visible module.
1972 $actions['hide'] = new action_menu_link_secondary(
1973 new moodle_url($baseurl, array('hide' => $mod->id)),
1974 new pix_icon('t/unblock', $str->makeunavailable, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1975 $str->makeunavailable,
1976 array('class' => 'editing_makeunavailable', 'data-action' => 'hide', 'data-sectionreturn' => $sr)
1978 } else if ($unavailable && (!$sectionvisible || $allowstealth) && $mod->has_view()) {
1979 // Allow to make visually hidden module available in gradebook and other reports by making it a "stealth" module.
1980 // When the section is hidden it is an equivalent of "showing" the module.
1981 // Activities without the link (i.e. labels) can not be made available but hidden on course page.
1982 $action = $sectionvisible ? 'stealth' : 'show';
1983 $actions[$action] = new action_menu_link_secondary(
1984 new moodle_url($baseurl, array($action => $mod->id)),
1985 new pix_icon('t/block', $str->makeavailable, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1986 $str->makeavailable,
1987 array('class' => 'editing_makeavailable', 'data-action' => $action, 'data-sectionreturn' => $sr)
1992 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
1993 if (has_all_capabilities($dupecaps, $coursecontext) &&
1994 plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2) &&
1995 course_allowed_module($mod->get_course(), $mod->modname)) {
1996 $actions['duplicate'] = new action_menu_link_secondary(
1997 new moodle_url($baseurl, array('duplicate' => $mod->id)),
1998 new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1999 $str->duplicate,
2000 array('class' => 'editing_duplicate', 'data-action' => 'duplicate', 'data-sectionreturn' => $sr)
2004 // Groupmode.
2005 if ($hasmanageactivities && !$mod->coursegroupmodeforce) {
2006 if (plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
2007 if ($mod->effectivegroupmode == SEPARATEGROUPS) {
2008 $nextgroupmode = VISIBLEGROUPS;
2009 $grouptitle = $str->groupsseparate;
2010 $actionname = 'groupsseparate';
2011 $nextactionname = 'groupsvisible';
2012 $groupimage = 'i/groups';
2013 } else if ($mod->effectivegroupmode == VISIBLEGROUPS) {
2014 $nextgroupmode = NOGROUPS;
2015 $grouptitle = $str->groupsvisible;
2016 $actionname = 'groupsvisible';
2017 $nextactionname = 'groupsnone';
2018 $groupimage = 'i/groupv';
2019 } else {
2020 $nextgroupmode = SEPARATEGROUPS;
2021 $grouptitle = $str->groupsnone;
2022 $actionname = 'groupsnone';
2023 $nextactionname = 'groupsseparate';
2024 $groupimage = 'i/groupn';
2027 $actions[$actionname] = new action_menu_link_primary(
2028 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $nextgroupmode)),
2029 new pix_icon($groupimage, $grouptitle, 'moodle', array('class' => 'iconsmall')),
2030 $grouptitle,
2031 array('class' => 'editing_'. $actionname, 'data-action' => $nextactionname,
2032 'aria-live' => 'assertive', 'data-sectionreturn' => $sr)
2034 } else {
2035 $actions['nogroupsupport'] = new action_menu_filler();
2039 // Assign.
2040 if (has_capability('moodle/role:assign', $modcontext)){
2041 $actions['assign'] = new action_menu_link_secondary(
2042 new moodle_url('/admin/roles/assign.php', array('contextid' => $modcontext->id)),
2043 new pix_icon('t/assignroles', $str->assign, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2044 $str->assign,
2045 array('class' => 'editing_assign', 'data-action' => 'assignroles', 'data-sectionreturn' => $sr)
2049 // Delete.
2050 if ($hasmanageactivities) {
2051 $actions['delete'] = new action_menu_link_secondary(
2052 new moodle_url($baseurl, array('delete' => $mod->id)),
2053 new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2054 $str->delete,
2055 array('class' => 'editing_delete', 'data-action' => 'delete', 'data-sectionreturn' => $sr)
2059 return $actions;
2063 * Returns the move action.
2065 * @param cm_info $mod The module to produce a move button for
2066 * @param int $sr The section to link back to (used for creating the links)
2067 * @return The markup for the move action, or an empty string if not available.
2069 function course_get_cm_move(cm_info $mod, $sr = null) {
2070 global $OUTPUT;
2072 static $str;
2073 static $baseurl;
2075 $modcontext = context_module::instance($mod->id);
2076 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
2078 if (!isset($str)) {
2079 $str = get_strings(array('move'));
2082 if (!isset($baseurl)) {
2083 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
2085 if ($sr !== null) {
2086 $baseurl->param('sr', $sr);
2090 if ($hasmanageactivities) {
2091 $pixicon = 'i/dragdrop';
2093 if (!course_ajax_enabled($mod->get_course())) {
2094 // Override for course frontpage until we get drag/drop working there.
2095 $pixicon = 't/move';
2098 return html_writer::link(
2099 new moodle_url($baseurl, array('copy' => $mod->id)),
2100 $OUTPUT->pix_icon($pixicon, $str->move, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2101 array('class' => 'editing_move', 'data-action' => 'move', 'data-sectionreturn' => $sr)
2104 return '';
2108 * given a course object with shortname & fullname, this function will
2109 * truncate the the number of chars allowed and add ... if it was too long
2111 function course_format_name ($course,$max=100) {
2113 $context = context_course::instance($course->id);
2114 $shortname = format_string($course->shortname, true, array('context' => $context));
2115 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
2116 $str = $shortname.': '. $fullname;
2117 if (core_text::strlen($str) <= $max) {
2118 return $str;
2120 else {
2121 return core_text::substr($str,0,$max-3).'...';
2126 * Is the user allowed to add this type of module to this course?
2127 * @param object $course the course settings. Only $course->id is used.
2128 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
2129 * @return bool whether the current user is allowed to add this type of module to this course.
2131 function course_allowed_module($course, $modname) {
2132 if (is_numeric($modname)) {
2133 throw new coding_exception('Function course_allowed_module no longer
2134 supports numeric module ids. Please update your code to pass the module name.');
2137 $capability = 'mod/' . $modname . ':addinstance';
2138 if (!get_capability_info($capability)) {
2139 // Debug warning that the capability does not exist, but no more than once per page.
2140 static $warned = array();
2141 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
2142 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
2143 debugging('The module ' . $modname . ' does not define the standard capability ' .
2144 $capability , DEBUG_DEVELOPER);
2145 $warned[$modname] = 1;
2148 // If the capability does not exist, the module can always be added.
2149 return true;
2152 $coursecontext = context_course::instance($course->id);
2153 return has_capability($capability, $coursecontext);
2157 * Efficiently moves many courses around while maintaining
2158 * sortorder in order.
2160 * @param array $courseids is an array of course ids
2161 * @param int $categoryid
2162 * @return bool success
2164 function move_courses($courseids, $categoryid) {
2165 global $DB;
2167 if (empty($courseids)) {
2168 // Nothing to do.
2169 return false;
2172 if (!$category = $DB->get_record('course_categories', array('id' => $categoryid))) {
2173 return false;
2176 $courseids = array_reverse($courseids);
2177 $newparent = context_coursecat::instance($category->id);
2178 $i = 1;
2180 list($where, $params) = $DB->get_in_or_equal($courseids);
2181 $dbcourses = $DB->get_records_select('course', 'id ' . $where, $params, '', 'id, category, shortname, fullname');
2182 foreach ($dbcourses as $dbcourse) {
2183 $course = new stdClass();
2184 $course->id = $dbcourse->id;
2185 $course->category = $category->id;
2186 $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
2187 if ($category->visible == 0) {
2188 // Hide the course when moving into hidden category, do not update the visibleold flag - we want to get
2189 // to previous state if somebody unhides the category.
2190 $course->visible = 0;
2193 $DB->update_record('course', $course);
2195 // Update context, so it can be passed to event.
2196 $context = context_course::instance($course->id);
2197 $context->update_moved($newparent);
2199 // Trigger a course updated event.
2200 $event = \core\event\course_updated::create(array(
2201 'objectid' => $course->id,
2202 'context' => context_course::instance($course->id),
2203 'other' => array('shortname' => $dbcourse->shortname,
2204 'fullname' => $dbcourse->fullname)
2206 $event->set_legacy_logdata(array($course->id, 'course', 'move', 'edit.php?id=' . $course->id, $course->id));
2207 $event->trigger();
2209 fix_course_sortorder();
2210 cache_helper::purge_by_event('changesincourse');
2212 return true;
2216 * Returns the display name of the given section that the course prefers
2218 * Implementation of this function is provided by course format
2219 * @see format_base::get_section_name()
2221 * @param int|stdClass $courseorid The course to get the section name for (object or just course id)
2222 * @param int|stdClass $section Section object from database or just field course_sections.section
2223 * @return string Display name that the course format prefers, e.g. "Week 2"
2225 function get_section_name($courseorid, $section) {
2226 return course_get_format($courseorid)->get_section_name($section);
2230 * Tells if current course format uses sections
2232 * @param string $format Course format ID e.g. 'weeks' $course->format
2233 * @return bool
2235 function course_format_uses_sections($format) {
2236 $course = new stdClass();
2237 $course->format = $format;
2238 return course_get_format($course)->uses_sections();
2242 * Returns the information about the ajax support in the given source format
2244 * The returned object's property (boolean)capable indicates that
2245 * the course format supports Moodle course ajax features.
2247 * @param string $format
2248 * @return stdClass
2250 function course_format_ajax_support($format) {
2251 $course = new stdClass();
2252 $course->format = $format;
2253 return course_get_format($course)->supports_ajax();
2257 * Can the current user delete this course?
2258 * Course creators have exception,
2259 * 1 day after the creation they can sill delete the course.
2260 * @param int $courseid
2261 * @return boolean
2263 function can_delete_course($courseid) {
2264 global $USER;
2266 $context = context_course::instance($courseid);
2268 if (has_capability('moodle/course:delete', $context)) {
2269 return true;
2272 // hack: now try to find out if creator created this course recently (1 day)
2273 if (!has_capability('moodle/course:create', $context)) {
2274 return false;
2277 $since = time() - 60*60*24;
2278 $course = get_course($courseid);
2280 if ($course->timecreated < $since) {
2281 return false; // Return if the course was not created in last 24 hours.
2284 $logmanger = get_log_manager();
2285 $readers = $logmanger->get_readers('\core\log\sql_reader');
2286 $reader = reset($readers);
2288 if (empty($reader)) {
2289 return false; // No log reader found.
2292 // A proper reader.
2293 $select = "userid = :userid AND courseid = :courseid AND eventname = :eventname AND timecreated > :since";
2294 $params = array('userid' => $USER->id, 'since' => $since, 'courseid' => $course->id, 'eventname' => '\core\event\course_created');
2296 return (bool)$reader->get_events_select_count($select, $params);
2300 * Save the Your name for 'Some role' strings.
2302 * @param integer $courseid the id of this course.
2303 * @param array $data the data that came from the course settings form.
2305 function save_local_role_names($courseid, $data) {
2306 global $DB;
2307 $context = context_course::instance($courseid);
2309 foreach ($data as $fieldname => $value) {
2310 if (strpos($fieldname, 'role_') !== 0) {
2311 continue;
2313 list($ignored, $roleid) = explode('_', $fieldname);
2315 // make up our mind whether we want to delete, update or insert
2316 if (!$value) {
2317 $DB->delete_records('role_names', array('contextid' => $context->id, 'roleid' => $roleid));
2319 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id, 'roleid' => $roleid))) {
2320 $rolename->name = $value;
2321 $DB->update_record('role_names', $rolename);
2323 } else {
2324 $rolename = new stdClass;
2325 $rolename->contextid = $context->id;
2326 $rolename->roleid = $roleid;
2327 $rolename->name = $value;
2328 $DB->insert_record('role_names', $rolename);
2330 // This will ensure the course contacts cache is purged..
2331 core_course_category::role_assignment_changed($roleid, $context);
2336 * Returns options to use in course overviewfiles filemanager
2338 * @param null|stdClass|core_course_list_element|int $course either object that has 'id' property or just the course id;
2339 * may be empty if course does not exist yet (course create form)
2340 * @return array|null array of options such as maxfiles, maxbytes, accepted_types, etc.
2341 * or null if overviewfiles are disabled
2343 function course_overviewfiles_options($course) {
2344 global $CFG;
2345 if (empty($CFG->courseoverviewfileslimit)) {
2346 return null;
2348 $accepted_types = preg_split('/\s*,\s*/', trim($CFG->courseoverviewfilesext), -1, PREG_SPLIT_NO_EMPTY);
2349 if (in_array('*', $accepted_types) || empty($accepted_types)) {
2350 $accepted_types = '*';
2351 } else {
2352 // Since config for $CFG->courseoverviewfilesext is a text box, human factor must be considered.
2353 // Make sure extensions are prefixed with dot unless they are valid typegroups
2354 foreach ($accepted_types as $i => $type) {
2355 if (substr($type, 0, 1) !== '.') {
2356 require_once($CFG->libdir. '/filelib.php');
2357 if (!count(file_get_typegroup('extension', $type))) {
2358 // It does not start with dot and is not a valid typegroup, this is most likely extension.
2359 $accepted_types[$i] = '.'. $type;
2360 $corrected = true;
2364 if (!empty($corrected)) {
2365 set_config('courseoverviewfilesext', join(',', $accepted_types));
2368 $options = array(
2369 'maxfiles' => $CFG->courseoverviewfileslimit,
2370 'maxbytes' => $CFG->maxbytes,
2371 'subdirs' => 0,
2372 'accepted_types' => $accepted_types
2374 if (!empty($course->id)) {
2375 $options['context'] = context_course::instance($course->id);
2376 } else if (is_int($course) && $course > 0) {
2377 $options['context'] = context_course::instance($course);
2379 return $options;
2383 * Create a course and either return a $course object
2385 * Please note this functions does not verify any access control,
2386 * the calling code is responsible for all validation (usually it is the form definition).
2388 * @param array $editoroptions course description editor options
2389 * @param object $data - all the data needed for an entry in the 'course' table
2390 * @return object new course instance
2392 function create_course($data, $editoroptions = NULL) {
2393 global $DB, $CFG;
2395 //check the categoryid - must be given for all new courses
2396 $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
2398 // Check if the shortname already exists.
2399 if (!empty($data->shortname)) {
2400 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
2401 throw new moodle_exception('shortnametaken', '', '', $data->shortname);
2405 // Check if the idnumber already exists.
2406 if (!empty($data->idnumber)) {
2407 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
2408 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber);
2412 if ($errorcode = course_validate_dates((array)$data)) {
2413 throw new moodle_exception($errorcode);
2416 // Check if timecreated is given.
2417 $data->timecreated = !empty($data->timecreated) ? $data->timecreated : time();
2418 $data->timemodified = $data->timecreated;
2420 // place at beginning of any category
2421 $data->sortorder = 0;
2423 if ($editoroptions) {
2424 // summary text is updated later, we need context to store the files first
2425 $data->summary = '';
2426 $data->summary_format = FORMAT_HTML;
2429 if (!isset($data->visible)) {
2430 // data not from form, add missing visibility info
2431 $data->visible = $category->visible;
2433 $data->visibleold = $data->visible;
2435 $newcourseid = $DB->insert_record('course', $data);
2436 $context = context_course::instance($newcourseid, MUST_EXIST);
2438 if ($editoroptions) {
2439 // Save the files used in the summary editor and store
2440 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2441 $DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid));
2442 $DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid));
2444 if ($overviewfilesoptions = course_overviewfiles_options($newcourseid)) {
2445 // Save the course overviewfiles
2446 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2449 // update course format options
2450 course_get_format($newcourseid)->update_course_format_options($data);
2452 $course = course_get_format($newcourseid)->get_course();
2454 fix_course_sortorder();
2455 // purge appropriate caches in case fix_course_sortorder() did not change anything
2456 cache_helper::purge_by_event('changesincourse');
2458 // Trigger a course created event.
2459 $event = \core\event\course_created::create(array(
2460 'objectid' => $course->id,
2461 'context' => context_course::instance($course->id),
2462 'other' => array('shortname' => $course->shortname,
2463 'fullname' => $course->fullname)
2466 $event->trigger();
2468 // Setup the blocks
2469 blocks_add_default_course_blocks($course);
2471 // Create default section and initial sections if specified (unless they've already been created earlier).
2472 // We do not want to call course_create_sections_if_missing() because to avoid creating course cache.
2473 $numsections = isset($data->numsections) ? $data->numsections : 0;
2474 $existingsections = $DB->get_fieldset_sql('SELECT section from {course_sections} WHERE course = ?', [$newcourseid]);
2475 $newsections = array_diff(range(0, $numsections), $existingsections);
2476 foreach ($newsections as $sectionnum) {
2477 course_create_section($newcourseid, $sectionnum, true);
2480 // Save any custom role names.
2481 save_local_role_names($course->id, (array)$data);
2483 // set up enrolments
2484 enrol_course_updated(true, $course, $data);
2486 // Update course tags.
2487 if (isset($data->tags)) {
2488 core_tag_tag::set_item_tags('core', 'course', $course->id, context_course::instance($course->id), $data->tags);
2491 return $course;
2495 * Update a course.
2497 * Please note this functions does not verify any access control,
2498 * the calling code is responsible for all validation (usually it is the form definition).
2500 * @param object $data - all the data needed for an entry in the 'course' table
2501 * @param array $editoroptions course description editor options
2502 * @return void
2504 function update_course($data, $editoroptions = NULL) {
2505 global $DB, $CFG;
2507 $data->timemodified = time();
2509 // Prevent changes on front page course.
2510 if ($data->id == SITEID) {
2511 throw new moodle_exception('invalidcourse', 'error');
2514 $oldcourse = course_get_format($data->id)->get_course();
2515 $context = context_course::instance($oldcourse->id);
2517 if ($editoroptions) {
2518 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2520 if ($overviewfilesoptions = course_overviewfiles_options($data->id)) {
2521 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2524 // Check we don't have a duplicate shortname.
2525 if (!empty($data->shortname) && $oldcourse->shortname != $data->shortname) {
2526 if ($DB->record_exists_sql('SELECT id from {course} WHERE shortname = ? AND id <> ?', array($data->shortname, $data->id))) {
2527 throw new moodle_exception('shortnametaken', '', '', $data->shortname);
2531 // Check we don't have a duplicate idnumber.
2532 if (!empty($data->idnumber) && $oldcourse->idnumber != $data->idnumber) {
2533 if ($DB->record_exists_sql('SELECT id from {course} WHERE idnumber = ? AND id <> ?', array($data->idnumber, $data->id))) {
2534 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber);
2538 if ($errorcode = course_validate_dates((array)$data)) {
2539 throw new moodle_exception($errorcode);
2542 if (!isset($data->category) or empty($data->category)) {
2543 // prevent nulls and 0 in category field
2544 unset($data->category);
2546 $changesincoursecat = $movecat = (isset($data->category) and $oldcourse->category != $data->category);
2548 if (!isset($data->visible)) {
2549 // data not from form, add missing visibility info
2550 $data->visible = $oldcourse->visible;
2553 if ($data->visible != $oldcourse->visible) {
2554 // reset the visibleold flag when manually hiding/unhiding course
2555 $data->visibleold = $data->visible;
2556 $changesincoursecat = true;
2557 } else {
2558 if ($movecat) {
2559 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category));
2560 if (empty($newcategory->visible)) {
2561 // make sure when moving into hidden category the course is hidden automatically
2562 $data->visible = 0;
2567 // Set newsitems to 0 if format does not support announcements.
2568 if (isset($data->format)) {
2569 $newcourseformat = course_get_format((object)['format' => $data->format]);
2570 if (!$newcourseformat->supports_news()) {
2571 $data->newsitems = 0;
2575 // Update with the new data
2576 $DB->update_record('course', $data);
2577 // make sure the modinfo cache is reset
2578 rebuild_course_cache($data->id);
2580 // update course format options with full course data
2581 course_get_format($data->id)->update_course_format_options($data, $oldcourse);
2583 $course = $DB->get_record('course', array('id'=>$data->id));
2585 if ($movecat) {
2586 $newparent = context_coursecat::instance($course->category);
2587 $context->update_moved($newparent);
2589 $fixcoursesortorder = $movecat || (isset($data->sortorder) && ($oldcourse->sortorder != $data->sortorder));
2590 if ($fixcoursesortorder) {
2591 fix_course_sortorder();
2594 // purge appropriate caches in case fix_course_sortorder() did not change anything
2595 cache_helper::purge_by_event('changesincourse');
2596 if ($changesincoursecat) {
2597 cache_helper::purge_by_event('changesincoursecat');
2600 // Test for and remove blocks which aren't appropriate anymore
2601 blocks_remove_inappropriate($course);
2603 // Save any custom role names.
2604 save_local_role_names($course->id, $data);
2606 // update enrol settings
2607 enrol_course_updated(false, $course, $data);
2609 // Update course tags.
2610 if (isset($data->tags)) {
2611 core_tag_tag::set_item_tags('core', 'course', $course->id, context_course::instance($course->id), $data->tags);
2614 // Trigger a course updated event.
2615 $event = \core\event\course_updated::create(array(
2616 'objectid' => $course->id,
2617 'context' => context_course::instance($course->id),
2618 'other' => array('shortname' => $course->shortname,
2619 'fullname' => $course->fullname)
2622 $event->set_legacy_logdata(array($course->id, 'course', 'update', 'edit.php?id=' . $course->id, $course->id));
2623 $event->trigger();
2625 if ($oldcourse->format !== $course->format) {
2626 // Remove all options stored for the previous format
2627 // We assume that new course format migrated everything it needed watching trigger
2628 // 'course_updated' and in method format_XXX::update_course_format_options()
2629 $DB->delete_records('course_format_options',
2630 array('courseid' => $course->id, 'format' => $oldcourse->format));
2635 * Average number of participants
2636 * @return integer
2638 function average_number_of_participants() {
2639 global $DB, $SITE;
2641 //count total of enrolments for visible course (except front page)
2642 $sql = 'SELECT COUNT(*) FROM (
2643 SELECT DISTINCT ue.userid, e.courseid
2644 FROM {user_enrolments} ue, {enrol} e, {course} c
2645 WHERE ue.enrolid = e.id
2646 AND e.courseid <> :siteid
2647 AND c.id = e.courseid
2648 AND c.visible = 1) total';
2649 $params = array('siteid' => $SITE->id);
2650 $enrolmenttotal = $DB->count_records_sql($sql, $params);
2653 //count total of visible courses (minus front page)
2654 $coursetotal = $DB->count_records('course', array('visible' => 1));
2655 $coursetotal = $coursetotal - 1 ;
2657 //average of enrolment
2658 if (empty($coursetotal)) {
2659 $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->requestcategoryselection)) {
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 * Returns the category where this course request should be created
2913 * Note that we don't check here that user has a capability to view
2914 * hidden categories if he has capabilities 'moodle/site:approvecourse' and
2915 * 'moodle/course:changecategory'
2917 * @return core_course_category
2919 public function get_category() {
2920 global $CFG;
2921 // If the category is not set, if the current user does not have the rights to change the category, or if the
2922 // category does not exist, we set the default category to the course to be approved.
2923 // The system level is used because the capability moodle/site:approvecourse is based on a system level.
2924 if (empty($this->properties->category) || !has_capability('moodle/course:changecategory', context_system::instance()) ||
2925 (!$category = core_course_category::get($this->properties->category, IGNORE_MISSING, true))) {
2926 $category = core_course_category::get($CFG->defaultrequestcategory, IGNORE_MISSING, true);
2928 if (!$category) {
2929 $category = core_course_category::get_default();
2931 return $category;
2935 * This function approves the request turning it into a course
2937 * This function converts the course request into a course, at the same time
2938 * transferring any files used in the summary to the new course and then removing
2939 * the course request and the files associated with it.
2941 * @return int The id of the course that was created from this request
2943 public function approve() {
2944 global $CFG, $DB, $USER;
2946 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
2948 $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted'=>0), '*', MUST_EXIST);
2950 $courseconfig = get_config('moodlecourse');
2952 // Transfer appropriate settings
2953 $data = clone($this->properties);
2954 unset($data->id);
2955 unset($data->reason);
2956 unset($data->requester);
2958 // Set category
2959 $category = $this->get_category();
2960 $data->category = $category->id;
2961 // Set misc settings
2962 $data->requested = 1;
2964 // Apply course default settings
2965 $data->format = $courseconfig->format;
2966 $data->newsitems = $courseconfig->newsitems;
2967 $data->showgrades = $courseconfig->showgrades;
2968 $data->showreports = $courseconfig->showreports;
2969 $data->maxbytes = $courseconfig->maxbytes;
2970 $data->groupmode = $courseconfig->groupmode;
2971 $data->groupmodeforce = $courseconfig->groupmodeforce;
2972 $data->visible = $courseconfig->visible;
2973 $data->visibleold = $data->visible;
2974 $data->lang = $courseconfig->lang;
2975 $data->enablecompletion = $courseconfig->enablecompletion;
2976 $data->numsections = $courseconfig->numsections;
2977 $data->startdate = usergetmidnight(time());
2978 if ($courseconfig->courseenddateenabled) {
2979 $data->enddate = usergetmidnight(time()) + $courseconfig->courseduration;
2982 list($data->fullname, $data->shortname) = restore_dbops::calculate_course_names(0, $data->fullname, $data->shortname);
2984 $course = create_course($data);
2985 $context = context_course::instance($course->id, MUST_EXIST);
2987 // add enrol instances
2988 if (!$DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
2989 if ($manual = enrol_get_plugin('manual')) {
2990 $manual->add_default_instance($course);
2994 // enrol the requester as teacher if necessary
2995 if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
2996 enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid);
2999 $this->delete();
3001 $a = new stdClass();
3002 $a->name = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
3003 $a->url = $CFG->wwwroot.'/course/view.php?id=' . $course->id;
3004 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a), $course->id);
3006 return $course->id;
3010 * Reject a course request
3012 * This function rejects a course request, emailing the requesting user the
3013 * provided notice and then removing the request from the database
3015 * @param string $notice The message to display to the user
3017 public function reject($notice) {
3018 global $USER, $DB;
3019 $user = $DB->get_record('user', array('id' => $this->properties->requester), '*', MUST_EXIST);
3020 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
3021 $this->delete();
3025 * Deletes the course request and any associated files
3027 public function delete() {
3028 global $DB;
3029 $DB->delete_records('course_request', array('id' => $this->properties->id));
3033 * Send a message from one user to another using events_trigger
3035 * @param object $touser
3036 * @param object $fromuser
3037 * @param string $name
3038 * @param string $subject
3039 * @param string $message
3040 * @param int|null $courseid
3042 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message, $courseid = null) {
3043 $eventdata = new \core\message\message();
3044 $eventdata->courseid = empty($courseid) ? SITEID : $courseid;
3045 $eventdata->component = 'moodle';
3046 $eventdata->name = $name;
3047 $eventdata->userfrom = $fromuser;
3048 $eventdata->userto = $touser;
3049 $eventdata->subject = $subject;
3050 $eventdata->fullmessage = $message;
3051 $eventdata->fullmessageformat = FORMAT_PLAIN;
3052 $eventdata->fullmessagehtml = '';
3053 $eventdata->smallmessage = '';
3054 $eventdata->notification = 1;
3055 message_send($eventdata);
3060 * Return a list of page types
3061 * @param string $pagetype current page type
3062 * @param context $parentcontext Block's parent context
3063 * @param context $currentcontext Current context of block
3064 * @return array array of page types
3066 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
3067 if ($pagetype === 'course-index' || $pagetype === 'course-index-category') {
3068 // For courses and categories browsing pages (/course/index.php) add option to show on ANY category page
3069 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
3070 'course-index-*' => get_string('page-course-index-x', 'pagetype'),
3072 } else if ($currentcontext && (!($coursecontext = $currentcontext->get_course_context(false)) || $coursecontext->instanceid == SITEID)) {
3073 // We know for sure that despite pagetype starts with 'course-' this is not a page in course context (i.e. /course/search.php, etc.)
3074 $pagetypes = array('*' => get_string('page-x', 'pagetype'));
3075 } else {
3076 // Otherwise consider it a page inside a course even if $currentcontext is null
3077 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
3078 'course-*' => get_string('page-course-x', 'pagetype'),
3079 'course-view-*' => get_string('page-course-view-x', 'pagetype')
3082 return $pagetypes;
3086 * Determine whether course ajax should be enabled for the specified course
3088 * @param stdClass $course The course to test against
3089 * @return boolean Whether course ajax is enabled or note
3091 function course_ajax_enabled($course) {
3092 global $CFG, $PAGE, $SITE;
3094 // The user must be editing for AJAX to be included
3095 if (!$PAGE->user_is_editing()) {
3096 return false;
3099 // Check that the theme suports
3100 if (!$PAGE->theme->enablecourseajax) {
3101 return false;
3104 // Check that the course format supports ajax functionality
3105 // The site 'format' doesn't have information on course format support
3106 if ($SITE->id !== $course->id) {
3107 $courseformatajaxsupport = course_format_ajax_support($course->format);
3108 if (!$courseformatajaxsupport->capable) {
3109 return false;
3113 // All conditions have been met so course ajax should be enabled
3114 return true;
3118 * Include the relevant javascript and language strings for the resource
3119 * toolbox YUI module
3121 * @param integer $id The ID of the course being applied to
3122 * @param array $usedmodules An array containing the names of the modules in use on the page
3123 * @param array $enabledmodules An array containing the names of the enabled (visible) modules on this site
3124 * @param stdClass $config An object containing configuration parameters for ajax modules including:
3125 * * resourceurl The URL to post changes to for resource changes
3126 * * sectionurl The URL to post changes to for section changes
3127 * * pageparams Additional parameters to pass through in the post
3128 * @return bool
3130 function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) {
3131 global $CFG, $PAGE, $SITE;
3133 // Ensure that ajax should be included
3134 if (!course_ajax_enabled($course)) {
3135 return false;
3138 if (!$config) {
3139 $config = new stdClass();
3142 // The URL to use for resource changes
3143 if (!isset($config->resourceurl)) {
3144 $config->resourceurl = '/course/rest.php';
3147 // The URL to use for section changes
3148 if (!isset($config->sectionurl)) {
3149 $config->sectionurl = '/course/rest.php';
3152 // Any additional parameters which need to be included on page submission
3153 if (!isset($config->pageparams)) {
3154 $config->pageparams = array();
3157 // Include course dragdrop
3158 if (course_format_uses_sections($course->format)) {
3159 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_section_dragdrop',
3160 array(array(
3161 'courseid' => $course->id,
3162 'ajaxurl' => $config->sectionurl,
3163 'config' => $config,
3164 )), null, true);
3166 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_resource_dragdrop',
3167 array(array(
3168 'courseid' => $course->id,
3169 'ajaxurl' => $config->resourceurl,
3170 'config' => $config,
3171 )), null, true);
3174 // Require various strings for the command toolbox
3175 $PAGE->requires->strings_for_js(array(
3176 'moveleft',
3177 'deletechecktype',
3178 'deletechecktypename',
3179 'edittitle',
3180 'edittitleinstructions',
3181 'show',
3182 'hide',
3183 'highlight',
3184 'highlightoff',
3185 'groupsnone',
3186 'groupsvisible',
3187 'groupsseparate',
3188 'clicktochangeinbrackets',
3189 'markthistopic',
3190 'markedthistopic',
3191 'movesection',
3192 'movecoursemodule',
3193 'movecoursesection',
3194 'movecontent',
3195 'tocontent',
3196 'emptydragdropregion',
3197 'afterresource',
3198 'aftersection',
3199 'totopofsection',
3200 ), 'moodle');
3202 // Include section-specific strings for formats which support sections.
3203 if (course_format_uses_sections($course->format)) {
3204 $PAGE->requires->strings_for_js(array(
3205 'showfromothers',
3206 'hidefromothers',
3207 ), 'format_' . $course->format);
3210 // For confirming resource deletion we need the name of the module in question
3211 foreach ($usedmodules as $module => $modname) {
3212 $PAGE->requires->string_for_js('pluginname', $module);
3215 // Load drag and drop upload AJAX.
3216 require_once($CFG->dirroot.'/course/dnduploadlib.php');
3217 dndupload_add_to_course($course, $enabledmodules);
3219 $PAGE->requires->js_call_amd('core_course/actions', 'initCoursePage', array($course->format));
3221 return true;
3225 * Returns the sorted list of available course formats, filtered by enabled if necessary
3227 * @param bool $enabledonly return only formats that are enabled
3228 * @return array array of sorted format names
3230 function get_sorted_course_formats($enabledonly = false) {
3231 global $CFG;
3232 $formats = core_component::get_plugin_list('format');
3234 if (!empty($CFG->format_plugins_sortorder)) {
3235 $order = explode(',', $CFG->format_plugins_sortorder);
3236 $order = array_merge(array_intersect($order, array_keys($formats)),
3237 array_diff(array_keys($formats), $order));
3238 } else {
3239 $order = array_keys($formats);
3241 if (!$enabledonly) {
3242 return $order;
3244 $sortedformats = array();
3245 foreach ($order as $formatname) {
3246 if (!get_config('format_'.$formatname, 'disabled')) {
3247 $sortedformats[] = $formatname;
3250 return $sortedformats;
3254 * The URL to use for the specified course (with section)
3256 * @param int|stdClass $courseorid The course to get the section name for (either object or just course id)
3257 * @param int|stdClass $section Section object from database or just field course_sections.section
3258 * if omitted the course view page is returned
3259 * @param array $options options for view URL. At the moment core uses:
3260 * 'navigation' (bool) if true and section has no separate page, the function returns null
3261 * 'sr' (int) used by multipage formats to specify to which section to return
3262 * @return moodle_url The url of course
3264 function course_get_url($courseorid, $section = null, $options = array()) {
3265 return course_get_format($courseorid)->get_view_url($section, $options);
3269 * Create a module.
3271 * It includes:
3272 * - capability checks and other checks
3273 * - create the module from the module info
3275 * @param object $module
3276 * @return object the created module info
3277 * @throws moodle_exception if user is not allowed to perform the action or module is not allowed in this course
3279 function create_module($moduleinfo) {
3280 global $DB, $CFG;
3282 require_once($CFG->dirroot . '/course/modlib.php');
3284 // Check manadatory attributs.
3285 $mandatoryfields = array('modulename', 'course', 'section', 'visible');
3286 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
3287 $mandatoryfields[] = 'introeditor';
3289 foreach($mandatoryfields as $mandatoryfield) {
3290 if (!isset($moduleinfo->{$mandatoryfield})) {
3291 throw new moodle_exception('createmodulemissingattribut', '', '', $mandatoryfield);
3295 // Some additional checks (capability / existing instances).
3296 $course = $DB->get_record('course', array('id'=>$moduleinfo->course), '*', MUST_EXIST);
3297 list($module, $context, $cw) = can_add_moduleinfo($course, $moduleinfo->modulename, $moduleinfo->section);
3299 // Add the module.
3300 $moduleinfo->module = $module->id;
3301 $moduleinfo = add_moduleinfo($moduleinfo, $course, null);
3303 return $moduleinfo;
3307 * Update a module.
3309 * It includes:
3310 * - capability and other checks
3311 * - update the module
3313 * @param object $module
3314 * @return object the updated module info
3315 * @throws moodle_exception if current user is not allowed to update the module
3317 function update_module($moduleinfo) {
3318 global $DB, $CFG;
3320 require_once($CFG->dirroot . '/course/modlib.php');
3322 // Check the course module exists.
3323 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule, 0, false, MUST_EXIST);
3325 // Check the course exists.
3326 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
3328 // Some checks (capaibility / existing instances).
3329 list($cm, $context, $module, $data, $cw) = can_update_moduleinfo($cm);
3331 // Retrieve few information needed by update_moduleinfo.
3332 $moduleinfo->modulename = $cm->modname;
3333 if (!isset($moduleinfo->scale)) {
3334 $moduleinfo->scale = 0;
3336 $moduleinfo->type = 'mod';
3338 // Update the module.
3339 list($cm, $moduleinfo) = update_moduleinfo($cm, $moduleinfo, $course, null);
3341 return $moduleinfo;
3345 * Duplicate a module on the course for ajax.
3347 * @see mod_duplicate_module()
3348 * @param object $course The course
3349 * @param object $cm The course module to duplicate
3350 * @param int $sr The section to link back to (used for creating the links)
3351 * @throws moodle_exception if the plugin doesn't support duplication
3352 * @return Object containing:
3353 * - fullcontent: The HTML markup for the created CM
3354 * - cmid: The CMID of the newly created CM
3355 * - redirect: Whether to trigger a redirect following this change
3357 function mod_duplicate_activity($course, $cm, $sr = null) {
3358 global $PAGE;
3360 $newcm = duplicate_module($course, $cm);
3362 $resp = new stdClass();
3363 if ($newcm) {
3364 $courserenderer = $PAGE->get_renderer('core', 'course');
3365 $completioninfo = new completion_info($course);
3366 $modulehtml = $courserenderer->course_section_cm($course, $completioninfo,
3367 $newcm, null, array());
3369 $resp->fullcontent = $courserenderer->course_section_cm_list_item($course, $completioninfo, $newcm, $sr);
3370 $resp->cmid = $newcm->id;
3371 } else {
3372 // Trigger a redirect.
3373 $resp->redirect = true;
3375 return $resp;
3379 * Api to duplicate a module.
3381 * @param object $course course object.
3382 * @param object $cm course module object to be duplicated.
3383 * @since Moodle 2.8
3385 * @throws Exception
3386 * @throws coding_exception
3387 * @throws moodle_exception
3388 * @throws restore_controller_exception
3390 * @return cm_info|null cminfo object if we sucessfully duplicated the mod and found the new cm.
3392 function duplicate_module($course, $cm) {
3393 global $CFG, $DB, $USER;
3394 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
3395 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
3396 require_once($CFG->libdir . '/filelib.php');
3398 $a = new stdClass();
3399 $a->modtype = get_string('modulename', $cm->modname);
3400 $a->modname = format_string($cm->name);
3402 if (!plugin_supports('mod', $cm->modname, FEATURE_BACKUP_MOODLE2)) {
3403 throw new moodle_exception('duplicatenosupport', 'error', '', $a);
3406 // Backup the activity.
3408 $bc = new backup_controller(backup::TYPE_1ACTIVITY, $cm->id, backup::FORMAT_MOODLE,
3409 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
3411 $backupid = $bc->get_backupid();
3412 $backupbasepath = $bc->get_plan()->get_basepath();
3414 $bc->execute_plan();
3416 $bc->destroy();
3418 // Restore the backup immediately.
3420 $rc = new restore_controller($backupid, $course->id,
3421 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, backup::TARGET_CURRENT_ADDING);
3423 $cmcontext = context_module::instance($cm->id);
3424 if (!$rc->execute_precheck()) {
3425 $precheckresults = $rc->get_precheck_results();
3426 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
3427 if (empty($CFG->keeptempdirectoriesonbackup)) {
3428 fulldelete($backupbasepath);
3433 $rc->execute_plan();
3435 // Now a bit hacky part follows - we try to get the cmid of the newly
3436 // restored copy of the module.
3437 $newcmid = null;
3438 $tasks = $rc->get_plan()->get_tasks();
3439 foreach ($tasks as $task) {
3440 if (is_subclass_of($task, 'restore_activity_task')) {
3441 if ($task->get_old_contextid() == $cmcontext->id) {
3442 $newcmid = $task->get_moduleid();
3443 break;
3448 $rc->destroy();
3450 if (empty($CFG->keeptempdirectoriesonbackup)) {
3451 fulldelete($backupbasepath);
3454 // If we know the cmid of the new course module, let us move it
3455 // right below the original one. otherwise it will stay at the
3456 // end of the section.
3457 if ($newcmid) {
3458 // Proceed with activity renaming before everything else. We don't use APIs here to avoid
3459 // triggering a lot of create/update duplicated events.
3460 $newcm = get_coursemodule_from_id($cm->modname, $newcmid, $cm->course);
3461 // Add ' (copy)' to duplicates. Note we don't cleanup or validate lengths here. It comes
3462 // from original name that was valid, so the copy should be too.
3463 $newname = get_string('duplicatedmodule', 'moodle', $newcm->name);
3464 $DB->set_field($cm->modname, 'name', $newname, ['id' => $newcm->instance]);
3466 $section = $DB->get_record('course_sections', array('id' => $cm->section, 'course' => $cm->course));
3467 $modarray = explode(",", trim($section->sequence));
3468 $cmindex = array_search($cm->id, $modarray);
3469 if ($cmindex !== false && $cmindex < count($modarray) - 1) {
3470 moveto_module($newcm, $section, $modarray[$cmindex + 1]);
3473 // Update calendar events with the duplicated module.
3474 // The following line is to be removed in MDL-58906.
3475 course_module_update_calendar_events($newcm->modname, null, $newcm);
3477 // Trigger course module created event. We can trigger the event only if we know the newcmid.
3478 $newcm = get_fast_modinfo($cm->course)->get_cm($newcmid);
3479 $event = \core\event\course_module_created::create_from_cm($newcm);
3480 $event->trigger();
3483 return isset($newcm) ? $newcm : null;
3487 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3488 * Sorts by descending order of time.
3490 * @param stdClass $a First object
3491 * @param stdClass $b Second object
3492 * @return int 0,1,-1 representing the order
3494 function compare_activities_by_time_desc($a, $b) {
3495 // Make sure the activities actually have a timestamp property.
3496 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3497 return 0;
3499 // We treat instances without timestamp as if they have a timestamp of 0.
3500 if ((!property_exists($a, 'timestamp')) && (property_exists($b,'timestamp'))) {
3501 return 1;
3503 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3504 return -1;
3506 if ($a->timestamp == $b->timestamp) {
3507 return 0;
3509 return ($a->timestamp > $b->timestamp) ? -1 : 1;
3513 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3514 * Sorts by ascending order of time.
3516 * @param stdClass $a First object
3517 * @param stdClass $b Second object
3518 * @return int 0,1,-1 representing the order
3520 function compare_activities_by_time_asc($a, $b) {
3521 // Make sure the activities actually have a timestamp property.
3522 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3523 return 0;
3525 // We treat instances without timestamp as if they have a timestamp of 0.
3526 if ((!property_exists($a, 'timestamp')) && (property_exists($b, 'timestamp'))) {
3527 return -1;
3529 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3530 return 1;
3532 if ($a->timestamp == $b->timestamp) {
3533 return 0;
3535 return ($a->timestamp < $b->timestamp) ? -1 : 1;
3539 * Changes the visibility of a course.
3541 * @param int $courseid The course to change.
3542 * @param bool $show True to make it visible, false otherwise.
3543 * @return bool
3545 function course_change_visibility($courseid, $show = true) {
3546 $course = new stdClass;
3547 $course->id = $courseid;
3548 $course->visible = ($show) ? '1' : '0';
3549 $course->visibleold = $course->visible;
3550 update_course($course);
3551 return true;
3555 * Changes the course sortorder by one, moving it up or down one in respect to sort order.
3557 * @param stdClass|core_course_list_element $course
3558 * @param bool $up If set to true the course will be moved up one. Otherwise down one.
3559 * @return bool
3561 function course_change_sortorder_by_one($course, $up) {
3562 global $DB;
3563 $params = array($course->sortorder, $course->category);
3564 if ($up) {
3565 $select = 'sortorder < ? AND category = ?';
3566 $sort = 'sortorder DESC';
3567 } else {
3568 $select = 'sortorder > ? AND category = ?';
3569 $sort = 'sortorder ASC';
3571 fix_course_sortorder();
3572 $swapcourse = $DB->get_records_select('course', $select, $params, $sort, '*', 0, 1);
3573 if ($swapcourse) {
3574 $swapcourse = reset($swapcourse);
3575 $DB->set_field('course', 'sortorder', $swapcourse->sortorder, array('id' => $course->id));
3576 $DB->set_field('course', 'sortorder', $course->sortorder, array('id' => $swapcourse->id));
3577 // Finally reorder courses.
3578 fix_course_sortorder();
3579 cache_helper::purge_by_event('changesincourse');
3580 return true;
3582 return false;
3586 * Changes the sort order of courses in a category so that the first course appears after the second.
3588 * @param int|stdClass $courseorid The course to focus on.
3589 * @param int $moveaftercourseid The course to shifter after or 0 if you want it to be the first course in the category.
3590 * @return bool
3592 function course_change_sortorder_after_course($courseorid, $moveaftercourseid) {
3593 global $DB;
3595 if (!is_object($courseorid)) {
3596 $course = get_course($courseorid);
3597 } else {
3598 $course = $courseorid;
3601 if ((int)$moveaftercourseid === 0) {
3602 // We've moving the course to the start of the queue.
3603 $sql = 'SELECT sortorder
3604 FROM {course}
3605 WHERE category = :categoryid
3606 ORDER BY sortorder';
3607 $params = array(
3608 'categoryid' => $course->category
3610 $sortorder = $DB->get_field_sql($sql, $params, IGNORE_MULTIPLE);
3612 $sql = 'UPDATE {course}
3613 SET sortorder = sortorder + 1
3614 WHERE category = :categoryid
3615 AND id <> :id';
3616 $params = array(
3617 'categoryid' => $course->category,
3618 'id' => $course->id,
3620 $DB->execute($sql, $params);
3621 $DB->set_field('course', 'sortorder', $sortorder, array('id' => $course->id));
3622 } else if ($course->id === $moveaftercourseid) {
3623 // They're the same - moronic.
3624 debugging("Invalid move after course given.", DEBUG_DEVELOPER);
3625 return false;
3626 } else {
3627 // Moving this course after the given course. It could be before it could be after.
3628 $moveaftercourse = get_course($moveaftercourseid);
3629 if ($course->category !== $moveaftercourse->category) {
3630 debugging("Cannot re-order courses. The given courses do not belong to the same category.", DEBUG_DEVELOPER);
3631 return false;
3633 // Increment all courses in the same category that are ordered after the moveafter course.
3634 // This makes a space for the course we're moving.
3635 $sql = 'UPDATE {course}
3636 SET sortorder = sortorder + 1
3637 WHERE category = :categoryid
3638 AND sortorder > :sortorder';
3639 $params = array(
3640 'categoryid' => $moveaftercourse->category,
3641 'sortorder' => $moveaftercourse->sortorder
3643 $DB->execute($sql, $params);
3644 $DB->set_field('course', 'sortorder', $moveaftercourse->sortorder + 1, array('id' => $course->id));
3646 fix_course_sortorder();
3647 cache_helper::purge_by_event('changesincourse');
3648 return true;
3652 * Trigger course viewed event. This API function is used when course view actions happens,
3653 * usually in course/view.php but also in external functions.
3655 * @param stdClass $context course context object
3656 * @param int $sectionnumber section number
3657 * @since Moodle 2.9
3659 function course_view($context, $sectionnumber = 0) {
3661 $eventdata = array('context' => $context);
3663 if (!empty($sectionnumber)) {
3664 $eventdata['other']['coursesectionnumber'] = $sectionnumber;
3667 $event = \core\event\course_viewed::create($eventdata);
3668 $event->trigger();
3670 user_accesstime_log($context->instanceid);
3674 * Returns courses tagged with a specified tag.
3676 * @param core_tag_tag $tag
3677 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
3678 * are displayed on the page and the per-page limit may be bigger
3679 * @param int $fromctx context id where the link was displayed, may be used by callbacks
3680 * to display items in the same context first
3681 * @param int $ctx context id where to search for records
3682 * @param bool $rec search in subcontexts as well
3683 * @param int $page 0-based number of page being displayed
3684 * @return \core_tag\output\tagindex
3686 function course_get_tagged_courses($tag, $exclusivemode = false, $fromctx = 0, $ctx = 0, $rec = 1, $page = 0) {
3687 global $CFG, $PAGE;
3689 $perpage = $exclusivemode ? $CFG->coursesperpage : 5;
3690 $displayoptions = array(
3691 'limit' => $perpage,
3692 'offset' => $page * $perpage,
3693 'viewmoreurl' => null,
3696 $courserenderer = $PAGE->get_renderer('core', 'course');
3697 $totalcount = core_course_category::search_courses_count(array('tagid' => $tag->id, 'ctx' => $ctx, 'rec' => $rec));
3698 $content = $courserenderer->tagged_courses($tag->id, $exclusivemode, $ctx, $rec, $displayoptions);
3699 $totalpages = ceil($totalcount / $perpage);
3701 return new core_tag\output\tagindex($tag, 'core', 'course', $content,
3702 $exclusivemode, $fromctx, $ctx, $rec, $page, $totalpages);
3706 * Implements callback inplace_editable() allowing to edit values in-place
3708 * @param string $itemtype
3709 * @param int $itemid
3710 * @param mixed $newvalue
3711 * @return \core\output\inplace_editable
3713 function core_course_inplace_editable($itemtype, $itemid, $newvalue) {
3714 if ($itemtype === 'activityname') {
3715 return \core_course\output\course_module_name::update($itemid, $newvalue);
3720 * This function calculates the minimum and maximum cutoff values for the timestart of
3721 * the given event.
3723 * It will return an array with two values, the first being the minimum cutoff value and
3724 * the second being the maximum cutoff value. Either or both values can be null, which
3725 * indicates there is no minimum or maximum, respectively.
3727 * If a cutoff is required then the function must return an array containing the cutoff
3728 * timestamp and error string to display to the user if the cutoff value is violated.
3730 * A minimum and maximum cutoff return value will look like:
3732 * [1505704373, 'The date must be after this date'],
3733 * [1506741172, 'The date must be before this date']
3736 * @param calendar_event $event The calendar event to get the time range for
3737 * @param stdClass $course The course object to get the range from
3738 * @return array Returns an array with min and max date.
3740 function core_course_core_calendar_get_valid_event_timestart_range(\calendar_event $event, $course) {
3741 $mindate = null;
3742 $maxdate = null;
3744 if ($course->startdate) {
3745 $mindate = [
3746 $course->startdate,
3747 get_string('errorbeforecoursestart', 'calendar')
3751 return [$mindate, $maxdate];
3755 * Returns course modules tagged with a specified tag ready for output on tag/index.php page
3757 * This is a callback used by the tag area core/course_modules to search for course modules
3758 * tagged with a specific tag.
3760 * @param core_tag_tag $tag
3761 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
3762 * are displayed on the page and the per-page limit may be bigger
3763 * @param int $fromcontextid context id where the link was displayed, may be used by callbacks
3764 * to display items in the same context first
3765 * @param int $contextid context id where to search for records
3766 * @param bool $recursivecontext search in subcontexts as well
3767 * @param int $page 0-based number of page being displayed
3768 * @return \core_tag\output\tagindex
3770 function course_get_tagged_course_modules($tag, $exclusivemode = false, $fromcontextid = 0, $contextid = 0,
3771 $recursivecontext = 1, $page = 0) {
3772 global $OUTPUT;
3773 $perpage = $exclusivemode ? 20 : 5;
3775 // Build select query.
3776 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
3777 $query = "SELECT cm.id AS cmid, c.id AS courseid, $ctxselect
3778 FROM {course_modules} cm
3779 JOIN {tag_instance} tt ON cm.id = tt.itemid
3780 JOIN {course} c ON cm.course = c.id
3781 JOIN {context} ctx ON ctx.instanceid = cm.id AND ctx.contextlevel = :coursemodulecontextlevel
3782 WHERE tt.itemtype = :itemtype AND tt.tagid = :tagid AND tt.component = :component
3783 AND cm.deletioninprogress = 0
3784 AND c.id %COURSEFILTER% AND cm.id %ITEMFILTER%";
3786 $params = array('itemtype' => 'course_modules', 'tagid' => $tag->id, 'component' => 'core',
3787 'coursemodulecontextlevel' => CONTEXT_MODULE);
3788 if ($contextid) {
3789 $context = context::instance_by_id($contextid);
3790 $query .= $recursivecontext ? ' AND (ctx.id = :contextid OR ctx.path LIKE :path)' : ' AND ctx.id = :contextid';
3791 $params['contextid'] = $context->id;
3792 $params['path'] = $context->path.'/%';
3795 $query .= ' ORDER BY';
3796 if ($fromcontextid) {
3797 // In order-clause specify that modules from inside "fromctx" context should be returned first.
3798 $fromcontext = context::instance_by_id($fromcontextid);
3799 $query .= ' (CASE WHEN ctx.id = :fromcontextid OR ctx.path LIKE :frompath THEN 0 ELSE 1 END),';
3800 $params['fromcontextid'] = $fromcontext->id;
3801 $params['frompath'] = $fromcontext->path.'/%';
3803 $query .= ' c.sortorder, cm.id';
3804 $totalpages = $page + 1;
3806 // Use core_tag_index_builder to build and filter the list of items.
3807 // Request one item more than we need so we know if next page exists.
3808 $builder = new core_tag_index_builder('core', 'course_modules', $query, $params, $page * $perpage, $perpage + 1);
3809 while ($item = $builder->has_item_that_needs_access_check()) {
3810 context_helper::preload_from_record($item);
3811 $courseid = $item->courseid;
3812 if (!$builder->can_access_course($courseid)) {
3813 $builder->set_accessible($item, false);
3814 continue;
3816 $modinfo = get_fast_modinfo($builder->get_course($courseid));
3817 // Set accessibility of this item and all other items in the same course.
3818 $builder->walk(function ($taggeditem) use ($courseid, $modinfo, $builder) {
3819 if ($taggeditem->courseid == $courseid) {
3820 $cm = $modinfo->get_cm($taggeditem->cmid);
3821 $builder->set_accessible($taggeditem, $cm->uservisible);
3826 $items = $builder->get_items();
3827 if (count($items) > $perpage) {
3828 $totalpages = $page + 2; // We don't need exact page count, just indicate that the next page exists.
3829 array_pop($items);
3832 // Build the display contents.
3833 if ($items) {
3834 $tagfeed = new core_tag\output\tagfeed();
3835 foreach ($items as $item) {
3836 context_helper::preload_from_record($item);
3837 $course = $builder->get_course($item->courseid);
3838 $modinfo = get_fast_modinfo($course);
3839 $cm = $modinfo->get_cm($item->cmid);
3840 $courseurl = course_get_url($item->courseid, $cm->sectionnum);
3841 $cmname = $cm->get_formatted_name();
3842 if (!$exclusivemode) {
3843 $cmname = shorten_text($cmname, 100);
3845 $cmname = html_writer::link($cm->url?:$courseurl, $cmname);
3846 $coursename = format_string($course->fullname, true,
3847 array('context' => context_course::instance($item->courseid)));
3848 $coursename = html_writer::link($courseurl, $coursename);
3849 $icon = html_writer::empty_tag('img', array('src' => $cm->get_icon_url()));
3850 $tagfeed->add($icon, $cmname, $coursename);
3853 $content = $OUTPUT->render_from_template('core_tag/tagfeed',
3854 $tagfeed->export_for_template($OUTPUT));
3856 return new core_tag\output\tagindex($tag, 'core', 'course_modules', $content,
3857 $exclusivemode, $fromcontextid, $contextid, $recursivecontext, $page, $totalpages);
3862 * Return an object with the list of navigation options in a course that are avaialable or not for the current user.
3863 * This function also handles the frontpage course.
3865 * @param stdClass $context context object (it can be a course context or the system context for frontpage settings)
3866 * @param stdClass $course the course where the settings are being rendered
3867 * @return stdClass the navigation options in a course and their availability status
3868 * @since Moodle 3.2
3870 function course_get_user_navigation_options($context, $course = null) {
3871 global $CFG;
3873 $isloggedin = isloggedin();
3874 $isguestuser = isguestuser();
3875 $isfrontpage = $context->contextlevel == CONTEXT_SYSTEM;
3877 if ($isfrontpage) {
3878 $sitecontext = $context;
3879 } else {
3880 $sitecontext = context_system::instance();
3883 // Sets defaults for all options.
3884 $options = (object) [
3885 'badges' => false,
3886 'blogs' => false,
3887 'calendar' => false,
3888 'competencies' => false,
3889 'grades' => false,
3890 'notes' => false,
3891 'participants' => false,
3892 'search' => false,
3893 'tags' => false,
3896 $options->blogs = !empty($CFG->enableblogs) &&
3897 ($CFG->bloglevel == BLOG_GLOBAL_LEVEL ||
3898 ($CFG->bloglevel == BLOG_SITE_LEVEL and ($isloggedin and !$isguestuser)))
3899 && has_capability('moodle/blog:view', $sitecontext);
3901 $options->notes = !empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $context);
3903 // Frontpage settings?
3904 if ($isfrontpage) {
3905 // We are on the front page, so make sure we use the proper capability (site:viewparticipants).
3906 $options->participants = course_can_view_participants($sitecontext);
3907 $options->badges = !empty($CFG->enablebadges) && has_capability('moodle/badges:viewbadges', $sitecontext);
3908 $options->tags = !empty($CFG->usetags) && $isloggedin;
3909 $options->search = !empty($CFG->enableglobalsearch) && has_capability('moodle/search:query', $sitecontext);
3910 $options->calendar = $isloggedin;
3911 } else {
3912 // We are in a course, so make sure we use the proper capability (course:viewparticipants).
3913 $options->participants = course_can_view_participants($context);
3914 $options->badges = !empty($CFG->enablebadges) && !empty($CFG->badges_allowcoursebadges) &&
3915 has_capability('moodle/badges:viewbadges', $context);
3916 // Add view grade report is permitted.
3917 $grades = false;
3919 if (has_capability('moodle/grade:viewall', $context)) {
3920 $grades = true;
3921 } else if (!empty($course->showgrades)) {
3922 $reports = core_component::get_plugin_list('gradereport');
3923 if (is_array($reports) && count($reports) > 0) { // Get all installed reports.
3924 arsort($reports); // User is last, we want to test it first.
3925 foreach ($reports as $plugin => $plugindir) {
3926 if (has_capability('gradereport/'.$plugin.':view', $context)) {
3927 // Stop when the first visible plugin is found.
3928 $grades = true;
3929 break;
3934 $options->grades = $grades;
3937 if (\core_competency\api::is_enabled()) {
3938 $capabilities = array('moodle/competency:coursecompetencyview', 'moodle/competency:coursecompetencymanage');
3939 $options->competencies = has_any_capability($capabilities, $context);
3941 return $options;
3945 * Return an object with the list of administration options in a course that are available or not for the current user.
3946 * This function also handles the frontpage settings.
3948 * @param stdClass $course course object (for frontpage it should be a clone of $SITE)
3949 * @param stdClass $context context object (course context)
3950 * @return stdClass the administration options in a course and their availability status
3951 * @since Moodle 3.2
3953 function course_get_user_administration_options($course, $context) {
3954 global $CFG;
3955 $isfrontpage = $course->id == SITEID;
3956 $completionenabled = $CFG->enablecompletion && $course->enablecompletion;
3957 $hascompletiontabs = count(core_completion\manager::get_available_completion_tabs($course, $context)) > 0;
3959 $options = new stdClass;
3960 $options->update = has_capability('moodle/course:update', $context);
3961 $options->editcompletion = $CFG->enablecompletion &&
3962 $course->enablecompletion &&
3963 ($options->update || $hascompletiontabs);
3964 $options->filters = has_capability('moodle/filter:manage', $context) &&
3965 count(filter_get_available_in_context($context)) > 0;
3966 $options->reports = has_capability('moodle/site:viewreports', $context);
3967 $options->backup = has_capability('moodle/backup:backupcourse', $context);
3968 $options->restore = has_capability('moodle/restore:restorecourse', $context);
3969 $options->files = ($course->legacyfiles == 2 && has_capability('moodle/course:managefiles', $context));
3971 if (!$isfrontpage) {
3972 $options->tags = has_capability('moodle/course:tag', $context);
3973 $options->gradebook = has_capability('moodle/grade:manage', $context);
3974 $options->outcomes = !empty($CFG->enableoutcomes) && has_capability('moodle/course:update', $context);
3975 $options->badges = !empty($CFG->enablebadges);
3976 $options->import = has_capability('moodle/restore:restoretargetimport', $context);
3977 $options->publish = has_capability('moodle/course:publish', $context);
3978 $options->reset = has_capability('moodle/course:reset', $context);
3979 $options->roles = has_capability('moodle/role:switchroles', $context);
3980 } else {
3981 // Set default options to false.
3982 $listofoptions = array('tags', 'gradebook', 'outcomes', 'badges', 'import', 'publish', 'reset', 'roles', 'grades');
3984 foreach ($listofoptions as $option) {
3985 $options->$option = false;
3989 return $options;
3993 * Validates course start and end dates.
3995 * Checks that the end course date is not greater than the start course date.
3997 * $coursedata['startdate'] or $coursedata['enddate'] may not be set, it depends on the form and user input.
3999 * @param array $coursedata May contain startdate and enddate timestamps, depends on the user input.
4000 * @return mixed False if everything alright, error codes otherwise.
4002 function course_validate_dates($coursedata) {
4004 // If both start and end dates are set end date should be later than the start date.
4005 if (!empty($coursedata['startdate']) && !empty($coursedata['enddate']) &&
4006 ($coursedata['enddate'] < $coursedata['startdate'])) {
4007 return 'enddatebeforestartdate';
4010 // If start date is not set end date can not be set.
4011 if (empty($coursedata['startdate']) && !empty($coursedata['enddate'])) {
4012 return 'nostartdatenoenddate';
4015 return false;
4019 * Check for course updates in the given context level instances (only modules supported right Now)
4021 * @param stdClass $course course object
4022 * @param array $tocheck instances to check for updates
4023 * @param array $filter check only for updates in these areas
4024 * @return array list of warnings and instances with updates information
4025 * @since Moodle 3.2
4027 function course_check_updates($course, $tocheck, $filter = array()) {
4028 global $CFG, $DB;
4030 $instances = array();
4031 $warnings = array();
4032 $modulescallbacksupport = array();
4033 $modinfo = get_fast_modinfo($course);
4035 $supportedplugins = get_plugin_list_with_function('mod', 'check_updates_since');
4037 // Check instances.
4038 foreach ($tocheck as $instance) {
4039 if ($instance['contextlevel'] == 'module') {
4040 // Check module visibility.
4041 try {
4042 $cm = $modinfo->get_cm($instance['id']);
4043 } catch (Exception $e) {
4044 $warnings[] = array(
4045 'item' => 'module',
4046 'itemid' => $instance['id'],
4047 'warningcode' => 'cmidnotincourse',
4048 'message' => 'This module id does not belong to this course.'
4050 continue;
4053 if (!$cm->uservisible) {
4054 $warnings[] = array(
4055 'item' => 'module',
4056 'itemid' => $instance['id'],
4057 'warningcode' => 'nonuservisible',
4058 'message' => 'You don\'t have access to this module.'
4060 continue;
4062 if (empty($supportedplugins['mod_' . $cm->modname])) {
4063 $warnings[] = array(
4064 'item' => 'module',
4065 'itemid' => $instance['id'],
4066 'warningcode' => 'missingcallback',
4067 'message' => 'This module does not implement the check_updates_since callback: ' . $instance['contextlevel'],
4069 continue;
4071 // Retrieve the module instance.
4072 $instances[] = array(
4073 'contextlevel' => $instance['contextlevel'],
4074 'id' => $instance['id'],
4075 'updates' => call_user_func($cm->modname . '_check_updates_since', $cm, $instance['since'], $filter)
4078 } else {
4079 $warnings[] = array(
4080 'item' => 'contextlevel',
4081 'itemid' => $instance['id'],
4082 'warningcode' => 'contextlevelnotsupported',
4083 'message' => 'Context level not yet supported ' . $instance['contextlevel'],
4087 return array($instances, $warnings);
4091 * This function classifies a course as past, in progress or future.
4093 * This function may incur a DB hit to calculate course completion.
4094 * @param stdClass $course Course record
4095 * @param stdClass $user User record (optional - defaults to $USER).
4096 * @param completion_info $completioninfo Completion record for the user (optional - will be fetched if required).
4097 * @return string (one of COURSE_TIMELINE_FUTURE, COURSE_TIMELINE_INPROGRESS or COURSE_TIMELINE_PAST)
4099 function course_classify_for_timeline($course, $user = null, $completioninfo = null) {
4100 global $USER;
4102 if ($user == null) {
4103 $user = $USER;
4106 $today = time();
4107 // End date past.
4108 if (!empty($course->enddate) && (course_classify_end_date($course) < $today)) {
4109 return COURSE_TIMELINE_PAST;
4112 if ($completioninfo == null) {
4113 $completioninfo = new completion_info($course);
4116 // Course was completed.
4117 if ($completioninfo->is_enabled() && $completioninfo->is_course_complete($user->id)) {
4118 return COURSE_TIMELINE_PAST;
4121 // Start date not reached.
4122 if (!empty($course->startdate) && (course_classify_start_date($course) > $today)) {
4123 return COURSE_TIMELINE_FUTURE;
4126 // Everything else is in progress.
4127 return COURSE_TIMELINE_INPROGRESS;
4131 * This function calculates the end date to use for display classification purposes,
4132 * incorporating the grace period, if any.
4134 * @param stdClass $course The course record.
4135 * @return int The new enddate.
4137 function course_classify_end_date($course) {
4138 global $CFG;
4139 $coursegraceperiodafter = (empty($CFG->coursegraceperiodafter)) ? 0 : $CFG->coursegraceperiodafter;
4140 $enddate = (new \DateTimeImmutable())->setTimestamp($course->enddate)->modify("+{$coursegraceperiodafter} days");
4141 return $enddate->getTimestamp();
4145 * This function calculates the start date to use for display classification purposes,
4146 * incorporating the grace period, if any.
4148 * @param stdClass $course The course record.
4149 * @return int The new startdate.
4151 function course_classify_start_date($course) {
4152 global $CFG;
4153 $coursegraceperiodbefore = (empty($CFG->coursegraceperiodbefore)) ? 0 : $CFG->coursegraceperiodbefore;
4154 $startdate = (new \DateTimeImmutable())->setTimestamp($course->startdate)->modify("-{$coursegraceperiodbefore} days");
4155 return $startdate->getTimestamp();
4159 * Group a list of courses into either past, future, or in progress.
4161 * The return value will be an array indexed by the COURSE_TIMELINE_* constants
4162 * with each value being an array of courses in that group.
4163 * E.g.
4165 * COURSE_TIMELINE_PAST => [... list of past courses ...],
4166 * COURSE_TIMELINE_FUTURE => [],
4167 * COURSE_TIMELINE_INPROGRESS => []
4170 * @param array $courses List of courses to be grouped.
4171 * @return array
4173 function course_classify_courses_for_timeline(array $courses) {
4174 return array_reduce($courses, function($carry, $course) {
4175 $classification = course_classify_for_timeline($course);
4176 array_push($carry[$classification], $course);
4178 return $carry;
4179 }, [
4180 COURSE_TIMELINE_PAST => [],
4181 COURSE_TIMELINE_FUTURE => [],
4182 COURSE_TIMELINE_INPROGRESS => []
4187 * Get the list of enrolled courses for the current user.
4189 * This function returns a Generator. The courses will be loaded from the database
4190 * in chunks rather than a single query.
4192 * @param int $limit Restrict result set to this amount
4193 * @param int $offset Skip this number of records from the start of the result set
4194 * @param string|null $sort SQL string for sorting
4195 * @param string|null $fields SQL string for fields to be returned
4196 * @param int $dbquerylimit The number of records to load per DB request
4197 * @param array $includecourses courses ids to be restricted
4198 * @param array $hiddencourses courses ids to be excluded
4199 * @return Generator
4201 function course_get_enrolled_courses_for_logged_in_user(
4202 int $limit = 0,
4203 int $offset = 0,
4204 string $sort = null,
4205 string $fields = null,
4206 int $dbquerylimit = COURSE_DB_QUERY_LIMIT,
4207 array $includecourses = [],
4208 array $hiddencourses = []
4209 ) : Generator {
4211 $haslimit = !empty($limit);
4212 $recordsloaded = 0;
4213 $querylimit = (!$haslimit || $limit > $dbquerylimit) ? $dbquerylimit : $limit;
4215 while ($courses = enrol_get_my_courses($fields, $sort, $querylimit, $includecourses, false, $offset, $hiddencourses)) {
4216 yield from $courses;
4218 $recordsloaded += $querylimit;
4220 if (count($courses) < $querylimit) {
4221 break;
4223 if ($haslimit && $recordsloaded >= $limit) {
4224 break;
4227 $offset += $querylimit;
4232 * Search the given $courses for any that match the given $classification up to the specified
4233 * $limit.
4235 * This function will return the subset of courses that match the classification as well as the
4236 * number of courses it had to process to build that subset.
4238 * It is recommended that for larger sets of courses this function is given a Generator that loads
4239 * the courses from the database in chunks.
4241 * @param array|Traversable $courses List of courses to process
4242 * @param string $classification One of the COURSE_TIMELINE_* constants
4243 * @param int $limit Limit the number of results to this amount
4244 * @return array First value is the filtered courses, second value is the number of courses processed
4246 function course_filter_courses_by_timeline_classification(
4247 $courses,
4248 string $classification,
4249 int $limit = 0
4250 ) : array {
4252 if (!in_array($classification,
4253 [COURSE_TIMELINE_ALL, COURSE_TIMELINE_PAST, COURSE_TIMELINE_INPROGRESS,
4254 COURSE_TIMELINE_FUTURE, COURSE_TIMELINE_HIDDEN])) {
4255 $message = 'Classification must be one of COURSE_TIMELINE_ALL, COURSE_TIMELINE_PAST, '
4256 . 'COURSE_TIMELINE_INPROGRESS or COURSE_TIMELINE_FUTURE';
4257 throw new moodle_exception($message);
4260 $filteredcourses = [];
4261 $numberofcoursesprocessed = 0;
4262 $filtermatches = 0;
4264 foreach ($courses as $course) {
4265 $numberofcoursesprocessed++;
4266 $pref = get_user_preferences('block_myoverview_hidden_course_' . $course->id, 0);
4268 // Added as of MDL-63457 toggle viewability for each user.
4269 if (($classification == COURSE_TIMELINE_HIDDEN && $pref) ||
4270 (($classification == COURSE_TIMELINE_ALL || $classification == course_classify_for_timeline($course)) && !$pref)) {
4271 $filteredcourses[] = $course;
4272 $filtermatches++;
4275 if ($limit && $filtermatches >= $limit) {
4276 // We've found the number of requested courses. No need to continue searching.
4277 break;
4281 // Return the number of filtered courses as well as the number of courses that were searched
4282 // in order to find the matching courses. This allows the calling code to do some kind of
4283 // pagination.
4284 return [$filteredcourses, $numberofcoursesprocessed];
4288 * Search the given $courses for any that match the given $classification up to the specified
4289 * $limit.
4291 * This function will return the subset of courses that are favourites as well as the
4292 * number of courses it had to process to build that subset.
4294 * It is recommended that for larger sets of courses this function is given a Generator that loads
4295 * the courses from the database in chunks.
4297 * @param array|Traversable $courses List of courses to process
4298 * @param array $favouritecourseids Array of favourite courses.
4299 * @param int $limit Limit the number of results to this amount
4300 * @return array First value is the filtered courses, second value is the number of courses processed
4302 function course_filter_courses_by_favourites(
4303 $courses,
4304 $favouritecourseids,
4305 int $limit = 0
4306 ) : array {
4308 $filteredcourses = [];
4309 $numberofcoursesprocessed = 0;
4310 $filtermatches = 0;
4312 foreach ($courses as $course) {
4313 $numberofcoursesprocessed++;
4315 if (in_array($course->id, $favouritecourseids)) {
4316 $filteredcourses[] = $course;
4317 $filtermatches++;
4320 if ($limit && $filtermatches >= $limit) {
4321 // We've found the number of requested courses. No need to continue searching.
4322 break;
4326 // Return the number of filtered courses as well as the number of courses that were searched
4327 // in order to find the matching courses. This allows the calling code to do some kind of
4328 // pagination.
4329 return [$filteredcourses, $numberofcoursesprocessed];
4333 * Check module updates since a given time.
4334 * This function checks for updates in the module config, file areas, completion, grades, comments and ratings.
4336 * @param cm_info $cm course module data
4337 * @param int $from the time to check
4338 * @param array $fileareas additional file ares to check
4339 * @param array $filter if we need to filter and return only selected updates
4340 * @return stdClass object with the different updates
4341 * @since Moodle 3.2
4343 function course_check_module_updates_since($cm, $from, $fileareas = array(), $filter = array()) {
4344 global $DB, $CFG, $USER;
4346 $context = $cm->context;
4347 $mod = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
4349 $updates = new stdClass();
4350 $course = get_course($cm->course);
4351 $component = 'mod_' . $cm->modname;
4353 // Check changes in the module configuration.
4354 if (isset($mod->timemodified) and (empty($filter) or in_array('configuration', $filter))) {
4355 $updates->configuration = (object) array('updated' => false);
4356 if ($updates->configuration->updated = $mod->timemodified > $from) {
4357 $updates->configuration->timeupdated = $mod->timemodified;
4361 // Check for updates in files.
4362 if (plugin_supports('mod', $cm->modname, FEATURE_MOD_INTRO)) {
4363 $fileareas[] = 'intro';
4365 if (!empty($fileareas) and (empty($filter) or in_array('fileareas', $filter))) {
4366 $fs = get_file_storage();
4367 $files = $fs->get_area_files($context->id, $component, $fileareas, false, "filearea, timemodified DESC", false, $from);
4368 foreach ($fileareas as $filearea) {
4369 $updates->{$filearea . 'files'} = (object) array('updated' => false);
4371 foreach ($files as $file) {
4372 $updates->{$file->get_filearea() . 'files'}->updated = true;
4373 $updates->{$file->get_filearea() . 'files'}->itemids[] = $file->get_id();
4377 // Check completion.
4378 $supportcompletion = plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_HAS_RULES);
4379 $supportcompletion = $supportcompletion or plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_TRACKS_VIEWS);
4380 if ($supportcompletion and (empty($filter) or in_array('completion', $filter))) {
4381 $updates->completion = (object) array('updated' => false);
4382 $completion = new completion_info($course);
4383 // Use wholecourse to cache all the modules the first time.
4384 $completiondata = $completion->get_data($cm, true);
4385 if ($updates->completion->updated = !empty($completiondata->timemodified) && $completiondata->timemodified > $from) {
4386 $updates->completion->timemodified = $completiondata->timemodified;
4390 // Check grades.
4391 $supportgrades = plugin_supports('mod', $cm->modname, FEATURE_GRADE_HAS_GRADE);
4392 $supportgrades = $supportgrades or plugin_supports('mod', $cm->modname, FEATURE_GRADE_OUTCOMES);
4393 if ($supportgrades and (empty($filter) or (in_array('gradeitems', $filter) or in_array('outcomes', $filter)))) {
4394 require_once($CFG->libdir . '/gradelib.php');
4395 $grades = grade_get_grades($course->id, 'mod', $cm->modname, $mod->id, $USER->id);
4397 if (empty($filter) or in_array('gradeitems', $filter)) {
4398 $updates->gradeitems = (object) array('updated' => false);
4399 foreach ($grades->items as $gradeitem) {
4400 foreach ($gradeitem->grades as $grade) {
4401 if ($grade->datesubmitted > $from or $grade->dategraded > $from) {
4402 $updates->gradeitems->updated = true;
4403 $updates->gradeitems->itemids[] = $gradeitem->id;
4409 if (empty($filter) or in_array('outcomes', $filter)) {
4410 $updates->outcomes = (object) array('updated' => false);
4411 foreach ($grades->outcomes as $outcome) {
4412 foreach ($outcome->grades as $grade) {
4413 if ($grade->datesubmitted > $from or $grade->dategraded > $from) {
4414 $updates->outcomes->updated = true;
4415 $updates->outcomes->itemids[] = $outcome->id;
4422 // Check comments.
4423 if (plugin_supports('mod', $cm->modname, FEATURE_COMMENT) and (empty($filter) or in_array('comments', $filter))) {
4424 $updates->comments = (object) array('updated' => false);
4425 require_once($CFG->dirroot . '/comment/lib.php');
4426 require_once($CFG->dirroot . '/comment/locallib.php');
4427 $manager = new comment_manager();
4428 $comments = $manager->get_component_comments_since($course, $context, $component, $from, $cm);
4429 if (!empty($comments)) {
4430 $updates->comments->updated = true;
4431 $updates->comments->itemids = array_keys($comments);
4435 // Check ratings.
4436 if (plugin_supports('mod', $cm->modname, FEATURE_RATE) and (empty($filter) or in_array('ratings', $filter))) {
4437 $updates->ratings = (object) array('updated' => false);
4438 require_once($CFG->dirroot . '/rating/lib.php');
4439 $manager = new rating_manager();
4440 $ratings = $manager->get_component_ratings_since($context, $component, $from);
4441 if (!empty($ratings)) {
4442 $updates->ratings->updated = true;
4443 $updates->ratings->itemids = array_keys($ratings);
4447 return $updates;
4451 * Returns true if the user can view the participant page, false otherwise,
4453 * @param context $context The context we are checking.
4454 * @return bool
4456 function course_can_view_participants($context) {
4457 $viewparticipantscap = 'moodle/course:viewparticipants';
4458 if ($context->contextlevel == CONTEXT_SYSTEM) {
4459 $viewparticipantscap = 'moodle/site:viewparticipants';
4462 return has_any_capability([$viewparticipantscap, 'moodle/course:enrolreview'], $context);
4466 * Checks if a user can view the participant page, if not throws an exception.
4468 * @param context $context The context we are checking.
4469 * @throws required_capability_exception
4471 function course_require_view_participants($context) {
4472 if (!course_can_view_participants($context)) {
4473 $viewparticipantscap = 'moodle/course:viewparticipants';
4474 if ($context->contextlevel == CONTEXT_SYSTEM) {
4475 $viewparticipantscap = 'moodle/site:viewparticipants';
4477 throw new required_capability_exception($context, $viewparticipantscap, 'nopermissions', '');
4482 * Return whether the user can download from the specified backup file area in the given context.
4484 * @param string $filearea the backup file area. E.g. 'course', 'backup' or 'automated'.
4485 * @param \context $context
4486 * @param stdClass $user the user object. If not provided, the current user will be checked.
4487 * @return bool true if the user is allowed to download in the context, false otherwise.
4489 function can_download_from_backup_filearea($filearea, \context $context, stdClass $user = null) {
4490 $candownload = false;
4491 switch ($filearea) {
4492 case 'course':
4493 case 'backup':
4494 $candownload = has_capability('moodle/backup:downloadfile', $context, $user);
4495 break;
4496 case 'automated':
4497 // Given the automated backups may contain userinfo, we restrict access such that only users who are able to
4498 // restore with userinfo are able to download the file. Users can't create these backups, so checking 'backup:userinfo'
4499 // doesn't make sense here.
4500 $candownload = has_capability('moodle/backup:downloadfile', $context, $user) &&
4501 has_capability('moodle/restore:userinfo', $context, $user);
4502 break;
4503 default:
4504 break;
4507 return $candownload;
4511 * Get a list of hidden courses
4513 * @param int|object|null $user User override to get the filter from. Defaults to current user
4514 * @return array $ids List of hidden courses
4515 * @throws coding_exception
4517 function get_hidden_courses_on_timeline($user = null) {
4518 global $USER;
4520 if (empty($user)) {
4521 $user = $USER->id;
4524 $preferences = get_user_preferences(null, null, $user);
4525 $ids = [];
4526 foreach ($preferences as $key => $value) {
4527 if (preg_match('/block_myoverview_hidden_course_(\d)+/', $key)) {
4528 $id = preg_split('/block_myoverview_hidden_course_/', $key);
4529 $ids[] = $id[1];
4533 return $ids;
4537 * Returns a list of the most recently courses accessed by a user
4539 * @param int $userid User id from which the courses will be obtained
4540 * @param int $limit Restrict result set to this amount
4541 * @param int $offset Skip this number of records from the start of the result set
4542 * @param string|null $sort SQL string for sorting
4543 * @return array
4545 function course_get_recent_courses(int $userid = null, int $limit = 0, int $offset = 0, string $sort = null) {
4547 global $CFG, $USER, $DB;
4549 if (empty($userid)) {
4550 $userid = $USER->id;
4553 $basefields = array('id', 'idnumber', 'summary', 'summaryformat', 'startdate', 'enddate', 'category',
4554 'shortname', 'fullname', 'timeaccess', 'component');
4556 $sort = trim($sort);
4557 if (empty($sort)) {
4558 $sort = 'timeaccess DESC';
4559 } else {
4560 $rawsorts = explode(',', $sort);
4561 $sorts = array();
4562 foreach ($rawsorts as $rawsort) {
4563 $rawsort = trim($rawsort);
4564 $sorts[] = trim($rawsort);
4566 $sort = implode(',', $sorts);
4569 $orderby = "ORDER BY $sort";
4571 $ctxfields = context_helper::get_preload_record_columns_sql('ctx');
4573 $coursefields = 'c.' .join(',', $basefields);
4575 $sql = "SELECT $ctxfields, $coursefields
4576 FROM {course} c
4577 JOIN {context} ctx
4578 ON ctx.contextlevel = :contextlevel
4579 AND ctx.instanceid = c.id
4580 JOIN {user_lastaccess} ul
4581 ON ul.courseid = c.id
4582 LEFT JOIN {favourite} f
4583 ON f.component = 'core_course'
4584 AND f.itemtype = 'courses'
4585 AND f.userid = ul.userid
4586 AND f.itemid = ul.courseid
4587 WHERE ul.userid = :userid
4588 $orderby";
4589 $params = ['userid' => $userid, 'contextlevel' => CONTEXT_COURSE];
4591 $recentcourses = $DB->get_records_sql($sql, $params, $offset, $limit);
4593 // Filter courses if last access field is hidden.
4594 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
4596 if ($userid != $USER->id && isset($hiddenfields['lastaccess'])) {
4597 $recentcourses = array_filter($recentcourses, function($course) {
4598 context_helper::preload_from_record($course);
4599 $context = context_course::instance($course->id, IGNORE_MISSING);
4600 // If last access was a hidden field, a user requesting info about another user would need permission to view hidden
4601 // fields.
4602 return has_capability('moodle/course:viewhiddenuserfields', $context);
4606 return $recentcourses;