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 require_once($CFG->libdir.'/completionlib.php');
28 require_once($CFG->libdir.'/filelib.php');
29 require_once($CFG->dirroot.'/course/format/lib.php');
31 define('COURSE_MAX_LOGS_PER_PAGE', 1000); // Records.
32 define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds.
35 * Number of courses to display when summaries are included.
37 * @deprecated since 2.4, use $CFG->courseswithsummarieslimit instead.
39 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10);
41 // Max courses in log dropdown before switching to optional.
42 define('COURSE_MAX_COURSES_PER_DROPDOWN', 1000);
43 // Max users in log dropdown before switching to optional.
44 define('COURSE_MAX_USERS_PER_DROPDOWN', 1000);
45 define('FRONTPAGENEWS', '0');
46 define('FRONTPAGECATEGORYNAMES', '2');
47 define('FRONTPAGECATEGORYCOMBO', '4');
48 define('FRONTPAGEENROLLEDCOURSELIST', '5');
49 define('FRONTPAGEALLCOURSELIST', '6');
50 define('FRONTPAGECOURSESEARCH', '7');
51 // Important! Replaced with $CFG->frontpagecourselimit - maximum number of courses displayed on the frontpage.
52 define('EXCELROWS', 65535);
53 define('FIRSTUSEDEXCELROW', 3);
55 define('MOD_CLASS_ACTIVITY', 0);
56 define('MOD_CLASS_RESOURCE', 1);
58 define('COURSE_TIMELINE_PAST', 'past');
59 define('COURSE_TIMELINE_INPROGRESS', 'inprogress');
60 define('COURSE_TIMELINE_FUTURE', 'future');
61 define('COURSE_DB_QUERY_LIMIT', 1000);
63 function make_log_url($module, $url) {
66 if (strpos($url, 'report/') === 0) {
67 // there is only one report type, course reports are deprecated
77 if (strpos($url, '../') === 0) {
78 $url = ltrim($url, '.');
80 $url = "/course/$url";
84 $url = "/calendar/$url";
88 $url = "/$module/$url";
101 $url = "/message/$url";
104 $url = "/notes/$url";
113 $url = "/grade/$url";
116 $url = "/mod/$module/$url";
120 //now let's sanitise urls - there might be some ugly nasties:-(
121 $parts = explode('?', $url);
122 $script = array_shift($parts);
123 if (strpos($script, 'http') === 0) {
124 $script = clean_param($script, PARAM_URL);
126 $script = clean_param($script, PARAM_PATH);
131 $query = implode('', $parts);
132 $query = str_replace('&', '&', $query); // both & and & are stored in db :-|
133 $parts = explode('&', $query);
134 $eq = urlencode('=');
135 foreach ($parts as $key=>$part) {
136 $part = urlencode(urldecode($part));
137 $part = str_replace($eq, '=', $part);
138 $parts[$key] = $part;
140 $query = '?'.implode('&', $parts);
143 return $script.$query;
147 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
148 $modname="", $modid=0, $modaction="", $groupid=0) {
151 // It is assumed that $date is the GMT time of midnight for that day,
152 // and so the next 86400 seconds worth of logs are printed.
154 /// Setup for group handling.
156 // TODO: I don't understand group/context/etc. enough to be able to do
157 // something interesting with it here
158 // What is the context of a remote course?
160 /// If the group mode is separate, and this user does not have editing privileges,
161 /// then only the user's group can be viewed.
162 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
163 // $groupid = get_current_group($course->id);
165 /// If this course doesn't have groups, no groupid can be specified.
166 //else if (!$course->groupmode) {
175 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
177 LEFT JOIN {user} u ON l.userid = u.id
181 $where .= "l.hostid = :hostid";
182 $params['hostid'] = $hostid;
184 // TODO: Is 1 really a magic number referring to the sitename?
185 if ($course != SITEID || $modid != 0) {
186 $where .= " AND l.course=:courseid";
187 $params['courseid'] = $course;
191 $where .= " AND l.module = :modname";
192 $params['modname'] = $modname;
195 if ('site_errors' === $modid) {
196 $where .= " AND ( l.action='error' OR l.action='infected' )";
198 //TODO: This assumes that modids are the same across sites... probably
200 $where .= " AND l.cmid = :modid";
201 $params['modid'] = $modid;
205 $firstletter = substr($modaction, 0, 1);
206 if ($firstletter == '-') {
207 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
208 $params['modaction'] = '%'.substr($modaction, 1).'%';
210 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
211 $params['modaction'] = '%'.$modaction.'%';
216 $where .= " AND l.userid = :user";
217 $params['user'] = $user;
221 $enddate = $date + 86400;
222 $where .= " AND l.time > :date AND l.time < :enddate";
223 $params['date'] = $date;
224 $params['enddate'] = $enddate;
228 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
229 if(!empty($result['totalcount'])) {
230 $where .= " ORDER BY $order";
231 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
233 $result['logs'] = array();
239 * Checks the integrity of the course data.
241 * In summary - compares course_sections.sequence and course_modules.section.
243 * More detailed, checks that:
244 * - course_sections.sequence contains each module id not more than once in the course
245 * - for each moduleid from course_sections.sequence the field course_modules.section
246 * refers to the same section id (this means course_sections.sequence is more
247 * important if they are different)
248 * - ($fullcheck only) each module in the course is present in one of
249 * course_sections.sequence
250 * - ($fullcheck only) removes non-existing course modules from section sequences
252 * If there are any mismatches, the changes are made and records are updated in DB.
254 * Course cache is NOT rebuilt if there are any errors!
256 * This function is used each time when course cache is being rebuilt with $fullcheck = false
257 * and in CLI script admin/cli/fix_course_sequence.php with $fullcheck = true
259 * @param int $courseid id of the course
260 * @param array $rawmods result of funciton {@link get_course_mods()} - containst
261 * the list of enabled course modules in the course. Retrieved from DB if not specified.
262 * Argument ignored in cashe of $fullcheck, the list is retrieved form DB anyway.
263 * @param array $sections records from course_sections table for this course.
264 * Retrieved from DB if not specified
265 * @param bool $fullcheck Will add orphaned modules to their sections and remove non-existing
266 * course modules from sequences. Only to be used in site maintenance mode when we are
267 * sure that another user is not in the middle of the process of moving/removing a module.
268 * @param bool $checkonly Only performs the check without updating DB, outputs all errors as debug messages.
269 * @return array array of messages with found problems. Empty output means everything is ok
271 function course_integrity_check($courseid, $rawmods = null, $sections = null, $fullcheck = false, $checkonly = false) {
274 if ($sections === null) {
275 $sections = $DB->get_records('course_sections', array('course' => $courseid), 'section', 'id,section,sequence');
278 // Retrieve all records from course_modules regardless of module type visibility.
279 $rawmods = $DB->get_records('course_modules', array('course' => $courseid), 'id', 'id,section');
281 if ($rawmods === null) {
282 $rawmods = get_course_mods($courseid);
284 if (!$fullcheck && (empty($sections) || empty($rawmods))) {
285 // If either of the arrays is empty, no modules are displayed anyway.
288 $debuggingprefix = 'Failed integrity check for course ['.$courseid.']. ';
290 // First make sure that each module id appears in section sequences only once.
291 // If it appears in several section sequences the last section wins.
292 // If it appears twice in one section sequence, the first occurence wins.
293 $modsection = array();
294 foreach ($sections as $sectionid => $section) {
295 $sections[$sectionid]->newsequence = $section->sequence;
296 if (!empty($section->sequence)) {
297 $sequence = explode(",", $section->sequence);
298 $sequenceunique = array_unique($sequence);
299 if (count($sequenceunique) != count($sequence)) {
300 // Some course module id appears in this section sequence more than once.
301 ksort($sequenceunique); // Preserve initial order of modules.
302 $sequence = array_values($sequenceunique);
303 $sections[$sectionid]->newsequence = join(',', $sequence);
304 $messages[] = $debuggingprefix.'Sequence for course section ['.
305 $sectionid.'] is "'.$sections[$sectionid]->sequence.'", must be "'.$sections[$sectionid]->newsequence.'"';
307 foreach ($sequence as $cmid) {
308 if (array_key_exists($cmid, $modsection) && isset($rawmods[$cmid])) {
309 // Some course module id appears to be in more than one section's sequences.
310 $wrongsectionid = $modsection[$cmid];
311 $sections[$wrongsectionid]->newsequence = trim(preg_replace("/,$cmid,/", ',', ','.$sections[$wrongsectionid]->newsequence. ','), ',');
312 $messages[] = $debuggingprefix.'Course module ['.$cmid.'] must be removed from sequence of section ['.
313 $wrongsectionid.'] because it is also present in sequence of section ['.$sectionid.']';
315 $modsection[$cmid] = $sectionid;
320 // Add orphaned modules to their sections if they exist or to section 0 otherwise.
322 foreach ($rawmods as $cmid => $mod) {
323 if (!isset($modsection[$cmid])) {
324 // This is a module that is not mentioned in course_section.sequence at all.
325 // Add it to the section $mod->section or to the last available section.
326 if ($mod->section && isset($sections[$mod->section])) {
327 $modsection[$cmid] = $mod->section;
329 $firstsection = reset($sections);
330 $modsection[$cmid] = $firstsection->id;
332 $sections[$modsection[$cmid]]->newsequence = trim($sections[$modsection[$cmid]]->newsequence.','.$cmid, ',');
333 $messages[] = $debuggingprefix.'Course module ['.$cmid.'] is missing from sequence of section ['.
334 $modsection[$cmid].']';
337 foreach ($modsection as $cmid => $sectionid) {
338 if (!isset($rawmods[$cmid])) {
339 // Section $sectionid refers to module id that does not exist.
340 $sections[$sectionid]->newsequence = trim(preg_replace("/,$cmid,/", ',', ','.$sections[$sectionid]->newsequence.','), ',');
341 $messages[] = $debuggingprefix.'Course module ['.$cmid.
342 '] does not exist but is present in the sequence of section ['.$sectionid.']';
347 // Update changed sections.
348 if (!$checkonly && !empty($messages)) {
349 foreach ($sections as $sectionid => $section) {
350 if ($section->newsequence !== $section->sequence) {
351 $DB->update_record('course_sections', array('id' => $sectionid, 'sequence' => $section->newsequence));
356 // Now make sure that all modules point to the correct sections.
357 foreach ($rawmods as $cmid => $mod) {
358 if (isset($modsection[$cmid]) && $modsection[$cmid] != $mod->section) {
360 $DB->update_record('course_modules', array('id' => $cmid, 'section' => $modsection[$cmid]));
362 $messages[] = $debuggingprefix.'Course module ['.$cmid.
363 '] points to section ['.$mod->section.'] instead of ['.$modsection[$cmid].']';
371 * For a given course, returns an array of course activity objects
372 * Each item in the array contains he following properties:
374 function get_array_of_activities($courseid) {
375 // cm - course module id
376 // mod - name of the module (eg forum)
377 // section - the number of the section (eg week or topic)
378 // name - the name of the instance
379 // visible - is the instance visible or not
380 // groupingid - grouping id
381 // extra - contains extra string to include in any link
384 $course = $DB->get_record('course', array('id'=>$courseid));
386 if (empty($course)) {
387 throw new moodle_exception('courseidnotfound');
392 $rawmods = get_course_mods($courseid);
393 if (empty($rawmods)) {
394 return $mod; // always return array
396 $courseformat = course_get_format($course);
398 if ($sections = $DB->get_records('course_sections', array('course' => $courseid),
399 'section ASC', 'id,section,sequence,visible')) {
400 // First check and correct obvious mismatches between course_sections.sequence and course_modules.section.
401 if ($errormessages = course_integrity_check($courseid, $rawmods, $sections)) {
402 debugging(join('<br>', $errormessages));
403 $rawmods = get_course_mods($courseid);
404 $sections = $DB->get_records('course_sections', array('course' => $courseid),
405 'section ASC', 'id,section,sequence,visible');
407 // Build array of activities.
408 foreach ($sections as $section) {
409 if (!empty($section->sequence)) {
410 $sequence = explode(",", $section->sequence);
411 foreach ($sequence as $seq) {
412 if (empty($rawmods[$seq])) {
415 // Adjust visibleoncoursepage, value in DB may not respect format availability.
416 $rawmods[$seq]->visibleoncoursepage = (!$rawmods[$seq]->visible
417 || $rawmods[$seq]->visibleoncoursepage
418 || empty($CFG->allowstealth)
419 || !$courseformat->allow_stealth_module_visibility($rawmods[$seq], $section)) ? 1 : 0;
421 // Create an object that will be cached.
422 $mod[$seq] = new stdClass();
423 $mod[$seq]->id = $rawmods[$seq]->instance;
424 $mod[$seq]->cm = $rawmods[$seq]->id;
425 $mod[$seq]->mod = $rawmods[$seq]->modname;
427 // Oh dear. Inconsistent names left here for backward compatibility.
428 $mod[$seq]->section = $section->section;
429 $mod[$seq]->sectionid = $rawmods[$seq]->section;
431 $mod[$seq]->module = $rawmods[$seq]->module;
432 $mod[$seq]->added = $rawmods[$seq]->added;
433 $mod[$seq]->score = $rawmods[$seq]->score;
434 $mod[$seq]->idnumber = $rawmods[$seq]->idnumber;
435 $mod[$seq]->visible = $rawmods[$seq]->visible;
436 $mod[$seq]->visibleoncoursepage = $rawmods[$seq]->visibleoncoursepage;
437 $mod[$seq]->visibleold = $rawmods[$seq]->visibleold;
438 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
439 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
440 $mod[$seq]->indent = $rawmods[$seq]->indent;
441 $mod[$seq]->completion = $rawmods[$seq]->completion;
442 $mod[$seq]->extra = "";
443 $mod[$seq]->completiongradeitemnumber =
444 $rawmods[$seq]->completiongradeitemnumber;
445 $mod[$seq]->completionview = $rawmods[$seq]->completionview;
446 $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected;
447 $mod[$seq]->showdescription = $rawmods[$seq]->showdescription;
448 $mod[$seq]->availability = $rawmods[$seq]->availability;
449 $mod[$seq]->deletioninprogress = $rawmods[$seq]->deletioninprogress;
451 $modname = $mod[$seq]->mod;
452 $functionname = $modname."_get_coursemodule_info";
454 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
458 include_once("$CFG->dirroot/mod/$modname/lib.php");
460 if ($hasfunction = function_exists($functionname)) {
461 if ($info = $functionname($rawmods[$seq])) {
462 if (!empty($info->icon)) {
463 $mod[$seq]->icon = $info->icon;
465 if (!empty($info->iconcomponent)) {
466 $mod[$seq]->iconcomponent = $info->iconcomponent;
468 if (!empty($info->name)) {
469 $mod[$seq]->name = $info->name;
471 if ($info instanceof cached_cm_info) {
472 // When using cached_cm_info you can include three new fields
473 // that aren't available for legacy code
474 if (!empty($info->content)) {
475 $mod[$seq]->content = $info->content;
477 if (!empty($info->extraclasses)) {
478 $mod[$seq]->extraclasses = $info->extraclasses;
480 if (!empty($info->iconurl)) {
481 // Convert URL to string as it's easier to store. Also serialized object contains \0 byte and can not be written to Postgres DB.
482 $url = new moodle_url($info->iconurl);
483 $mod[$seq]->iconurl = $url->out(false);
485 if (!empty($info->onclick)) {
486 $mod[$seq]->onclick = $info->onclick;
488 if (!empty($info->customdata)) {
489 $mod[$seq]->customdata = $info->customdata;
492 // When using a stdclass, the (horrible) deprecated ->extra field
493 // is available for BC
494 if (!empty($info->extra)) {
495 $mod[$seq]->extra = $info->extra;
500 // When there is no modname_get_coursemodule_info function,
501 // but showdescriptions is enabled, then we use the 'intro'
502 // and 'introformat' fields in the module table
503 if (!$hasfunction && $rawmods[$seq]->showdescription) {
504 if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
505 array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
506 // Set content from intro and introformat. Filters are disabled
507 // because we filter it with format_text at display time
508 $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
509 $modvalues, $rawmods[$seq]->id, false);
511 // To save making another query just below, put name in here
512 $mod[$seq]->name = $modvalues->name;
515 if (!isset($mod[$seq]->name)) {
516 $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
519 // Minimise the database size by unsetting default options when they are
520 // 'empty'. This list corresponds to code in the cm_info constructor.
521 foreach (array('idnumber', 'groupmode', 'groupingid',
522 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
523 'icon', 'iconcomponent', 'customdata', 'availability', 'completionview',
524 'completionexpected', 'score', 'showdescription', 'deletioninprogress') as $property) {
525 if (property_exists($mod[$seq], $property) &&
526 empty($mod[$seq]->{$property})) {
527 unset($mod[$seq]->{$property});
530 // Special case: this value is usually set to null, but may be 0
531 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
532 is_null($mod[$seq]->completiongradeitemnumber)) {
533 unset($mod[$seq]->completiongradeitemnumber);
543 * Returns the localised human-readable names of all used modules
545 * @param bool $plural if true returns the plural forms of the names
546 * @return array where key is the module name (component name without 'mod_') and
547 * the value is the human-readable string. Array sorted alphabetically by value
549 function get_module_types_names($plural = false) {
550 static $modnames = null;
552 if ($modnames === null) {
553 $modnames = array(0 => array(), 1 => array());
554 if ($allmods = $DB->get_records("modules")) {
555 foreach ($allmods as $mod) {
556 if (file_exists("$CFG->dirroot/mod/$mod->name/lib.php") && $mod->visible) {
557 $modnames[0][$mod->name] = get_string("modulename", "$mod->name");
558 $modnames[1][$mod->name] = get_string("modulenameplural", "$mod->name");
561 core_collator::asort($modnames[0]);
562 core_collator::asort($modnames[1]);
565 return $modnames[(int)$plural];
569 * Set highlighted section. Only one section can be highlighted at the time.
571 * @param int $courseid course id
572 * @param int $marker highlight section with this number, 0 means remove higlightin
575 function course_set_marker($courseid, $marker) {
577 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
578 if ($COURSE && $COURSE->id == $courseid) {
579 $COURSE->marker = $marker;
581 if (class_exists('format_base')) {
582 format_base::reset_course_cache($courseid);
584 course_modinfo::clear_instance_cache($courseid);
588 * For a given course section, marks it visible or hidden,
589 * and does the same for every activity in that section
591 * @param int $courseid course id
592 * @param int $sectionnumber The section number to adjust
593 * @param int $visibility The new visibility
594 * @return array A list of resources which were hidden in the section
596 function set_section_visible($courseid, $sectionnumber, $visibility) {
599 $resourcestotoggle = array();
600 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
601 course_update_section($courseid, $section, array('visible' => $visibility));
603 // Determine which modules are visible for AJAX update
604 $modules = !empty($section->sequence) ? explode(',', $section->sequence) : array();
605 if (!empty($modules)) {
606 list($insql, $params) = $DB->get_in_or_equal($modules);
607 $select = 'id ' . $insql . ' AND visible = ?';
608 array_push($params, $visibility);
610 $select .= ' AND visibleold = 1';
612 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
615 return $resourcestotoggle;
619 * Retrieve all metadata for the requested modules
621 * @param object $course The Course
622 * @param array $modnames An array containing the list of modules and their
624 * @param int $sectionreturn The section to return to
625 * @return array A list of stdClass objects containing metadata about each
628 function get_module_metadata($course, $modnames, $sectionreturn = null) {
631 // get_module_metadata will be called once per section on the page and courses may show
632 // different modules to one another
633 static $modlist = array();
634 if (!isset($modlist[$course->id])) {
635 $modlist[$course->id] = array();
639 $urlbase = new moodle_url('/course/mod.php', array('id' => $course->id, 'sesskey' => sesskey()));
640 if ($sectionreturn !== null) {
641 $urlbase->param('sr', $sectionreturn);
643 foreach($modnames as $modname => $modnamestr) {
644 if (!course_allowed_module($course, $modname)) {
647 if (isset($modlist[$course->id][$modname])) {
648 // This module is already cached
649 $return += $modlist[$course->id][$modname];
652 $modlist[$course->id][$modname] = array();
654 // Create an object for a default representation of this module type in the activity chooser. It will be used
655 // if module does not implement callback get_shortcuts() and it will also be passed to the callback if it exists.
656 $defaultmodule = new stdClass();
657 $defaultmodule->title = $modnamestr;
658 $defaultmodule->name = $modname;
659 $defaultmodule->link = new moodle_url($urlbase, array('add' => $modname));
660 $defaultmodule->icon = $OUTPUT->pix_icon('icon', '', $defaultmodule->name, array('class' => 'icon'));
661 $sm = get_string_manager();
662 if ($sm->string_exists('modulename_help', $modname)) {
663 $defaultmodule->help = get_string('modulename_help', $modname);
664 if ($sm->string_exists('modulename_link', $modname)) { // Link to further info in Moodle docs.
665 $link = get_string('modulename_link', $modname);
666 $linktext = get_string('morehelp');
667 $defaultmodule->help .= html_writer::tag('div',
668 $OUTPUT->doc_link($link, $linktext, true), array('class' => 'helpdoclink'));
671 $defaultmodule->archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
673 // Each module can implement callback modulename_get_shortcuts() in its lib.php and return the list
674 // of elements to be added to activity chooser.
675 $items = component_callback($modname, 'get_shortcuts', array($defaultmodule), null);
676 if ($items !== null) {
677 foreach ($items as $item) {
678 // Add all items to the return array. All items must have different links, use them as a key in the return array.
679 if (!isset($item->archetype)) {
680 $item->archetype = $defaultmodule->archetype;
682 if (!isset($item->icon)) {
683 $item->icon = $defaultmodule->icon;
685 // If plugin returned the only one item with the same link as default item - cache it as $modname,
686 // otherwise append the link url to the module name.
687 $item->name = (count($items) == 1 &&
688 $item->link->out() === $defaultmodule->link->out()) ? $modname : $modname . ':' . $item->link;
690 // If the module provides the helptext property, append it to the help text to match the look and feel
691 // of the default course modules.
692 if (isset($item->help) && isset($item->helplink)) {
693 $linktext = get_string('morehelp');
694 $item->help .= html_writer::tag('div',
695 $OUTPUT->doc_link($item->helplink, $linktext, true), array('class' => 'helpdoclink'));
697 $modlist[$course->id][$modname][$item->name] = $item;
699 $return += $modlist[$course->id][$modname];
700 // If get_shortcuts() callback is defined, the default module action is not added.
701 // It is a responsibility of the callback to add it to the return value unless it is not needed.
705 // The callback get_shortcuts() was not found, use the default item for the activity chooser.
706 $modlist[$course->id][$modname][$modname] = $defaultmodule;
707 $return[$modname] = $defaultmodule;
710 core_collator::asort_objects_by_property($return, 'title');
715 * Return the course category context for the category with id $categoryid, except
716 * that if $categoryid is 0, return the system context.
718 * @param integer $categoryid a category id or 0.
719 * @return context the corresponding context
721 function get_category_or_system_context($categoryid) {
723 return context_coursecat::instance($categoryid, IGNORE_MISSING);
725 return context_system::instance();
730 * Returns full course categories trees to be used in html_writer::select()
732 * Calls {@link core_course_category::make_categories_list()} to build the tree and
733 * adds whitespace to denote nesting
735 * @return array array mapping course category id to the display name
737 function make_categories_options() {
738 $cats = core_course_category::make_categories_list('', 0, ' / ');
739 foreach ($cats as $key => $value) {
740 // Prefix the value with the number of spaces equal to category depth (number of separators in the value).
741 $cats[$key] = str_repeat(' ', substr_count($value, ' / ')). $value;
747 * Print the buttons relating to course requests.
749 * @param object $context current page context.
751 function print_course_request_buttons($context) {
752 global $CFG, $DB, $OUTPUT;
753 if (empty($CFG->enablecourserequests)) {
756 if (!has_capability('moodle/course:create', $context) && has_capability('moodle/course:request', $context)) {
757 /// Print a button to request a new course
758 echo $OUTPUT->single_button(new moodle_url('/course/request.php'), get_string('requestcourse'), 'get');
760 /// Print a button to manage pending requests
761 if ($context->contextlevel == CONTEXT_SYSTEM && has_capability('moodle/site:approvecourse', $context)) {
762 $disabled = !$DB->record_exists('course_request', array());
763 echo $OUTPUT->single_button(new moodle_url('/course/pending.php'), get_string('coursespending'), 'get', array('disabled' => $disabled));
768 * Does the user have permission to edit things in this category?
770 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
771 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
773 function can_edit_in_category($categoryid = 0) {
774 $context = get_category_or_system_context($categoryid);
775 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
778 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
780 function add_course_module($mod) {
783 $mod->added = time();
786 $cmid = $DB->insert_record("course_modules", $mod);
787 rebuild_course_cache($mod->course, true);
792 * Creates a course section and adds it to the specified position
794 * @param int|stdClass $courseorid course id or course object
795 * @param int $position position to add to, 0 means to the end. If position is greater than
796 * number of existing secitons, the section is added to the end. This will become sectionnum of the
797 * new section. All existing sections at this or bigger position will be shifted down.
798 * @param bool $skipcheck the check has already been made and we know that the section with this position does not exist
799 * @return stdClass created section object
801 function course_create_section($courseorid, $position = 0, $skipcheck = false) {
803 $courseid = is_object($courseorid) ? $courseorid->id : $courseorid;
805 // Find the last sectionnum among existing sections.
807 $lastsection = $position - 1;
809 $lastsection = (int)$DB->get_field_sql('SELECT max(section) from {course_sections} WHERE course = ?', [$courseid]);
812 // First add section to the end.
813 $cw = new stdClass();
814 $cw->course = $courseid;
815 $cw->section = $lastsection + 1;
817 $cw->summaryformat = FORMAT_HTML;
821 $cw->availability = null;
822 $cw->timemodified = time();
823 $cw->id = $DB->insert_record("course_sections", $cw);
825 // Now move it to the specified position.
826 if ($position > 0 && $position <= $lastsection) {
827 $course = is_object($courseorid) ? $courseorid : get_course($courseorid);
828 move_section_to($course, $cw->section, $position, true);
829 $cw->section = $position;
832 core\event\course_section_created::create_from_section($cw)->trigger();
834 rebuild_course_cache($courseid, true);
839 * Creates missing course section(s) and rebuilds course cache
841 * @param int|stdClass $courseorid course id or course object
842 * @param int|array $sections list of relative section numbers to create
843 * @return bool if there were any sections created
845 function course_create_sections_if_missing($courseorid, $sections) {
846 if (!is_array($sections)) {
847 $sections = array($sections);
849 $existing = array_keys(get_fast_modinfo($courseorid)->get_section_info_all());
850 if ($newsections = array_diff($sections, $existing)) {
851 foreach ($newsections as $sectionnum) {
852 course_create_section($courseorid, $sectionnum, true);
860 * Adds an existing module to the section
862 * Updates both tables {course_sections} and {course_modules}
864 * Note: This function does not use modinfo PROVIDED that the section you are
865 * adding the module to already exists. If the section does not exist, it will
866 * build modinfo if necessary and create the section.
868 * @param int|stdClass $courseorid course id or course object
869 * @param int $cmid id of the module already existing in course_modules table
870 * @param int $sectionnum relative number of the section (field course_sections.section)
871 * If section does not exist it will be created
872 * @param int|stdClass $beforemod id or object with field id corresponding to the module
873 * before which the module needs to be included. Null for inserting in the
875 * @return int The course_sections ID where the module is inserted
877 function course_add_cm_to_section($courseorid, $cmid, $sectionnum, $beforemod = null) {
879 if (is_object($beforemod)) {
880 $beforemod = $beforemod->id;
882 if (is_object($courseorid)) {
883 $courseid = $courseorid->id;
885 $courseid = $courseorid;
887 // Do not try to use modinfo here, there is no guarantee it is valid!
888 $section = $DB->get_record('course_sections',
889 array('course' => $courseid, 'section' => $sectionnum), '*', IGNORE_MISSING);
891 // This function call requires modinfo.
892 course_create_sections_if_missing($courseorid, $sectionnum);
893 $section = $DB->get_record('course_sections',
894 array('course' => $courseid, 'section' => $sectionnum), '*', MUST_EXIST);
897 $modarray = explode(",", trim($section->sequence));
898 if (empty($section->sequence)) {
899 $newsequence = "$cmid";
900 } else if ($beforemod && ($key = array_keys($modarray, $beforemod))) {
901 $insertarray = array($cmid, $beforemod);
902 array_splice($modarray, $key[0], 1, $insertarray);
903 $newsequence = implode(",", $modarray);
905 $newsequence = "$section->sequence,$cmid";
907 $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id));
908 $DB->set_field('course_modules', 'section', $section->id, array('id' => $cmid));
909 if (is_object($courseorid)) {
910 rebuild_course_cache($courseorid->id, true);
912 rebuild_course_cache($courseorid, true);
914 return $section->id; // Return course_sections ID that was used.
918 * Change the group mode of a course module.
920 * Note: Do not forget to trigger the event \core\event\course_module_updated as it needs
921 * to be triggered manually, refer to {@link \core\event\course_module_updated::create_from_cm()}.
923 * @param int $id course module ID.
924 * @param int $groupmode the new groupmode value.
925 * @return bool True if the $groupmode was updated.
927 function set_coursemodule_groupmode($id, $groupmode) {
929 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST);
930 if ($cm->groupmode != $groupmode) {
931 $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id));
932 rebuild_course_cache($cm->course, true);
934 return ($cm->groupmode != $groupmode);
937 function set_coursemodule_idnumber($id, $idnumber) {
939 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST);
940 if ($cm->idnumber != $idnumber) {
941 $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id));
942 rebuild_course_cache($cm->course, true);
944 return ($cm->idnumber != $idnumber);
948 * Set the visibility of a module and inherent properties.
950 * Note: Do not forget to trigger the event \core\event\course_module_updated as it needs
951 * to be triggered manually, refer to {@link \core\event\course_module_updated::create_from_cm()}.
953 * From 2.4 the parameter $prevstateoverrides has been removed, the logic it triggered
954 * has been moved to {@link set_section_visible()} which was the only place from which
955 * the parameter was used.
957 * @param int $id of the module
958 * @param int $visible state of the module
959 * @param int $visibleoncoursepage state of the module on the course page
960 * @return bool false when the module was not found, true otherwise
962 function set_coursemodule_visible($id, $visible, $visibleoncoursepage = 1) {
964 require_once($CFG->libdir.'/gradelib.php');
965 require_once($CFG->dirroot.'/calendar/lib.php');
967 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
971 // Create events and propagate visibility to associated grade items if the value has changed.
972 // Only do this if it's changed to avoid accidently overwriting manual showing/hiding of student grades.
973 if ($cm->visible == $visible && $cm->visibleoncoursepage == $visibleoncoursepage) {
977 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
980 if (($cm->visible != $visible) &&
981 ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename)))) {
982 foreach($events as $event) {
984 $event = new calendar_event($event);
985 $event->toggle_visibility(true);
987 $event = new calendar_event($event);
988 $event->toggle_visibility(false);
993 // Updating visible and visibleold to keep them in sync. Only changing a section visibility will
994 // affect visibleold to allow for an original visibility restore. See set_section_visible().
995 $cminfo = new stdClass();
997 $cminfo->visible = $visible;
998 $cminfo->visibleoncoursepage = $visibleoncoursepage;
999 $cminfo->visibleold = $visible;
1000 $DB->update_record('course_modules', $cminfo);
1002 // Hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there.
1003 // Note that this must be done after updating the row in course_modules, in case
1004 // the modules grade_item_update function needs to access $cm->visible.
1005 if ($cm->visible != $visible &&
1006 plugin_supports('mod', $modulename, FEATURE_CONTROLS_GRADE_VISIBILITY) &&
1007 component_callback_exists('mod_' . $modulename, 'grade_item_update')) {
1008 $instance = $DB->get_record($modulename, array('id' => $cm->instance), '*', MUST_EXIST);
1009 component_callback('mod_' . $modulename, 'grade_item_update', array($instance));
1010 } else if ($cm->visible != $visible) {
1011 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
1013 foreach ($grade_items as $grade_item) {
1014 $grade_item->set_hidden(!$visible);
1019 rebuild_course_cache($cm->course, true);
1024 * Changes the course module name
1026 * @param int $id course module id
1027 * @param string $name new value for a name
1028 * @return bool whether a change was made
1030 function set_coursemodule_name($id, $name) {
1032 require_once($CFG->libdir . '/gradelib.php');
1034 $cm = get_coursemodule_from_id('', $id, 0, false, MUST_EXIST);
1036 $module = new \stdClass();
1037 $module->id = $cm->instance;
1039 // Escape strings as they would be by mform.
1040 if (!empty($CFG->formatstringstriptags)) {
1041 $module->name = clean_param($name, PARAM_TEXT);
1043 $module->name = clean_param($name, PARAM_CLEANHTML);
1045 if ($module->name === $cm->name || strval($module->name) === '') {
1048 if (\core_text::strlen($module->name) > 255) {
1049 throw new \moodle_exception('maximumchars', 'moodle', '', 255);
1052 $module->timemodified = time();
1053 $DB->update_record($cm->modname, $module);
1054 $cm->name = $module->name;
1055 \core\event\course_module_updated::create_from_cm($cm)->trigger();
1056 rebuild_course_cache($cm->course, true);
1058 // Attempt to update the grade item if relevant.
1059 $grademodule = $DB->get_record($cm->modname, array('id' => $cm->instance));
1060 $grademodule->cmidnumber = $cm->idnumber;
1061 $grademodule->modname = $cm->modname;
1062 grade_update_mod_grades($grademodule);
1064 // Update calendar events with the new name.
1065 course_module_update_calendar_events($cm->modname, $grademodule, $cm);
1071 * This function will handle the whole deletion process of a module. This includes calling
1072 * the modules delete_instance function, deleting files, events, grades, conditional data,
1073 * the data in the course_module and course_sections table and adding a module deletion
1076 * @param int $cmid the course module id
1077 * @param bool $async whether or not to try to delete the module using an adhoc task. Async also depends on a plugin hook.
1078 * @throws moodle_exception
1081 function course_delete_module($cmid, $async = false) {
1082 // Check the 'course_module_background_deletion_recommended' hook first.
1083 // Only use asynchronous deletion if at least one plugin returns true and if async deletion has been requested.
1084 // Both are checked because plugins should not be allowed to dictate the deletion behaviour, only support/decline it.
1085 // It's up to plugins to handle things like whether or not they are enabled.
1086 if ($async && $pluginsfunction = get_plugins_with_function('course_module_background_deletion_recommended')) {
1087 foreach ($pluginsfunction as $plugintype => $plugins) {
1088 foreach ($plugins as $pluginfunction) {
1089 if ($pluginfunction()) {
1090 return course_module_flag_for_async_deletion($cmid);
1098 require_once($CFG->libdir.'/gradelib.php');
1099 require_once($CFG->libdir.'/questionlib.php');
1100 require_once($CFG->dirroot.'/blog/lib.php');
1101 require_once($CFG->dirroot.'/calendar/lib.php');
1103 // Get the course module.
1104 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
1108 // Get the module context.
1109 $modcontext = context_module::instance($cm->id);
1111 // Get the course module name.
1112 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
1114 // Get the file location of the delete_instance function for this module.
1115 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
1117 // Include the file required to call the delete_instance function for this module.
1118 if (file_exists($modlib)) {
1119 require_once($modlib);
1121 throw new moodle_exception('cannotdeletemodulemissinglib', '', '', null,
1122 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
1125 $deleteinstancefunction = $modulename . '_delete_instance';
1127 // Ensure the delete_instance function exists for this module.
1128 if (!function_exists($deleteinstancefunction)) {
1129 throw new moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
1130 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
1133 // Allow plugins to use this course module before we completely delete it.
1134 if ($pluginsfunction = get_plugins_with_function('pre_course_module_delete')) {
1135 foreach ($pluginsfunction as $plugintype => $plugins) {
1136 foreach ($plugins as $pluginfunction) {
1137 $pluginfunction($cm);
1142 // Delete activity context questions and question categories.
1143 question_delete_activity($cm);
1145 // Call the delete_instance function, if it returns false throw an exception.
1146 if (!$deleteinstancefunction($cm->instance)) {
1147 throw new moodle_exception('cannotdeletemoduleinstance', '', '', null,
1148 "Cannot delete the module $modulename (instance).");
1151 // Remove all module files in case modules forget to do that.
1152 $fs = get_file_storage();
1153 $fs->delete_area_files($modcontext->id);
1155 // Delete events from calendar.
1156 if ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename))) {
1157 $coursecontext = context_course::instance($cm->course);
1158 foreach($events as $event) {
1159 $event->context = $coursecontext;
1160 $calendarevent = calendar_event::load($event);
1161 $calendarevent->delete();
1165 // Delete grade items, outcome items and grades attached to modules.
1166 if ($grade_items = grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $modulename,
1167 'iteminstance' => $cm->instance, 'courseid' => $cm->course))) {
1168 foreach ($grade_items as $grade_item) {
1169 $grade_item->delete('moddelete');
1173 // Delete associated blogs and blog tag instances.
1174 blog_remove_associations_for_module($modcontext->id);
1176 // Delete completion and availability data; it is better to do this even if the
1177 // features are not turned on, in case they were turned on previously (these will be
1178 // very quick on an empty table).
1179 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
1180 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
1181 'course' => $cm->course,
1182 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
1184 // Delete all tag instances associated with the instance of this module.
1185 core_tag_tag::delete_instances('mod_' . $modulename, null, $modcontext->id);
1186 core_tag_tag::remove_all_item_tags('core', 'course_modules', $cm->id);
1188 // Notify the competency subsystem.
1189 \core_competency\api::hook_course_module_deleted($cm);
1191 // Delete the context.
1192 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
1194 // Delete the module from the course_modules table.
1195 $DB->delete_records('course_modules', array('id' => $cm->id));
1197 // Delete module from that section.
1198 if (!delete_mod_from_section($cm->id, $cm->section)) {
1199 throw new moodle_exception('cannotdeletemodulefromsection', '', '', null,
1200 "Cannot delete the module $modulename (instance) from section.");
1203 // Trigger event for course module delete action.
1204 $event = \core\event\course_module_deleted::create(array(
1205 'courseid' => $cm->course,
1206 'context' => $modcontext,
1207 'objectid' => $cm->id,
1209 'modulename' => $modulename,
1210 'instanceid' => $cm->instance,
1213 $event->add_record_snapshot('course_modules', $cm);
1215 rebuild_course_cache($cm->course, true);
1219 * Schedule a course module for deletion in the background using an adhoc task.
1221 * This method should not be called directly. Instead, please use course_delete_module($cmid, true), to denote async deletion.
1222 * The real deletion of the module is handled by the task, which calls 'course_delete_module($cmid)'.
1224 * @param int $cmid the course module id.
1225 * @return bool whether the module was successfully scheduled for deletion.
1226 * @throws \moodle_exception
1228 function course_module_flag_for_async_deletion($cmid) {
1229 global $CFG, $DB, $USER;
1230 require_once($CFG->libdir.'/gradelib.php');
1231 require_once($CFG->libdir.'/questionlib.php');
1232 require_once($CFG->dirroot.'/blog/lib.php');
1233 require_once($CFG->dirroot.'/calendar/lib.php');
1235 // Get the course module.
1236 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
1240 // We need to be reasonably certain the deletion is going to succeed before we background the process.
1241 // Make the necessary delete_instance checks, etc. before proceeding further. Throw exceptions if required.
1243 // Get the course module name.
1244 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
1246 // Get the file location of the delete_instance function for this module.
1247 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
1249 // Include the file required to call the delete_instance function for this module.
1250 if (file_exists($modlib)) {
1251 require_once($modlib);
1253 throw new \moodle_exception('cannotdeletemodulemissinglib', '', '', null,
1254 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
1257 $deleteinstancefunction = $modulename . '_delete_instance';
1259 // Ensure the delete_instance function exists for this module.
1260 if (!function_exists($deleteinstancefunction)) {
1261 throw new \moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
1262 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
1265 // We are going to defer the deletion as we can't be sure how long the module's pre_delete code will run for.
1266 $cm->deletioninprogress = '1';
1267 $DB->update_record('course_modules', $cm);
1269 // Create an adhoc task for the deletion of the course module. The task takes an array of course modules for removal.
1270 $removaltask = new \core_course\task\course_delete_modules();
1271 $removaltask->set_custom_data(array(
1272 'cms' => array($cm),
1273 'userid' => $USER->id,
1274 'realuserid' => \core\session\manager::get_realuser()->id
1277 // Queue the task for the next run.
1278 \core\task\manager::queue_adhoc_task($removaltask);
1280 // Reset the course cache to hide the module.
1281 rebuild_course_cache($cm->course, true);
1285 * Checks whether the given course has any course modules scheduled for adhoc deletion.
1287 * @param int $courseid the id of the course.
1288 * @return bool true if the course contains any modules pending deletion, false otherwise.
1290 function course_modules_pending_deletion($courseid) {
1291 if (empty($courseid)) {
1294 $modinfo = get_fast_modinfo($courseid);
1295 foreach ($modinfo->get_cms() as $module) {
1296 if ($module->deletioninprogress == '1') {
1304 * Checks whether the course module, as defined by modulename and instanceid, is scheduled for deletion within the given course.
1306 * @param int $courseid the course id.
1307 * @param string $modulename the module name. E.g. 'assign', 'book', etc.
1308 * @param int $instanceid the module instance id.
1309 * @return bool true if the course module is pending deletion, false otherwise.
1311 function course_module_instance_pending_deletion($courseid, $modulename, $instanceid) {
1312 if (empty($courseid) || empty($modulename) || empty($instanceid)) {
1315 $modinfo = get_fast_modinfo($courseid);
1316 $instances = $modinfo->get_instances_of($modulename);
1317 return isset($instances[$instanceid]) && $instances[$instanceid]->deletioninprogress;
1320 function delete_mod_from_section($modid, $sectionid) {
1323 if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
1325 $modarray = explode(",", $section->sequence);
1327 if ($key = array_keys ($modarray, $modid)) {
1328 array_splice($modarray, $key[0], 1);
1329 $newsequence = implode(",", $modarray);
1330 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
1331 rebuild_course_cache($section->course, true);
1342 * This function updates the calendar events from the information stored in the module table and the course
1345 * @param string $modulename Module name
1346 * @param stdClass $instance Module object. Either the $instance or the $cm must be supplied.
1347 * @param stdClass $cm Course module object. Either the $instance or the $cm must be supplied.
1348 * @return bool Returns true if calendar events are updated.
1349 * @since Moodle 3.3.4
1351 function course_module_update_calendar_events($modulename, $instance = null, $cm = null) {
1354 if (isset($instance) || isset($cm)) {
1356 if (!isset($instance)) {
1357 $instance = $DB->get_record($modulename, array('id' => $cm->instance), '*', MUST_EXIST);
1360 $cm = get_coursemodule_from_instance($modulename, $instance->id, $instance->course);
1363 course_module_calendar_event_update_process($instance, $cm);
1371 * Update all instances through out the site or in a course.
1373 * @param string $modulename Module type to update.
1374 * @param integer $courseid Course id to update events. 0 for the whole site.
1375 * @return bool Returns True if the update was successful.
1376 * @since Moodle 3.3.4
1378 function course_module_bulk_update_calendar_events($modulename, $courseid = 0) {
1383 if (!$instances = $DB->get_records($modulename, array('course' => $courseid))) {
1387 if (!$instances = $DB->get_records($modulename)) {
1392 foreach ($instances as $instance) {
1393 if ($cm = get_coursemodule_from_instance($modulename, $instance->id, $instance->course)) {
1394 course_module_calendar_event_update_process($instance, $cm);
1401 * Calendar events for a module instance are updated.
1403 * @param stdClass $instance Module instance object.
1404 * @param stdClass $cm Course Module object.
1405 * @since Moodle 3.3.4
1407 function course_module_calendar_event_update_process($instance, $cm) {
1408 // We need to call *_refresh_events() first because some modules delete 'old' events at the end of the code which
1409 // will remove the completion events.
1410 $refresheventsfunction = $cm->modname . '_refresh_events';
1411 if (function_exists($refresheventsfunction)) {
1412 call_user_func($refresheventsfunction, $cm->course, $instance, $cm);
1414 $completionexpected = (!empty($cm->completionexpected)) ? $cm->completionexpected : null;
1415 \core_completion\api::update_completion_date_event($cm->id, $cm->modname, $instance, $completionexpected);
1419 * Moves a section within a course, from a position to another.
1420 * Be very careful: $section and $destination refer to section number,
1423 * @param object $course
1424 * @param int $section Section number (not id!!!)
1425 * @param int $destination
1426 * @param bool $ignorenumsections
1427 * @return boolean Result
1429 function move_section_to($course, $section, $destination, $ignorenumsections = false) {
1430 /// Moves a whole course section up and down within the course
1433 if (!$destination && $destination != 0) {
1437 // compartibility with course formats using field 'numsections'
1438 $courseformatoptions = course_get_format($course)->get_format_options();
1439 if ((!$ignorenumsections && array_key_exists('numsections', $courseformatoptions) &&
1440 ($destination > $courseformatoptions['numsections'])) || ($destination < 1)) {
1444 // Get all sections for this course and re-order them (2 of them should now share the same section number)
1445 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
1446 'section ASC, id ASC', 'id, section')) {
1450 $movedsections = reorder_sections($sections, $section, $destination);
1452 // Update all sections. Do this in 2 steps to avoid breaking database
1453 // uniqueness constraint
1454 $transaction = $DB->start_delegated_transaction();
1455 foreach ($movedsections as $id => $position) {
1456 if ($sections[$id] !== $position) {
1457 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
1460 foreach ($movedsections as $id => $position) {
1461 if ($sections[$id] !== $position) {
1462 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
1466 // If we move the highlighted section itself, then just highlight the destination.
1467 // Adjust the higlighted section location if we move something over it either direction.
1468 if ($section == $course->marker) {
1469 course_set_marker($course->id, $destination);
1470 } elseif ($section > $course->marker && $course->marker >= $destination) {
1471 course_set_marker($course->id, $course->marker+1);
1472 } elseif ($section < $course->marker && $course->marker <= $destination) {
1473 course_set_marker($course->id, $course->marker-1);
1476 $transaction->allow_commit();
1477 rebuild_course_cache($course->id, true);
1482 * This method will delete a course section and may delete all modules inside it.
1484 * No permissions are checked here, use {@link course_can_delete_section()} to
1485 * check if section can actually be deleted.
1487 * @param int|stdClass $course
1488 * @param int|stdClass|section_info $section
1489 * @param bool $forcedeleteifnotempty if set to false section will not be deleted if it has modules in it.
1490 * @param bool $async whether or not to try to delete the section using an adhoc task. Async also depends on a plugin hook.
1491 * @return bool whether section was deleted
1493 function course_delete_section($course, $section, $forcedeleteifnotempty = true, $async = false) {
1496 // Prepare variables.
1497 $courseid = (is_object($course)) ? $course->id : (int)$course;
1498 $sectionnum = (is_object($section)) ? $section->section : (int)$section;
1499 $section = $DB->get_record('course_sections', array('course' => $courseid, 'section' => $sectionnum));
1501 // No section exists, can't proceed.
1505 // Check the 'course_module_background_deletion_recommended' hook first.
1506 // Only use asynchronous deletion if at least one plugin returns true and if async deletion has been requested.
1507 // Both are checked because plugins should not be allowed to dictate the deletion behaviour, only support/decline it.
1508 // It's up to plugins to handle things like whether or not they are enabled.
1509 if ($async && $pluginsfunction = get_plugins_with_function('course_module_background_deletion_recommended')) {
1510 foreach ($pluginsfunction as $plugintype => $plugins) {
1511 foreach ($plugins as $pluginfunction) {
1512 if ($pluginfunction()) {
1513 return course_delete_section_async($section, $forcedeleteifnotempty);
1519 $format = course_get_format($course);
1520 $sectionname = $format->get_section_name($section);
1523 $result = $format->delete_section($section, $forcedeleteifnotempty);
1525 // Trigger an event for course section deletion.
1527 $context = context_course::instance($courseid);
1528 $event = \core\event\course_section_deleted::create(
1530 'objectid' => $section->id,
1531 'courseid' => $courseid,
1532 'context' => $context,
1534 'sectionnum' => $section->section,
1535 'sectionname' => $sectionname,
1539 $event->add_record_snapshot('course_sections', $section);
1546 * Course section deletion, using an adhoc task for deletion of the modules it contains.
1547 * 1. Schedule all modules within the section for adhoc removal.
1548 * 2. Move all modules to course section 0.
1549 * 3. Delete the resulting empty section.
1551 * @param \stdClass $section the section to schedule for deletion.
1552 * @param bool $forcedeleteifnotempty whether to force section deletion if it contains modules.
1553 * @return bool true if the section was scheduled for deletion, false otherwise.
1555 function course_delete_section_async($section, $forcedeleteifnotempty = true) {
1558 // Objects only, and only valid ones.
1559 if (!is_object($section) || empty($section->id)) {
1563 // Does the object currently exist in the DB for removal (check for stale objects).
1564 $section = $DB->get_record('course_sections', array('id' => $section->id));
1565 if (!$section || !$section->section) {
1566 // No section exists, or the section is 0. Can't proceed.
1570 // Check whether the section can be removed.
1571 if (!$forcedeleteifnotempty && (!empty($section->sequence) || !empty($section->summary))) {
1575 $format = course_get_format($section->course);
1576 $sectionname = $format->get_section_name($section);
1578 // Flag those modules having no existing deletion flag. Some modules may have been scheduled for deletion manually, and we don't
1579 // want to create additional adhoc deletion tasks for these. Moving them to section 0 will suffice.
1580 $affectedmods = $DB->get_records_select('course_modules', 'course = ? AND section = ? AND deletioninprogress <> ?',
1581 [$section->course, $section->id, 1], '', 'id');
1582 $DB->set_field('course_modules', 'deletioninprogress', '1', ['course' => $section->course, 'section' => $section->id]);
1584 // Move all modules to section 0.
1585 $modules = $DB->get_records('course_modules', ['section' => $section->id], '');
1586 $sectionzero = $DB->get_record('course_sections', ['course' => $section->course, 'section' => '0']);
1587 foreach ($modules as $mod) {
1588 moveto_module($mod, $sectionzero);
1591 // Create and queue an adhoc task for the deletion of the modules.
1592 $removaltask = new \core_course\task\course_delete_modules();
1594 'cms' => $affectedmods,
1595 'userid' => $USER->id,
1596 'realuserid' => \core\session\manager::get_realuser()->id
1598 $removaltask->set_custom_data($data);
1599 \core\task\manager::queue_adhoc_task($removaltask);
1601 // Delete the now empty section, passing in only the section number, which forces the function to fetch a new object.
1602 // The refresh is needed because the section->sequence is now stale.
1603 $result = $format->delete_section($section->section, $forcedeleteifnotempty);
1605 // Trigger an event for course section deletion.
1607 $context = \context_course::instance($section->course);
1608 $event = \core\event\course_section_deleted::create(
1610 'objectid' => $section->id,
1611 'courseid' => $section->course,
1612 'context' => $context,
1614 'sectionnum' => $section->section,
1615 'sectionname' => $sectionname,
1619 $event->add_record_snapshot('course_sections', $section);
1622 rebuild_course_cache($section->course, true);
1628 * Updates the course section
1630 * This function does not check permissions or clean values - this has to be done prior to calling it.
1632 * @param int|stdClass $course
1633 * @param stdClass $section record from course_sections table - it will be updated with the new values
1634 * @param array|stdClass $data
1636 function course_update_section($course, $section, $data) {
1639 $courseid = (is_object($course)) ? $course->id : (int)$course;
1641 // Some fields can not be updated using this method.
1642 $data = array_diff_key((array)$data, array('id', 'course', 'section', 'sequence'));
1643 $changevisibility = (array_key_exists('visible', $data) && (bool)$data['visible'] != (bool)$section->visible);
1644 if (array_key_exists('name', $data) && \core_text::strlen($data['name']) > 255) {
1645 throw new moodle_exception('maximumchars', 'moodle', '', 255);
1648 // Update record in the DB and course format options.
1649 $data['id'] = $section->id;
1650 $data['timemodified'] = time();
1651 $DB->update_record('course_sections', $data);
1652 rebuild_course_cache($courseid, true);
1653 course_get_format($courseid)->update_section_format_options($data);
1655 // Update fields of the $section object.
1656 foreach ($data as $key => $value) {
1657 if (property_exists($section, $key)) {
1658 $section->$key = $value;
1662 // Trigger an event for course section update.
1663 $event = \core\event\course_section_updated::create(
1665 'objectid' => $section->id,
1666 'courseid' => $courseid,
1667 'context' => context_course::instance($courseid),
1668 'other' => array('sectionnum' => $section->section)
1673 // If section visibility was changed, hide the modules in this section too.
1674 if ($changevisibility && !empty($section->sequence)) {
1675 $modules = explode(',', $section->sequence);
1676 foreach ($modules as $moduleid) {
1677 if ($cm = get_coursemodule_from_id(null, $moduleid, $courseid)) {
1678 if ($data['visible']) {
1679 // As we unhide the section, we use the previously saved visibility stored in visibleold.
1680 set_coursemodule_visible($moduleid, $cm->visibleold, $cm->visibleoncoursepage);
1682 // We hide the section, so we hide the module but we store the original state in visibleold.
1683 set_coursemodule_visible($moduleid, 0, $cm->visibleoncoursepage);
1684 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id' => $moduleid));
1686 \core\event\course_module_updated::create_from_cm($cm)->trigger();
1693 * Checks if the current user can delete a section (if course format allows it and user has proper permissions).
1695 * @param int|stdClass $course
1696 * @param int|stdClass|section_info $section
1699 function course_can_delete_section($course, $section) {
1700 if (is_object($section)) {
1701 $section = $section->section;
1704 // Not possible to delete 0-section.
1707 // Course format should allow to delete sections.
1708 if (!course_get_format($course)->can_delete_section($section)) {
1711 // Make sure user has capability to update course and move sections.
1712 $context = context_course::instance(is_object($course) ? $course->id : $course);
1713 if (!has_all_capabilities(array('moodle/course:movesections', 'moodle/course:update'), $context)) {
1716 // Make sure user has capability to delete each activity in this section.
1717 $modinfo = get_fast_modinfo($course);
1718 if (!empty($modinfo->sections[$section])) {
1719 foreach ($modinfo->sections[$section] as $cmid) {
1720 if (!has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
1729 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
1730 * an original position number and a target position number, rebuilds the array so that the
1731 * move is made without any duplication of section positions.
1732 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
1733 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
1735 * @param array $sections
1736 * @param int $origin_position
1737 * @param int $target_position
1740 function reorder_sections($sections, $origin_position, $target_position) {
1741 if (!is_array($sections)) {
1745 // We can't move section position 0
1746 if ($origin_position < 1) {
1747 echo "We can't move section position 0";
1751 // Locate origin section in sections array
1752 if (!$origin_key = array_search($origin_position, $sections)) {
1753 echo "searched position not in sections array";
1754 return false; // searched position not in sections array
1757 // Extract origin section
1758 $origin_section = $sections[$origin_key];
1759 unset($sections[$origin_key]);
1761 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
1763 $append_array = array();
1764 foreach ($sections as $id => $position) {
1766 $append_array[$id] = $position;
1767 unset($sections[$id]);
1769 if ($position == $target_position) {
1770 if ($target_position < $origin_position) {
1771 $append_array[$id] = $position;
1772 unset($sections[$id]);
1778 // Append moved section
1779 $sections[$origin_key] = $origin_section;
1781 // Append rest of array (if applicable)
1782 if (!empty($append_array)) {
1783 foreach ($append_array as $id => $position) {
1784 $sections[$id] = $position;
1788 // Renumber positions
1790 foreach ($sections as $id => $p) {
1791 $sections[$id] = $position;
1800 * Move the module object $mod to the specified $section
1801 * If $beforemod exists then that is the module
1802 * before which $modid should be inserted
1804 * @param stdClass|cm_info $mod
1805 * @param stdClass|section_info $section
1806 * @param int|stdClass $beforemod id or object with field id corresponding to the module
1807 * before which the module needs to be included. Null for inserting in the
1808 * end of the section
1809 * @return int new value for module visibility (0 or 1)
1811 function moveto_module($mod, $section, $beforemod=NULL) {
1812 global $OUTPUT, $DB;
1814 // Current module visibility state - return value of this function.
1815 $modvisible = $mod->visible;
1817 // Remove original module from original section.
1818 if (! delete_mod_from_section($mod->id, $mod->section)) {
1819 echo $OUTPUT->notification("Could not delete module from existing section");
1822 // If moving to a hidden section then hide module.
1823 if ($mod->section != $section->id) {
1824 if (!$section->visible && $mod->visible) {
1825 // Module was visible but must become hidden after moving to hidden section.
1827 set_coursemodule_visible($mod->id, 0);
1828 // Set visibleold to 1 so module will be visible when section is made visible.
1829 $DB->set_field('course_modules', 'visibleold', 1, array('id' => $mod->id));
1831 if ($section->visible && !$mod->visible) {
1832 // Hidden module was moved to the visible section, restore the module visibility from visibleold.
1833 set_coursemodule_visible($mod->id, $mod->visibleold);
1834 $modvisible = $mod->visibleold;
1838 // Add the module into the new section.
1839 course_add_cm_to_section($section->course, $mod->id, $section->section, $beforemod);
1844 * Returns the list of all editing actions that current user can perform on the module
1846 * @param cm_info $mod The module to produce editing buttons for
1847 * @param int $indent The current indenting (default -1 means no move left-right actions)
1848 * @param int $sr The section to link back to (used for creating the links)
1849 * @return array array of action_link or pix_icon objects
1851 function course_get_cm_edit_actions(cm_info $mod, $indent = -1, $sr = null) {
1852 global $COURSE, $SITE, $CFG;
1856 $coursecontext = context_course::instance($mod->course);
1857 $modcontext = context_module::instance($mod->id);
1858 $courseformat = course_get_format($mod->get_course());
1860 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
1861 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
1863 // No permission to edit anything.
1864 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
1868 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
1871 $str = get_strings(array('delete', 'move', 'moveright', 'moveleft',
1872 'editsettings', 'duplicate', 'modhide', 'makeavailable', 'makeunavailable', 'modshow'), 'moodle');
1873 $str->assign = get_string('assignroles', 'role');
1874 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
1875 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
1876 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
1879 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
1882 $baseurl->param('sr', $sr);
1887 if ($hasmanageactivities) {
1888 $actions['update'] = new action_menu_link_secondary(
1889 new moodle_url($baseurl, array('update' => $mod->id)),
1890 new pix_icon('t/edit', $str->editsettings, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1892 array('class' => 'editing_update', 'data-action' => 'update')
1897 if ($hasmanageactivities && $indent >= 0) {
1898 $indentlimits = new stdClass();
1899 $indentlimits->min = 0;
1900 $indentlimits->max = 16;
1901 if (right_to_left()) { // Exchange arrows on RTL
1902 $rightarrow = 't/left';
1903 $leftarrow = 't/right';
1905 $rightarrow = 't/right';
1906 $leftarrow = 't/left';
1909 if ($indent >= $indentlimits->max) {
1910 $enabledclass = 'hidden';
1914 $actions['moveright'] = new action_menu_link_secondary(
1915 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
1916 new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1918 array('class' => 'editing_moveright ' . $enabledclass, 'data-action' => 'moveright',
1919 'data-keepopen' => true, 'data-sectionreturn' => $sr)
1922 if ($indent <= $indentlimits->min) {
1923 $enabledclass = 'hidden';
1927 $actions['moveleft'] = new action_menu_link_secondary(
1928 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
1929 new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1931 array('class' => 'editing_moveleft ' . $enabledclass, 'data-action' => 'moveleft',
1932 'data-keepopen' => true, 'data-sectionreturn' => $sr)
1937 // Hide/Show/Available/Unavailable.
1938 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
1939 $allowstealth = !empty($CFG->allowstealth) && $courseformat->allow_stealth_module_visibility($mod, $mod->get_section_info());
1941 $sectionvisible = $mod->get_section_info()->visible;
1942 // The module on the course page may be in one of the following states:
1943 // - Available and displayed on the course page ($displayedoncoursepage);
1944 // - Not available and not displayed on the course page ($unavailable);
1945 // - Available but not displayed on the course page ($stealth) - this can also be a visible activity in a hidden section.
1946 $displayedoncoursepage = $mod->visible && $mod->visibleoncoursepage && $sectionvisible;
1947 $unavailable = !$mod->visible;
1948 $stealth = $mod->visible && (!$mod->visibleoncoursepage || !$sectionvisible);
1949 if ($displayedoncoursepage) {
1950 $actions['hide'] = new action_menu_link_secondary(
1951 new moodle_url($baseurl, array('hide' => $mod->id)),
1952 new pix_icon('t/hide', $str->modhide, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1954 array('class' => 'editing_hide', 'data-action' => 'hide')
1956 } else if (!$displayedoncoursepage && $sectionvisible) {
1957 // Offer to "show" only if the section is visible.
1958 $actions['show'] = new action_menu_link_secondary(
1959 new moodle_url($baseurl, array('show' => $mod->id)),
1960 new pix_icon('t/show', $str->modshow, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1962 array('class' => 'editing_show', 'data-action' => 'show')
1967 // When making the "stealth" module unavailable we perform the same action as hiding the visible module.
1968 $actions['hide'] = new action_menu_link_secondary(
1969 new moodle_url($baseurl, array('hide' => $mod->id)),
1970 new pix_icon('t/unblock', $str->makeunavailable, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1971 $str->makeunavailable,
1972 array('class' => 'editing_makeunavailable', 'data-action' => 'hide', 'data-sectionreturn' => $sr)
1974 } else if ($unavailable && (!$sectionvisible || $allowstealth) && $mod->has_view()) {
1975 // Allow to make visually hidden module available in gradebook and other reports by making it a "stealth" module.
1976 // When the section is hidden it is an equivalent of "showing" the module.
1977 // Activities without the link (i.e. labels) can not be made available but hidden on course page.
1978 $action = $sectionvisible ? 'stealth' : 'show';
1979 $actions[$action] = new action_menu_link_secondary(
1980 new moodle_url($baseurl, array($action => $mod->id)),
1981 new pix_icon('t/block', $str->makeavailable, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1982 $str->makeavailable,
1983 array('class' => 'editing_makeavailable', 'data-action' => $action, 'data-sectionreturn' => $sr)
1988 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
1989 if (has_all_capabilities($dupecaps, $coursecontext) &&
1990 plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2) &&
1991 course_allowed_module($mod->get_course(), $mod->modname)) {
1992 $actions['duplicate'] = new action_menu_link_secondary(
1993 new moodle_url($baseurl, array('duplicate' => $mod->id)),
1994 new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1996 array('class' => 'editing_duplicate', 'data-action' => 'duplicate', 'data-sectionreturn' => $sr)
2001 if ($hasmanageactivities && !$mod->coursegroupmodeforce) {
2002 if (plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
2003 if ($mod->effectivegroupmode == SEPARATEGROUPS) {
2004 $nextgroupmode = VISIBLEGROUPS;
2005 $grouptitle = $str->groupsseparate;
2006 $actionname = 'groupsseparate';
2007 $nextactionname = 'groupsvisible';
2008 $groupimage = 'i/groups';
2009 } else if ($mod->effectivegroupmode == VISIBLEGROUPS) {
2010 $nextgroupmode = NOGROUPS;
2011 $grouptitle = $str->groupsvisible;
2012 $actionname = 'groupsvisible';
2013 $nextactionname = 'groupsnone';
2014 $groupimage = 'i/groupv';
2016 $nextgroupmode = SEPARATEGROUPS;
2017 $grouptitle = $str->groupsnone;
2018 $actionname = 'groupsnone';
2019 $nextactionname = 'groupsseparate';
2020 $groupimage = 'i/groupn';
2023 $actions[$actionname] = new action_menu_link_primary(
2024 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $nextgroupmode)),
2025 new pix_icon($groupimage, $grouptitle, 'moodle', array('class' => 'iconsmall')),
2027 array('class' => 'editing_'. $actionname, 'data-action' => $nextactionname,
2028 'aria-live' => 'assertive', 'data-sectionreturn' => $sr)
2031 $actions['nogroupsupport'] = new action_menu_filler();
2036 if (has_capability('moodle/role:assign', $modcontext)){
2037 $actions['assign'] = new action_menu_link_secondary(
2038 new moodle_url('/admin/roles/assign.php', array('contextid' => $modcontext->id)),
2039 new pix_icon('t/assignroles', $str->assign, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2041 array('class' => 'editing_assign', 'data-action' => 'assignroles', 'data-sectionreturn' => $sr)
2046 if ($hasmanageactivities) {
2047 $actions['delete'] = new action_menu_link_secondary(
2048 new moodle_url($baseurl, array('delete' => $mod->id)),
2049 new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2051 array('class' => 'editing_delete', 'data-action' => 'delete', 'data-sectionreturn' => $sr)
2059 * Returns the move action.
2061 * @param cm_info $mod The module to produce a move button for
2062 * @param int $sr The section to link back to (used for creating the links)
2063 * @return The markup for the move action, or an empty string if not available.
2065 function course_get_cm_move(cm_info $mod, $sr = null) {
2071 $modcontext = context_module::instance($mod->id);
2072 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
2075 $str = get_strings(array('move'));
2078 if (!isset($baseurl)) {
2079 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
2082 $baseurl->param('sr', $sr);
2086 if ($hasmanageactivities) {
2087 $pixicon = 'i/dragdrop';
2089 if (!course_ajax_enabled($mod->get_course())) {
2090 // Override for course frontpage until we get drag/drop working there.
2091 $pixicon = 't/move';
2094 return html_writer::link(
2095 new moodle_url($baseurl, array('copy' => $mod->id)),
2096 $OUTPUT->pix_icon($pixicon, $str->move, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2097 array('class' => 'editing_move', 'data-action' => 'move', 'data-sectionreturn' => $sr)
2104 * given a course object with shortname & fullname, this function will
2105 * truncate the the number of chars allowed and add ... if it was too long
2107 function course_format_name ($course,$max=100) {
2109 $context = context_course::instance($course->id);
2110 $shortname = format_string($course->shortname, true, array('context' => $context));
2111 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
2112 $str = $shortname.': '. $fullname;
2113 if (core_text::strlen($str) <= $max) {
2117 return core_text::substr($str,0,$max-3).'...';
2122 * Is the user allowed to add this type of module to this course?
2123 * @param object $course the course settings. Only $course->id is used.
2124 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
2125 * @return bool whether the current user is allowed to add this type of module to this course.
2127 function course_allowed_module($course, $modname) {
2128 if (is_numeric($modname)) {
2129 throw new coding_exception('Function course_allowed_module no longer
2130 supports numeric module ids. Please update your code to pass the module name.');
2133 $capability = 'mod/' . $modname . ':addinstance';
2134 if (!get_capability_info($capability)) {
2135 // Debug warning that the capability does not exist, but no more than once per page.
2136 static $warned = array();
2137 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
2138 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
2139 debugging('The module ' . $modname . ' does not define the standard capability ' .
2140 $capability , DEBUG_DEVELOPER);
2141 $warned[$modname] = 1;
2144 // If the capability does not exist, the module can always be added.
2148 $coursecontext = context_course::instance($course->id);
2149 return has_capability($capability, $coursecontext);
2153 * Efficiently moves many courses around while maintaining
2154 * sortorder in order.
2156 * @param array $courseids is an array of course ids
2157 * @param int $categoryid
2158 * @return bool success
2160 function move_courses($courseids, $categoryid) {
2163 if (empty($courseids)) {
2168 if (!$category = $DB->get_record('course_categories', array('id' => $categoryid))) {
2172 $courseids = array_reverse($courseids);
2173 $newparent = context_coursecat::instance($category->id);
2176 list($where, $params) = $DB->get_in_or_equal($courseids);
2177 $dbcourses = $DB->get_records_select('course', 'id ' . $where, $params, '', 'id, category, shortname, fullname');
2178 foreach ($dbcourses as $dbcourse) {
2179 $course = new stdClass();
2180 $course->id = $dbcourse->id;
2181 $course->category = $category->id;
2182 $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
2183 if ($category->visible == 0) {
2184 // Hide the course when moving into hidden category, do not update the visibleold flag - we want to get
2185 // to previous state if somebody unhides the category.
2186 $course->visible = 0;
2189 $DB->update_record('course', $course);
2191 // Update context, so it can be passed to event.
2192 $context = context_course::instance($course->id);
2193 $context->update_moved($newparent);
2195 // Trigger a course updated event.
2196 $event = \core\event\course_updated::create(array(
2197 'objectid' => $course->id,
2198 'context' => context_course::instance($course->id),
2199 'other' => array('shortname' => $dbcourse->shortname,
2200 'fullname' => $dbcourse->fullname)
2202 $event->set_legacy_logdata(array($course->id, 'course', 'move', 'edit.php?id=' . $course->id, $course->id));
2205 fix_course_sortorder();
2206 cache_helper::purge_by_event('changesincourse');
2212 * Returns the display name of the given section that the course prefers
2214 * Implementation of this function is provided by course format
2215 * @see format_base::get_section_name()
2217 * @param int|stdClass $courseorid The course to get the section name for (object or just course id)
2218 * @param int|stdClass $section Section object from database or just field course_sections.section
2219 * @return string Display name that the course format prefers, e.g. "Week 2"
2221 function get_section_name($courseorid, $section) {
2222 return course_get_format($courseorid)->get_section_name($section);
2226 * Tells if current course format uses sections
2228 * @param string $format Course format ID e.g. 'weeks' $course->format
2231 function course_format_uses_sections($format) {
2232 $course = new stdClass();
2233 $course->format = $format;
2234 return course_get_format($course)->uses_sections();
2238 * Returns the information about the ajax support in the given source format
2240 * The returned object's property (boolean)capable indicates that
2241 * the course format supports Moodle course ajax features.
2243 * @param string $format
2246 function course_format_ajax_support($format) {
2247 $course = new stdClass();
2248 $course->format = $format;
2249 return course_get_format($course)->supports_ajax();
2253 * Can the current user delete this course?
2254 * Course creators have exception,
2255 * 1 day after the creation they can sill delete the course.
2256 * @param int $courseid
2259 function can_delete_course($courseid) {
2262 $context = context_course::instance($courseid);
2264 if (has_capability('moodle/course:delete', $context)) {
2268 // hack: now try to find out if creator created this course recently (1 day)
2269 if (!has_capability('moodle/course:create', $context)) {
2273 $since = time() - 60*60*24;
2274 $course = get_course($courseid);
2276 if ($course->timecreated < $since) {
2277 return false; // Return if the course was not created in last 24 hours.
2280 $logmanger = get_log_manager();
2281 $readers = $logmanger->get_readers('\core\log\sql_reader');
2282 $reader = reset($readers);
2284 if (empty($reader)) {
2285 return false; // No log reader found.
2289 $select = "userid = :userid AND courseid = :courseid AND eventname = :eventname AND timecreated > :since";
2290 $params = array('userid' => $USER->id, 'since' => $since, 'courseid' => $course->id, 'eventname' => '\core\event\course_created');
2292 return (bool)$reader->get_events_select_count($select, $params);
2296 * Save the Your name for 'Some role' strings.
2298 * @param integer $courseid the id of this course.
2299 * @param array $data the data that came from the course settings form.
2301 function save_local_role_names($courseid, $data) {
2303 $context = context_course::instance($courseid);
2305 foreach ($data as $fieldname => $value) {
2306 if (strpos($fieldname, 'role_') !== 0) {
2309 list($ignored, $roleid) = explode('_', $fieldname);
2311 // make up our mind whether we want to delete, update or insert
2313 $DB->delete_records('role_names', array('contextid' => $context->id, 'roleid' => $roleid));
2315 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id, 'roleid' => $roleid))) {
2316 $rolename->name = $value;
2317 $DB->update_record('role_names', $rolename);
2320 $rolename = new stdClass;
2321 $rolename->contextid = $context->id;
2322 $rolename->roleid = $roleid;
2323 $rolename->name = $value;
2324 $DB->insert_record('role_names', $rolename);
2326 // This will ensure the course contacts cache is purged..
2327 core_course_category::role_assignment_changed($roleid, $context);
2332 * Returns options to use in course overviewfiles filemanager
2334 * @param null|stdClass|core_course_list_element|int $course either object that has 'id' property or just the course id;
2335 * may be empty if course does not exist yet (course create form)
2336 * @return array|null array of options such as maxfiles, maxbytes, accepted_types, etc.
2337 * or null if overviewfiles are disabled
2339 function course_overviewfiles_options($course) {
2341 if (empty($CFG->courseoverviewfileslimit)) {
2344 $accepted_types = preg_split('/\s*,\s*/', trim($CFG->courseoverviewfilesext), -1, PREG_SPLIT_NO_EMPTY);
2345 if (in_array('*', $accepted_types) || empty($accepted_types)) {
2346 $accepted_types = '*';
2348 // Since config for $CFG->courseoverviewfilesext is a text box, human factor must be considered.
2349 // Make sure extensions are prefixed with dot unless they are valid typegroups
2350 foreach ($accepted_types as $i => $type) {
2351 if (substr($type, 0, 1) !== '.') {
2352 require_once($CFG->libdir. '/filelib.php');
2353 if (!count(file_get_typegroup('extension', $type))) {
2354 // It does not start with dot and is not a valid typegroup, this is most likely extension.
2355 $accepted_types[$i] = '.'. $type;
2360 if (!empty($corrected)) {
2361 set_config('courseoverviewfilesext', join(',', $accepted_types));
2365 'maxfiles' => $CFG->courseoverviewfileslimit,
2366 'maxbytes' => $CFG->maxbytes,
2368 'accepted_types' => $accepted_types
2370 if (!empty($course->id)) {
2371 $options['context'] = context_course::instance($course->id);
2372 } else if (is_int($course) && $course > 0) {
2373 $options['context'] = context_course::instance($course);
2379 * Create a course and either return a $course object
2381 * Please note this functions does not verify any access control,
2382 * the calling code is responsible for all validation (usually it is the form definition).
2384 * @param array $editoroptions course description editor options
2385 * @param object $data - all the data needed for an entry in the 'course' table
2386 * @return object new course instance
2388 function create_course($data, $editoroptions = NULL) {
2391 //check the categoryid - must be given for all new courses
2392 $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
2394 // Check if the shortname already exists.
2395 if (!empty($data->shortname)) {
2396 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
2397 throw new moodle_exception('shortnametaken', '', '', $data->shortname);
2401 // Check if the idnumber already exists.
2402 if (!empty($data->idnumber)) {
2403 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
2404 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber);
2408 if ($errorcode = course_validate_dates((array)$data)) {
2409 throw new moodle_exception($errorcode);
2412 // Check if timecreated is given.
2413 $data->timecreated = !empty($data->timecreated) ? $data->timecreated : time();
2414 $data->timemodified = $data->timecreated;
2416 // place at beginning of any category
2417 $data->sortorder = 0;
2419 if ($editoroptions) {
2420 // summary text is updated later, we need context to store the files first
2421 $data->summary = '';
2422 $data->summary_format = FORMAT_HTML;
2425 if (!isset($data->visible)) {
2426 // data not from form, add missing visibility info
2427 $data->visible = $category->visible;
2429 $data->visibleold = $data->visible;
2431 $newcourseid = $DB->insert_record('course', $data);
2432 $context = context_course::instance($newcourseid, MUST_EXIST);
2434 if ($editoroptions) {
2435 // Save the files used in the summary editor and store
2436 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2437 $DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid));
2438 $DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid));
2440 if ($overviewfilesoptions = course_overviewfiles_options($newcourseid)) {
2441 // Save the course overviewfiles
2442 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2445 // update course format options
2446 course_get_format($newcourseid)->update_course_format_options($data);
2448 $course = course_get_format($newcourseid)->get_course();
2450 fix_course_sortorder();
2451 // purge appropriate caches in case fix_course_sortorder() did not change anything
2452 cache_helper::purge_by_event('changesincourse');
2454 // Trigger a course created event.
2455 $event = \core\event\course_created::create(array(
2456 'objectid' => $course->id,
2457 'context' => context_course::instance($course->id),
2458 'other' => array('shortname' => $course->shortname,
2459 'fullname' => $course->fullname)
2465 blocks_add_default_course_blocks($course);
2467 // Create default section and initial sections if specified (unless they've already been created earlier).
2468 // We do not want to call course_create_sections_if_missing() because to avoid creating course cache.
2469 $numsections = isset($data->numsections) ? $data->numsections : 0;
2470 $existingsections = $DB->get_fieldset_sql('SELECT section from {course_sections} WHERE course = ?', [$newcourseid]);
2471 $newsections = array_diff(range(0, $numsections), $existingsections);
2472 foreach ($newsections as $sectionnum) {
2473 course_create_section($newcourseid, $sectionnum, true);
2476 // Save any custom role names.
2477 save_local_role_names($course->id, (array)$data);
2479 // set up enrolments
2480 enrol_course_updated(true, $course, $data);
2482 // Update course tags.
2483 if (isset($data->tags)) {
2484 core_tag_tag::set_item_tags('core', 'course', $course->id, context_course::instance($course->id), $data->tags);
2493 * Please note this functions does not verify any access control,
2494 * the calling code is responsible for all validation (usually it is the form definition).
2496 * @param object $data - all the data needed for an entry in the 'course' table
2497 * @param array $editoroptions course description editor options
2500 function update_course($data, $editoroptions = NULL) {
2503 $data->timemodified = time();
2505 // Prevent changes on front page course.
2506 if ($data->id == SITEID) {
2507 throw new moodle_exception('invalidcourse', 'error');
2510 $oldcourse = course_get_format($data->id)->get_course();
2511 $context = context_course::instance($oldcourse->id);
2513 if ($editoroptions) {
2514 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2516 if ($overviewfilesoptions = course_overviewfiles_options($data->id)) {
2517 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2520 // Check we don't have a duplicate shortname.
2521 if (!empty($data->shortname) && $oldcourse->shortname != $data->shortname) {
2522 if ($DB->record_exists_sql('SELECT id from {course} WHERE shortname = ? AND id <> ?', array($data->shortname, $data->id))) {
2523 throw new moodle_exception('shortnametaken', '', '', $data->shortname);
2527 // Check we don't have a duplicate idnumber.
2528 if (!empty($data->idnumber) && $oldcourse->idnumber != $data->idnumber) {
2529 if ($DB->record_exists_sql('SELECT id from {course} WHERE idnumber = ? AND id <> ?', array($data->idnumber, $data->id))) {
2530 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber);
2534 if ($errorcode = course_validate_dates((array)$data)) {
2535 throw new moodle_exception($errorcode);
2538 if (!isset($data->category) or empty($data->category)) {
2539 // prevent nulls and 0 in category field
2540 unset($data->category);
2542 $changesincoursecat = $movecat = (isset($data->category) and $oldcourse->category != $data->category);
2544 if (!isset($data->visible)) {
2545 // data not from form, add missing visibility info
2546 $data->visible = $oldcourse->visible;
2549 if ($data->visible != $oldcourse->visible) {
2550 // reset the visibleold flag when manually hiding/unhiding course
2551 $data->visibleold = $data->visible;
2552 $changesincoursecat = true;
2555 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category));
2556 if (empty($newcategory->visible)) {
2557 // make sure when moving into hidden category the course is hidden automatically
2563 // Set newsitems to 0 if format does not support announcements.
2564 if (isset($data->format)) {
2565 $newcourseformat = course_get_format((object)['format' => $data->format]);
2566 if (!$newcourseformat->supports_news()) {
2567 $data->newsitems = 0;
2571 // Update with the new data
2572 $DB->update_record('course', $data);
2573 // make sure the modinfo cache is reset
2574 rebuild_course_cache($data->id);
2576 // update course format options with full course data
2577 course_get_format($data->id)->update_course_format_options($data, $oldcourse);
2579 $course = $DB->get_record('course', array('id'=>$data->id));
2582 $newparent = context_coursecat::instance($course->category);
2583 $context->update_moved($newparent);
2585 $fixcoursesortorder = $movecat || (isset($data->sortorder) && ($oldcourse->sortorder != $data->sortorder));
2586 if ($fixcoursesortorder) {
2587 fix_course_sortorder();
2590 // purge appropriate caches in case fix_course_sortorder() did not change anything
2591 cache_helper::purge_by_event('changesincourse');
2592 if ($changesincoursecat) {
2593 cache_helper::purge_by_event('changesincoursecat');
2596 // Test for and remove blocks which aren't appropriate anymore
2597 blocks_remove_inappropriate($course);
2599 // Save any custom role names.
2600 save_local_role_names($course->id, $data);
2602 // update enrol settings
2603 enrol_course_updated(false, $course, $data);
2605 // Update course tags.
2606 if (isset($data->tags)) {
2607 core_tag_tag::set_item_tags('core', 'course', $course->id, context_course::instance($course->id), $data->tags);
2610 // Trigger a course updated event.
2611 $event = \core\event\course_updated::create(array(
2612 'objectid' => $course->id,
2613 'context' => context_course::instance($course->id),
2614 'other' => array('shortname' => $course->shortname,
2615 'fullname' => $course->fullname)
2618 $event->set_legacy_logdata(array($course->id, 'course', 'update', 'edit.php?id=' . $course->id, $course->id));
2621 if ($oldcourse->format !== $course->format) {
2622 // Remove all options stored for the previous format
2623 // We assume that new course format migrated everything it needed watching trigger
2624 // 'course_updated' and in method format_XXX::update_course_format_options()
2625 $DB->delete_records('course_format_options',
2626 array('courseid' => $course->id, 'format' => $oldcourse->format));
2631 * Average number of participants
2634 function average_number_of_participants() {
2637 //count total of enrolments for visible course (except front page)
2638 $sql = 'SELECT COUNT(*) FROM (
2639 SELECT DISTINCT ue.userid, e.courseid
2640 FROM {user_enrolments} ue, {enrol} e, {course} c
2641 WHERE ue.enrolid = e.id
2642 AND e.courseid <> :siteid
2643 AND c.id = e.courseid
2644 AND c.visible = 1) total';
2645 $params = array('siteid' => $SITE->id);
2646 $enrolmenttotal = $DB->count_records_sql($sql, $params);
2649 //count total of visible courses (minus front page)
2650 $coursetotal = $DB->count_records('course', array('visible' => 1));
2651 $coursetotal = $coursetotal - 1 ;
2653 //average of enrolment
2654 if (empty($coursetotal)) {
2655 $participantaverage = 0;
2657 $participantaverage = $enrolmenttotal / $coursetotal;
2660 return $participantaverage;
2664 * Average number of course modules
2667 function average_number_of_courses_modules() {
2670 //count total of visible course module (except front page)
2671 $sql = 'SELECT COUNT(*) FROM (
2672 SELECT cm.course, cm.module
2673 FROM {course} c, {course_modules} cm
2674 WHERE c.id = cm.course
2677 AND c.visible = 1) total';
2678 $params = array('siteid' => $SITE->id);
2679 $moduletotal = $DB->count_records_sql($sql, $params);
2682 //count total of visible courses (minus front page)
2683 $coursetotal = $DB->count_records('course', array('visible' => 1));
2684 $coursetotal = $coursetotal - 1 ;
2686 //average of course module
2687 if (empty($coursetotal)) {
2688 $coursemoduleaverage = 0;
2690 $coursemoduleaverage = $moduletotal / $coursetotal;
2693 return $coursemoduleaverage;
2697 * This class pertains to course requests and contains methods associated with
2698 * create, approving, and removing course requests.
2700 * Please note we do not allow embedded images here because there is no context
2701 * to store them with proper access control.
2703 * @copyright 2009 Sam Hemelryk
2704 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2707 * @property-read int $id
2708 * @property-read string $fullname
2709 * @property-read string $shortname
2710 * @property-read string $summary
2711 * @property-read int $summaryformat
2712 * @property-read int $summarytrust
2713 * @property-read string $reason
2714 * @property-read int $requester
2716 class course_request {
2719 * This is the stdClass that stores the properties for the course request
2720 * and is externally accessed through the __get magic method
2723 protected $properties;
2726 * An array of options for the summary editor used by course request forms.
2727 * This is initially set by {@link summary_editor_options()}
2731 protected static $summaryeditoroptions;
2734 * Static function to prepare the summary editor for working with a course
2738 * @param null|stdClass $data Optional, an object containing the default values
2739 * for the form, these may be modified when preparing the
2740 * editor so this should be called before creating the form
2741 * @return stdClass An object that can be used to set the default values for
2744 public static function prepare($data=null) {
2745 if ($data === null) {
2746 $data = new stdClass;
2748 $data = file_prepare_standard_editor($data, 'summary', self::summary_editor_options());
2753 * Static function to create a new course request when passed an array of properties
2756 * This function also handles saving any files that may have been used in the editor
2759 * @param stdClass $data
2760 * @return course_request The newly created course request
2762 public static function create($data) {
2763 global $USER, $DB, $CFG;
2764 $data->requester = $USER->id;
2766 // Setting the default category if none set.
2767 if (empty($data->category) || empty($CFG->requestcategoryselection)) {
2768 $data->category = $CFG->defaultrequestcategory;
2771 // Summary is a required field so copy the text over
2772 $data->summary = $data->summary_editor['text'];
2773 $data->summaryformat = $data->summary_editor['format'];
2775 $data->id = $DB->insert_record('course_request', $data);
2777 // Create a new course_request object and return it
2778 $request = new course_request($data);
2780 // Notify the admin if required.
2781 if ($users = get_users_from_config($CFG->courserequestnotify, 'moodle/site:approvecourse')) {
2784 $a->link = "$CFG->wwwroot/course/pending.php";
2785 $a->user = fullname($USER);
2786 $subject = get_string('courserequest');
2787 $message = get_string('courserequestnotifyemail', 'admin', $a);
2788 foreach ($users as $user) {
2789 $request->notify($user, $USER, 'courserequested', $subject, $message);
2797 * Returns an array of options to use with a summary editor
2799 * @uses course_request::$summaryeditoroptions
2800 * @return array An array of options to use with the editor
2802 public static function summary_editor_options() {
2804 if (self::$summaryeditoroptions === null) {
2805 self::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
2807 return self::$summaryeditoroptions;
2811 * Loads the properties for this course request object. Id is required and if
2812 * only id is provided then we load the rest of the properties from the database
2814 * @param stdClass|int $properties Either an object containing properties
2815 * or the course_request id to load
2817 public function __construct($properties) {
2819 if (empty($properties->id)) {
2820 if (empty($properties)) {
2821 throw new coding_exception('You must provide a course request id when creating a course_request object');
2824 $properties = new stdClass;
2825 $properties->id = (int)$id;
2828 if (empty($properties->requester)) {
2829 if (!($this->properties = $DB->get_record('course_request', array('id' => $properties->id)))) {
2830 print_error('unknowncourserequest');
2833 $this->properties = $properties;
2835 $this->properties->collision = null;
2839 * Returns the requested property
2841 * @param string $key
2844 public function __get($key) {
2845 return $this->properties->$key;
2849 * Override this to ensure empty($request->blah) calls return a reliable answer...
2851 * This is required because we define the __get method
2854 * @return bool True is it not empty, false otherwise
2856 public function __isset($key) {
2857 return (!empty($this->properties->$key));
2861 * Returns the user who requested this course
2863 * Uses a static var to cache the results and cut down the number of db queries
2865 * @staticvar array $requesters An array of cached users
2866 * @return stdClass The user who requested the course
2868 public function get_requester() {
2870 static $requesters= array();
2871 if (!array_key_exists($this->properties->requester, $requesters)) {
2872 $requesters[$this->properties->requester] = $DB->get_record('user', array('id'=>$this->properties->requester));
2874 return $requesters[$this->properties->requester];
2878 * Checks that the shortname used by the course does not conflict with any other
2879 * courses that exist
2881 * @param string|null $shortnamemark The string to append to the requests shortname
2882 * should a conflict be found
2883 * @return bool true is there is a conflict, false otherwise
2885 public function check_shortname_collision($shortnamemark = '[*]') {
2888 if ($this->properties->collision !== null) {
2889 return $this->properties->collision;
2892 if (empty($this->properties->shortname)) {
2893 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER);
2894 $this->properties->collision = false;
2895 } else if ($DB->record_exists('course', array('shortname' => $this->properties->shortname))) {
2896 if (!empty($shortnamemark)) {
2897 $this->properties->shortname .= ' '.$shortnamemark;
2899 $this->properties->collision = true;
2901 $this->properties->collision = false;
2903 return $this->properties->collision;
2907 * Returns the category where this course request should be created
2909 * Note that we don't check here that user has a capability to view
2910 * hidden categories if he has capabilities 'moodle/site:approvecourse' and
2911 * 'moodle/course:changecategory'
2913 * @return core_course_category
2915 public function get_category() {
2917 // If the category is not set, if the current user does not have the rights to change the category, or if the
2918 // category does not exist, we set the default category to the course to be approved.
2919 // The system level is used because the capability moodle/site:approvecourse is based on a system level.
2920 if (empty($this->properties->category) || !has_capability('moodle/course:changecategory', context_system::instance()) ||
2921 (!$category = core_course_category::get($this->properties->category, IGNORE_MISSING, true))) {
2922 $category = core_course_category::get($CFG->defaultrequestcategory, IGNORE_MISSING, true);
2925 $category = core_course_category::get_default();
2931 * This function approves the request turning it into a course
2933 * This function converts the course request into a course, at the same time
2934 * transferring any files used in the summary to the new course and then removing
2935 * the course request and the files associated with it.
2937 * @return int The id of the course that was created from this request
2939 public function approve() {
2940 global $CFG, $DB, $USER;
2942 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
2944 $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted'=>0), '*', MUST_EXIST);
2946 $courseconfig = get_config('moodlecourse');
2948 // Transfer appropriate settings
2949 $data = clone($this->properties);
2951 unset($data->reason);
2952 unset($data->requester);
2955 $category = $this->get_category();
2956 $data->category = $category->id;
2957 // Set misc settings
2958 $data->requested = 1;
2960 // Apply course default settings
2961 $data->format = $courseconfig->format;
2962 $data->newsitems = $courseconfig->newsitems;
2963 $data->showgrades = $courseconfig->showgrades;
2964 $data->showreports = $courseconfig->showreports;
2965 $data->maxbytes = $courseconfig->maxbytes;
2966 $data->groupmode = $courseconfig->groupmode;
2967 $data->groupmodeforce = $courseconfig->groupmodeforce;
2968 $data->visible = $courseconfig->visible;
2969 $data->visibleold = $data->visible;
2970 $data->lang = $courseconfig->lang;
2971 $data->enablecompletion = $courseconfig->enablecompletion;
2972 $data->numsections = $courseconfig->numsections;
2973 $data->startdate = usergetmidnight(time());
2974 if ($courseconfig->courseenddateenabled) {
2975 $data->enddate = usergetmidnight(time()) + $courseconfig->courseduration;
2978 list($data->fullname, $data->shortname) = restore_dbops::calculate_course_names(0, $data->fullname, $data->shortname);
2980 $course = create_course($data);
2981 $context = context_course::instance($course->id, MUST_EXIST);
2983 // add enrol instances
2984 if (!$DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
2985 if ($manual = enrol_get_plugin('manual')) {
2986 $manual->add_default_instance($course);
2990 // enrol the requester as teacher if necessary
2991 if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
2992 enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid);
2997 $a = new stdClass();
2998 $a->name = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
2999 $a->url = $CFG->wwwroot.'/course/view.php?id=' . $course->id;
3000 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a), $course->id);
3006 * Reject a course request
3008 * This function rejects a course request, emailing the requesting user the
3009 * provided notice and then removing the request from the database
3011 * @param string $notice The message to display to the user
3013 public function reject($notice) {
3015 $user = $DB->get_record('user', array('id' => $this->properties->requester), '*', MUST_EXIST);
3016 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
3021 * Deletes the course request and any associated files
3023 public function delete() {
3025 $DB->delete_records('course_request', array('id' => $this->properties->id));
3029 * Send a message from one user to another using events_trigger
3031 * @param object $touser
3032 * @param object $fromuser
3033 * @param string $name
3034 * @param string $subject
3035 * @param string $message
3036 * @param int|null $courseid
3038 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message, $courseid = null) {
3039 $eventdata = new \core\message\message();
3040 $eventdata->courseid = empty($courseid) ? SITEID : $courseid;
3041 $eventdata->component = 'moodle';
3042 $eventdata->name = $name;
3043 $eventdata->userfrom = $fromuser;
3044 $eventdata->userto = $touser;
3045 $eventdata->subject = $subject;
3046 $eventdata->fullmessage = $message;
3047 $eventdata->fullmessageformat = FORMAT_PLAIN;
3048 $eventdata->fullmessagehtml = '';
3049 $eventdata->smallmessage = '';
3050 $eventdata->notification = 1;
3051 message_send($eventdata);
3056 * Return a list of page types
3057 * @param string $pagetype current page type
3058 * @param context $parentcontext Block's parent context
3059 * @param context $currentcontext Current context of block
3060 * @return array array of page types
3062 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
3063 if ($pagetype === 'course-index' || $pagetype === 'course-index-category') {
3064 // For courses and categories browsing pages (/course/index.php) add option to show on ANY category page
3065 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
3066 'course-index-*' => get_string('page-course-index-x', 'pagetype'),
3068 } else if ($currentcontext && (!($coursecontext = $currentcontext->get_course_context(false)) || $coursecontext->instanceid == SITEID)) {
3069 // We know for sure that despite pagetype starts with 'course-' this is not a page in course context (i.e. /course/search.php, etc.)
3070 $pagetypes = array('*' => get_string('page-x', 'pagetype'));
3072 // Otherwise consider it a page inside a course even if $currentcontext is null
3073 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
3074 'course-*' => get_string('page-course-x', 'pagetype'),
3075 'course-view-*' => get_string('page-course-view-x', 'pagetype')
3082 * Determine whether course ajax should be enabled for the specified course
3084 * @param stdClass $course The course to test against
3085 * @return boolean Whether course ajax is enabled or note
3087 function course_ajax_enabled($course) {
3088 global $CFG, $PAGE, $SITE;
3090 // The user must be editing for AJAX to be included
3091 if (!$PAGE->user_is_editing()) {
3095 // Check that the theme suports
3096 if (!$PAGE->theme->enablecourseajax) {
3100 // Check that the course format supports ajax functionality
3101 // The site 'format' doesn't have information on course format support
3102 if ($SITE->id !== $course->id) {
3103 $courseformatajaxsupport = course_format_ajax_support($course->format);
3104 if (!$courseformatajaxsupport->capable) {
3109 // All conditions have been met so course ajax should be enabled
3114 * Include the relevant javascript and language strings for the resource
3115 * toolbox YUI module
3117 * @param integer $id The ID of the course being applied to
3118 * @param array $usedmodules An array containing the names of the modules in use on the page
3119 * @param array $enabledmodules An array containing the names of the enabled (visible) modules on this site
3120 * @param stdClass $config An object containing configuration parameters for ajax modules including:
3121 * * resourceurl The URL to post changes to for resource changes
3122 * * sectionurl The URL to post changes to for section changes
3123 * * pageparams Additional parameters to pass through in the post
3126 function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) {
3127 global $CFG, $PAGE, $SITE;
3129 // Ensure that ajax should be included
3130 if (!course_ajax_enabled($course)) {
3135 $config = new stdClass();
3138 // The URL to use for resource changes
3139 if (!isset($config->resourceurl)) {
3140 $config->resourceurl = '/course/rest.php';
3143 // The URL to use for section changes
3144 if (!isset($config->sectionurl)) {
3145 $config->sectionurl = '/course/rest.php';
3148 // Any additional parameters which need to be included on page submission
3149 if (!isset($config->pageparams)) {
3150 $config->pageparams = array();
3153 // Include course dragdrop
3154 if (course_format_uses_sections($course->format)) {
3155 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_section_dragdrop',
3157 'courseid' => $course->id,
3158 'ajaxurl' => $config->sectionurl,
3159 'config' => $config,
3162 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_resource_dragdrop',
3164 'courseid' => $course->id,
3165 'ajaxurl' => $config->resourceurl,
3166 'config' => $config,
3170 // Require various strings for the command toolbox
3171 $PAGE->requires->strings_for_js(array(
3174 'deletechecktypename',
3176 'edittitleinstructions',
3184 'clicktochangeinbrackets',
3189 'movecoursesection',
3192 'emptydragdropregion',
3198 // Include section-specific strings for formats which support sections.
3199 if (course_format_uses_sections($course->format)) {
3200 $PAGE->requires->strings_for_js(array(
3203 ), 'format_' . $course->format);
3206 // For confirming resource deletion we need the name of the module in question
3207 foreach ($usedmodules as $module => $modname) {
3208 $PAGE->requires->string_for_js('pluginname', $module);
3211 // Load drag and drop upload AJAX.
3212 require_once($CFG->dirroot.'/course/dnduploadlib.php');
3213 dndupload_add_to_course($course, $enabledmodules);
3215 $PAGE->requires->js_call_amd('core_course/actions', 'initCoursePage', array($course->format));
3221 * Returns the sorted list of available course formats, filtered by enabled if necessary
3223 * @param bool $enabledonly return only formats that are enabled
3224 * @return array array of sorted format names
3226 function get_sorted_course_formats($enabledonly = false) {
3228 $formats = core_component::get_plugin_list('format');
3230 if (!empty($CFG->format_plugins_sortorder)) {
3231 $order = explode(',', $CFG->format_plugins_sortorder);
3232 $order = array_merge(array_intersect($order, array_keys($formats)),
3233 array_diff(array_keys($formats), $order));
3235 $order = array_keys($formats);
3237 if (!$enabledonly) {
3240 $sortedformats = array();
3241 foreach ($order as $formatname) {
3242 if (!get_config('format_'.$formatname, 'disabled')) {
3243 $sortedformats[] = $formatname;
3246 return $sortedformats;
3250 * The URL to use for the specified course (with section)
3252 * @param int|stdClass $courseorid The course to get the section name for (either object or just course id)
3253 * @param int|stdClass $section Section object from database or just field course_sections.section
3254 * if omitted the course view page is returned
3255 * @param array $options options for view URL. At the moment core uses:
3256 * 'navigation' (bool) if true and section has no separate page, the function returns null
3257 * 'sr' (int) used by multipage formats to specify to which section to return
3258 * @return moodle_url The url of course
3260 function course_get_url($courseorid, $section = null, $options = array()) {
3261 return course_get_format($courseorid)->get_view_url($section, $options);
3268 * - capability checks and other checks
3269 * - create the module from the module info
3271 * @param object $module
3272 * @return object the created module info
3273 * @throws moodle_exception if user is not allowed to perform the action or module is not allowed in this course
3275 function create_module($moduleinfo) {
3278 require_once($CFG->dirroot . '/course/modlib.php');
3280 // Check manadatory attributs.
3281 $mandatoryfields = array('modulename', 'course', 'section', 'visible');
3282 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
3283 $mandatoryfields[] = 'introeditor';
3285 foreach($mandatoryfields as $mandatoryfield) {
3286 if (!isset($moduleinfo->{$mandatoryfield})) {
3287 throw new moodle_exception('createmodulemissingattribut', '', '', $mandatoryfield);
3291 // Some additional checks (capability / existing instances).
3292 $course = $DB->get_record('course', array('id'=>$moduleinfo->course), '*', MUST_EXIST);
3293 list($module, $context, $cw) = can_add_moduleinfo($course, $moduleinfo->modulename, $moduleinfo->section);
3296 $moduleinfo->module = $module->id;
3297 $moduleinfo = add_moduleinfo($moduleinfo, $course, null);
3306 * - capability and other checks
3307 * - update the module
3309 * @param object $module
3310 * @return object the updated module info
3311 * @throws moodle_exception if current user is not allowed to update the module
3313 function update_module($moduleinfo) {
3316 require_once($CFG->dirroot . '/course/modlib.php');
3318 // Check the course module exists.
3319 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule, 0, false, MUST_EXIST);
3321 // Check the course exists.
3322 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
3324 // Some checks (capaibility / existing instances).
3325 list($cm, $context, $module, $data, $cw) = can_update_moduleinfo($cm);
3327 // Retrieve few information needed by update_moduleinfo.
3328 $moduleinfo->modulename = $cm->modname;
3329 if (!isset($moduleinfo->scale)) {
3330 $moduleinfo->scale = 0;
3332 $moduleinfo->type = 'mod';
3334 // Update the module.
3335 list($cm, $moduleinfo) = update_moduleinfo($cm, $moduleinfo, $course, null);
3341 * Duplicate a module on the course for ajax.
3343 * @see mod_duplicate_module()
3344 * @param object $course The course
3345 * @param object $cm The course module to duplicate
3346 * @param int $sr The section to link back to (used for creating the links)
3347 * @throws moodle_exception if the plugin doesn't support duplication
3348 * @return Object containing:
3349 * - fullcontent: The HTML markup for the created CM
3350 * - cmid: The CMID of the newly created CM
3351 * - redirect: Whether to trigger a redirect following this change
3353 function mod_duplicate_activity($course, $cm, $sr = null) {
3356 $newcm = duplicate_module($course, $cm);
3358 $resp = new stdClass();
3360 $courserenderer = $PAGE->get_renderer('core', 'course');
3361 $completioninfo = new completion_info($course);
3362 $modulehtml = $courserenderer->course_section_cm($course, $completioninfo,
3363 $newcm, null, array());
3365 $resp->fullcontent = $courserenderer->course_section_cm_list_item($course, $completioninfo, $newcm, $sr);
3366 $resp->cmid = $newcm->id;
3368 // Trigger a redirect.
3369 $resp->redirect = true;
3375 * Api to duplicate a module.
3377 * @param object $course course object.
3378 * @param object $cm course module object to be duplicated.
3382 * @throws coding_exception
3383 * @throws moodle_exception
3384 * @throws restore_controller_exception
3386 * @return cm_info|null cminfo object if we sucessfully duplicated the mod and found the new cm.
3388 function duplicate_module($course, $cm) {
3389 global $CFG, $DB, $USER;
3390 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
3391 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
3392 require_once($CFG->libdir . '/filelib.php');
3394 $a = new stdClass();
3395 $a->modtype = get_string('modulename', $cm->modname);
3396 $a->modname = format_string($cm->name);
3398 if (!plugin_supports('mod', $cm->modname, FEATURE_BACKUP_MOODLE2)) {
3399 throw new moodle_exception('duplicatenosupport', 'error', '', $a);
3402 // Backup the activity.
3404 $bc = new backup_controller(backup::TYPE_1ACTIVITY, $cm->id, backup::FORMAT_MOODLE,
3405 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
3407 $backupid = $bc->get_backupid();
3408 $backupbasepath = $bc->get_plan()->get_basepath();
3410 $bc->execute_plan();
3414 // Restore the backup immediately.
3416 $rc = new restore_controller($backupid, $course->id,
3417 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, backup::TARGET_CURRENT_ADDING);
3419 $cmcontext = context_module::instance($cm->id);
3420 if (!$rc->execute_precheck()) {
3421 $precheckresults = $rc->get_precheck_results();
3422 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
3423 if (empty($CFG->keeptempdirectoriesonbackup)) {
3424 fulldelete($backupbasepath);
3429 $rc->execute_plan();
3431 // Now a bit hacky part follows - we try to get the cmid of the newly
3432 // restored copy of the module.
3434 $tasks = $rc->get_plan()->get_tasks();
3435 foreach ($tasks as $task) {
3436 if (is_subclass_of($task, 'restore_activity_task')) {
3437 if ($task->get_old_contextid() == $cmcontext->id) {
3438 $newcmid = $task->get_moduleid();
3446 if (empty($CFG->keeptempdirectoriesonbackup)) {
3447 fulldelete($backupbasepath);
3450 // If we know the cmid of the new course module, let us move it
3451 // right below the original one. otherwise it will stay at the
3452 // end of the section.
3454 // Proceed with activity renaming before everything else. We don't use APIs here to avoid
3455 // triggering a lot of create/update duplicated events.
3456 $newcm = get_coursemodule_from_id($cm->modname, $newcmid, $cm->course);
3457 // Add ' (copy)' to duplicates. Note we don't cleanup or validate lengths here. It comes
3458 // from original name that was valid, so the copy should be too.
3459 $newname = get_string('duplicatedmodule', 'moodle', $newcm->name);
3460 $DB->set_field($cm->modname, 'name', $newname, ['id' => $newcm->instance]);
3462 $section = $DB->get_record('course_sections', array('id' => $cm->section, 'course' => $cm->course));
3463 $modarray = explode(",", trim($section->sequence));
3464 $cmindex = array_search($cm->id, $modarray);
3465 if ($cmindex !== false && $cmindex < count($modarray) - 1) {
3466 moveto_module($newcm, $section, $modarray[$cmindex + 1]);
3469 // Update calendar events with the duplicated module.
3470 // The following line is to be removed in MDL-58906.
3471 course_module_update_calendar_events($newcm->modname, null, $newcm);
3473 // Trigger course module created event. We can trigger the event only if we know the newcmid.
3474 $newcm = get_fast_modinfo($cm->course)->get_cm($newcmid);
3475 $event = \core\event\course_module_created::create_from_cm($newcm);
3479 return isset($newcm) ? $newcm : null;
3483 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3484 * Sorts by descending order of time.
3486 * @param stdClass $a First object
3487 * @param stdClass $b Second object
3488 * @return int 0,1,-1 representing the order
3490 function compare_activities_by_time_desc($a, $b) {
3491 // Make sure the activities actually have a timestamp property.
3492 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3495 // We treat instances without timestamp as if they have a timestamp of 0.
3496 if ((!property_exists($a, 'timestamp')) && (property_exists($b,'timestamp'))) {
3499 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3502 if ($a->timestamp == $b->timestamp) {
3505 return ($a->timestamp > $b->timestamp) ? -1 : 1;
3509 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3510 * Sorts by ascending order of time.
3512 * @param stdClass $a First object
3513 * @param stdClass $b Second object
3514 * @return int 0,1,-1 representing the order
3516 function compare_activities_by_time_asc($a, $b) {
3517 // Make sure the activities actually have a timestamp property.
3518 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3521 // We treat instances without timestamp as if they have a timestamp of 0.
3522 if ((!property_exists($a, 'timestamp')) && (property_exists($b, 'timestamp'))) {
3525 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3528 if ($a->timestamp == $b->timestamp) {
3531 return ($a->timestamp < $b->timestamp) ? -1 : 1;
3535 * Changes the visibility of a course.
3537 * @param int $courseid The course to change.
3538 * @param bool $show True to make it visible, false otherwise.
3541 function course_change_visibility($courseid, $show = true) {
3542 $course = new stdClass;
3543 $course->id = $courseid;
3544 $course->visible = ($show) ? '1' : '0';
3545 $course->visibleold = $course->visible;
3546 update_course($course);
3551 * Changes the course sortorder by one, moving it up or down one in respect to sort order.
3553 * @param stdClass|core_course_list_element $course
3554 * @param bool $up If set to true the course will be moved up one. Otherwise down one.
3557 function course_change_sortorder_by_one($course, $up) {
3559 $params = array($course->sortorder, $course->category);
3561 $select = 'sortorder < ? AND category = ?';
3562 $sort = 'sortorder DESC';
3564 $select = 'sortorder > ? AND category = ?';
3565 $sort = 'sortorder ASC';
3567 fix_course_sortorder();
3568 $swapcourse = $DB->get_records_select('course', $select, $params, $sort, '*', 0, 1);
3570 $swapcourse = reset($swapcourse);
3571 $DB->set_field('course', 'sortorder', $swapcourse->sortorder, array('id' => $course->id));
3572 $DB->set_field('course', 'sortorder', $course->sortorder, array('id' => $swapcourse->id));
3573 // Finally reorder courses.
3574 fix_course_sortorder();
3575 cache_helper::purge_by_event('changesincourse');
3582 * Changes the sort order of courses in a category so that the first course appears after the second.
3584 * @param int|stdClass $courseorid The course to focus on.
3585 * @param int $moveaftercourseid The course to shifte