2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
18 * Library of useful functions
20 * @copyright 1999 Martin Dougiamas http://dougiamas.com
21 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
22 * @package core_course
25 defined('MOODLE_INTERNAL') ||
die;
27 use core_courseformat\base
as course_format
;
29 require_once($CFG->libdir
.'/completionlib.php');
30 require_once($CFG->libdir
.'/filelib.php');
31 require_once($CFG->libdir
.'/datalib.php');
32 require_once($CFG->dirroot
.'/course/format/lib.php');
34 define('COURSE_MAX_LOGS_PER_PAGE', 1000); // Records.
35 define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds.
38 * Number of courses to display when summaries are included.
40 * @deprecated since 2.4, use $CFG->courseswithsummarieslimit instead.
42 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10);
44 // Max courses in log dropdown before switching to optional.
45 define('COURSE_MAX_COURSES_PER_DROPDOWN', 1000);
46 // Max users in log dropdown before switching to optional.
47 define('COURSE_MAX_USERS_PER_DROPDOWN', 1000);
48 define('FRONTPAGENEWS', '0');
49 define('FRONTPAGECATEGORYNAMES', '2');
50 define('FRONTPAGECATEGORYCOMBO', '4');
51 define('FRONTPAGEENROLLEDCOURSELIST', '5');
52 define('FRONTPAGEALLCOURSELIST', '6');
53 define('FRONTPAGECOURSESEARCH', '7');
54 // Important! Replaced with $CFG->frontpagecourselimit - maximum number of courses displayed on the frontpage.
55 define('EXCELROWS', 65535);
56 define('FIRSTUSEDEXCELROW', 3);
58 define('MOD_CLASS_ACTIVITY', 0);
59 define('MOD_CLASS_RESOURCE', 1);
61 define('COURSE_TIMELINE_ALLINCLUDINGHIDDEN', 'allincludinghidden');
62 define('COURSE_TIMELINE_ALL', 'all');
63 define('COURSE_TIMELINE_PAST', 'past');
64 define('COURSE_TIMELINE_INPROGRESS', 'inprogress');
65 define('COURSE_TIMELINE_FUTURE', 'future');
66 define('COURSE_TIMELINE_SEARCH', 'search');
67 define('COURSE_FAVOURITES', 'favourites');
68 define('COURSE_TIMELINE_HIDDEN', 'hidden');
69 define('COURSE_CUSTOMFIELD', 'customfield');
70 define('COURSE_DB_QUERY_LIMIT', 1000);
71 /** Searching for all courses that have no value for the specified custom field. */
72 define('COURSE_CUSTOMFIELD_EMPTY', -1);
74 // Course activity chooser footer default display option.
75 define('COURSE_CHOOSER_FOOTER_NONE', 'hidden');
77 // Download course content options.
78 define('DOWNLOAD_COURSE_CONTENT_DISABLED', 0);
79 define('DOWNLOAD_COURSE_CONTENT_ENABLED', 1);
80 define('DOWNLOAD_COURSE_CONTENT_SITE_DEFAULT', 2);
82 function make_log_url($module, $url) {
85 if (strpos($url, 'report/') === 0) {
86 // there is only one report type, course reports are deprecated
96 if (strpos($url, '../') === 0) {
97 $url = ltrim($url, '.');
99 $url = "/course/$url";
103 $url = "/calendar/$url";
107 $url = "/$module/$url";
120 $url = "/message/$url";
123 $url = "/notes/$url";
132 $url = "/grade/$url";
135 $url = "/mod/$module/$url";
139 //now let's sanitise urls - there might be some ugly nasties:-(
140 $parts = explode('?', $url);
141 $script = array_shift($parts);
142 if (strpos($script, 'http') === 0) {
143 $script = clean_param($script, PARAM_URL
);
145 $script = clean_param($script, PARAM_PATH
);
150 $query = implode('', $parts);
151 $query = str_replace('&', '&', $query); // both & and & are stored in db :-|
152 $parts = explode('&', $query);
153 $eq = urlencode('=');
154 foreach ($parts as $key=>$part) {
155 $part = urlencode(urldecode($part));
156 $part = str_replace($eq, '=', $part);
157 $parts[$key] = $part;
159 $query = '?'.implode('&', $parts);
162 return $script.$query;
166 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
167 $modname="", $modid=0, $modaction="", $groupid=0) {
170 // It is assumed that $date is the GMT time of midnight for that day,
171 // and so the next 86400 seconds worth of logs are printed.
173 /// Setup for group handling.
175 // TODO: I don't understand group/context/etc. enough to be able to do
176 // something interesting with it here
177 // What is the context of a remote course?
179 /// If the group mode is separate, and this user does not have editing privileges,
180 /// then only the user's group can be viewed.
181 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
182 // $groupid = get_current_group($course->id);
184 /// If this course doesn't have groups, no groupid can be specified.
185 //else if (!$course->groupmode) {
194 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
196 LEFT JOIN {user} u ON l.userid = u.id
200 $where .= "l.hostid = :hostid";
201 $params['hostid'] = $hostid;
203 // TODO: Is 1 really a magic number referring to the sitename?
204 if ($course != SITEID ||
$modid != 0) {
205 $where .= " AND l.course=:courseid";
206 $params['courseid'] = $course;
210 $where .= " AND l.module = :modname";
211 $params['modname'] = $modname;
214 if ('site_errors' === $modid) {
215 $where .= " AND ( l.action='error' OR l.action='infected' )";
217 //TODO: This assumes that modids are the same across sites... probably
219 $where .= " AND l.cmid = :modid";
220 $params['modid'] = $modid;
224 $firstletter = substr($modaction, 0, 1);
225 if ($firstletter == '-') {
226 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
227 $params['modaction'] = '%'.substr($modaction, 1).'%';
229 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
230 $params['modaction'] = '%'.$modaction.'%';
235 $where .= " AND l.userid = :user";
236 $params['user'] = $user;
240 $enddate = $date +
86400;
241 $where .= " AND l.time > :date AND l.time < :enddate";
242 $params['date'] = $date;
243 $params['enddate'] = $enddate;
247 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
248 if(!empty($result['totalcount'])) {
249 $where .= " ORDER BY $order";
250 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
252 $result['logs'] = array();
258 * Checks the integrity of the course data.
260 * In summary - compares course_sections.sequence and course_modules.section.
262 * More detailed, checks that:
263 * - course_sections.sequence contains each module id not more than once in the course
264 * - for each moduleid from course_sections.sequence the field course_modules.section
265 * refers to the same section id (this means course_sections.sequence is more
266 * important if they are different)
267 * - ($fullcheck only) each module in the course is present in one of
268 * course_sections.sequence
269 * - ($fullcheck only) removes non-existing course modules from section sequences
271 * If there are any mismatches, the changes are made and records are updated in DB.
273 * Course cache is NOT rebuilt if there are any errors!
275 * This function is used each time when course cache is being rebuilt with $fullcheck = false
276 * and in CLI script admin/cli/fix_course_sequence.php with $fullcheck = true
278 * @param int $courseid id of the course
279 * @param array $rawmods result of funciton {@link get_course_mods()} - containst
280 * the list of enabled course modules in the course. Retrieved from DB if not specified.
281 * Argument ignored in cashe of $fullcheck, the list is retrieved form DB anyway.
282 * @param array $sections records from course_sections table for this course.
283 * Retrieved from DB if not specified
284 * @param bool $fullcheck Will add orphaned modules to their sections and remove non-existing
285 * course modules from sequences. Only to be used in site maintenance mode when we are
286 * sure that another user is not in the middle of the process of moving/removing a module.
287 * @param bool $checkonly Only performs the check without updating DB, outputs all errors as debug messages.
288 * @return array array of messages with found problems. Empty output means everything is ok
290 function course_integrity_check($courseid, $rawmods = null, $sections = null, $fullcheck = false, $checkonly = false) {
293 if ($sections === null) {
294 $sections = $DB->get_records('course_sections', array('course' => $courseid), 'section', 'id,section,sequence');
297 // Retrieve all records from course_modules regardless of module type visibility.
298 $rawmods = $DB->get_records('course_modules', array('course' => $courseid), 'id', 'id,section');
300 if ($rawmods === null) {
301 $rawmods = get_course_mods($courseid);
303 if (!$fullcheck && (empty($sections) ||
empty($rawmods))) {
304 // If either of the arrays is empty, no modules are displayed anyway.
307 $debuggingprefix = 'Failed integrity check for course ['.$courseid.']. ';
309 // First make sure that each module id appears in section sequences only once.
310 // If it appears in several section sequences the last section wins.
311 // If it appears twice in one section sequence, the first occurence wins.
312 $modsection = array();
313 foreach ($sections as $sectionid => $section) {
314 $sections[$sectionid]->newsequence
= $section->sequence
;
315 if (!empty($section->sequence
)) {
316 $sequence = explode(",", $section->sequence
);
317 $sequenceunique = array_unique($sequence);
318 if (count($sequenceunique) != count($sequence)) {
319 // Some course module id appears in this section sequence more than once.
320 ksort($sequenceunique); // Preserve initial order of modules.
321 $sequence = array_values($sequenceunique);
322 $sections[$sectionid]->newsequence
= join(',', $sequence);
323 $messages[] = $debuggingprefix.'Sequence for course section ['.
324 $sectionid.'] is "'.$sections[$sectionid]->sequence
.'", must be "'.$sections[$sectionid]->newsequence
.'"';
326 foreach ($sequence as $cmid) {
327 if (array_key_exists($cmid, $modsection) && isset($rawmods[$cmid])) {
328 // Some course module id appears to be in more than one section's sequences.
329 $wrongsectionid = $modsection[$cmid];
330 $sections[$wrongsectionid]->newsequence
= trim(preg_replace("/,$cmid,/", ',', ','.$sections[$wrongsectionid]->newsequence
. ','), ',');
331 $messages[] = $debuggingprefix.'Course module ['.$cmid.'] must be removed from sequence of section ['.
332 $wrongsectionid.'] because it is also present in sequence of section ['.$sectionid.']';
334 $modsection[$cmid] = $sectionid;
339 // Add orphaned modules to their sections if they exist or to section 0 otherwise.
341 foreach ($rawmods as $cmid => $mod) {
342 if (!isset($modsection[$cmid])) {
343 // This is a module that is not mentioned in course_section.sequence at all.
344 // Add it to the section $mod->section or to the last available section.
345 if ($mod->section
&& isset($sections[$mod->section
])) {
346 $modsection[$cmid] = $mod->section
;
348 $firstsection = reset($sections);
349 $modsection[$cmid] = $firstsection->id
;
351 $sections[$modsection[$cmid]]->newsequence
= trim($sections[$modsection[$cmid]]->newsequence
.','.$cmid, ',');
352 $messages[] = $debuggingprefix.'Course module ['.$cmid.'] is missing from sequence of section ['.
353 $modsection[$cmid].']';
356 foreach ($modsection as $cmid => $sectionid) {
357 if (!isset($rawmods[$cmid])) {
358 // Section $sectionid refers to module id that does not exist.
359 $sections[$sectionid]->newsequence
= trim(preg_replace("/,$cmid,/", ',', ','.$sections[$sectionid]->newsequence
.','), ',');
360 $messages[] = $debuggingprefix.'Course module ['.$cmid.
361 '] does not exist but is present in the sequence of section ['.$sectionid.']';
366 // Update changed sections.
367 if (!$checkonly && !empty($messages)) {
368 foreach ($sections as $sectionid => $section) {
369 if ($section->newsequence
!== $section->sequence
) {
370 $DB->update_record('course_sections', array('id' => $sectionid, 'sequence' => $section->newsequence
));
375 // Now make sure that all modules point to the correct sections.
376 foreach ($rawmods as $cmid => $mod) {
377 if (isset($modsection[$cmid]) && $modsection[$cmid] != $mod->section
) {
379 $DB->update_record('course_modules', array('id' => $cmid, 'section' => $modsection[$cmid]));
381 $messages[] = $debuggingprefix.'Course module ['.$cmid.
382 '] points to section ['.$mod->section
.'] instead of ['.$modsection[$cmid].']';
390 * Returns an array where the key is the module name (component name without 'mod_')
391 * and the value is a lang_string object with a human-readable string.
393 * @param bool $plural If true, the function returns the plural forms of the names.
394 * @param bool $resetcache If true, the static cache will be reset
395 * @return lang_string[] Localised human-readable names of all used modules.
397 function get_module_types_names($plural = false, $resetcache = false) {
398 static $modnames = null;
400 if ($modnames === null ||
$resetcache) {
401 $modnames = array(0 => array(), 1 => array());
402 if ($allmods = $DB->get_records("modules")) {
403 foreach ($allmods as $mod) {
404 if (file_exists("$CFG->dirroot/mod/$mod->name/lib.php") && $mod->visible
) {
405 $modnames[0][$mod->name
] = get_string("modulename", "$mod->name", null, true);
406 $modnames[1][$mod->name
] = get_string("modulenameplural", "$mod->name", null, true);
411 return $modnames[(int)$plural];
415 * Set highlighted section. Only one section can be highlighted at the time.
417 * @param int $courseid course id
418 * @param int $marker highlight section with this number, 0 means remove higlightin
421 function course_set_marker($courseid, $marker) {
423 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
424 if ($COURSE && $COURSE->id
== $courseid) {
425 $COURSE->marker
= $marker;
427 core_courseformat\base
::reset_course_cache($courseid);
428 course_modinfo
::clear_instance_cache($courseid);
432 * For a given course section, marks it visible or hidden,
433 * and does the same for every activity in that section
435 * @param int $courseid course id
436 * @param int $sectionnumber The section number to adjust
437 * @param int $visibility The new visibility
438 * @return array A list of resources which were hidden in the section
440 function set_section_visible($courseid, $sectionnumber, $visibility) {
443 $resourcestotoggle = array();
444 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
445 course_update_section($courseid, $section, array('visible' => $visibility));
447 // Determine which modules are visible for AJAX update
448 $modules = !empty($section->sequence
) ?
explode(',', $section->sequence
) : array();
449 if (!empty($modules)) {
450 list($insql, $params) = $DB->get_in_or_equal($modules);
451 $select = 'id ' . $insql . ' AND visible = ?';
452 array_push($params, $visibility);
454 $select .= ' AND visibleold = 1';
456 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
459 return $resourcestotoggle;
463 * Return the course category context for the category with id $categoryid, except
464 * that if $categoryid is 0, return the system context.
466 * @param integer $categoryid a category id or 0.
467 * @return context the corresponding context
469 function get_category_or_system_context($categoryid) {
471 return context_coursecat
::instance($categoryid, IGNORE_MISSING
);
473 return context_system
::instance();
478 * Print the buttons relating to course requests.
480 * @param context $context current page context.
481 * @deprecated since Moodle 4.0
482 * @todo Final deprecation MDL-73976
484 function print_course_request_buttons($context) {
485 global $CFG, $DB, $OUTPUT;
486 debugging("print_course_request_buttons() is deprecated. " .
487 "This is replaced with the category_action_bar tertiary navigation.", DEBUG_DEVELOPER
);
488 if (empty($CFG->enablecourserequests
)) {
491 if (course_request
::can_request($context)) {
492 // Print a button to request a new course.
494 if ($context instanceof context_coursecat
) {
495 $params['category'] = $context->instanceid
;
497 echo $OUTPUT->single_button(new moodle_url('/course/request.php', $params),
498 get_string('requestcourse'), 'get');
500 /// Print a button to manage pending requests
501 if (has_capability('moodle/site:approvecourse', $context)) {
502 $disabled = !$DB->record_exists('course_request', array());
503 echo $OUTPUT->single_button(new moodle_url('/course/pending.php'), get_string('coursespending'), 'get', array('disabled' => $disabled));
508 * Does the user have permission to edit things in this category?
510 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
511 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
513 function can_edit_in_category($categoryid = 0) {
514 $context = get_category_or_system_context($categoryid);
515 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
518 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
520 function add_course_module($mod) {
523 $mod->added
= time();
526 $cmid = $DB->insert_record("course_modules", $mod);
527 rebuild_course_cache($mod->course
, true);
532 * Creates a course section and adds it to the specified position
534 * @param int|stdClass $courseorid course id or course object
535 * @param int $position position to add to, 0 means to the end. If position is greater than
536 * number of existing secitons, the section is added to the end. This will become sectionnum of the
537 * new section. All existing sections at this or bigger position will be shifted down.
538 * @param bool $skipcheck the check has already been made and we know that the section with this position does not exist
539 * @return stdClass created section object
541 function course_create_section($courseorid, $position = 0, $skipcheck = false) {
543 $courseid = is_object($courseorid) ?
$courseorid->id
: $courseorid;
545 // Find the last sectionnum among existing sections.
547 $lastsection = $position - 1;
549 $lastsection = (int)$DB->get_field_sql('SELECT max(section) from {course_sections} WHERE course = ?', [$courseid]);
552 // First add section to the end.
553 $cw = new stdClass();
554 $cw->course
= $courseid;
555 $cw->section
= $lastsection +
1;
557 $cw->summaryformat
= FORMAT_HTML
;
561 $cw->availability
= null;
562 $cw->timemodified
= time();
563 $cw->id
= $DB->insert_record("course_sections", $cw);
565 // Now move it to the specified position.
566 if ($position > 0 && $position <= $lastsection) {
567 $course = is_object($courseorid) ?
$courseorid : get_course($courseorid);
568 move_section_to($course, $cw->section
, $position, true);
569 $cw->section
= $position;
572 core\event\course_section_created
::create_from_section($cw)->trigger();
574 rebuild_course_cache($courseid, true);
579 * Creates missing course section(s) and rebuilds course cache
581 * @param int|stdClass $courseorid course id or course object
582 * @param int|array $sections list of relative section numbers to create
583 * @return bool if there were any sections created
585 function course_create_sections_if_missing($courseorid, $sections) {
586 if (!is_array($sections)) {
587 $sections = array($sections);
589 $existing = array_keys(get_fast_modinfo($courseorid)->get_section_info_all());
590 if ($newsections = array_diff($sections, $existing)) {
591 foreach ($newsections as $sectionnum) {
592 course_create_section($courseorid, $sectionnum, true);
600 * Adds an existing module to the section
602 * Updates both tables {course_sections} and {course_modules}
604 * Note: This function does not use modinfo PROVIDED that the section you are
605 * adding the module to already exists. If the section does not exist, it will
606 * build modinfo if necessary and create the section.
608 * @param int|stdClass $courseorid course id or course object
609 * @param int $cmid id of the module already existing in course_modules table
610 * @param int $sectionnum relative number of the section (field course_sections.section)
611 * If section does not exist it will be created
612 * @param int|stdClass $beforemod id or object with field id corresponding to the module
613 * before which the module needs to be included. Null for inserting in the
615 * @return int The course_sections ID where the module is inserted
617 function course_add_cm_to_section($courseorid, $cmid, $sectionnum, $beforemod = null) {
619 if (is_object($beforemod)) {
620 $beforemod = $beforemod->id
;
622 if (is_object($courseorid)) {
623 $courseid = $courseorid->id
;
625 $courseid = $courseorid;
627 // Do not try to use modinfo here, there is no guarantee it is valid!
628 $section = $DB->get_record('course_sections',
629 array('course' => $courseid, 'section' => $sectionnum), '*', IGNORE_MISSING
);
631 // This function call requires modinfo.
632 course_create_sections_if_missing($courseorid, $sectionnum);
633 $section = $DB->get_record('course_sections',
634 array('course' => $courseid, 'section' => $sectionnum), '*', MUST_EXIST
);
637 $modarray = explode(",", trim($section->sequence
));
638 if (empty($section->sequence
)) {
639 $newsequence = "$cmid";
640 } else if ($beforemod && ($key = array_keys($modarray, $beforemod))) {
641 $insertarray = array($cmid, $beforemod);
642 array_splice($modarray, $key[0], 1, $insertarray);
643 $newsequence = implode(",", $modarray);
645 $newsequence = "$section->sequence,$cmid";
647 $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id
));
648 $DB->set_field('course_modules', 'section', $section->id
, array('id' => $cmid));
649 rebuild_course_cache($courseid, true);
650 return $section->id
; // Return course_sections ID that was used.
654 * Change the group mode of a course module.
656 * Note: Do not forget to trigger the event \core\event\course_module_updated as it needs
657 * to be triggered manually, refer to {@link \core\event\course_module_updated::create_from_cm()}.
659 * @param int $id course module ID.
660 * @param int $groupmode the new groupmode value.
661 * @return bool True if the $groupmode was updated.
663 function set_coursemodule_groupmode($id, $groupmode) {
665 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST
);
666 if ($cm->groupmode
!= $groupmode) {
667 $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id
));
668 \course_modinfo
::purge_course_module_cache($cm->course
, $cm->id
);
669 rebuild_course_cache($cm->course
, false, true);
671 return ($cm->groupmode
!= $groupmode);
674 function set_coursemodule_idnumber($id, $idnumber) {
676 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST
);
677 if ($cm->idnumber
!= $idnumber) {
678 $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id
));
679 \course_modinfo
::purge_course_module_cache($cm->course
, $cm->id
);
680 rebuild_course_cache($cm->course
, false, true);
682 return ($cm->idnumber
!= $idnumber);
686 * Set downloadcontent value to course module.
688 * @param int $id The id of the module.
689 * @param bool $downloadcontent Whether the module can be downloaded when download course content is enabled.
690 * @return bool True if downloadcontent has been updated, false otherwise.
692 function set_downloadcontent(int $id, bool $downloadcontent): bool {
694 $cm = $DB->get_record('course_modules', ['id' => $id], 'id, course, downloadcontent', MUST_EXIST
);
695 if ($cm->downloadcontent
!= $downloadcontent) {
696 $DB->set_field('course_modules', 'downloadcontent', $downloadcontent, ['id' => $cm->id
]);
697 rebuild_course_cache($cm->course
, true);
699 return ($cm->downloadcontent
!= $downloadcontent);
703 * Set the visibility of a module and inherent properties.
705 * Note: Do not forget to trigger the event \core\event\course_module_updated as it needs
706 * to be triggered manually, refer to {@link \core\event\course_module_updated::create_from_cm()}.
708 * From 2.4 the parameter $prevstateoverrides has been removed, the logic it triggered
709 * has been moved to {@link set_section_visible()} which was the only place from which
710 * the parameter was used.
712 * @param int $id of the module
713 * @param int $visible state of the module
714 * @param int $visibleoncoursepage state of the module on the course page
715 * @return bool false when the module was not found, true otherwise
717 function set_coursemodule_visible($id, $visible, $visibleoncoursepage = 1) {
719 require_once($CFG->libdir
.'/gradelib.php');
720 require_once($CFG->dirroot
.'/calendar/lib.php');
722 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
726 // Create events and propagate visibility to associated grade items if the value has changed.
727 // Only do this if it's changed to avoid accidently overwriting manual showing/hiding of student grades.
728 if ($cm->visible
== $visible && $cm->visibleoncoursepage
== $visibleoncoursepage) {
732 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module
))) {
735 if (($cm->visible
!= $visible) &&
736 ($events = $DB->get_records('event', array('instance' => $cm->instance
, 'modulename' => $modulename)))) {
737 foreach($events as $event) {
739 $event = new calendar_event($event);
740 $event->toggle_visibility(true);
742 $event = new calendar_event($event);
743 $event->toggle_visibility(false);
748 // Updating visible and visibleold to keep them in sync. Only changing a section visibility will
749 // affect visibleold to allow for an original visibility restore. See set_section_visible().
750 $cminfo = new stdClass();
752 $cminfo->visible
= $visible;
753 $cminfo->visibleoncoursepage
= $visibleoncoursepage;
754 $cminfo->visibleold
= $visible;
755 $DB->update_record('course_modules', $cminfo);
757 // Hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there.
758 // Note that this must be done after updating the row in course_modules, in case
759 // the modules grade_item_update function needs to access $cm->visible.
760 if ($cm->visible
!= $visible &&
761 plugin_supports('mod', $modulename, FEATURE_CONTROLS_GRADE_VISIBILITY
) &&
762 component_callback_exists('mod_' . $modulename, 'grade_item_update')) {
763 $instance = $DB->get_record($modulename, array('id' => $cm->instance
), '*', MUST_EXIST
);
764 component_callback('mod_' . $modulename, 'grade_item_update', array($instance));
765 } else if ($cm->visible
!= $visible) {
766 $grade_items = grade_item
::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance
, 'courseid'=>$cm->course
));
768 foreach ($grade_items as $grade_item) {
769 $grade_item->set_hidden(!$visible);
774 \course_modinfo
::purge_course_module_cache($cm->course
, $cm->id
);
775 rebuild_course_cache($cm->course
, false, true);
780 * Changes the course module name
782 * @param int $id course module id
783 * @param string $name new value for a name
784 * @return bool whether a change was made
786 function set_coursemodule_name($id, $name) {
788 require_once($CFG->libdir
. '/gradelib.php');
790 $cm = get_coursemodule_from_id('', $id, 0, false, MUST_EXIST
);
792 $module = new \
stdClass();
793 $module->id
= $cm->instance
;
795 // Escape strings as they would be by mform.
796 if (!empty($CFG->formatstringstriptags
)) {
797 $module->name
= clean_param($name, PARAM_TEXT
);
799 $module->name
= clean_param($name, PARAM_CLEANHTML
);
801 if ($module->name
=== $cm->name ||
strval($module->name
) === '') {
804 if (\core_text
::strlen($module->name
) > 255) {
805 throw new \
moodle_exception('maximumchars', 'moodle', '', 255);
808 $module->timemodified
= time();
809 $DB->update_record($cm->modname
, $module);
810 $cm->name
= $module->name
;
811 \core\event\course_module_updated
::create_from_cm($cm)->trigger();
812 \course_modinfo
::purge_course_module_cache($cm->course
, $cm->id
);
813 rebuild_course_cache($cm->course
, false, true);
815 // Attempt to update the grade item if relevant.
816 $grademodule = $DB->get_record($cm->modname
, array('id' => $cm->instance
));
817 $grademodule->cmidnumber
= $cm->idnumber
;
818 $grademodule->modname
= $cm->modname
;
819 grade_update_mod_grades($grademodule);
821 // Update calendar events with the new name.
822 course_module_update_calendar_events($cm->modname
, $grademodule, $cm);
828 * This function will handle the whole deletion process of a module. This includes calling
829 * the modules delete_instance function, deleting files, events, grades, conditional data,
830 * the data in the course_module and course_sections table and adding a module deletion
833 * @param int $cmid the course module id
834 * @param bool $async whether or not to try to delete the module using an adhoc task. Async also depends on a plugin hook.
835 * @throws moodle_exception
838 function course_delete_module($cmid, $async = false) {
839 // Check the 'course_module_background_deletion_recommended' hook first.
840 // Only use asynchronous deletion if at least one plugin returns true and if async deletion has been requested.
841 // Both are checked because plugins should not be allowed to dictate the deletion behaviour, only support/decline it.
842 // It's up to plugins to handle things like whether or not they are enabled.
843 if ($async && $pluginsfunction = get_plugins_with_function('course_module_background_deletion_recommended')) {
844 foreach ($pluginsfunction as $plugintype => $plugins) {
845 foreach ($plugins as $pluginfunction) {
846 if ($pluginfunction()) {
847 return course_module_flag_for_async_deletion($cmid);
855 require_once($CFG->libdir
.'/gradelib.php');
856 require_once($CFG->libdir
.'/questionlib.php');
857 require_once($CFG->dirroot
.'/blog/lib.php');
858 require_once($CFG->dirroot
.'/calendar/lib.php');
860 // Get the course module.
861 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
865 // Get the module context.
866 $modcontext = context_module
::instance($cm->id
);
868 // Get the course module name.
869 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module
), MUST_EXIST
);
871 // Get the file location of the delete_instance function for this module.
872 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
874 // Include the file required to call the delete_instance function for this module.
875 if (file_exists($modlib)) {
876 require_once($modlib);
878 throw new moodle_exception('cannotdeletemodulemissinglib', '', '', null,
879 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
882 $deleteinstancefunction = $modulename . '_delete_instance';
884 // Ensure the delete_instance function exists for this module.
885 if (!function_exists($deleteinstancefunction)) {
886 throw new moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
887 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
890 // Allow plugins to use this course module before we completely delete it.
891 if ($pluginsfunction = get_plugins_with_function('pre_course_module_delete')) {
892 foreach ($pluginsfunction as $plugintype => $plugins) {
893 foreach ($plugins as $pluginfunction) {
894 $pluginfunction($cm);
899 // Call the delete_instance function, if it returns false throw an exception.
900 if (!$deleteinstancefunction($cm->instance
)) {
901 throw new moodle_exception('cannotdeletemoduleinstance', '', '', null,
902 "Cannot delete the module $modulename (instance).");
905 question_delete_activity($cm);
907 // Remove all module files in case modules forget to do that.
908 $fs = get_file_storage();
909 $fs->delete_area_files($modcontext->id
);
911 // Delete events from calendar.
912 if ($events = $DB->get_records('event', array('instance' => $cm->instance
, 'modulename' => $modulename))) {
913 $coursecontext = context_course
::instance($cm->course
);
914 foreach($events as $event) {
915 $event->context
= $coursecontext;
916 $calendarevent = calendar_event
::load($event);
917 $calendarevent->delete();
921 // Delete grade items, outcome items and grades attached to modules.
922 if ($grade_items = grade_item
::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $modulename,
923 'iteminstance' => $cm->instance
, 'courseid' => $cm->course
))) {
924 foreach ($grade_items as $grade_item) {
925 $grade_item->delete('moddelete');
929 // Delete associated blogs and blog tag instances.
930 blog_remove_associations_for_module($modcontext->id
);
932 // Delete completion and availability data; it is better to do this even if the
933 // features are not turned on, in case they were turned on previously (these will be
934 // very quick on an empty table).
935 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id
));
936 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id
,
937 'course' => $cm->course
,
938 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY
));
940 // Delete all tag instances associated with the instance of this module.
941 core_tag_tag
::delete_instances('mod_' . $modulename, null, $modcontext->id
);
942 core_tag_tag
::remove_all_item_tags('core', 'course_modules', $cm->id
);
944 // Notify the competency subsystem.
945 \core_competency\api
::hook_course_module_deleted($cm);
947 // Delete the context.
948 context_helper
::delete_instance(CONTEXT_MODULE
, $cm->id
);
950 // Delete the module from the course_modules table.
951 $DB->delete_records('course_modules', array('id' => $cm->id
));
953 // Delete module from that section.
954 if (!delete_mod_from_section($cm->id
, $cm->section
)) {
955 throw new moodle_exception('cannotdeletemodulefromsection', '', '', null,
956 "Cannot delete the module $modulename (instance) from section.");
959 // Trigger event for course module delete action.
960 $event = \core\event\course_module_deleted
::create(array(
961 'courseid' => $cm->course
,
962 'context' => $modcontext,
963 'objectid' => $cm->id
,
965 'modulename' => $modulename,
966 'instanceid' => $cm->instance
,
969 $event->add_record_snapshot('course_modules', $cm);
971 \course_modinfo
::purge_course_module_cache($cm->course
, $cm->id
);
972 rebuild_course_cache($cm->course
, false, true);
976 * Schedule a course module for deletion in the background using an adhoc task.
978 * This method should not be called directly. Instead, please use course_delete_module($cmid, true), to denote async deletion.
979 * The real deletion of the module is handled by the task, which calls 'course_delete_module($cmid)'.
981 * @param int $cmid the course module id.
982 * @return bool whether the module was successfully scheduled for deletion.
983 * @throws \moodle_exception
985 function course_module_flag_for_async_deletion($cmid) {
986 global $CFG, $DB, $USER;
987 require_once($CFG->libdir
.'/gradelib.php');
988 require_once($CFG->libdir
.'/questionlib.php');
989 require_once($CFG->dirroot
.'/blog/lib.php');
990 require_once($CFG->dirroot
.'/calendar/lib.php');
992 // Get the course module.
993 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
997 // We need to be reasonably certain the deletion is going to succeed before we background the process.
998 // Make the necessary delete_instance checks, etc. before proceeding further. Throw exceptions if required.
1000 // Get the course module name.
1001 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module
), MUST_EXIST
);
1003 // Get the file location of the delete_instance function for this module.
1004 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
1006 // Include the file required to call the delete_instance function for this module.
1007 if (file_exists($modlib)) {
1008 require_once($modlib);
1010 throw new \
moodle_exception('cannotdeletemodulemissinglib', '', '', null,
1011 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
1014 $deleteinstancefunction = $modulename . '_delete_instance';
1016 // Ensure the delete_instance function exists for this module.
1017 if (!function_exists($deleteinstancefunction)) {
1018 throw new \
moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
1019 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
1022 // We are going to defer the deletion as we can't be sure how long the module's pre_delete code will run for.
1023 $cm->deletioninprogress
= '1';
1024 $DB->update_record('course_modules', $cm);
1026 // Create an adhoc task for the deletion of the course module. The task takes an array of course modules for removal.
1027 $removaltask = new \core_course\task\
course_delete_modules();
1028 $removaltask->set_custom_data(array(
1029 'cms' => array($cm),
1030 'userid' => $USER->id
,
1031 'realuserid' => \core\session\manager
::get_realuser()->id
1034 // Queue the task for the next run.
1035 \core\task\manager
::queue_adhoc_task($removaltask);
1037 // Reset the course cache to hide the module.
1038 rebuild_course_cache($cm->course
, true);
1042 * Checks whether the given course has any course modules scheduled for adhoc deletion.
1044 * @param int $courseid the id of the course.
1045 * @param bool $onlygradable whether to check only gradable modules or all modules.
1046 * @return bool true if the course contains any modules pending deletion, false otherwise.
1048 function course_modules_pending_deletion(int $courseid, bool $onlygradable = false) : bool {
1049 if (empty($courseid)) {
1053 if ($onlygradable) {
1054 // Fetch modules with grade items.
1055 if (!$coursegradeitems = grade_item
::fetch_all(['itemtype' => 'mod', 'courseid' => $courseid])) {
1056 // Return early when there is none.
1061 $modinfo = get_fast_modinfo($courseid);
1062 foreach ($modinfo->get_cms() as $module) {
1063 if ($module->deletioninprogress
== '1') {
1064 if ($onlygradable) {
1065 // Check if the module being deleted is in the list of course modules with grade items.
1066 foreach ($coursegradeitems as $coursegradeitem) {
1067 if ($coursegradeitem->itemmodule
== $module->modname
&& $coursegradeitem->iteminstance
== $module->instance
) {
1068 // The module being deleted is within the gradable modules.
1081 * Checks whether the course module, as defined by modulename and instanceid, is scheduled for deletion within the given course.
1083 * @param int $courseid the course id.
1084 * @param string $modulename the module name. E.g. 'assign', 'book', etc.
1085 * @param int $instanceid the module instance id.
1086 * @return bool true if the course module is pending deletion, false otherwise.
1088 function course_module_instance_pending_deletion($courseid, $modulename, $instanceid) {
1089 if (empty($courseid) ||
empty($modulename) ||
empty($instanceid)) {
1092 $modinfo = get_fast_modinfo($courseid);
1093 $instances = $modinfo->get_instances_of($modulename);
1094 return isset($instances[$instanceid]) && $instances[$instanceid]->deletioninprogress
;
1097 function delete_mod_from_section($modid, $sectionid) {
1100 if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
1102 $modarray = explode(",", $section->sequence
);
1104 if ($key = array_keys ($modarray, $modid)) {
1105 array_splice($modarray, $key[0], 1);
1106 $newsequence = implode(",", $modarray);
1107 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id
));
1108 rebuild_course_cache($section->course
, true);
1119 * This function updates the calendar events from the information stored in the module table and the course
1122 * @param string $modulename Module name
1123 * @param stdClass $instance Module object. Either the $instance or the $cm must be supplied.
1124 * @param stdClass $cm Course module object. Either the $instance or the $cm must be supplied.
1125 * @return bool Returns true if calendar events are updated.
1126 * @since Moodle 3.3.4
1128 function course_module_update_calendar_events($modulename, $instance = null, $cm = null) {
1131 if (isset($instance) ||
isset($cm)) {
1133 if (!isset($instance)) {
1134 $instance = $DB->get_record($modulename, array('id' => $cm->instance
), '*', MUST_EXIST
);
1137 $cm = get_coursemodule_from_instance($modulename, $instance->id
, $instance->course
);
1140 course_module_calendar_event_update_process($instance, $cm);
1148 * Update all instances through out the site or in a course.
1150 * @param string $modulename Module type to update.
1151 * @param integer $courseid Course id to update events. 0 for the whole site.
1152 * @return bool Returns True if the update was successful.
1153 * @since Moodle 3.3.4
1155 function course_module_bulk_update_calendar_events($modulename, $courseid = 0) {
1160 if (!$instances = $DB->get_records($modulename, array('course' => $courseid))) {
1164 if (!$instances = $DB->get_records($modulename)) {
1169 foreach ($instances as $instance) {
1170 if ($cm = get_coursemodule_from_instance($modulename, $instance->id
, $instance->course
)) {
1171 course_module_calendar_event_update_process($instance, $cm);
1178 * Calendar events for a module instance are updated.
1180 * @param stdClass $instance Module instance object.
1181 * @param stdClass $cm Course Module object.
1182 * @since Moodle 3.3.4
1184 function course_module_calendar_event_update_process($instance, $cm) {
1185 // We need to call *_refresh_events() first because some modules delete 'old' events at the end of the code which
1186 // will remove the completion events.
1187 $refresheventsfunction = $cm->modname
. '_refresh_events';
1188 if (function_exists($refresheventsfunction)) {
1189 call_user_func($refresheventsfunction, $cm->course
, $instance, $cm);
1191 $completionexpected = (!empty($cm->completionexpected
)) ?
$cm->completionexpected
: null;
1192 \core_completion\api
::update_completion_date_event($cm->id
, $cm->modname
, $instance, $completionexpected);
1196 * Moves a section within a course, from a position to another.
1197 * Be very careful: $section and $destination refer to section number,
1200 * @param object $course
1201 * @param int $section Section number (not id!!!)
1202 * @param int $destination
1203 * @param bool $ignorenumsections
1204 * @return boolean Result
1206 function move_section_to($course, $section, $destination, $ignorenumsections = false) {
1207 /// Moves a whole course section up and down within the course
1210 if (!$destination && $destination != 0) {
1214 // compartibility with course formats using field 'numsections'
1215 $courseformatoptions = course_get_format($course)->get_format_options();
1216 if ((!$ignorenumsections && array_key_exists('numsections', $courseformatoptions) &&
1217 ($destination > $courseformatoptions['numsections'])) ||
($destination < 1)) {
1221 // Get all sections for this course and re-order them (2 of them should now share the same section number)
1222 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id
),
1223 'section ASC, id ASC', 'id, section')) {
1227 $movedsections = reorder_sections($sections, $section, $destination);
1229 // Update all sections. Do this in 2 steps to avoid breaking database
1230 // uniqueness constraint
1231 $transaction = $DB->start_delegated_transaction();
1232 foreach ($movedsections as $id => $position) {
1233 if ((int) $sections[$id] !== $position) {
1234 $DB->set_field('course_sections', 'section', -$position, ['id' => $id]);
1235 // Invalidate the section cache by given section id.
1236 course_modinfo
::purge_course_section_cache_by_id($course->id
, $id);
1239 foreach ($movedsections as $id => $position) {
1240 if ((int) $sections[$id] !== $position) {
1241 $DB->set_field('course_sections', 'section', $position, ['id' => $id]);
1242 // Invalidate the section cache by given section id.
1243 course_modinfo
::purge_course_section_cache_by_id($course->id
, $id);
1247 // If we move the highlighted section itself, then just highlight the destination.
1248 // Adjust the higlighted section location if we move something over it either direction.
1249 if ($section == $course->marker
) {
1250 course_set_marker($course->id
, $destination);
1251 } else if ($section > $course->marker
&& $course->marker
>= $destination) {
1252 course_set_marker($course->id
, $course->marker+
1);
1253 } else if ($section < $course->marker
&& $course->marker
<= $destination) {
1254 course_set_marker($course->id
, $course->marker
-1);
1257 $transaction->allow_commit();
1258 rebuild_course_cache($course->id
, true, true);
1263 * This method will delete a course section and may delete all modules inside it.
1265 * No permissions are checked here, use {@link course_can_delete_section()} to
1266 * check if section can actually be deleted.
1268 * @param int|stdClass $course
1269 * @param int|stdClass|section_info $section
1270 * @param bool $forcedeleteifnotempty if set to false section will not be deleted if it has modules in it.
1271 * @param bool $async whether or not to try to delete the section using an adhoc task. Async also depends on a plugin hook.
1272 * @return bool whether section was deleted
1274 function course_delete_section($course, $section, $forcedeleteifnotempty = true, $async = false) {
1277 // Prepare variables.
1278 $courseid = (is_object($course)) ?
$course->id
: (int)$course;
1279 $sectionnum = (is_object($section)) ?
$section->section
: (int)$section;
1280 $section = $DB->get_record('course_sections', array('course' => $courseid, 'section' => $sectionnum));
1282 // No section exists, can't proceed.
1286 // Check the 'course_module_background_deletion_recommended' hook first.
1287 // Only use asynchronous deletion if at least one plugin returns true and if async deletion has been requested.
1288 // Both are checked because plugins should not be allowed to dictate the deletion behaviour, only support/decline it.
1289 // It's up to plugins to handle things like whether or not they are enabled.
1290 if ($async && $pluginsfunction = get_plugins_with_function('course_module_background_deletion_recommended')) {
1291 foreach ($pluginsfunction as $plugintype => $plugins) {
1292 foreach ($plugins as $pluginfunction) {
1293 if ($pluginfunction()) {
1294 return course_delete_section_async($section, $forcedeleteifnotempty);
1300 $format = course_get_format($course);
1301 $sectionname = $format->get_section_name($section);
1304 $result = $format->delete_section($section, $forcedeleteifnotempty);
1306 // Trigger an event for course section deletion.
1308 $context = context_course
::instance($courseid);
1309 $event = \core\event\course_section_deleted
::create(
1311 'objectid' => $section->id
,
1312 'courseid' => $courseid,
1313 'context' => $context,
1315 'sectionnum' => $section->section
,
1316 'sectionname' => $sectionname,
1320 $event->add_record_snapshot('course_sections', $section);
1327 * Course section deletion, using an adhoc task for deletion of the modules it contains.
1328 * 1. Schedule all modules within the section for adhoc removal.
1329 * 2. Move all modules to course section 0.
1330 * 3. Delete the resulting empty section.
1332 * @param \stdClass $section the section to schedule for deletion.
1333 * @param bool $forcedeleteifnotempty whether to force section deletion if it contains modules.
1334 * @return bool true if the section was scheduled for deletion, false otherwise.
1336 function course_delete_section_async($section, $forcedeleteifnotempty = true) {
1339 // Objects only, and only valid ones.
1340 if (!is_object($section) ||
empty($section->id
)) {
1344 // Does the object currently exist in the DB for removal (check for stale objects).
1345 $section = $DB->get_record('course_sections', array('id' => $section->id
));
1346 if (!$section ||
!$section->section
) {
1347 // No section exists, or the section is 0. Can't proceed.
1351 // Check whether the section can be removed.
1352 if (!$forcedeleteifnotempty && (!empty($section->sequence
) ||
!empty($section->summary
))) {
1356 $format = course_get_format($section->course
);
1357 $sectionname = $format->get_section_name($section);
1359 // Flag those modules having no existing deletion flag. Some modules may have been scheduled for deletion manually, and we don't
1360 // want to create additional adhoc deletion tasks for these. Moving them to section 0 will suffice.
1361 $affectedmods = $DB->get_records_select('course_modules', 'course = ? AND section = ? AND deletioninprogress <> ?',
1362 [$section->course
, $section->id
, 1], '', 'id');
1363 $DB->set_field('course_modules', 'deletioninprogress', '1', ['course' => $section->course
, 'section' => $section->id
]);
1365 // Move all modules to section 0.
1366 $modules = $DB->get_records('course_modules', ['section' => $section->id
], '');
1367 $sectionzero = $DB->get_record('course_sections', ['course' => $section->course
, 'section' => '0']);
1368 foreach ($modules as $mod) {
1369 moveto_module($mod, $sectionzero);
1372 // Create and queue an adhoc task for the deletion of the modules.
1373 $removaltask = new \core_course\task\
course_delete_modules();
1375 'cms' => $affectedmods,
1376 'userid' => $USER->id
,
1377 'realuserid' => \core\session\manager
::get_realuser()->id
1379 $removaltask->set_custom_data($data);
1380 \core\task\manager
::queue_adhoc_task($removaltask);
1382 // Delete the now empty section, passing in only the section number, which forces the function to fetch a new object.
1383 // The refresh is needed because the section->sequence is now stale.
1384 $result = $format->delete_section($section->section
, $forcedeleteifnotempty);
1386 // Trigger an event for course section deletion.
1388 $context = \context_course
::instance($section->course
);
1389 $event = \core\event\course_section_deleted
::create(
1391 'objectid' => $section->id
,
1392 'courseid' => $section->course
,
1393 'context' => $context,
1395 'sectionnum' => $section->section
,
1396 'sectionname' => $sectionname,
1400 $event->add_record_snapshot('course_sections', $section);
1403 rebuild_course_cache($section->course
, true);
1409 * Updates the course section
1411 * This function does not check permissions or clean values - this has to be done prior to calling it.
1413 * @param int|stdClass $course
1414 * @param stdClass $section record from course_sections table - it will be updated with the new values
1415 * @param array|stdClass $data
1417 function course_update_section($course, $section, $data) {
1420 $courseid = (is_object($course)) ?
$course->id
: (int)$course;
1422 // Some fields can not be updated using this method.
1423 $data = array_diff_key((array)$data, array('id', 'course', 'section', 'sequence'));
1424 $changevisibility = (array_key_exists('visible', $data) && (bool)$data['visible'] != (bool)$section->visible
);
1425 if (array_key_exists('name', $data) && \core_text
::strlen($data['name']) > 255) {
1426 throw new moodle_exception('maximumchars', 'moodle', '', 255);
1429 // Update record in the DB and course format options.
1430 $data['id'] = $section->id
;
1431 $data['timemodified'] = time();
1432 $DB->update_record('course_sections', $data);
1433 // Invalidate the section cache by given section id.
1434 course_modinfo
::purge_course_section_cache_by_id($courseid, $section->id
);
1435 rebuild_course_cache($courseid, false, true);
1436 course_get_format($courseid)->update_section_format_options($data);
1438 // Update fields of the $section object.
1439 foreach ($data as $key => $value) {
1440 if (property_exists($section, $key)) {
1441 $section->$key = $value;
1445 // Trigger an event for course section update.
1446 $event = \core\event\course_section_updated
::create(
1448 'objectid' => $section->id
,
1449 'courseid' => $courseid,
1450 'context' => context_course
::instance($courseid),
1451 'other' => array('sectionnum' => $section->section
)
1456 // If section visibility was changed, hide the modules in this section too.
1457 if ($changevisibility && !empty($section->sequence
)) {
1458 $modules = explode(',', $section->sequence
);
1459 foreach ($modules as $moduleid) {
1460 if ($cm = get_coursemodule_from_id(null, $moduleid, $courseid)) {
1461 if ($data['visible']) {
1462 // As we unhide the section, we use the previously saved visibility stored in visibleold.
1463 set_coursemodule_visible($moduleid, $cm->visibleold
, $cm->visibleoncoursepage
);
1465 // We hide the section, so we hide the module but we store the original state in visibleold.
1466 set_coursemodule_visible($moduleid, 0, $cm->visibleoncoursepage
);
1467 $DB->set_field('course_modules', 'visibleold', $cm->visible
, ['id' => $moduleid]);
1468 \course_modinfo
::purge_course_module_cache($cm->course
, $cm->id
);
1470 \core\event\course_module_updated
::create_from_cm($cm)->trigger();
1473 rebuild_course_cache($courseid, false, true);
1478 * Checks if the current user can delete a section (if course format allows it and user has proper permissions).
1480 * @param int|stdClass $course
1481 * @param int|stdClass|section_info $section
1484 function course_can_delete_section($course, $section) {
1485 if (is_object($section)) {
1486 $section = $section->section
;
1489 // Not possible to delete 0-section.
1492 // Course format should allow to delete sections.
1493 if (!course_get_format($course)->can_delete_section($section)) {
1496 // Make sure user has capability to update course and move sections.
1497 $context = context_course
::instance(is_object($course) ?
$course->id
: $course);
1498 if (!has_all_capabilities(array('moodle/course:movesections', 'moodle/course:update'), $context)) {
1501 // Make sure user has capability to delete each activity in this section.
1502 $modinfo = get_fast_modinfo($course);
1503 if (!empty($modinfo->sections
[$section])) {
1504 foreach ($modinfo->sections
[$section] as $cmid) {
1505 if (!has_capability('moodle/course:manageactivities', context_module
::instance($cmid))) {
1514 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
1515 * an original position number and a target position number, rebuilds the array so that the
1516 * move is made without any duplication of section positions.
1517 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
1518 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
1520 * @param array $sections
1521 * @param int $origin_position
1522 * @param int $target_position
1525 function reorder_sections($sections, $origin_position, $target_position) {
1526 if (!is_array($sections)) {
1530 // We can't move section position 0
1531 if ($origin_position < 1) {
1532 echo "We can't move section position 0";
1536 // Locate origin section in sections array
1537 if (!$origin_key = array_search($origin_position, $sections)) {
1538 echo "searched position not in sections array";
1539 return false; // searched position not in sections array
1542 // Extract origin section
1543 $origin_section = $sections[$origin_key];
1544 unset($sections[$origin_key]);
1546 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
1548 $append_array = array();
1549 foreach ($sections as $id => $position) {
1551 $append_array[$id] = $position;
1552 unset($sections[$id]);
1554 if ($position == $target_position) {
1555 if ($target_position < $origin_position) {
1556 $append_array[$id] = $position;
1557 unset($sections[$id]);
1563 // Append moved section
1564 $sections[$origin_key] = $origin_section;
1566 // Append rest of array (if applicable)
1567 if (!empty($append_array)) {
1568 foreach ($append_array as $id => $position) {
1569 $sections[$id] = $position;
1573 // Renumber positions
1575 foreach ($sections as $id => $p) {
1576 $sections[$id] = $position;
1585 * Move the module object $mod to the specified $section
1586 * If $beforemod exists then that is the module
1587 * before which $modid should be inserted
1589 * @param stdClass|cm_info $mod
1590 * @param stdClass|section_info $section
1591 * @param int|stdClass $beforemod id or object with field id corresponding to the module
1592 * before which the module needs to be included. Null for inserting in the
1593 * end of the section
1594 * @return int new value for module visibility (0 or 1)
1596 function moveto_module($mod, $section, $beforemod=NULL) {
1597 global $OUTPUT, $DB;
1599 // Current module visibility state - return value of this function.
1600 $modvisible = $mod->visible
;
1602 // Remove original module from original section.
1603 if (! delete_mod_from_section($mod->id
, $mod->section
)) {
1604 echo $OUTPUT->notification("Could not delete module from existing section");
1607 // Add the module into the new section.
1608 course_add_cm_to_section($section->course
, $mod->id
, $section->section
, $beforemod);
1610 // If moving to a hidden section then hide module.
1611 if ($mod->section
!= $section->id
) {
1612 if (!$section->visible
&& $mod->visible
) {
1613 // Module was visible but must become hidden after moving to hidden section.
1615 set_coursemodule_visible($mod->id
, 0);
1616 // Set visibleold to 1 so module will be visible when section is made visible.
1617 $DB->set_field('course_modules', 'visibleold', 1, array('id' => $mod->id
));
1619 if ($section->visible
&& !$mod->visible
) {
1620 // Hidden module was moved to the visible section, restore the module visibility from visibleold.
1621 set_coursemodule_visible($mod->id
, $mod->visibleold
);
1622 $modvisible = $mod->visibleold
;
1630 * Returns the list of all editing actions that current user can perform on the module
1632 * @param cm_info $mod The module to produce editing buttons for
1633 * @param int $indent The current indenting (default -1 means no move left-right actions)
1634 * @param int $sr The section to link back to (used for creating the links)
1635 * @return array array of action_link or pix_icon objects
1637 function course_get_cm_edit_actions(cm_info
$mod, $indent = -1, $sr = null) {
1638 global $COURSE, $SITE, $CFG;
1642 $coursecontext = context_course
::instance($mod->course
);
1643 $modcontext = context_module
::instance($mod->id
);
1644 $courseformat = course_get_format($mod->get_course());
1645 $usecomponents = $courseformat->supports_components();
1647 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
1648 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
1650 // No permission to edit anything.
1651 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
1655 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
1658 $str = get_strings(array('delete', 'move', 'moveright', 'moveleft',
1659 'editsettings', 'duplicate', 'modhide', 'makeavailable', 'makeunavailable', 'modshow'), 'moodle');
1660 $str->assign
= get_string('assignroles', 'role');
1661 $str->groupsnone
= get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
1662 $str->groupsseparate
= get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
1663 $str->groupsvisible
= get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
1666 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
1669 $baseurl->param('sr', $sr);
1674 if ($hasmanageactivities) {
1675 $actions['update'] = new action_menu_link_secondary(
1676 new moodle_url($baseurl, array('update' => $mod->id
)),
1677 new pix_icon('t/edit', '', 'moodle', array('class' => 'iconsmall')),
1679 array('class' => 'editing_update', 'data-action' => 'update')
1683 // Move (only for component compatible formats).
1684 if ($usecomponents) {
1685 $actions['move'] = new action_menu_link_secondary(
1686 new moodle_url($baseurl, [
1687 'sesskey' => sesskey(),
1690 new pix_icon('i/dragdrop', '', 'moodle', ['class' => 'iconsmall']),
1693 'class' => 'editing_movecm',
1694 'data-action' => 'moveCm',
1695 'data-id' => $mod->id
,
1701 if ($hasmanageactivities && $indent >= 0) {
1702 $indentlimits = new stdClass();
1703 $indentlimits->min
= 0;
1704 $indentlimits->max
= 16;
1705 if (right_to_left()) { // Exchange arrows on RTL
1706 $rightarrow = 't/left';
1707 $leftarrow = 't/right';
1709 $rightarrow = 't/right';
1710 $leftarrow = 't/left';
1713 if ($indent >= $indentlimits->max
) {
1714 $enabledclass = 'hidden';
1718 $actions['moveright'] = new action_menu_link_secondary(
1719 new moodle_url($baseurl, array('id' => $mod->id
, 'indent' => '1')),
1720 new pix_icon($rightarrow, '', 'moodle', array('class' => 'iconsmall')),
1722 array('class' => 'editing_moveright ' . $enabledclass, 'data-action' => 'moveright',
1723 'data-keepopen' => true, 'data-sectionreturn' => $sr)
1726 if ($indent <= $indentlimits->min
) {
1727 $enabledclass = 'hidden';
1731 $actions['moveleft'] = new action_menu_link_secondary(
1732 new moodle_url($baseurl, array('id' => $mod->id
, 'indent' => '-1')),
1733 new pix_icon($leftarrow, '', 'moodle', array('class' => 'iconsmall')),
1735 array('class' => 'editing_moveleft ' . $enabledclass, 'data-action' => 'moveleft',
1736 'data-keepopen' => true, 'data-sectionreturn' => $sr)
1741 // Hide/Show/Available/Unavailable.
1742 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
1743 $allowstealth = !empty($CFG->allowstealth
) && $courseformat->allow_stealth_module_visibility($mod, $mod->get_section_info());
1745 $sectionvisible = $mod->get_section_info()->visible
;
1746 // The module on the course page may be in one of the following states:
1747 // - Available and displayed on the course page ($displayedoncoursepage);
1748 // - Not available and not displayed on the course page ($unavailable);
1749 // - Available but not displayed on the course page ($stealth) - this can also be a visible activity in a hidden section.
1750 $displayedoncoursepage = $mod->visible
&& $mod->visibleoncoursepage
&& $sectionvisible;
1751 $unavailable = !$mod->visible
;
1752 $stealth = $mod->visible
&& (!$mod->visibleoncoursepage ||
!$sectionvisible);
1753 if ($displayedoncoursepage) {
1754 $actions['hide'] = new action_menu_link_secondary(
1755 new moodle_url($baseurl, array('hide' => $mod->id
)),
1756 new pix_icon('t/hide', '', 'moodle', array('class' => 'iconsmall')),
1759 'class' => 'editing_hide',
1760 'data-action' => ($usecomponents) ?
'cmHide' : 'hide',
1761 'data-id' => $mod->id
,
1764 } else if (!$displayedoncoursepage && $sectionvisible) {
1765 // Offer to "show" only if the section is visible.
1766 $actions['show'] = new action_menu_link_secondary(
1767 new moodle_url($baseurl, array('show' => $mod->id
)),
1768 new pix_icon('t/show', '', 'moodle', array('class' => 'iconsmall')),
1771 'class' => 'editing_show',
1772 'data-action' => ($usecomponents) ?
'cmShow' : 'show',
1773 'data-id' => $mod->id
,
1779 // When making the "stealth" module unavailable we perform the same action as hiding the visible module.
1780 $actions['hide'] = new action_menu_link_secondary(
1781 new moodle_url($baseurl, array('hide' => $mod->id
)),
1782 new pix_icon('t/unblock', '', 'moodle', array('class' => 'iconsmall')),
1783 $str->makeunavailable
,
1785 'class' => 'editing_makeunavailable',
1786 'data-action' => ($usecomponents) ?
'cmHide' : 'hide',
1787 'data-sectionreturn' => $sr,
1788 'data-id' => $mod->id
,
1791 } else if ($unavailable && (!$sectionvisible ||
$allowstealth) && $mod->has_view()) {
1792 // Allow to make visually hidden module available in gradebook and other reports by making it a "stealth" module.
1793 // When the section is hidden it is an equivalent of "showing" the module.
1794 // Activities without the link (i.e. labels) can not be made available but hidden on course page.
1795 $action = $sectionvisible ?
'stealth' : 'show';
1796 if ($usecomponents) {
1797 $action = 'cm' . ucfirst($action);
1799 $actions[$action] = new action_menu_link_secondary(
1800 new moodle_url($baseurl, array('stealth' => $mod->id
)),
1801 new pix_icon('t/block', '', 'moodle', array('class' => 'iconsmall')),
1802 $str->makeavailable
,
1804 'class' => 'editing_makeavailable',
1805 'data-action' => $action,
1806 'data-sectionreturn' => $sr,
1807 'data-id' => $mod->id
,
1813 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
1814 if (has_all_capabilities($dupecaps, $coursecontext) &&
1815 plugin_supports('mod', $mod->modname
, FEATURE_BACKUP_MOODLE2
) &&
1816 course_allowed_module($mod->get_course(), $mod->modname
)) {
1817 $actions['duplicate'] = new action_menu_link_secondary(
1818 new moodle_url($baseurl, array('duplicate' => $mod->id
)),
1819 new pix_icon('t/copy', '', 'moodle', array('class' => 'iconsmall')),
1821 array('class' => 'editing_duplicate', 'data-action' => 'duplicate', 'data-sectionreturn' => $sr)
1826 if (has_capability('moodle/role:assign', $modcontext)){
1827 $actions['assign'] = new action_menu_link_secondary(
1828 new moodle_url('/admin/roles/assign.php', array('contextid' => $modcontext->id
)),
1829 new pix_icon('t/assignroles', '', 'moodle', array('class' => 'iconsmall')),
1831 array('class' => 'editing_assign', 'data-action' => 'assignroles', 'data-sectionreturn' => $sr)
1836 if ($hasmanageactivities) {
1837 $actions['delete'] = new action_menu_link_secondary(
1838 new moodle_url($baseurl, array('delete' => $mod->id
)),
1839 new pix_icon('t/delete', '', 'moodle', array('class' => 'iconsmall')),
1841 array('class' => 'editing_delete', 'data-action' => 'delete', 'data-sectionreturn' => $sr)
1849 * Returns the move action.
1851 * @param cm_info $mod The module to produce a move button for
1852 * @param int $sr The section to link back to (used for creating the links)
1853 * @return The markup for the move action, or an empty string if not available.
1855 function course_get_cm_move(cm_info
$mod, $sr = null) {
1861 $modcontext = context_module
::instance($mod->id
);
1862 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
1865 $str = get_strings(array('move'));
1868 if (!isset($baseurl)) {
1869 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
1872 $baseurl->param('sr', $sr);
1876 if ($hasmanageactivities) {
1877 $pixicon = 'i/dragdrop';
1879 if (!course_ajax_enabled($mod->get_course())) {
1880 // Override for course frontpage until we get drag/drop working there.
1881 $pixicon = 't/move';
1885 'class' => 'editing_move',
1886 'data-action' => 'move',
1887 'data-sectionreturn' => $sr,
1888 'title' => $str->move
,
1889 'aria-label' => $str->move
,
1891 return html_writer
::link(
1892 new moodle_url($baseurl, ['copy' => $mod->id
]),
1893 $OUTPUT->pix_icon($pixicon, '', 'moodle', ['class' => 'iconsmall']),
1901 * given a course object with shortname & fullname, this function will
1902 * truncate the the number of chars allowed and add ... if it was too long
1904 function course_format_name ($course,$max=100) {
1906 $context = context_course
::instance($course->id
);
1907 $shortname = format_string($course->shortname
, true, array('context' => $context));
1908 $fullname = format_string($course->fullname
, true, array('context' => context_course
::instance($course->id
)));
1909 $str = $shortname.': '. $fullname;
1910 if (core_text
::strlen($str) <= $max) {
1914 return core_text
::substr($str,0,$max-3).'...';
1919 * Is the user allowed to add this type of module to this course?
1920 * @param object $course the course settings. Only $course->id is used.
1921 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
1922 * @param \stdClass $user the user to check, defaults to the global user if not provided.
1923 * @return bool whether the current user is allowed to add this type of module to this course.
1925 function course_allowed_module($course, $modname, \stdClass
$user = null) {
1927 $user = $user ??
$USER;
1928 if (is_numeric($modname)) {
1929 throw new coding_exception('Function course_allowed_module no longer
1930 supports numeric module ids. Please update your code to pass the module name.');
1933 $capability = 'mod/' . $modname . ':addinstance';
1934 if (!get_capability_info($capability)) {
1935 // Debug warning that the capability does not exist, but no more than once per page.
1936 static $warned = array();
1937 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE
, MOD_ARCHETYPE_OTHER
);
1938 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM
) {
1939 debugging('The module ' . $modname . ' does not define the standard capability ' .
1940 $capability , DEBUG_DEVELOPER
);
1941 $warned[$modname] = 1;
1944 // If the capability does not exist, the module can always be added.
1948 $coursecontext = context_course
::instance($course->id
);
1949 return has_capability($capability, $coursecontext, $user);
1953 * Efficiently moves many courses around while maintaining
1954 * sortorder in order.
1956 * @param array $courseids is an array of course ids
1957 * @param int $categoryid
1958 * @return bool success
1960 function move_courses($courseids, $categoryid) {
1963 if (empty($courseids)) {
1968 if (!$category = $DB->get_record('course_categories', array('id' => $categoryid))) {
1972 $courseids = array_reverse($courseids);
1973 $newparent = context_coursecat
::instance($category->id
);
1976 list($where, $params) = $DB->get_in_or_equal($courseids);
1977 $dbcourses = $DB->get_records_select('course', 'id ' . $where, $params, '', 'id, category, shortname, fullname');
1978 foreach ($dbcourses as $dbcourse) {
1979 $course = new stdClass();
1980 $course->id
= $dbcourse->id
;
1981 $course->timemodified
= time();
1982 $course->category
= $category->id
;
1983 $course->sortorder
= $category->sortorder +
get_max_courses_in_category() - $i++
;
1984 if ($category->visible
== 0) {
1985 // Hide the course when moving into hidden category, do not update the visibleold flag - we want to get
1986 // to previous state if somebody unhides the category.
1987 $course->visible
= 0;
1990 $DB->update_record('course', $course);
1992 // Update context, so it can be passed to event.
1993 $context = context_course
::instance($course->id
);
1994 $context->update_moved($newparent);
1996 // Trigger a course updated event.
1997 $event = \core\event\course_updated
::create(array(
1998 'objectid' => $course->id
,
1999 'context' => context_course
::instance($course->id
),
2000 'other' => array('shortname' => $dbcourse->shortname
,
2001 'fullname' => $dbcourse->fullname
,
2002 'updatedfields' => array('category' => $category->id
))
2004 $event->set_legacy_logdata(array($course->id
, 'course', 'move', 'edit.php?id=' . $course->id
, $course->id
));
2007 fix_course_sortorder();
2008 cache_helper
::purge_by_event('changesincourse');
2014 * Returns the display name of the given section that the course prefers
2016 * Implementation of this function is provided by course format
2017 * @see core_courseformat\base::get_section_name()
2019 * @param int|stdClass $courseorid The course to get the section name for (object or just course id)
2020 * @param int|stdClass $section Section object from database or just field course_sections.section
2021 * @return string Display name that the course format prefers, e.g. "Week 2"
2023 function get_section_name($courseorid, $section) {
2024 return course_get_format($courseorid)->get_section_name($section);
2028 * Tells if current course format uses sections
2030 * @param string $format Course format ID e.g. 'weeks' $course->format
2033 function course_format_uses_sections($format) {
2034 $course = new stdClass();
2035 $course->format
= $format;
2036 return course_get_format($course)->uses_sections();
2040 * Returns the information about the ajax support in the given source format
2042 * The returned object's property (boolean)capable indicates that
2043 * the course format supports Moodle course ajax features.
2045 * @param string $format
2048 function course_format_ajax_support($format) {
2049 $course = new stdClass();
2050 $course->format
= $format;
2051 return course_get_format($course)->supports_ajax();
2055 * Can the current user delete this course?
2056 * Course creators have exception,
2057 * 1 day after the creation they can sill delete the course.
2058 * @param int $courseid
2061 function can_delete_course($courseid) {
2064 $context = context_course
::instance($courseid);
2066 if (has_capability('moodle/course:delete', $context)) {
2070 // hack: now try to find out if creator created this course recently (1 day)
2071 if (!has_capability('moodle/course:create', $context)) {
2075 $since = time() - 60*60*24;
2076 $course = get_course($courseid);
2078 if ($course->timecreated
< $since) {
2079 return false; // Return if the course was not created in last 24 hours.
2082 $logmanger = get_log_manager();
2083 $readers = $logmanger->get_readers('\core\log\sql_reader');
2084 $reader = reset($readers);
2086 if (empty($reader)) {
2087 return false; // No log reader found.
2091 $select = "userid = :userid AND courseid = :courseid AND eventname = :eventname AND timecreated > :since";
2092 $params = array('userid' => $USER->id
, 'since' => $since, 'courseid' => $course->id
, 'eventname' => '\core\event\course_created');
2094 return (bool)$reader->get_events_select_count($select, $params);
2098 * Save the Your name for 'Some role' strings.
2100 * @param integer $courseid the id of this course.
2101 * @param array $data the data that came from the course settings form.
2103 function save_local_role_names($courseid, $data) {
2105 $context = context_course
::instance($courseid);
2107 foreach ($data as $fieldname => $value) {
2108 if (strpos($fieldname, 'role_') !== 0) {
2111 list($ignored, $roleid) = explode('_', $fieldname);
2113 // make up our mind whether we want to delete, update or insert
2115 $DB->delete_records('role_names', array('contextid' => $context->id
, 'roleid' => $roleid));
2117 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id
, 'roleid' => $roleid))) {
2118 $rolename->name
= $value;
2119 $DB->update_record('role_names', $rolename);
2122 $rolename = new stdClass
;
2123 $rolename->contextid
= $context->id
;
2124 $rolename->roleid
= $roleid;
2125 $rolename->name
= $value;
2126 $DB->insert_record('role_names', $rolename);
2128 // This will ensure the course contacts cache is purged..
2129 core_course_category
::role_assignment_changed($roleid, $context);
2134 * Returns options to use in course overviewfiles filemanager
2136 * @param null|stdClass|core_course_list_element|int $course either object that has 'id' property or just the course id;
2137 * may be empty if course does not exist yet (course create form)
2138 * @return array|null array of options such as maxfiles, maxbytes, accepted_types, etc.
2139 * or null if overviewfiles are disabled
2141 function course_overviewfiles_options($course) {
2143 if (empty($CFG->courseoverviewfileslimit
)) {
2147 // Create accepted file types based on config value, falling back to default all.
2148 $acceptedtypes = (new \core_form\filetypes_util
)->normalize_file_types($CFG->courseoverviewfilesext
);
2149 if (in_array('*', $acceptedtypes) ||
empty($acceptedtypes)) {
2150 $acceptedtypes = '*';
2154 'maxfiles' => $CFG->courseoverviewfileslimit
,
2155 'maxbytes' => $CFG->maxbytes
,
2157 'accepted_types' => $acceptedtypes
2159 if (!empty($course->id
)) {
2160 $options['context'] = context_course
::instance($course->id
);
2161 } else if (is_int($course) && $course > 0) {
2162 $options['context'] = context_course
::instance($course);
2168 * Create a course and either return a $course object
2170 * Please note this functions does not verify any access control,
2171 * the calling code is responsible for all validation (usually it is the form definition).
2173 * @param array $editoroptions course description editor options
2174 * @param object $data - all the data needed for an entry in the 'course' table
2175 * @return object new course instance
2177 function create_course($data, $editoroptions = NULL) {
2180 //check the categoryid - must be given for all new courses
2181 $category = $DB->get_record('course_categories', array('id'=>$data->category
), '*', MUST_EXIST
);
2183 // Check if the shortname already exists.
2184 if (!empty($data->shortname
)) {
2185 if ($DB->record_exists('course', array('shortname' => $data->shortname
))) {
2186 throw new moodle_exception('shortnametaken', '', '', $data->shortname
);
2190 // Check if the idnumber already exists.
2191 if (!empty($data->idnumber
)) {
2192 if ($DB->record_exists('course', array('idnumber' => $data->idnumber
))) {
2193 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber
);
2197 if (empty($CFG->enablecourserelativedates
)) {
2198 // Make sure we're not setting the relative dates mode when the setting is disabled.
2199 unset($data->relativedatesmode
);
2202 if ($errorcode = course_validate_dates((array)$data)) {
2203 throw new moodle_exception($errorcode);
2206 // Check if timecreated is given.
2207 $data->timecreated
= !empty($data->timecreated
) ?
$data->timecreated
: time();
2208 $data->timemodified
= $data->timecreated
;
2210 // place at beginning of any category
2211 $data->sortorder
= 0;
2213 if ($editoroptions) {
2214 // summary text is updated later, we need context to store the files first
2215 $data->summary
= '';
2216 $data->summary_format
= FORMAT_HTML
;
2219 // Get default completion settings as a fallback in case the enablecompletion field is not set.
2220 $courseconfig = get_config('moodlecourse');
2221 $defaultcompletion = !empty($CFG->enablecompletion
) ?
$courseconfig->enablecompletion
: COMPLETION_DISABLED
;
2222 $enablecompletion = $data->enablecompletion ??
$defaultcompletion;
2223 // Unset showcompletionconditions when completion tracking is not enabled for the course.
2224 if ($enablecompletion == COMPLETION_DISABLED
) {
2225 unset($data->showcompletionconditions
);
2226 } else if (!isset($data->showcompletionconditions
)) {
2227 // Show completion conditions should have a default value when completion is enabled. Set it to the site defaults.
2228 // This scenario can happen when a course is created through data generators or through a web service.
2229 $data->showcompletionconditions
= $courseconfig->showcompletionconditions
;
2232 if (!isset($data->visible
)) {
2233 // data not from form, add missing visibility info
2234 $data->visible
= $category->visible
;
2236 $data->visibleold
= $data->visible
;
2238 $newcourseid = $DB->insert_record('course', $data);
2239 $context = context_course
::instance($newcourseid, MUST_EXIST
);
2241 if ($editoroptions) {
2242 // Save the files used in the summary editor and store
2243 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2244 $DB->set_field('course', 'summary', $data->summary
, array('id'=>$newcourseid));
2245 $DB->set_field('course', 'summaryformat', $data->summary_format
, array('id'=>$newcourseid));
2247 if ($overviewfilesoptions = course_overviewfiles_options($newcourseid)) {
2248 // Save the course overviewfiles
2249 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2252 // update course format options
2253 course_get_format($newcourseid)->update_course_format_options($data);
2255 $course = course_get_format($newcourseid)->get_course();
2257 fix_course_sortorder();
2258 // purge appropriate caches in case fix_course_sortorder() did not change anything
2259 cache_helper
::purge_by_event('changesincourse');
2261 // Trigger a course created event.
2262 $event = \core\event\course_created
::create(array(
2263 'objectid' => $course->id
,
2264 'context' => context_course
::instance($course->id
),
2265 'other' => array('shortname' => $course->shortname
,
2266 'fullname' => $course->fullname
)
2272 blocks_add_default_course_blocks($course);
2274 // Create default section and initial sections if specified (unless they've already been created earlier).
2275 // We do not want to call course_create_sections_if_missing() because to avoid creating course cache.
2276 $numsections = isset($data->numsections
) ?
$data->numsections
: 0;
2277 $existingsections = $DB->get_fieldset_sql('SELECT section from {course_sections} WHERE course = ?', [$newcourseid]);
2278 $newsections = array_diff(range(0, $numsections), $existingsections);
2279 foreach ($newsections as $sectionnum) {
2280 course_create_section($newcourseid, $sectionnum, true);
2283 // Save any custom role names.
2284 save_local_role_names($course->id
, (array)$data);
2286 // set up enrolments
2287 enrol_course_updated(true, $course, $data);
2289 // Update course tags.
2290 if (isset($data->tags
)) {
2291 core_tag_tag
::set_item_tags('core', 'course', $course->id
, context_course
::instance($course->id
), $data->tags
);
2294 // Save custom fields if there are any of them in the form.
2295 $handler = core_course\customfield\course_handler
::create();
2296 // Make sure to set the handler's parent context first.
2297 $coursecatcontext = context_coursecat
::instance($category->id
);
2298 $handler->set_parent_context($coursecatcontext);
2299 // Save the custom field data.
2300 $data->id
= $course->id
;
2301 $handler->instance_form_save($data, true);
2309 * Please note this functions does not verify any access control,
2310 * the calling code is responsible for all validation (usually it is the form definition).
2312 * @param object $data - all the data needed for an entry in the 'course' table
2313 * @param array $editoroptions course description editor options
2316 function update_course($data, $editoroptions = NULL) {
2319 // Prevent changes on front page course.
2320 if ($data->id
== SITEID
) {
2321 throw new moodle_exception('invalidcourse', 'error');
2324 $oldcourse = course_get_format($data->id
)->get_course();
2325 $context = context_course
::instance($oldcourse->id
);
2327 // Make sure we're not changing whatever the course's relativedatesmode setting is.
2328 unset($data->relativedatesmode
);
2330 // Capture the updated fields for the log data.
2331 $updatedfields = [];
2332 foreach (get_object_vars($oldcourse) as $field => $value) {
2333 if ($field == 'summary_editor') {
2334 if (($data->$field)['text'] !== $value['text']) {
2335 // The summary might be very long, we don't wan't to fill up the log record with the full text.
2336 $updatedfields[$field] = '(updated)';
2338 } else if ($field == 'tags' && isset($data->tags
)) {
2339 // Tags might not have the same array keys, just check the values.
2340 if (array_values($data->$field) !== array_values($value)) {
2341 $updatedfields[$field] = $data->$field;
2344 if (isset($data->$field) && $data->$field != $value) {
2345 $updatedfields[$field] = $data->$field;
2350 $data->timemodified
= time();
2352 if ($editoroptions) {
2353 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2355 if ($overviewfilesoptions = course_overviewfiles_options($data->id
)) {
2356 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2359 // Check we don't have a duplicate shortname.
2360 if (!empty($data->shortname
) && $oldcourse->shortname
!= $data->shortname
) {
2361 if ($DB->record_exists_sql('SELECT id from {course} WHERE shortname = ? AND id <> ?', array($data->shortname
, $data->id
))) {
2362 throw new moodle_exception('shortnametaken', '', '', $data->shortname
);
2366 // Check we don't have a duplicate idnumber.
2367 if (!empty($data->idnumber
) && $oldcourse->idnumber
!= $data->idnumber
) {
2368 if ($DB->record_exists_sql('SELECT id from {course} WHERE idnumber = ? AND id <> ?', array($data->idnumber
, $data->id
))) {
2369 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber
);
2373 if ($errorcode = course_validate_dates((array)$data)) {
2374 throw new moodle_exception($errorcode);
2377 if (!isset($data->category
) or empty($data->category
)) {
2378 // prevent nulls and 0 in category field
2379 unset($data->category
);
2381 $changesincoursecat = $movecat = (isset($data->category
) and $oldcourse->category
!= $data->category
);
2383 if (!isset($data->visible
)) {
2384 // data not from form, add missing visibility info
2385 $data->visible
= $oldcourse->visible
;
2388 if ($data->visible
!= $oldcourse->visible
) {
2389 // reset the visibleold flag when manually hiding/unhiding course
2390 $data->visibleold
= $data->visible
;
2391 $changesincoursecat = true;
2394 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category
));
2395 if (empty($newcategory->visible
)) {
2396 // make sure when moving into hidden category the course is hidden automatically
2402 // Set newsitems to 0 if format does not support announcements.
2403 if (isset($data->format
)) {
2404 $newcourseformat = course_get_format((object)['format' => $data->format
]);
2405 if (!$newcourseformat->supports_news()) {
2406 $data->newsitems
= 0;
2410 // Set showcompletionconditions to null when completion tracking has been disabled for the course.
2411 if (isset($data->enablecompletion
) && $data->enablecompletion
== COMPLETION_DISABLED
) {
2412 $data->showcompletionconditions
= null;
2415 // Update custom fields if there are any of them in the form.
2416 $handler = core_course\customfield\course_handler
::create();
2417 $handler->instance_form_save($data);
2419 // Update with the new data
2420 $DB->update_record('course', $data);
2421 // make sure the modinfo cache is reset
2422 rebuild_course_cache($data->id
);
2424 // Purge course image cache in case if course image has been updated.
2425 \cache
::make('core', 'course_image')->delete($data->id
);
2427 // update course format options with full course data
2428 course_get_format($data->id
)->update_course_format_options($data, $oldcourse);
2430 $course = $DB->get_record('course', array('id'=>$data->id
));
2433 $newparent = context_coursecat
::instance($course->category
);
2434 $context->update_moved($newparent);
2436 $fixcoursesortorder = $movecat ||
(isset($data->sortorder
) && ($oldcourse->sortorder
!= $data->sortorder
));
2437 if ($fixcoursesortorder) {
2438 fix_course_sortorder();
2441 // purge appropriate caches in case fix_course_sortorder() did not change anything
2442 cache_helper
::purge_by_event('changesincourse');
2443 if ($changesincoursecat) {
2444 cache_helper
::purge_by_event('changesincoursecat');
2447 // Test for and remove blocks which aren't appropriate anymore
2448 blocks_remove_inappropriate($course);
2450 // Save any custom role names.
2451 save_local_role_names($course->id
, $data);
2453 // update enrol settings
2454 enrol_course_updated(false, $course, $data);
2456 // Update course tags.
2457 if (isset($data->tags
)) {
2458 core_tag_tag
::set_item_tags('core', 'course', $course->id
, context_course
::instance($course->id
), $data->tags
);
2461 // Trigger a course updated event.
2462 $event = \core\event\course_updated
::create(array(
2463 'objectid' => $course->id
,
2464 'context' => context_course
::instance($course->id
),
2465 'other' => array('shortname' => $course->shortname
,
2466 'fullname' => $course->fullname
,
2467 'updatedfields' => $updatedfields)
2470 $event->set_legacy_logdata(array($course->id
, 'course', 'update', 'edit.php?id=' . $course->id
, $course->id
));
2473 if ($oldcourse->format
!== $course->format
) {
2474 // Remove all options stored for the previous format
2475 // We assume that new course format migrated everything it needed watching trigger
2476 // 'course_updated' and in method format_XXX::update_course_format_options()
2477 $DB->delete_records('course_format_options',
2478 array('courseid' => $course->id
, 'format' => $oldcourse->format
));
2483 * Calculate the average number of enrolled participants per course.
2485 * This is intended for statistics purposes during the site registration. Only visible courses are taken into account.
2486 * Front page enrolments are excluded.
2488 * @param bool $onlyactive Consider only active enrolments in enabled plugins and obey the enrolment time restrictions.
2489 * @param int $lastloginsince If specified, count only users who logged in after this timestamp.
2492 function average_number_of_participants(bool $onlyactive = false, int $lastloginsince = null): float {
2497 $sql = "SELECT DISTINCT ue.userid, e.courseid
2498 FROM {user_enrolments} ue
2499 JOIN {enrol} e ON e.id = ue.enrolid
2500 JOIN {course} c ON c.id = e.courseid ";
2502 if ($onlyactive ||
$lastloginsince) {
2503 $sql .= "JOIN {user} u ON u.id = ue.userid ";
2506 $sql .= "WHERE e.courseid <> " . SITEID
. " AND c.visible = 1 ";
2509 $sql .= "AND ue.status = :active
2510 AND e.status = :enabled
2511 AND ue.timestart < :now1
2512 AND (ue.timeend = 0 OR ue.timeend > :now2) ";
2514 // Same as in the enrollib - the rounding should help caching in the database.
2515 $now = round(time(), -2);
2518 'active' => ENROL_USER_ACTIVE
,
2519 'enabled' => ENROL_INSTANCE_ENABLED
,
2525 if ($lastloginsince) {
2526 $sql .= "AND u.lastlogin > :lastlogin ";
2527 $params['lastlogin'] = $lastloginsince;
2530 $sql = "SELECT COUNT(*)
2533 $enrolmenttotal = $DB->count_records_sql($sql, $params);
2535 // Get the number of visible courses (exclude the front page).
2536 $coursetotal = $DB->count_records('course', ['visible' => 1]);
2537 $coursetotal = $coursetotal - 1;
2539 if (empty($coursetotal)) {
2540 $participantaverage = 0;
2543 $participantaverage = $enrolmenttotal / $coursetotal;
2546 return $participantaverage;
2550 * Average number of course modules
2553 function average_number_of_courses_modules() {
2556 //count total of visible course module (except front page)
2557 $sql = 'SELECT COUNT(*) FROM (
2558 SELECT cm.course, cm.module
2559 FROM {course} c, {course_modules} cm
2560 WHERE c.id = cm.course
2563 AND c.visible = 1) total';
2564 $params = array('siteid' => $SITE->id
);
2565 $moduletotal = $DB->count_records_sql($sql, $params);
2568 //count total of visible courses (minus front page)
2569 $coursetotal = $DB->count_records('course', array('visible' => 1));
2570 $coursetotal = $coursetotal - 1 ;
2572 //average of course module
2573 if (empty($coursetotal)) {
2574 $coursemoduleaverage = 0;
2576 $coursemoduleaverage = $moduletotal / $coursetotal;
2579 return $coursemoduleaverage;
2583 * This class pertains to course requests and contains methods associated with
2584 * create, approving, and removing course requests.
2586 * Please note we do not allow embedded images here because there is no context
2587 * to store them with proper access control.
2589 * @copyright 2009 Sam Hemelryk
2590 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2593 * @property-read int $id
2594 * @property-read string $fullname
2595 * @property-read string $shortname
2596 * @property-read string $summary
2597 * @property-read int $summaryformat
2598 * @property-read int $summarytrust
2599 * @property-read string $reason
2600 * @property-read int $requester
2602 class course_request
{
2605 * This is the stdClass that stores the properties for the course request
2606 * and is externally accessed through the __get magic method
2609 protected $properties;
2612 * An array of options for the summary editor used by course request forms.
2613 * This is initially set by {@link summary_editor_options()}
2617 protected static $summaryeditoroptions;
2620 * Static function to prepare the summary editor for working with a course
2624 * @param null|stdClass $data Optional, an object containing the default values
2625 * for the form, these may be modified when preparing the
2626 * editor so this should be called before creating the form
2627 * @return stdClass An object that can be used to set the default values for
2630 public static function prepare($data=null) {
2631 if ($data === null) {
2632 $data = new stdClass
;
2634 $data = file_prepare_standard_editor($data, 'summary', self
::summary_editor_options());
2639 * Static function to create a new course request when passed an array of properties
2642 * This function also handles saving any files that may have been used in the editor
2645 * @param stdClass $data
2646 * @return course_request The newly created course request
2648 public static function create($data) {
2649 global $USER, $DB, $CFG;
2650 $data->requester
= $USER->id
;
2652 // Setting the default category if none set.
2653 if (empty($data->category
) ||
!empty($CFG->lockrequestcategory
)) {
2654 $data->category
= $CFG->defaultrequestcategory
;
2657 // Summary is a required field so copy the text over
2658 $data->summary
= $data->summary_editor
['text'];
2659 $data->summaryformat
= $data->summary_editor
['format'];
2661 $data->id
= $DB->insert_record('course_request', $data);
2663 // Create a new course_request object and return it
2664 $request = new course_request($data);
2666 // Notify the admin if required.
2667 if ($users = get_users_from_config($CFG->courserequestnotify
, 'moodle/site:approvecourse')) {
2670 $a->link
= "$CFG->wwwroot/course/pending.php";
2671 $a->user
= fullname($USER);
2672 $subject = get_string('courserequest');
2673 $message = get_string('courserequestnotifyemail', 'admin', $a);
2674 foreach ($users as $user) {
2675 $request->notify($user, $USER, 'courserequested', $subject, $message);
2683 * Returns an array of options to use with a summary editor
2685 * @uses course_request::$summaryeditoroptions
2686 * @return array An array of options to use with the editor
2688 public static function summary_editor_options() {
2690 if (self
::$summaryeditoroptions === null) {
2691 self
::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
2693 return self
::$summaryeditoroptions;
2697 * Loads the properties for this course request object. Id is required and if
2698 * only id is provided then we load the rest of the properties from the database
2700 * @param stdClass|int $properties Either an object containing properties
2701 * or the course_request id to load
2703 public function __construct($properties) {
2705 if (empty($properties->id
)) {
2706 if (empty($properties)) {
2707 throw new coding_exception('You must provide a course request id when creating a course_request object');
2710 $properties = new stdClass
;
2711 $properties->id
= (int)$id;
2714 if (empty($properties->requester
)) {
2715 if (!($this->properties
= $DB->get_record('course_request', array('id' => $properties->id
)))) {
2716 throw new \
moodle_exception('unknowncourserequest');
2719 $this->properties
= $properties;
2721 $this->properties
->collision
= null;
2725 * Returns the requested property
2727 * @param string $key
2730 public function __get($key) {
2731 return $this->properties
->$key;
2735 * Override this to ensure empty($request->blah) calls return a reliable answer...
2737 * This is required because we define the __get method
2740 * @return bool True is it not empty, false otherwise
2742 public function __isset($key) {
2743 return (!empty($this->properties
->$key));
2747 * Returns the user who requested this course
2749 * Uses a static var to cache the results and cut down the number of db queries
2751 * @staticvar array $requesters An array of cached users
2752 * @return stdClass The user who requested the course
2754 public function get_requester() {
2756 static $requesters= array();
2757 if (!array_key_exists($this->properties
->requester
, $requesters)) {
2758 $requesters[$this->properties
->requester
] = $DB->get_record('user', array('id'=>$this->properties
->requester
));
2760 return $requesters[$this->properties
->requester
];
2764 * Checks that the shortname used by the course does not conflict with any other
2765 * courses that exist
2767 * @param string|null $shortnamemark The string to append to the requests shortname
2768 * should a conflict be found
2769 * @return bool true is there is a conflict, false otherwise
2771 public function check_shortname_collision($shortnamemark = '[*]') {
2774 if ($this->properties
->collision
!== null) {
2775 return $this->properties
->collision
;
2778 if (empty($this->properties
->shortname
)) {
2779 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER
);
2780 $this->properties
->collision
= false;
2781 } else if ($DB->record_exists('course', array('shortname' => $this->properties
->shortname
))) {
2782 if (!empty($shortnamemark)) {
2783 $this->properties
->shortname
.= ' '.$shortnamemark;
2785 $this->properties
->collision
= true;
2787 $this->properties
->collision
= false;
2789 return $this->properties
->collision
;
2793 * Checks user capability to approve a requested course
2795 * If course was requested without category for some reason (might happen if $CFG->defaultrequestcategory is
2796 * misconfigured), we check capabilities 'moodle/site:approvecourse' and 'moodle/course:changecategory'.
2800 public function can_approve() {
2803 if ($this->properties
->category
) {
2804 $category = core_course_category
::get($this->properties
->category
, IGNORE_MISSING
);
2805 } else if ($CFG->defaultrequestcategory
) {
2806 $category = core_course_category
::get($CFG->defaultrequestcategory
, IGNORE_MISSING
);
2809 return has_capability('moodle/site:approvecourse', $category->get_context());
2812 // We can not determine the context where the course should be created. The approver should have
2813 // both capabilities to approve courses and change course category in the system context.
2814 return has_all_capabilities(['moodle/site:approvecourse', 'moodle/course:changecategory'], context_system
::instance());
2818 * Returns the category where this course request should be created
2820 * Note that we don't check here that user has a capability to view
2821 * hidden categories if he has capabilities 'moodle/site:approvecourse' and
2822 * 'moodle/course:changecategory'
2824 * @return core_course_category
2826 public function get_category() {
2828 if ($this->properties
->category
&& ($category = core_course_category
::get($this->properties
->category
, IGNORE_MISSING
))) {
2830 } else if ($CFG->defaultrequestcategory
&&
2831 ($category = core_course_category
::get($CFG->defaultrequestcategory
, IGNORE_MISSING
))) {
2834 return core_course_category
::get_default();
2839 * This function approves the request turning it into a course
2841 * This function converts the course request into a course, at the same time
2842 * transferring any files used in the summary to the new course and then removing
2843 * the course request and the files associated with it.
2845 * @return int The id of the course that was created from this request
2847 public function approve() {
2848 global $CFG, $DB, $USER;
2850 require_once($CFG->dirroot
. '/backup/util/includes/restore_includes.php');
2852 $user = $DB->get_record('user', array('id' => $this->properties
->requester
, 'deleted'=>0), '*', MUST_EXIST
);
2854 $courseconfig = get_config('moodlecourse');
2856 // Transfer appropriate settings
2857 $data = clone($this->properties
);
2859 unset($data->reason
);
2860 unset($data->requester
);
2863 $category = $this->get_category();
2864 $data->category
= $category->id
;
2865 // Set misc settings
2866 $data->requested
= 1;
2868 // Apply course default settings
2869 $data->format
= $courseconfig->format
;
2870 $data->newsitems
= $courseconfig->newsitems
;
2871 $data->showgrades
= $courseconfig->showgrades
;
2872 $data->showreports
= $courseconfig->showreports
;
2873 $data->maxbytes
= $courseconfig->maxbytes
;
2874 $data->groupmode
= $courseconfig->groupmode
;
2875 $data->groupmodeforce
= $courseconfig->groupmodeforce
;
2876 $data->visible
= $courseconfig->visible
;
2877 $data->visibleold
= $data->visible
;
2878 $data->lang
= $courseconfig->lang
;
2879 $data->enablecompletion
= $courseconfig->enablecompletion
;
2880 $data->numsections
= $courseconfig->numsections
;
2881 $data->startdate
= usergetmidnight(time());
2882 if ($courseconfig->courseenddateenabled
) {
2883 $data->enddate
= usergetmidnight(time()) +
$courseconfig->courseduration
;
2886 list($data->fullname
, $data->shortname
) = restore_dbops
::calculate_course_names(0, $data->fullname
, $data->shortname
);
2888 $course = create_course($data);
2889 $context = context_course
::instance($course->id
, MUST_EXIST
);
2891 // add enrol instances
2892 if (!$DB->record_exists('enrol', array('courseid'=>$course->id
, 'enrol'=>'manual'))) {
2893 if ($manual = enrol_get_plugin('manual')) {
2894 $manual->add_default_instance($course);
2898 // enrol the requester as teacher if necessary
2899 if (!empty($CFG->creatornewroleid
) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
2900 enrol_try_internal_enrol($course->id
, $user->id
, $CFG->creatornewroleid
);
2905 $a = new stdClass();
2906 $a->name
= format_string($course->fullname
, true, array('context' => context_course
::instance($course->id
)));
2907 $a->url
= $CFG->wwwroot
.'/course/view.php?id=' . $course->id
;
2908 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a), $course->id
);
2914 * Reject a course request
2916 * This function rejects a course request, emailing the requesting user the
2917 * provided notice and then removing the request from the database
2919 * @param string $notice The message to display to the user
2921 public function reject($notice) {
2923 $user = $DB->get_record('user', array('id' => $this->properties
->requester
), '*', MUST_EXIST
);
2924 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
2929 * Deletes the course request and any associated files
2931 public function delete() {
2933 $DB->delete_records('course_request', array('id' => $this->properties
->id
));
2937 * Send a message from one user to another using events_trigger
2939 * @param object $touser
2940 * @param object $fromuser
2941 * @param string $name
2942 * @param string $subject
2943 * @param string $message
2944 * @param int|null $courseid
2946 protected function notify($touser, $fromuser, $name, $subject, $message, $courseid = null) {
2947 $eventdata = new \core\message\
message();
2948 $eventdata->courseid
= empty($courseid) ? SITEID
: $courseid;
2949 $eventdata->component
= 'moodle';
2950 $eventdata->name
= $name;
2951 $eventdata->userfrom
= $fromuser;
2952 $eventdata->userto
= $touser;
2953 $eventdata->subject
= $subject;
2954 $eventdata->fullmessage
= $message;
2955 $eventdata->fullmessageformat
= FORMAT_PLAIN
;
2956 $eventdata->fullmessagehtml
= '';
2957 $eventdata->smallmessage
= '';
2958 $eventdata->notification
= 1;
2959 message_send($eventdata);
2963 * Checks if current user can request a course in this context
2965 * @param context $context
2968 public static function can_request(context
$context) {
2970 if (empty($CFG->enablecourserequests
)) {
2973 if (has_capability('moodle/course:create', $context)) {
2977 if ($context instanceof context_system
) {
2978 $defaultcontext = context_coursecat
::instance($CFG->defaultrequestcategory
, IGNORE_MISSING
);
2979 return $defaultcontext &&
2980 has_capability('moodle/course:request', $defaultcontext);
2981 } else if ($context instanceof context_coursecat
) {
2982 if (!$CFG->lockrequestcategory ||
$CFG->defaultrequestcategory
== $context->instanceid
) {
2983 return has_capability('moodle/course:request', $context);
2991 * Return a list of page types
2992 * @param string $pagetype current page type
2993 * @param context $parentcontext Block's parent context
2994 * @param context $currentcontext Current context of block
2995 * @return array array of page types
2997 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
2998 if ($pagetype === 'course-index' ||
$pagetype === 'course-index-category') {
2999 // For courses and categories browsing pages (/course/index.php) add option to show on ANY category page
3000 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
3001 'course-index-*' => get_string('page-course-index-x', 'pagetype'),
3003 } else if ($currentcontext && (!($coursecontext = $currentcontext->get_course_context(false)) ||
$coursecontext->instanceid
== SITEID
)) {
3004 // We know for sure that despite pagetype starts with 'course-' this is not a page in course context (i.e. /course/search.php, etc.)
3005 $pagetypes = array('*' => get_string('page-x', 'pagetype'));
3007 // Otherwise consider it a page inside a course even if $currentcontext is null
3008 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
3009 'course-*' => get_string('page-course-x', 'pagetype'),
3010 'course-view-*' => get_string('page-course-view-x', 'pagetype')
3017 * Determine whether course ajax should be enabled for the specified course
3019 * @param stdClass $course The course to test against
3020 * @return boolean Whether course ajax is enabled or note
3022 function course_ajax_enabled($course) {
3023 global $CFG, $PAGE, $SITE;
3025 // The user must be editing for AJAX to be included
3026 if (!$PAGE->user_is_editing()) {
3030 // Check that the theme suports
3031 if (!$PAGE->theme
->enablecourseajax
) {
3035 // Check that the course format supports ajax functionality
3036 // The site 'format' doesn't have information on course format support
3037 if ($SITE->id
!== $course->id
) {
3038 $courseformatajaxsupport = course_format_ajax_support($course->format
);
3039 if (!$courseformatajaxsupport->capable
) {
3044 // All conditions have been met so course ajax should be enabled
3049 * Include the relevant javascript and language strings for the resource
3050 * toolbox YUI module
3052 * @param integer $id The ID of the course being applied to
3053 * @param array $usedmodules An array containing the names of the modules in use on the page
3054 * @param array $enabledmodules An array containing the names of the enabled (visible) modules on this site
3055 * @param stdClass $config An object containing configuration parameters for ajax modules including:
3056 * * resourceurl The URL to post changes to for resource changes
3057 * * sectionurl The URL to post changes to for section changes
3058 * * pageparams Additional parameters to pass through in the post
3061 function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) {
3062 global $CFG, $PAGE, $SITE;
3064 // Init the course editor module to support UI components.
3065 $format = course_get_format($course);
3066 include_course_editor($format);
3068 // Ensure that ajax should be included
3069 if (!course_ajax_enabled($course)) {
3073 // Component based formats don't use YUI drag and drop anymore.
3074 if (!$format->supports_components() && course_format_uses_sections($course->format
)) {
3077 $config = new stdClass();
3080 // The URL to use for resource changes.
3081 if (!isset($config->resourceurl
)) {
3082 $config->resourceurl
= '/course/rest.php';
3085 // The URL to use for section changes.
3086 if (!isset($config->sectionurl
)) {
3087 $config->sectionurl
= '/course/rest.php';
3090 // Any additional parameters which need to be included on page submission.
3091 if (!isset($config->pageparams
)) {
3092 $config->pageparams
= array();
3095 $PAGE->requires
->yui_module('moodle-course-dragdrop', 'M.course.init_section_dragdrop',
3097 'courseid' => $course->id
,
3098 'ajaxurl' => $config->sectionurl
,
3099 'config' => $config,
3102 $PAGE->requires
->yui_module('moodle-course-dragdrop', 'M.course.init_resource_dragdrop',
3104 'courseid' => $course->id
,
3105 'ajaxurl' => $config->resourceurl
,
3106 'config' => $config,
3110 // Require various strings for the command toolbox
3111 $PAGE->requires
->strings_for_js(array(
3114 'deletechecktypename',
3116 'edittitleinstructions',
3124 'clicktochangeinbrackets',
3129 'movecoursesection',
3132 'emptydragdropregion',
3138 // Include section-specific strings for formats which support sections.
3139 if (course_format_uses_sections($course->format
)) {
3140 $PAGE->requires
->strings_for_js(array(
3143 ), 'format_' . $course->format
);
3146 // For confirming resource deletion we need the name of the module in question
3147 foreach ($usedmodules as $module => $modname) {
3148 $PAGE->requires
->string_for_js('pluginname', $module);
3151 // Load drag and drop upload AJAX.
3152 require_once($CFG->dirroot
.'/course/dnduploadlib.php');
3153 dndupload_add_to_course($course, $enabledmodules);
3155 $PAGE->requires
->js_call_amd('core_course/actions', 'initCoursePage', array($course->format
));
3161 * Include and configure the course editor modules.
3163 * @param course_format $format the course format instance.
3165 function include_course_editor(course_format
$format) {
3166 global $PAGE, $SITE;
3168 $course = $format->get_course();
3170 if ($SITE->id
=== $course->id
) {
3174 $statekey = course_format
::session_cache($course);
3176 // Edition mode and some format specs must be passed to the init method.
3178 'editing' => $format->show_editor(),
3179 'supportscomponents' => $format->supports_components(),
3180 'statekey' => $statekey,
3182 // All the new editor elements will be loaded after the course is presented and
3183 // the initial course state will be generated using core_course_get_state webservice.
3184 $PAGE->requires
->js_call_amd('core_courseformat/courseeditor', 'setViewFormat', [$course->id
, $setup]);
3188 * Returns the sorted list of available course formats, filtered by enabled if necessary
3190 * @param bool $enabledonly return only formats that are enabled
3191 * @return array array of sorted format names
3193 function get_sorted_course_formats($enabledonly = false) {
3195 $formats = core_component
::get_plugin_list('format');
3197 if (!empty($CFG->format_plugins_sortorder
)) {
3198 $order = explode(',', $CFG->format_plugins_sortorder
);
3199 $order = array_merge(array_intersect($order, array_keys($formats)),
3200 array_diff(array_keys($formats), $order));
3202 $order = array_keys($formats);
3204 if (!$enabledonly) {
3207 $sortedformats = array();
3208 foreach ($order as $formatname) {
3209 if (!get_config('format_'.$formatname, 'disabled')) {
3210 $sortedformats[] = $formatname;
3213 return $sortedformats;
3217 * The URL to use for the specified course (with section)
3219 * @param int|stdClass $courseorid The course to get the section name for (either object or just course id)
3220 * @param int|stdClass $section Section object from database or just field course_sections.section
3221 * if omitted the course view page is returned
3222 * @param array $options options for view URL. At the moment core uses:
3223 * 'navigation' (bool) if true and section has no separate page, the function returns null
3224 * 'sr' (int) used by multipage formats to specify to which section to return
3225 * @return moodle_url The url of course
3227 function course_get_url($courseorid, $section = null, $options = array()) {
3228 return course_get_format($courseorid)->get_view_url($section, $options);
3235 * - capability checks and other checks
3236 * - create the module from the module info
3238 * @param object $module
3239 * @return object the created module info
3240 * @throws moodle_exception if user is not allowed to perform the action or module is not allowed in this course
3242 function create_module($moduleinfo) {
3245 require_once($CFG->dirroot
. '/course/modlib.php');
3247 // Check manadatory attributs.
3248 $mandatoryfields = array('modulename', 'course', 'section', 'visible');
3249 if (plugin_supports('mod', $moduleinfo->modulename
, FEATURE_MOD_INTRO
, true)) {
3250 $mandatoryfields[] = 'introeditor';
3252 foreach($mandatoryfields as $mandatoryfield) {
3253 if (!isset($moduleinfo->{$mandatoryfield})) {
3254 throw new moodle_exception('createmodulemissingattribut', '', '', $mandatoryfield);
3258 // Some additional checks (capability / existing instances).
3259 $course = $DB->get_record('course', array('id'=>$moduleinfo->course
), '*', MUST_EXIST
);
3260 list($module, $context, $cw) = can_add_moduleinfo($course, $moduleinfo->modulename
, $moduleinfo->section
);
3263 $moduleinfo->module
= $module->id
;
3264 $moduleinfo = add_moduleinfo($moduleinfo, $course, null);
3273 * - capability and other checks
3274 * - update the module
3276 * @param object $module
3277 * @return object the updated module info
3278 * @throws moodle_exception if current user is not allowed to update the module
3280 function update_module($moduleinfo) {
3283 require_once($CFG->dirroot
. '/course/modlib.php');
3285 // Check the course module exists.
3286 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule
, 0, false, MUST_EXIST
);
3288 // Check the course exists.
3289 $course = $DB->get_record('course', array('id'=>$cm->course
), '*', MUST_EXIST
);
3291 // Some checks (capaibility / existing instances).
3292 list($cm, $context, $module, $data, $cw) = can_update_moduleinfo($cm);
3294 // Retrieve few information needed by update_moduleinfo.
3295 $moduleinfo->modulename
= $cm->modname
;
3296 if (!isset($moduleinfo->scale
)) {
3297 $moduleinfo->scale
= 0;
3299 $moduleinfo->type
= 'mod';
3301 // Update the module.
3302 list($cm, $moduleinfo) = update_moduleinfo($cm, $moduleinfo, $course, null);
3308 * Duplicate a module on the course for ajax.
3310 * @see mod_duplicate_module()
3311 * @param object $course The course
3312 * @param object $cm The course module to duplicate
3313 * @param int $sr The section to link back to (used for creating the links)
3314 * @throws moodle_exception if the plugin doesn't support duplication
3315 * @return Object containing:
3316 * - fullcontent: The HTML markup for the created CM
3317 * - cmid: The CMID of the newly created CM
3318 * - redirect: Whether to trigger a redirect following this change
3320 function mod_duplicate_activity($course, $cm, $sr = null) {
3323 $newcm = duplicate_module($course, $cm);
3325 $resp = new stdClass();
3328 $format = course_get_format($course);
3329 $renderer = $format->get_renderer($PAGE);
3330 $modinfo = $format->get_modinfo();
3331 $section = $modinfo->get_section_info($newcm->sectionnum
);
3333 // Get the new element html content.
3334 $resp->fullcontent
= $renderer->course_section_updated_cm_item($format, $section, $newcm);
3336 $resp->cmid
= $newcm->id
;
3338 // Trigger a redirect.
3339 $resp->redirect
= true;
3345 * Api to duplicate a module.
3347 * @param object $course course object.
3348 * @param object $cm course module object to be duplicated.
3352 * @throws coding_exception
3353 * @throws moodle_exception
3354 * @throws restore_controller_exception
3356 * @return cm_info|null cminfo object if we sucessfully duplicated the mod and found the new cm.
3358 function duplicate_module($course, $cm) {
3359 global $CFG, $DB, $USER;
3360 require_once($CFG->dirroot
. '/backup/util/includes/backup_includes.php');
3361 require_once($CFG->dirroot
. '/backup/util/includes/restore_includes.php');
3362 require_once($CFG->libdir
. '/filelib.php');
3364 $a = new stdClass();
3365 $a->modtype
= get_string('modulename', $cm->modname
);
3366 $a->modname
= format_string($cm->name
);
3368 if (!plugin_supports('mod', $cm->modname
, FEATURE_BACKUP_MOODLE2
)) {
3369 throw new moodle_exception('duplicatenosupport', 'error', '', $a);
3372 // Backup the activity.
3374 $bc = new backup_controller(backup
::TYPE_1ACTIVITY
, $cm->id
, backup
::FORMAT_MOODLE
,
3375 backup
::INTERACTIVE_NO
, backup
::MODE_IMPORT
, $USER->id
);
3377 $backupid = $bc->get_backupid();
3378 $backupbasepath = $bc->get_plan()->get_basepath();
3380 $bc->execute_plan();
3384 // Restore the backup immediately.
3386 $rc = new restore_controller($backupid, $course->id
,
3387 backup
::INTERACTIVE_NO
, backup
::MODE_IMPORT
, $USER->id
, backup
::TARGET_CURRENT_ADDING
);
3389 // Make sure that the restore_general_groups setting is always enabled when duplicating an activity.
3390 $plan = $rc->get_plan();
3391 $groupsetting = $plan->get_setting('groups');
3392 if (empty($groupsetting->get_value())) {
3393 $groupsetting->set_value(true);
3396 $cmcontext = context_module
::instance($cm->id
);
3397 if (!$rc->execute_precheck()) {
3398 $precheckresults = $rc->get_precheck_results();
3399 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
3400 if (empty($CFG->keeptempdirectoriesonbackup
)) {
3401 fulldelete($backupbasepath);
3406 $rc->execute_plan();
3408 // Now a bit hacky part follows - we try to get the cmid of the newly
3409 // restored copy of the module.
3411 $tasks = $rc->get_plan()->get_tasks();
3412 foreach ($tasks as $task) {
3413 if (is_subclass_of($task, 'restore_activity_task')) {
3414 if ($task->get_old_contextid() == $cmcontext->id
) {
3415 $newcmid = $task->get_moduleid();
3423 if (empty($CFG->keeptempdirectoriesonbackup
)) {
3424 fulldelete($backupbasepath);
3427 // If we know the cmid of the new course module, let us move it
3428 // right below the original one. otherwise it will stay at the
3429 // end of the section.
3431 // Proceed with activity renaming before everything else. We don't use APIs here to avoid
3432 // triggering a lot of create/update duplicated events.
3433 $newcm = get_coursemodule_from_id($cm->modname
, $newcmid, $cm->course
);
3434 // Add ' (copy)' to duplicates. Note we don't cleanup or validate lengths here. It comes
3435 // from original name that was valid, so the copy should be too.
3436 $newname = get_string('duplicatedmodule', 'moodle', $newcm->name
);
3437 $DB->set_field($cm->modname
, 'name', $newname, ['id' => $newcm->instance
]);
3439 $section = $DB->get_record('course_sections', array('id' => $cm->section
, 'course' => $cm->course
));
3440 $modarray = explode(",", trim($section->sequence
));
3441 $cmindex = array_search($cm->id
, $modarray);
3442 if ($cmindex !== false && $cmindex < count($modarray) - 1) {
3443 moveto_module($newcm, $section, $modarray[$cmindex +
1]);
3446 // Update calendar events with the duplicated module.
3447 // The following line is to be removed in MDL-58906.
3448 course_module_update_calendar_events($newcm->modname
, null, $newcm);
3450 // Trigger course module created event. We can trigger the event only if we know the newcmid.
3451 $newcm = get_fast_modinfo($cm->course
)->get_cm($newcmid);
3452 $event = \core\event\course_module_created
::create_from_cm($newcm);
3456 return isset($newcm) ?
$newcm : null;
3460 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3461 * Sorts by descending order of time.
3463 * @param stdClass $a First object
3464 * @param stdClass $b Second object
3465 * @return int 0,1,-1 representing the order
3467 function compare_activities_by_time_desc($a, $b) {
3468 // Make sure the activities actually have a timestamp property.
3469 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3472 // We treat instances without timestamp as if they have a timestamp of 0.
3473 if ((!property_exists($a, 'timestamp')) && (property_exists($b,'timestamp'))) {
3476 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3479 if ($a->timestamp
== $b->timestamp
) {
3482 return ($a->timestamp
> $b->timestamp
) ?
-1 : 1;
3486 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3487 * Sorts by ascending order of time.
3489 * @param stdClass $a First object
3490 * @param stdClass $b Second object
3491 * @return int 0,1,-1 representing the order
3493 function compare_activities_by_time_asc($a, $b) {
3494 // Make sure the activities actually have a timestamp property.
3495 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3498 // We treat instances without timestamp as if they have a timestamp of 0.
3499 if ((!property_exists($a, 'timestamp')) && (property_exists($b, 'timestamp'))) {
3502 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3505 if ($a->timestamp
== $b->timestamp
) {
3508 return ($a->timestamp
< $b->timestamp
) ?
-1 : 1;
3512 * Changes the visibility of a course.
3514 * @param int $courseid The course to change.
3515 * @param bool $show True to make it visible, false otherwise.
3518 function course_change_visibility($courseid, $show = true) {
3519 $course = new stdClass
;
3520 $course->id
= $courseid;
3521 $course->visible
= ($show) ?
'1' : '0';
3522 $course->visibleold
= $course->visible
;
3523 update_course($course);
3528 * Changes the course sortorder by one, moving it up or down one in respect to sort order.
3530 * @param stdClass|core_course_list_element $course
3531 * @param bool $up If set to true the course will be moved up one. Otherwise down one.
3534 function course_change_sortorder_by_one($course, $up) {
3536 $params = array($course->sortorder
, $course->category
);
3538 $select = 'sortorder < ? AND category = ?';
3539 $sort = 'sortorder DESC';
3541 $select = 'sortorder > ? AND category = ?';
3542 $sort = 'sortorder ASC';
3544 fix_course_sortorder();
3545 $swapcourse = $DB->get_records_select('course', $select, $params, $sort, '*', 0, 1);
3547 $swapcourse = reset($swapcourse);
3548 $DB->set_field('course', 'sortorder', $swapcourse->sortorder
, array('id' => $course->id
));
3549 $DB->set_field('course', 'sortorder', $course->sortorder
, array('id' => $swapcourse->id
));
3550 // Finally reorder courses.
3551 fix_course_sortorder();
3552 cache_helper
::purge_by_event('changesincourse');
3559 * Changes the sort order of courses in a category so that the first course appears after the second.
3561 * @param int|stdClass $courseorid The course to focus on.
3562 * @param int $moveaftercourseid The course to shifter after or 0 if you want it to be the first course in the category.
3565 function course_change_sortorder_after_course($courseorid, $moveaftercourseid) {
3568 if (!is_object($courseorid)) {
3569 $course = get_course($courseorid);
3571 $course = $courseorid;
3574 if ((int)$moveaftercourseid === 0) {
3575 // We've moving the course to the start of the queue.
3576 $sql = 'SELECT sortorder
3578 WHERE category = :categoryid
3579 ORDER BY sortorder';
3581 'categoryid' => $course->category
3583 $sortorder = $DB->get_field_sql($sql, $params, IGNORE_MULTIPLE
);
3585 $sql = 'UPDATE {course}
3586 SET sortorder = sortorder + 1
3587 WHERE category = :categoryid
3590 'categoryid' => $course->category
,
3591 'id' => $course->id
,
3593 $DB->execute($sql, $params);
3594 $DB->set_field('course', 'sortorder', $sortorder, array('id' => $course->id
));
3595 } else if ($course->id
=== $moveaftercourseid) {
3596 // They're the same - moronic.
3597 debugging("Invalid move after course given.", DEBUG_DEVELOPER
);
3600 // Moving this course after the given course. It could be before it could be after.
3601 $moveaftercourse = get_course($moveaftercourseid);
3602 if ($course->category
!== $moveaftercourse->category
) {
3603 debugging("Cannot re-order courses. The given courses do not belong to the same category.", DEBUG_DEVELOPER
);
3606 // Increment all courses in the same category that are ordered after the moveafter course.
3607 // This makes a space for the course we're moving.
3608 $sql = 'UPDATE {course}
3609 SET sortorder = sortorder + 1
3610 WHERE category = :categoryid
3611 AND sortorder > :sortorder';
3613 'categoryid' => $moveaftercourse->category
,
3614 'sortorder' => $moveaftercourse->sortorder
3616 $DB->execute($sql, $params);
3617 $DB->set_field('course', 'sortorder', $moveaftercourse->sortorder +
1, array('id' => $course->id
));
3619 fix_course_sortorder();
3620 cache_helper
::purge_by_event('changesincourse');
3625 * Trigger course viewed event. This API function is used when course view actions happens,
3626 * usually in course/view.php but also in external functions.
3628 * @param stdClass $context course context object
3629 * @param int $sectionnumber section number
3632 function course_view($context, $sectionnumber = 0) {
3634 $eventdata = array('context' => $context);
3636 if (!empty($sectionnumber)) {
3637 $eventdata['other']['coursesectionnumber'] = $sectionnumber;
3640 $event = \core\event\course_viewed
::create($eventdata);
3643 user_accesstime_log($context->instanceid
);
3647 * Returns courses tagged with a specified tag.
3649 * @param core_tag_tag $tag
3650 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
3651 * are displayed on the page and the per-page limit may be bigger
3652 * @param int $fromctx context id where the link was displayed, may be used by callbacks
3653 * to display items in the same context first
3654 * @param int $ctx context id where to search for records
3655 * @param bool $rec search in subcontexts as well
3656 * @param int $page 0-based number of page being displayed
3657 * @return \core_tag\output\tagindex
3659 function course_get_tagged_courses($tag, $exclusivemode = false, $fromctx = 0, $ctx = 0, $rec = 1, $page = 0) {
3662 $perpage = $exclusivemode ?
$CFG->coursesperpage
: 5;
3663 $displayoptions = array(
3664 'limit' => $perpage,
3665 'offset' => $page * $perpage,
3666 'viewmoreurl' => null,
3669 $courserenderer = $PAGE->get_renderer('core', 'course');
3670 $totalcount = core_course_category
::search_courses_count(array('tagid' => $tag->id
, 'ctx' => $ctx, 'rec' => $rec));
3671 $content = $courserenderer->tagged_courses($tag->id
, $exclusivemode, $ctx, $rec, $displayoptions);
3672 $totalpages = ceil($totalcount / $perpage);
3674 return new core_tag\output\tagindex
($tag, 'core', 'course', $content,
3675 $exclusivemode, $fromctx, $ctx, $rec, $page, $totalpages);
3679 * Implements callback inplace_editable() allowing to edit values in-place
3681 * @param string $itemtype
3682 * @param int $itemid
3683 * @param mixed $newvalue
3684 * @return \core\output\inplace_editable
3686 function core_course_inplace_editable($itemtype, $itemid, $newvalue) {
3687 if ($itemtype === 'activityname') {
3688 return \core_courseformat\output\local\content\cm\title
::update($itemid, $newvalue);
3693 * This function calculates the minimum and maximum cutoff values for the timestart of
3696 * It will return an array with two values, the first being the minimum cutoff value and
3697 * the second being the maximum cutoff value. Either or both values can be null, which
3698 * indicates there is no minimum or maximum, respectively.
3700 * If a cutoff is required then the function must return an array containing the cutoff
3701 * timestamp and error string to display to the user if the cutoff value is violated.
3703 * A minimum and maximum cutoff return value will look like:
3705 * [1505704373, 'The date must be after this date'],
3706 * [1506741172, 'The date must be before this date']
3709 * @param calendar_event $event The calendar event to get the time range for
3710 * @param stdClass $course The course object to get the range from
3711 * @return array Returns an array with min and max date.
3713 function core_course_core_calendar_get_valid_event_timestart_range(\calendar_event
$event, $course) {
3717 if ($course->startdate
) {
3720 get_string('errorbeforecoursestart', 'calendar')
3724 return [$mindate, $maxdate];
3728 * Render the message drawer to be included in the top of the body of each page.
3730 * @return string HTML
3732 function core_course_drawer(): string {
3735 // Only add course index on non-site course pages.
3736 if (!$PAGE->course ||
$PAGE->course
->id
== SITEID
) {
3740 // Show course index to users can access the course only.
3741 if (!can_access_course($PAGE->course
)) {
3745 $format = course_get_format($PAGE->course
);
3746 $renderer = $format->get_renderer($PAGE);
3747 if (method_exists($renderer, 'course_index_drawer')) {
3748 return $renderer->course_index_drawer($format);
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) {
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
);
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);
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.
3832 // Build the display contents.
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
3870 function course_get_user_navigation_options($context, $course = null) {
3873 $isloggedin = isloggedin();
3874 $isguestuser = isguestuser();
3875 $isfrontpage = $context->contextlevel
== CONTEXT_SYSTEM
;
3878 $sitecontext = $context;
3880 $sitecontext = context_system
::instance();
3883 // Sets defaults for all options.
3884 $options = (object) [
3887 'competencies' => false,
3890 'participants' => false,
3895 $options->blogs
= !empty($CFG->enableblogs
) &&
3896 ($CFG->bloglevel
== BLOG_GLOBAL_LEVEL ||
3897 ($CFG->bloglevel
== BLOG_SITE_LEVEL
and ($isloggedin and !$isguestuser)))
3898 && has_capability('moodle/blog:view', $sitecontext);
3900 $options->notes
= !empty($CFG->enablenotes
) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $context);
3902 // Frontpage settings?
3904 // We are on the front page, so make sure we use the proper capability (site:viewparticipants).
3905 $options->participants
= course_can_view_participants($sitecontext);
3906 $options->badges
= !empty($CFG->enablebadges
) && has_capability('moodle/badges:viewbadges', $sitecontext);
3907 $options->tags
= !empty($CFG->usetags
) && $isloggedin;
3908 $options->search
= !empty($CFG->enableglobalsearch
) && has_capability('moodle/search:query', $sitecontext);
3910 // We are in a course, so make sure we use the proper capability (course:viewparticipants).
3911 $options->participants
= course_can_view_participants($context);
3913 // Only display badges if they are enabled and the current user can manage them or if they can view them and have,
3914 // at least, one available badge.
3915 if (!empty($CFG->enablebadges
) && !empty($CFG->badges_allowcoursebadges
)) {
3916 $canmanage = has_any_capability([
3917 'moodle/badges:createbadge',
3918 'moodle/badges:awardbadge',
3919 'moodle/badges:configurecriteria',
3920 'moodle/badges:configuremessages',
3921 'moodle/badges:configuredetails',
3922 'moodle/badges:deletebadge',
3929 // This only needs to be calculated if the user can't manage badges (to improve performance).
3930 $canview = has_capability('moodle/badges:viewbadges', $context);
3932 require_once($CFG->dirroot
.'/lib/badgeslib.php');
3933 if (is_null($course)) {
3934 $totalbadges = count(badges_get_badges(BADGE_TYPE_SITE
, 0, '', '', 0, 0, $USER->id
));
3936 $totalbadges = count(badges_get_badges(BADGE_TYPE_COURSE
, $course->id
, '', '', 0, 0, $USER->id
));
3941 $options->badges
= ($canmanage ||
($canview && $totalbadges > 0));
3943 // Add view grade report is permitted.
3946 if (has_capability('moodle/grade:viewall', $context)) {
3948 } else if (!empty($course->showgrades
)) {
3949 $reports = core_component
::get_plugin_list('gradereport');
3950 if (is_array($reports) && count($reports) > 0) { // Get all installed reports.
3951 arsort($reports); // User is last, we want to test it first.
3952 foreach ($reports as $plugin => $plugindir) {
3953 if (has_capability('gradereport/'.$plugin.':view', $context)) {
3954 // Stop when the first visible plugin is found.
3961 $options->grades
= $grades;
3964 if (\core_competency\api
::is_enabled()) {
3965 $capabilities = array('moodle/competency:coursecompetencyview', 'moodle/competency:coursecompetencymanage');
3966 $options->competencies
= has_any_capability($capabilities, $context);
3972 * Return an object with the list of administration options in a course that are available or not for the current user.
3973 * This function also handles the frontpage settings.
3975 * @param stdClass $course course object (for frontpage it should be a clone of $SITE)
3976 * @param stdClass $context context object (course context)
3977 * @return stdClass the administration options in a course and their availability status
3980 function course_get_user_administration_options($course, $context) {
3982 $isfrontpage = $course->id
== SITEID
;
3983 $completionenabled = $CFG->enablecompletion
&& $course->enablecompletion
;
3984 $hascompletionoptions = count(core_completion\manager
::get_available_completion_options($course->id
)) > 0;
3985 $options = new stdClass
;
3986 $options->update
= has_capability('moodle/course:update', $context);
3987 $options->editcompletion
= $CFG->enablecompletion
&& $course->enablecompletion
&&
3988 ($options->update ||
$hascompletionoptions);
3989 $options->filters
= has_capability('moodle/filter:manage', $context) &&
3990 count(filter_get_available_in_context($context)) > 0;
3991 $options->reports
= has_capability('moodle/site:viewreports', $context);
3992 $options->backup
= has_capability('moodle/backup:backupcourse', $context);
3993 $options->restore
= has_capability('moodle/restore:restorecourse', $context);
3994 $options->copy
= \core_course\management\helper
::can_copy_course($course->id
);
3995 $options->files
= ($course->legacyfiles
== 2 && has_capability('moodle/course:managefiles', $context));
3997 if (!$isfrontpage) {
3998 $options->tags
= has_capability('moodle/course:tag', $context);
3999 $options->gradebook
= has_capability('moodle/grade:manage', $context);
4000 $options->outcomes
= !empty($CFG->enableoutcomes
) && has_capability('moodle/course:update', $context);
4001 $options->badges
= !empty($CFG->enablebadges
);
4002 $options->import
= has_capability('moodle/restore:restoretargetimport', $context);
4003 $options->reset
= has_capability('moodle/course:reset', $context);
4004 $options->roles
= has_capability('moodle/role:switchroles', $context);
4006 // Set default options to false.
4007 $listofoptions = array('tags', 'gradebook', 'outcomes', 'badges', 'import', 'publish', 'reset', 'roles', 'grades');
4009 foreach ($listofoptions as $option) {
4010 $options->$option = false;
4018 * Validates course start and end dates.
4020 * Checks that the end course date is not greater than the start course date.
4022 * $coursedata['startdate'] or $coursedata['enddate'] may not be set, it depends on the form and user input.
4024 * @param array $coursedata May contain startdate and enddate timestamps, depends on the user input.
4025 * @return mixed False if everything alright, error codes otherwise.
4027 function course_validate_dates($coursedata) {
4029 // If both start and end dates are set end date should be later than the start date.
4030 if (!empty($coursedata['startdate']) && !empty($coursedata['enddate']) &&
4031 ($coursedata['enddate'] < $coursedata['startdate'])) {
4032 return 'enddatebeforestartdate';
4035 // If start date is not set end date can not be set.
4036 if (empty($coursedata['startdate']) && !empty($coursedata['enddate'])) {
4037 return 'nostartdatenoenddate';
4044 * Check for course updates in the given context level instances (only modules supported right Now)
4046 * @param stdClass $course course object
4047 * @param array $tocheck instances to check for updates
4048 * @param array $filter check only for updates in these areas
4049 * @return array list of warnings and instances with updates information
4052 function course_check_updates($course, $tocheck, $filter = array()) {
4055 $instances = array();
4056 $warnings = array();
4057 $modulescallbacksupport = array();
4058 $modinfo = get_fast_modinfo($course);
4060 $supportedplugins = get_plugin_list_with_function('mod', 'check_updates_since');
4063 foreach ($tocheck as $instance) {
4064 if ($instance['contextlevel'] == 'module') {
4065 // Check module visibility.
4067 $cm = $modinfo->get_cm($instance['id']);
4068 } catch (Exception
$e) {
4069 $warnings[] = array(
4071 'itemid' => $instance['id'],
4072 'warningcode' => 'cmidnotincourse',
4073 'message' => 'This module id does not belong to this course.'
4078 if (!$cm->uservisible
) {
4079 $warnings[] = array(
4081 'itemid' => $instance['id'],
4082 'warningcode' => 'nonuservisible',
4083 'message' => 'You don\'t have access to this module.'
4087 if (empty($supportedplugins['mod_' . $cm->modname
])) {
4088 $warnings[] = array(
4090 'itemid' => $instance['id'],
4091 'warningcode' => 'missingcallback',
4092 'message' => 'This module does not implement the check_updates_since callback: ' . $instance['contextlevel'],
4096 // Retrieve the module instance.
4097 $instances[] = array(
4098 'contextlevel' => $instance['contextlevel'],
4099 'id' => $instance['id'],
4100 'updates' => call_user_func($cm->modname
. '_check_updates_since', $cm, $instance['since'], $filter)
4104 $warnings[] = array(
4105 'item' => 'contextlevel',
4106 'itemid' => $instance['id'],
4107 'warningcode' => 'contextlevelnotsupported',
4108 'message' => 'Context level not yet supported ' . $instance['contextlevel'],
4112 return array($instances, $warnings);
4116 * This function classifies a course as past, in progress or future.
4118 * This function may incur a DB hit to calculate course completion.
4119 * @param stdClass $course Course record
4120 * @param stdClass $user User record (optional - defaults to $USER).
4121 * @param completion_info $completioninfo Completion record for the user (optional - will be fetched if required).
4122 * @return string (one of COURSE_TIMELINE_FUTURE, COURSE_TIMELINE_INPROGRESS or COURSE_TIMELINE_PAST)
4124 function course_classify_for_timeline($course, $user = null, $completioninfo = null) {
4127 if ($user == null) {
4131 if ($completioninfo == null) {
4132 $completioninfo = new completion_info($course);
4135 // Let plugins override data for timeline classification.
4136 $pluginsfunction = get_plugins_with_function('extend_course_classify_for_timeline', 'lib.php');
4137 foreach ($pluginsfunction as $plugintype => $plugins) {
4138 foreach ($plugins as $pluginfunction) {
4139 $pluginfunction($course, $user, $completioninfo);
4145 if (!empty($course->enddate
) && (course_classify_end_date($course) < $today)) {
4146 return COURSE_TIMELINE_PAST
;
4149 // Course was completed.
4150 if ($completioninfo->is_enabled() && $completioninfo->is_course_complete($user->id
)) {
4151 return COURSE_TIMELINE_PAST
;
4154 // Start date not reached.
4155 if (!empty($course->startdate
) && (course_classify_start_date($course) > $today)) {
4156 return COURSE_TIMELINE_FUTURE
;
4159 // Everything else is in progress.
4160 return COURSE_TIMELINE_INPROGRESS
;
4164 * This function calculates the end date to use for display classification purposes,
4165 * incorporating the grace period, if any.
4167 * @param stdClass $course The course record.
4168 * @return int The new enddate.
4170 function course_classify_end_date($course) {
4172 $coursegraceperiodafter = (empty($CFG->coursegraceperiodafter
)) ?
0 : $CFG->coursegraceperiodafter
;
4173 $enddate = (new \
DateTimeImmutable())->setTimestamp($course->enddate
)->modify("+{$coursegraceperiodafter} days");
4174 return $enddate->getTimestamp();
4178 * This function calculates the start date to use for display classification purposes,
4179 * incorporating the grace period, if any.
4181 * @param stdClass $course The course record.
4182 * @return int The new startdate.
4184 function course_classify_start_date($course) {
4186 $coursegraceperiodbefore = (empty($CFG->coursegraceperiodbefore
)) ?
0 : $CFG->coursegraceperiodbefore
;
4187 $startdate = (new \
DateTimeImmutable())->setTimestamp($course->startdate
)->modify("-{$coursegraceperiodbefore} days");
4188 return $startdate->getTimestamp();
4192 * Group a list of courses into either past, future, or in progress.
4194 * The return value will be an array indexed by the COURSE_TIMELINE_* constants
4195 * with each value being an array of courses in that group.
4198 * COURSE_TIMELINE_PAST => [... list of past courses ...],
4199 * COURSE_TIMELINE_FUTURE => [],
4200 * COURSE_TIMELINE_INPROGRESS => []
4203 * @param array $courses List of courses to be grouped.
4206 function course_classify_courses_for_timeline(array $courses) {
4207 return array_reduce($courses, function($carry, $course) {
4208 $classification = course_classify_for_timeline($course);
4209 array_push($carry[$classification], $course);
4213 COURSE_TIMELINE_PAST
=> [],
4214 COURSE_TIMELINE_FUTURE
=> [],
4215 COURSE_TIMELINE_INPROGRESS
=> []
4220 * Get the list of enrolled courses for the current user.
4222 * This function returns a Generator. The courses will be loaded from the database
4223 * in chunks rather than a single query.
4225 * @param int $limit Restrict result set to this amount
4226 * @param int $offset Skip this number of records from the start of the result set
4227 * @param string|null $sort SQL string for sorting
4228 * @param string|null $fields SQL string for fields to be returned
4229 * @param int $dbquerylimit The number of records to load per DB request
4230 * @param array $includecourses courses ids to be restricted
4231 * @param array $hiddencourses courses ids to be excluded
4234 function course_get_enrolled_courses_for_logged_in_user(
4237 string $sort = null,
4238 string $fields = null,
4239 int $dbquerylimit = COURSE_DB_QUERY_LIMIT
,
4240 array $includecourses = [],
4241 array $hiddencourses = []
4244 $haslimit = !empty($limit);
4246 $querylimit = (!$haslimit ||
$limit > $dbquerylimit) ?
$dbquerylimit : $limit;
4248 while ($courses = enrol_get_my_courses($fields, $sort, $querylimit, $includecourses, false, $offset, $hiddencourses)) {
4249 yield from
$courses;
4251 $recordsloaded +
= $querylimit;
4253 if (count($courses) < $querylimit) {
4256 if ($haslimit && $recordsloaded >= $limit) {
4260 $offset +
= $querylimit;
4265 * Get the list of enrolled courses the current user searched for.
4267 * This function returns a Generator. The courses will be loaded from the database
4268 * in chunks rather than a single query.
4270 * @param int $limit Restrict result set to this amount
4271 * @param int $offset Skip this number of records from the start of the result set
4272 * @param string|null $sort SQL string for sorting
4273 * @param string|null $fields SQL string for fields to be returned
4274 * @param int $dbquerylimit The number of records to load per DB request
4275 * @param array $searchcriteria contains search criteria
4276 * @param array $options display options, same as in get_courses() except 'recursive' is ignored -
4277 * search is always category-independent
4280 function course_get_enrolled_courses_for_logged_in_user_from_search(
4283 string $sort = null,
4284 string $fields = null,
4285 int $dbquerylimit = COURSE_DB_QUERY_LIMIT
,
4286 array $searchcriteria = [],
4290 $haslimit = !empty($limit);
4292 $querylimit = (!$haslimit ||
$limit > $dbquerylimit) ?
$dbquerylimit : $limit;
4293 $ids = core_course_category
::search_courses($searchcriteria, $options);
4295 // If no courses were found matching the criteria return back.
4300 while ($courses = enrol_get_my_courses($fields, $sort, $querylimit, $ids, false, $offset)) {
4301 yield from
$courses;
4303 $recordsloaded +
= $querylimit;
4305 if (count($courses) < $querylimit) {
4308 if ($haslimit && $recordsloaded >= $limit) {
4312 $offset +
= $querylimit;
4317 * Search the given $courses for any that match the given $classification up to the specified
4320 * This function will return the subset of courses that match the classification as well as the
4321 * number of courses it had to process to build that subset.
4323 * It is recommended that for larger sets of courses this function is given a Generator that loads
4324 * the courses from the database in chunks.
4326 * @param array|Traversable $courses List of courses to process
4327 * @param string $classification One of the COURSE_TIMELINE_* constants
4328 * @param int $limit Limit the number of results to this amount
4329 * @return array First value is the filtered courses, second value is the number of courses processed
4331 function course_filter_courses_by_timeline_classification(
4333 string $classification,
4337 if (!in_array($classification,
4338 [COURSE_TIMELINE_ALLINCLUDINGHIDDEN
, COURSE_TIMELINE_ALL
, COURSE_TIMELINE_PAST
, COURSE_TIMELINE_INPROGRESS
,
4339 COURSE_TIMELINE_FUTURE
, COURSE_TIMELINE_HIDDEN
, COURSE_TIMELINE_SEARCH
])) {
4340 $message = 'Classification must be one of COURSE_TIMELINE_ALLINCLUDINGHIDDEN, COURSE_TIMELINE_ALL, COURSE_TIMELINE_PAST, '
4341 . 'COURSE_TIMELINE_INPROGRESS, COURSE_TIMELINE_SEARCH or COURSE_TIMELINE_FUTURE';
4342 throw new moodle_exception($message);
4345 $filteredcourses = [];
4346 $numberofcoursesprocessed = 0;
4349 foreach ($courses as $course) {
4350 $numberofcoursesprocessed++
;
4351 $pref = get_user_preferences('block_myoverview_hidden_course_' . $course->id
, 0);
4353 // Added as of MDL-63457 toggle viewability for each user.
4354 if ($classification == COURSE_TIMELINE_ALLINCLUDINGHIDDEN ||
($classification == COURSE_TIMELINE_HIDDEN
&& $pref) ||
4355 $classification == COURSE_TIMELINE_SEARCH||
4356 (($classification == COURSE_TIMELINE_ALL ||
$classification == course_classify_for_timeline($course)) && !$pref)) {
4357 $filteredcourses[] = $course;
4361 if ($limit && $filtermatches >= $limit) {
4362 // We've found the number of requested courses. No need to continue searching.
4367 // Return the number of filtered courses as well as the number of courses that were searched
4368 // in order to find the matching courses. This allows the calling code to do some kind of
4370 return [$filteredcourses, $numberofcoursesprocessed];
4374 * Search the given $courses for any that match the given $classification up to the specified
4377 * This function will return the subset of courses that are favourites as well as the
4378 * number of courses it had to process to build that subset.
4380 * It is recommended that for larger sets of courses this function is given a Generator that loads
4381 * the courses from the database in chunks.
4383 * @param array|Traversable $courses List of courses to process
4384 * @param array $favouritecourseids Array of favourite courses.
4385 * @param int $limit Limit the number of results to this amount
4386 * @return array First value is the filtered courses, second value is the number of courses processed
4388 function course_filter_courses_by_favourites(
4390 $favouritecourseids,
4394 $filteredcourses = [];
4395 $numberofcoursesprocessed = 0;
4398 foreach ($courses as $course) {
4399 $numberofcoursesprocessed++
;
4401 if (in_array($course->id
, $favouritecourseids)) {
4402 $filteredcourses[] = $course;
4406 if ($limit && $filtermatches >= $limit) {
4407 // We've found the number of requested courses. No need to continue searching.
4412 // Return the number of filtered courses as well as the number of courses that were searched
4413 // in order to find the matching courses. This allows the calling code to do some kind of
4415 return [$filteredcourses, $numberofcoursesprocessed];
4419 * Search the given $courses for any that have a $customfieldname value that matches the given
4420 * $customfieldvalue, up to the specified $limit.
4422 * This function will return the subset of courses that matches the value as well as the
4423 * number of courses it had to process to build that subset.
4425 * It is recommended that for larger sets of courses this function is given a Generator that loads
4426 * the courses from the database in chunks.
4428 * @param array|Traversable $courses List of courses to process
4429 * @param string $customfieldname the shortname of the custom field to match against
4430 * @param string $customfieldvalue the value this custom field needs to match
4431 * @param int $limit Limit the number of results to this amount
4432 * @return array First value is the filtered courses, second value is the number of courses processed
4434 function course_filter_courses_by_customfield(
4446 // Prepare the list of courses to search through.
4448 foreach ($courses as $course) {
4449 $coursesbyid[$course->id
] = $course;
4451 if (!$coursesbyid) {
4454 list($csql, $params) = $DB->get_in_or_equal(array_keys($coursesbyid), SQL_PARAMS_NAMED
);
4456 // Get the id of the custom field.
4459 FROM {customfield_field} f
4460 JOIN {customfield_category} cat ON cat.id = f.categoryid
4461 WHERE f.shortname = ?
4462 AND cat.component = 'core_course'
4463 AND cat.area = 'course'
4465 $fieldid = $DB->get_field_sql($sql, [$customfieldname]);
4470 // Get a list of courseids that match that custom field value.
4471 if ($customfieldvalue == COURSE_CUSTOMFIELD_EMPTY
) {
4472 $comparevalue = $DB->sql_compare_text('cd.value');
4476 LEFT JOIN {customfield_data} cd ON cd.instanceid = c.id AND cd.fieldid = :fieldid
4478 AND (cd.value IS NULL OR $comparevalue = '' OR $comparevalue = '0')
4480 $params['fieldid'] = $fieldid;
4481 $matchcourseids = $DB->get_fieldset_sql($sql, $params);
4483 $comparevalue = $DB->sql_compare_text('value');
4484 $select = "fieldid = :fieldid AND $comparevalue = :customfieldvalue AND instanceid $csql";
4485 $params['fieldid'] = $fieldid;
4486 $params['customfieldvalue'] = $customfieldvalue;
4487 $matchcourseids = $DB->get_fieldset_select('customfield_data', 'instanceid', $select, $params);
4490 // Prepare the list of courses to return.
4491 $filteredcourses = [];
4492 $numberofcoursesprocessed = 0;
4495 foreach ($coursesbyid as $course) {
4496 $numberofcoursesprocessed++
;
4498 if (in_array($course->id
, $matchcourseids)) {
4499 $filteredcourses[] = $course;
4503 if ($limit && $filtermatches >= $limit) {
4504 // We've found the number of requested courses. No need to continue searching.
4509 // Return the number of filtered courses as well as the number of courses that were searched
4510 // in order to find the matching courses. This allows the calling code to do some kind of
4512 return [$filteredcourses, $numberofcoursesprocessed];
4516 * Check module updates since a given time.
4517 * This function checks for updates in the module config, file areas, completion, grades, comments and ratings.
4519 * @param cm_info $cm course module data
4520 * @param int $from the time to check
4521 * @param array $fileareas additional file ares to check
4522 * @param array $filter if we need to filter and return only selected updates
4523 * @return stdClass object with the different updates
4526 function course_check_module_updates_since($cm, $from, $fileareas = array(), $filter = array()) {
4527 global $DB, $CFG, $USER;
4529 $context = $cm->context
;
4530 $mod = $DB->get_record($cm->modname
, array('id' => $cm->instance
), '*', MUST_EXIST
);
4532 $updates = new stdClass();
4533 $course = get_course($cm->course
);
4534 $component = 'mod_' . $cm->modname
;
4536 // Check changes in the module configuration.
4537 if (isset($mod->timemodified
) and (empty($filter) or in_array('configuration', $filter))) {
4538 $updates->configuration
= (object) array('updated' => false);
4539 if ($updates->configuration
->updated
= $mod->timemodified
> $from) {
4540 $updates->configuration
->timeupdated
= $mod->timemodified
;
4544 // Check for updates in files.
4545 if (plugin_supports('mod', $cm->modname
, FEATURE_MOD_INTRO
)) {
4546 $fileareas[] = 'intro';
4548 if (!empty($fileareas) and (empty($filter) or in_array('fileareas', $filter))) {
4549 $fs = get_file_storage();
4550 $files = $fs->get_area_files($context->id
, $component, $fileareas, false, "filearea, timemodified DESC", false, $from);
4551 foreach ($fileareas as $filearea) {
4552 $updates->{$filearea . 'files'} = (object) array('updated' => false);
4554 foreach ($files as $file) {
4555 $updates->{$file->get_filearea() . 'files'}->updated
= true;
4556 $updates->{$file->get_filearea() . 'files'}->itemids
[] = $file->get_id();
4560 // Check completion.
4561 $supportcompletion = plugin_supports('mod', $cm->modname
, FEATURE_COMPLETION_HAS_RULES
);
4562 $supportcompletion = $supportcompletion or plugin_supports('mod', $cm->modname
, FEATURE_COMPLETION_TRACKS_VIEWS
);
4563 if ($supportcompletion and (empty($filter) or in_array('completion', $filter))) {
4564 $updates->completion
= (object) array('updated' => false);
4565 $completion = new completion_info($course);
4566 // Use wholecourse to cache all the modules the first time.
4567 $completiondata = $completion->get_data($cm, true);
4568 if ($updates->completion
->updated
= !empty($completiondata->timemodified
) && $completiondata->timemodified
> $from) {
4569 $updates->completion
->timemodified
= $completiondata->timemodified
;
4574 $supportgrades = plugin_supports('mod', $cm->modname
, FEATURE_GRADE_HAS_GRADE
);
4575 $supportgrades = $supportgrades or plugin_supports('mod', $cm->modname
, FEATURE_GRADE_OUTCOMES
);
4576 if ($supportgrades and (empty($filter) or (in_array('gradeitems', $filter) or in_array('outcomes', $filter)))) {
4577 require_once($CFG->libdir
. '/gradelib.php');
4578 $grades = grade_get_grades($course->id
, 'mod', $cm->modname
, $mod->id
, $USER->id
);
4580 if (empty($filter) or in_array('gradeitems', $filter)) {
4581 $updates->gradeitems
= (object) array('updated' => false);
4582 foreach ($grades->items
as $gradeitem) {
4583 foreach ($gradeitem->grades
as $grade) {
4584 if ($grade->datesubmitted
> $from or $grade->dategraded
> $from) {
4585 $updates->gradeitems
->updated
= true;
4586 $updates->gradeitems
->itemids
[] = $gradeitem->id
;
4592 if (empty($filter) or in_array('outcomes', $filter)) {
4593 $updates->outcomes
= (object) array('updated' => false);
4594 foreach ($grades->outcomes
as $outcome) {
4595 foreach ($outcome->grades
as $grade) {
4596 if ($grade->datesubmitted
> $from or $grade->dategraded
> $from) {
4597 $updates->outcomes
->updated
= true;
4598 $updates->outcomes
->itemids
[] = $outcome->id
;
4606 if (plugin_supports('mod', $cm->modname
, FEATURE_COMMENT
) and (empty($filter) or in_array('comments', $filter))) {
4607 $updates->comments
= (object) array('updated' => false);
4608 require_once($CFG->dirroot
. '/comment/lib.php');
4609 require_once($CFG->dirroot
. '/comment/locallib.php');
4610 $manager = new comment_manager();
4611 $comments = $manager->get_component_comments_since($course, $context, $component, $from, $cm);
4612 if (!empty($comments)) {
4613 $updates->comments
->updated
= true;
4614 $updates->comments
->itemids
= array_keys($comments);
4619 if (plugin_supports('mod', $cm->modname
, FEATURE_RATE
) and (empty($filter) or in_array('ratings', $filter))) {
4620 $updates->ratings
= (object) array('updated' => false);
4621 require_once($CFG->dirroot
. '/rating/lib.php');
4622 $manager = new rating_manager();
4623 $ratings = $manager->get_component_ratings_since($context, $component, $from);
4624 if (!empty($ratings)) {
4625 $updates->ratings
->updated
= true;
4626 $updates->ratings
->itemids
= array_keys($ratings);
4634 * Returns true if the user can view the participant page, false otherwise,
4636 * @param context $context The context we are checking.
4639 function course_can_view_participants($context) {
4640 $viewparticipantscap = 'moodle/course:viewparticipants';
4641 if ($context->contextlevel
== CONTEXT_SYSTEM
) {
4642 $viewparticipantscap = 'moodle/site:viewparticipants';
4645 return has_any_capability([$viewparticipantscap, 'moodle/course:enrolreview'], $context);
4649 * Checks if a user can view the participant page, if not throws an exception.
4651 * @param context $context The context we are checking.
4652 * @throws required_capability_exception
4654 function course_require_view_participants($context) {
4655 if (!course_can_view_participants($context)) {
4656 $viewparticipantscap = 'moodle/course:viewparticipants';
4657 if ($context->contextlevel
== CONTEXT_SYSTEM
) {
4658 $viewparticipantscap = 'moodle/site:viewparticipants';
4660 throw new required_capability_exception($context, $viewparticipantscap, 'nopermissions', '');
4665 * Return whether the user can download from the specified backup file area in the given context.
4667 * @param string $filearea the backup file area. E.g. 'course', 'backup' or 'automated'.
4668 * @param \context $context
4669 * @param stdClass $user the user object. If not provided, the current user will be checked.
4670 * @return bool true if the user is allowed to download in the context, false otherwise.
4672 function can_download_from_backup_filearea($filearea, \context
$context, stdClass
$user = null) {
4673 $candownload = false;
4674 switch ($filearea) {
4677 $candownload = has_capability('moodle/backup:downloadfile', $context, $user);
4680 // Given the automated backups may contain userinfo, we restrict access such that only users who are able to
4681 // restore with userinfo are able to download the file. Users can't create these backups, so checking 'backup:userinfo'
4682 // doesn't make sense here.
4683 $candownload = has_capability('moodle/backup:downloadfile', $context, $user) &&
4684 has_capability('moodle/restore:userinfo', $context, $user);
4690 return $candownload;
4694 * Get a list of hidden courses
4696 * @param int|object|null $user User override to get the filter from. Defaults to current user
4697 * @return array $ids List of hidden courses
4698 * @throws coding_exception
4700 function get_hidden_courses_on_timeline($user = null) {
4707 $preferences = get_user_preferences(null, null, $user);
4709 foreach ($preferences as $key => $value) {
4710 if (preg_match('/block_myoverview_hidden_course_(\d)+/', $key)) {
4711 $id = preg_split('/block_myoverview_hidden_course_/', $key);
4720 * Returns a list of the most recently courses accessed by a user
4722 * @param int $userid User id from which the courses will be obtained
4723 * @param int $limit Restrict result set to this amount
4724 * @param int $offset Skip this number of records from the start of the result set
4725 * @param string|null $sort SQL string for sorting
4728 function course_get_recent_courses(int $userid = null, int $limit = 0, int $offset = 0, string $sort = null) {
4730 global $CFG, $USER, $DB;
4732 if (empty($userid)) {
4733 $userid = $USER->id
;
4737 'id', 'idnumber', 'summary', 'summaryformat', 'startdate', 'enddate', 'category',
4738 'shortname', 'fullname', 'timeaccess', 'component', 'visible',
4739 'showactivitydates', 'showcompletionconditions',
4743 $sort = 'timeaccess DESC';
4745 // The SQL string for sorting can define sorting by multiple columns.
4746 $rawsorts = explode(',', $sort);
4748 // Validate and trim the sort parameters in the SQL string for sorting.
4749 foreach ($rawsorts as $rawsort) {
4750 $sort = trim($rawsort);
4751 $sortparams = explode(' ', $sort);
4752 // A valid sort statement can not have more than 2 params (ex. 'summary desc' or 'timeaccess').
4753 if (count($sortparams) > 2) {
4754 throw new invalid_parameter_exception(
4755 'Invalid structure of the sort parameter, allowed structure: fieldname [ASC|DESC].');
4757 $sortfield = trim($sortparams[0]);
4758 // Validate the value which defines the field to sort by.
4759 if (!in_array($sortfield, $basefields)) {
4760 throw new invalid_parameter_exception('Invalid field in the sort parameter, allowed fields: ' .
4761 implode(', ', $basefields) . '.');
4763 $sortdirection = isset($sortparams[1]) ?
trim($sortparams[1]) : '';
4764 // Validate the value which defines the sort direction (if present).
4765 $allowedsortdirections = ['asc', 'desc'];
4766 if (!empty($sortdirection) && !in_array(strtolower($sortdirection), $allowedsortdirections)) {
4767 throw new invalid_parameter_exception('Invalid sort direction in the sort parameter, allowed values: ' .
4768 implode(', ', $allowedsortdirections) . '.');
4772 $sort = implode(',', $sorts);
4775 $ctxfields = context_helper
::get_preload_record_columns_sql('ctx');
4777 $coursefields = 'c.' . join(',', $basefields);
4779 // Ask the favourites service to give us the join SQL for favourited courses,
4780 // so we can include favourite information in the query.
4781 $usercontext = \context_user
::instance($userid);
4782 $favservice = \core_favourites\service_factory
::get_service_for_user_context($usercontext);
4783 list($favsql, $favparams) = $favservice->get_join_sql_by_type('core_course', 'courses', 'fav', 'ul.courseid');
4785 $sql = "SELECT $coursefields, $ctxfields
4788 ON ctx.contextlevel = :contextlevel
4789 AND ctx.instanceid = c.id
4790 JOIN {user_lastaccess} ul
4791 ON ul.courseid = c.id
4793 LEFT JOIN {enrol} eg ON eg.courseid = c.id AND eg.status = :statusenrolg AND eg.enrol = :guestenrol
4794 WHERE ul.userid = :userid
4795 AND c.visible = :visible
4796 AND (eg.id IS NOT NULL
4797 OR EXISTS (SELECT e.id
4799 JOIN {user_enrolments} ue ON ue.enrolid = e.id
4800 WHERE e.courseid = c.id
4801 AND e.status = :statusenrol
4802 AND ue.status = :status
4803 AND ue.userid = :userid2
4804 AND ue.timestart < :now1
4805 AND (ue.timeend = 0 OR ue.timeend > :now2)
4809 $now = round(time(), -2); // Improves db caching.
4810 $params = ['userid' => $userid, 'contextlevel' => CONTEXT_COURSE
, 'visible' => 1, 'status' => ENROL_USER_ACTIVE
,
4811 'statusenrol' => ENROL_INSTANCE_ENABLED
, 'guestenrol' => 'guest', 'now1' => $now, 'now2' => $now,
4812 'userid2' => $userid, 'statusenrolg' => ENROL_INSTANCE_ENABLED
] +
$favparams;
4814 $recentcourses = $DB->get_records_sql($sql, $params, $offset, $limit);
4816 // Filter courses if last access field is hidden.
4817 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields
));
4819 if ($userid != $USER->id
&& isset($hiddenfields['lastaccess'])) {
4820 $recentcourses = array_filter($recentcourses, function($course) {
4821 context_helper
::preload_from_record($course);
4822 $context = context_course
::instance($course->id
, IGNORE_MISSING
);
4823 // If last access was a hidden field, a user requesting info about another user would need permission to view hidden
4825 return has_capability('moodle/course:viewhiddenuserfields', $context);
4829 return $recentcourses;
4833 * Calculate the course start date and offset for the given user ids.
4835 * If the course is a fixed date course then the course start date will be returned.
4836 * If the course is a relative date course then the course date will be calculated and
4837 * and offset provided.
4839 * The dates are returned as an array with the index being the user id. The array
4840 * contains the start date and start offset values for the user.
4842 * If the user is not enrolled in the course then the course start date will be returned.
4844 * If we have a course which starts on 1563244000 and 2 users, id 123 and 456, where the
4845 * former is enrolled in the course at 1563244693 and the latter is not enrolled then the
4846 * return value would look like:
4849 * 'start' => 1563244693,
4850 * 'startoffset' => 693
4853 * 'start' => 1563244000,
4854 * 'startoffset' => 0
4858 * @param stdClass $course The course to fetch dates for.
4859 * @param array $userids The list of user ids to get dates for.
4862 function course_get_course_dates_for_user_ids(stdClass
$course, array $userids): array {
4863 if (empty($course->relativedatesmode
)) {
4864 // This course isn't set to relative dates so we can early return with the course
4866 return array_reduce($userids, function($carry, $userid) use ($course) {
4868 'start' => $course->startdate
,
4875 // We're dealing with a relative dates course now so we need to calculate some dates.
4876 $cache = cache
::make('core', 'course_user_dates');
4878 $uncacheduserids = [];
4880 // Try fetching the values from the cache so that we don't need to do a DB request.
4881 foreach ($userids as $userid) {
4882 $cachekey = "{$course->id}_{$userid}";
4883 $cachedvalue = $cache->get($cachekey);
4885 if ($cachedvalue === false) {
4886 // Looks like we haven't seen this user for this course before so we'll have
4888 $uncacheduserids[] = $userid;
4890 [$start, $startoffset] = $cachedvalue;
4893 'startoffset' => $startoffset
4898 if (!empty($uncacheduserids)) {
4899 // Load the enrolments for any users we haven't seen yet. Set the "onlyactive" param
4900 // to false because it filters out users with enrolment start times in the future which
4902 $enrolments = enrol_get_course_users($course->id
, false, $uncacheduserids);
4904 foreach ($uncacheduserids as $userid) {
4905 // Find the user enrolment that has the earliest start date.
4906 $enrolment = array_reduce(array_values($enrolments), function($carry, $enrolment) use ($userid) {
4907 // Only consider enrolments for this user if the user enrolment is active and the
4908 // enrolment method is enabled.
4910 $enrolment->uestatus
== ENROL_USER_ACTIVE
&&
4911 $enrolment->estatus
== ENROL_INSTANCE_ENABLED
&&
4912 $enrolment->id
== $userid
4914 if (is_null($carry)) {
4915 // Haven't found an enrolment yet for this user so use the one we just found.
4916 $carry = $enrolment;
4918 // We've already found an enrolment for this user so let's use which ever one
4919 // has the earliest start time.
4920 $carry = $carry->uetimestart
< $enrolment->uetimestart ?
$carry : $enrolment;
4928 // The course is in relative dates mode so we calculate the student's start
4929 // date based on their enrolment start date.
4930 $start = $course->startdate
> $enrolment->uetimestart ?
$course->startdate
: $enrolment->uetimestart
;
4931 $startoffset = $start - $course->startdate
;
4933 // The user is not enrolled in the course so default back to the course start date.
4934 $start = $course->startdate
;
4940 'startoffset' => $startoffset
4943 $cachekey = "{$course->id}_{$userid}";
4944 $cache->set($cachekey, [$start, $startoffset]);
4952 * Calculate the course start date and offset for the given user id.
4954 * If the course is a fixed date course then the course start date will be returned.
4955 * If the course is a relative date course then the course date will be calculated and
4956 * and offset provided.
4958 * The return array contains the start date and start offset values for the user.
4960 * If the user is not enrolled in the course then the course start date will be returned.
4962 * If we have a course which starts on 1563244000. If a user's enrolment starts on 1563244693
4963 * then the return would be:
4965 * 'start' => 1563244693,
4966 * 'startoffset' => 693
4969 * If the use was not enrolled then the return would be:
4971 * 'start' => 1563244000,
4972 * 'startoffset' => 0
4975 * @param stdClass $course The course to fetch dates for.
4976 * @param int $userid The user id to get dates for.
4979 function course_get_course_dates_for_user_id(stdClass
$course, int $userid): array {
4980 return (course_get_course_dates_for_user_ids($course, [$userid]))[$userid];
4984 * Renders the course copy form for the modal on the course management screen.
4986 * @param array $args
4987 * @return string $o Form HTML.
4989 function course_output_fragment_new_base_form($args) {
4991 $serialiseddata = json_decode($args['jsonformdata'], true);
4993 if (!empty($serialiseddata)) {
4994 parse_str($serialiseddata, $formdata);
4997 $context = context_course
::instance($args['courseid']);
4998 $copycaps = \core_course\management\helper
::get_course_copy_capabilities();
4999 require_all_capabilities($copycaps, $context);
5001 $course = get_course($args['courseid']);
5002 $mform = new \core_backup\output\
copy_form(
5004 array('course' => $course, 'returnto' => '', 'returnurl' => ''),
5005 'post', '', ['class' => 'ignoredirty'], true, $formdata);
5007 if (!empty($serialiseddata)) {
5008 // If we were passed non-empty form data we want the mform to call validation functions and show errors.
5009 $mform->is_validated();
5014 $o = ob_get_contents();