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 function make_log_url($module, $url) {
61 if (strpos($url, 'report/') === 0) {
62 // there is only one report type, course reports are deprecated
72 if (strpos($url, '../') === 0) {
73 $url = ltrim($url, '.');
75 $url = "/course/$url";
79 $url = "/calendar/$url";
83 $url = "/$module/$url";
96 $url = "/message/$url";
108 $url = "/grade/$url";
111 $url = "/mod/$module/$url";
115 //now let's sanitise urls - there might be some ugly nasties:-(
116 $parts = explode('?', $url);
117 $script = array_shift($parts);
118 if (strpos($script, 'http') === 0) {
119 $script = clean_param($script, PARAM_URL);
121 $script = clean_param($script, PARAM_PATH);
126 $query = implode('', $parts);
127 $query = str_replace('&', '&', $query); // both & and & are stored in db :-|
128 $parts = explode('&', $query);
129 $eq = urlencode('=');
130 foreach ($parts as $key=>$part) {
131 $part = urlencode(urldecode($part));
132 $part = str_replace($eq, '=', $part);
133 $parts[$key] = $part;
135 $query = '?'.implode('&', $parts);
138 return $script.$query;
142 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
143 $modname="", $modid=0, $modaction="", $groupid=0) {
146 // It is assumed that $date is the GMT time of midnight for that day,
147 // and so the next 86400 seconds worth of logs are printed.
149 /// Setup for group handling.
151 // TODO: I don't understand group/context/etc. enough to be able to do
152 // something interesting with it here
153 // What is the context of a remote course?
155 /// If the group mode is separate, and this user does not have editing privileges,
156 /// then only the user's group can be viewed.
157 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
158 // $groupid = get_current_group($course->id);
160 /// If this course doesn't have groups, no groupid can be specified.
161 //else if (!$course->groupmode) {
170 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
172 LEFT JOIN {user} u ON l.userid = u.id
176 $where .= "l.hostid = :hostid";
177 $params['hostid'] = $hostid;
179 // TODO: Is 1 really a magic number referring to the sitename?
180 if ($course != SITEID || $modid != 0) {
181 $where .= " AND l.course=:courseid";
182 $params['courseid'] = $course;
186 $where .= " AND l.module = :modname";
187 $params['modname'] = $modname;
190 if ('site_errors' === $modid) {
191 $where .= " AND ( l.action='error' OR l.action='infected' )";
193 //TODO: This assumes that modids are the same across sites... probably
195 $where .= " AND l.cmid = :modid";
196 $params['modid'] = $modid;
200 $firstletter = substr($modaction, 0, 1);
201 if ($firstletter == '-') {
202 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
203 $params['modaction'] = '%'.substr($modaction, 1).'%';
205 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
206 $params['modaction'] = '%'.$modaction.'%';
211 $where .= " AND l.userid = :user";
212 $params['user'] = $user;
216 $enddate = $date + 86400;
217 $where .= " AND l.time > :date AND l.time < :enddate";
218 $params['date'] = $date;
219 $params['enddate'] = $enddate;
223 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
224 if(!empty($result['totalcount'])) {
225 $where .= " ORDER BY $order";
226 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
228 $result['logs'] = array();
234 * Checks the integrity of the course data.
236 * In summary - compares course_sections.sequence and course_modules.section.
238 * More detailed, checks that:
239 * - course_sections.sequence contains each module id not more than once in the course
240 * - for each moduleid from course_sections.sequence the field course_modules.section
241 * refers to the same section id (this means course_sections.sequence is more
242 * important if they are different)
243 * - ($fullcheck only) each module in the course is present in one of
244 * course_sections.sequence
245 * - ($fullcheck only) removes non-existing course modules from section sequences
247 * If there are any mismatches, the changes are made and records are updated in DB.
249 * Course cache is NOT rebuilt if there are any errors!
251 * This function is used each time when course cache is being rebuilt with $fullcheck = false
252 * and in CLI script admin/cli/fix_course_sequence.php with $fullcheck = true
254 * @param int $courseid id of the course
255 * @param array $rawmods result of funciton {@link get_course_mods()} - containst
256 * the list of enabled course modules in the course. Retrieved from DB if not specified.
257 * Argument ignored in cashe of $fullcheck, the list is retrieved form DB anyway.
258 * @param array $sections records from course_sections table for this course.
259 * Retrieved from DB if not specified
260 * @param bool $fullcheck Will add orphaned modules to their sections and remove non-existing
261 * course modules from sequences. Only to be used in site maintenance mode when we are
262 * sure that another user is not in the middle of the process of moving/removing a module.
263 * @param bool $checkonly Only performs the check without updating DB, outputs all errors as debug messages.
264 * @return array array of messages with found problems. Empty output means everything is ok
266 function course_integrity_check($courseid, $rawmods = null, $sections = null, $fullcheck = false, $checkonly = false) {
269 if ($sections === null) {
270 $sections = $DB->get_records('course_sections', array('course' => $courseid), 'section', 'id,section,sequence');
273 // Retrieve all records from course_modules regardless of module type visibility.
274 $rawmods = $DB->get_records('course_modules', array('course' => $courseid), 'id', 'id,section');
276 if ($rawmods === null) {
277 $rawmods = get_course_mods($courseid);
279 if (!$fullcheck && (empty($sections) || empty($rawmods))) {
280 // If either of the arrays is empty, no modules are displayed anyway.
283 $debuggingprefix = 'Failed integrity check for course ['.$courseid.']. ';
285 // First make sure that each module id appears in section sequences only once.
286 // If it appears in several section sequences the last section wins.
287 // If it appears twice in one section sequence, the first occurence wins.
288 $modsection = array();
289 foreach ($sections as $sectionid => $section) {
290 $sections[$sectionid]->newsequence = $section->sequence;
291 if (!empty($section->sequence)) {
292 $sequence = explode(",", $section->sequence);
293 $sequenceunique = array_unique($sequence);
294 if (count($sequenceunique) != count($sequence)) {
295 // Some course module id appears in this section sequence more than once.
296 ksort($sequenceunique); // Preserve initial order of modules.
297 $sequence = array_values($sequenceunique);
298 $sections[$sectionid]->newsequence = join(',', $sequence);
299 $messages[] = $debuggingprefix.'Sequence for course section ['.
300 $sectionid.'] is "'.$sections[$sectionid]->sequence.'", must be "'.$sections[$sectionid]->newsequence.'"';
302 foreach ($sequence as $cmid) {
303 if (array_key_exists($cmid, $modsection) && isset($rawmods[$cmid])) {
304 // Some course module id appears to be in more than one section's sequences.
305 $wrongsectionid = $modsection[$cmid];
306 $sections[$wrongsectionid]->newsequence = trim(preg_replace("/,$cmid,/", ',', ','.$sections[$wrongsectionid]->newsequence. ','), ',');
307 $messages[] = $debuggingprefix.'Course module ['.$cmid.'] must be removed from sequence of section ['.
308 $wrongsectionid.'] because it is also present in sequence of section ['.$sectionid.']';
310 $modsection[$cmid] = $sectionid;
315 // Add orphaned modules to their sections if they exist or to section 0 otherwise.
317 foreach ($rawmods as $cmid => $mod) {
318 if (!isset($modsection[$cmid])) {
319 // This is a module that is not mentioned in course_section.sequence at all.
320 // Add it to the section $mod->section or to the last available section.
321 if ($mod->section && isset($sections[$mod->section])) {
322 $modsection[$cmid] = $mod->section;
324 $firstsection = reset($sections);
325 $modsection[$cmid] = $firstsection->id;
327 $sections[$modsection[$cmid]]->newsequence = trim($sections[$modsection[$cmid]]->newsequence.','.$cmid, ',');
328 $messages[] = $debuggingprefix.'Course module ['.$cmid.'] is missing from sequence of section ['.
329 $modsection[$cmid].']';
332 foreach ($modsection as $cmid => $sectionid) {
333 if (!isset($rawmods[$cmid])) {
334 // Section $sectionid refers to module id that does not exist.
335 $sections[$sectionid]->newsequence = trim(preg_replace("/,$cmid,/", ',', ','.$sections[$sectionid]->newsequence.','), ',');
336 $messages[] = $debuggingprefix.'Course module ['.$cmid.
337 '] does not exist but is present in the sequence of section ['.$sectionid.']';
342 // Update changed sections.
343 if (!$checkonly && !empty($messages)) {
344 foreach ($sections as $sectionid => $section) {
345 if ($section->newsequence !== $section->sequence) {
346 $DB->update_record('course_sections', array('id' => $sectionid, 'sequence' => $section->newsequence));
351 // Now make sure that all modules point to the correct sections.
352 foreach ($rawmods as $cmid => $mod) {
353 if (isset($modsection[$cmid]) && $modsection[$cmid] != $mod->section) {
355 $DB->update_record('course_modules', array('id' => $cmid, 'section' => $modsection[$cmid]));
357 $messages[] = $debuggingprefix.'Course module ['.$cmid.
358 '] points to section ['.$mod->section.'] instead of ['.$modsection[$cmid].']';
366 * For a given course, returns an array of course activity objects
367 * Each item in the array contains he following properties:
369 function get_array_of_activities($courseid) {
370 // cm - course module id
371 // mod - name of the module (eg forum)
372 // section - the number of the section (eg week or topic)
373 // name - the name of the instance
374 // visible - is the instance visible or not
375 // groupingid - grouping id
376 // extra - contains extra string to include in any link
379 $course = $DB->get_record('course', array('id'=>$courseid));
381 if (empty($course)) {
382 throw new moodle_exception('courseidnotfound');
387 $rawmods = get_course_mods($courseid);
388 if (empty($rawmods)) {
389 return $mod; // always return array
391 $courseformat = course_get_format($course);
393 if ($sections = $DB->get_records('course_sections', array('course' => $courseid),
394 'section ASC', 'id,section,sequence,visible')) {
395 // First check and correct obvious mismatches between course_sections.sequence and course_modules.section.
396 if ($errormessages = course_integrity_check($courseid, $rawmods, $sections)) {
397 debugging(join('<br>', $errormessages));
398 $rawmods = get_course_mods($courseid);
399 $sections = $DB->get_records('course_sections', array('course' => $courseid),
400 'section ASC', 'id,section,sequence,visible');
402 // Build array of activities.
403 foreach ($sections as $section) {
404 if (!empty($section->sequence)) {
405 $sequence = explode(",", $section->sequence);
406 foreach ($sequence as $seq) {
407 if (empty($rawmods[$seq])) {
410 // Adjust visibleoncoursepage, value in DB may not respect format availability.
411 $rawmods[$seq]->visibleoncoursepage = (!$rawmods[$seq]->visible
412 || $rawmods[$seq]->visibleoncoursepage
413 || empty($CFG->allowstealth)
414 || !$courseformat->allow_stealth_module_visibility($rawmods[$seq], $section)) ? 1 : 0;
416 // Create an object that will be cached.
417 $mod[$seq] = new stdClass();
418 $mod[$seq]->id = $rawmods[$seq]->instance;
419 $mod[$seq]->cm = $rawmods[$seq]->id;
420 $mod[$seq]->mod = $rawmods[$seq]->modname;
422 // Oh dear. Inconsistent names left here for backward compatibility.
423 $mod[$seq]->section = $section->section;
424 $mod[$seq]->sectionid = $rawmods[$seq]->section;
426 $mod[$seq]->module = $rawmods[$seq]->module;
427 $mod[$seq]->added = $rawmods[$seq]->added;
428 $mod[$seq]->score = $rawmods[$seq]->score;
429 $mod[$seq]->idnumber = $rawmods[$seq]->idnumber;
430 $mod[$seq]->visible = $rawmods[$seq]->visible;
431 $mod[$seq]->visibleoncoursepage = $rawmods[$seq]->visibleoncoursepage;
432 $mod[$seq]->visibleold = $rawmods[$seq]->visibleold;
433 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
434 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
435 $mod[$seq]->indent = $rawmods[$seq]->indent;
436 $mod[$seq]->completion = $rawmods[$seq]->completion;
437 $mod[$seq]->extra = "";
438 $mod[$seq]->completiongradeitemnumber =
439 $rawmods[$seq]->completiongradeitemnumber;
440 $mod[$seq]->completionview = $rawmods[$seq]->completionview;
441 $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected;
442 $mod[$seq]->showdescription = $rawmods[$seq]->showdescription;
443 $mod[$seq]->availability = $rawmods[$seq]->availability;
444 $mod[$seq]->deletioninprogress = $rawmods[$seq]->deletioninprogress;
446 $modname = $mod[$seq]->mod;
447 $functionname = $modname."_get_coursemodule_info";
449 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
453 include_once("$CFG->dirroot/mod/$modname/lib.php");
455 if ($hasfunction = function_exists($functionname)) {
456 if ($info = $functionname($rawmods[$seq])) {
457 if (!empty($info->icon)) {
458 $mod[$seq]->icon = $info->icon;
460 if (!empty($info->iconcomponent)) {
461 $mod[$seq]->iconcomponent = $info->iconcomponent;
463 if (!empty($info->name)) {
464 $mod[$seq]->name = $info->name;
466 if ($info instanceof cached_cm_info) {
467 // When using cached_cm_info you can include three new fields
468 // that aren't available for legacy code
469 if (!empty($info->content)) {
470 $mod[$seq]->content = $info->content;
472 if (!empty($info->extraclasses)) {
473 $mod[$seq]->extraclasses = $info->extraclasses;
475 if (!empty($info->iconurl)) {
476 // Convert URL to string as it's easier to store. Also serialized object contains \0 byte and can not be written to Postgres DB.
477 $url = new moodle_url($info->iconurl);
478 $mod[$seq]->iconurl = $url->out(false);
480 if (!empty($info->onclick)) {
481 $mod[$seq]->onclick = $info->onclick;
483 if (!empty($info->customdata)) {
484 $mod[$seq]->customdata = $info->customdata;
487 // When using a stdclass, the (horrible) deprecated ->extra field
488 // is available for BC
489 if (!empty($info->extra)) {
490 $mod[$seq]->extra = $info->extra;
495 // When there is no modname_get_coursemodule_info function,
496 // but showdescriptions is enabled, then we use the 'intro'
497 // and 'introformat' fields in the module table
498 if (!$hasfunction && $rawmods[$seq]->showdescription) {
499 if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
500 array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
501 // Set content from intro and introformat. Filters are disabled
502 // because we filter it with format_text at display time
503 $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
504 $modvalues, $rawmods[$seq]->id, false);
506 // To save making another query just below, put name in here
507 $mod[$seq]->name = $modvalues->name;
510 if (!isset($mod[$seq]->name)) {
511 $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
514 // Minimise the database size by unsetting default options when they are
515 // 'empty'. This list corresponds to code in the cm_info constructor.
516 foreach (array('idnumber', 'groupmode', 'groupingid',
517 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
518 'icon', 'iconcomponent', 'customdata', 'availability', 'completionview',
519 'completionexpected', 'score', 'showdescription', 'deletioninprogress') as $property) {
520 if (property_exists($mod[$seq], $property) &&
521 empty($mod[$seq]->{$property})) {
522 unset($mod[$seq]->{$property});
525 // Special case: this value is usually set to null, but may be 0
526 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
527 is_null($mod[$seq]->completiongradeitemnumber)) {
528 unset($mod[$seq]->completiongradeitemnumber);
538 * Returns the localised human-readable names of all used modules
540 * @param bool $plural if true returns the plural forms of the names
541 * @return array where key is the module name (component name without 'mod_') and
542 * the value is the human-readable string. Array sorted alphabetically by value
544 function get_module_types_names($plural = false) {
545 static $modnames = null;
547 if ($modnames === null) {
548 $modnames = array(0 => array(), 1 => array());
549 if ($allmods = $DB->get_records("modules")) {
550 foreach ($allmods as $mod) {
551 if (file_exists("$CFG->dirroot/mod/$mod->name/lib.php") && $mod->visible) {
552 $modnames[0][$mod->name] = get_string("modulename", "$mod->name");
553 $modnames[1][$mod->name] = get_string("modulenameplural", "$mod->name");
556 core_collator::asort($modnames[0]);
557 core_collator::asort($modnames[1]);
560 return $modnames[(int)$plural];
564 * Set highlighted section. Only one section can be highlighted at the time.
566 * @param int $courseid course id
567 * @param int $marker highlight section with this number, 0 means remove higlightin
570 function course_set_marker($courseid, $marker) {
572 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
573 if ($COURSE && $COURSE->id == $courseid) {
574 $COURSE->marker = $marker;
576 if (class_exists('format_base')) {
577 format_base::reset_course_cache($courseid);
579 course_modinfo::clear_instance_cache($courseid);
583 * For a given course section, marks it visible or hidden,
584 * and does the same for every activity in that section
586 * @param int $courseid course id
587 * @param int $sectionnumber The section number to adjust
588 * @param int $visibility The new visibility
589 * @return array A list of resources which were hidden in the section
591 function set_section_visible($courseid, $sectionnumber, $visibility) {
594 $resourcestotoggle = array();
595 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
596 course_update_section($courseid, $section, array('visible' => $visibility));
598 // Determine which modules are visible for AJAX update
599 $modules = !empty($section->sequence) ? explode(',', $section->sequence) : array();
600 if (!empty($modules)) {
601 list($insql, $params) = $DB->get_in_or_equal($modules);
602 $select = 'id ' . $insql . ' AND visible = ?';
603 array_push($params, $visibility);
605 $select .= ' AND visibleold = 1';
607 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
610 return $resourcestotoggle;
614 * Retrieve all metadata for the requested modules
616 * @param object $course The Course
617 * @param array $modnames An array containing the list of modules and their
619 * @param int $sectionreturn The section to return to
620 * @return array A list of stdClass objects containing metadata about each
623 function get_module_metadata($course, $modnames, $sectionreturn = null) {
626 // get_module_metadata will be called once per section on the page and courses may show
627 // different modules to one another
628 static $modlist = array();
629 if (!isset($modlist[$course->id])) {
630 $modlist[$course->id] = array();
634 $urlbase = new moodle_url('/course/mod.php', array('id' => $course->id, 'sesskey' => sesskey()));
635 if ($sectionreturn !== null) {
636 $urlbase->param('sr', $sectionreturn);
638 foreach($modnames as $modname => $modnamestr) {
639 if (!course_allowed_module($course, $modname)) {
642 if (isset($modlist[$course->id][$modname])) {
643 // This module is already cached
644 $return += $modlist[$course->id][$modname];
647 $modlist[$course->id][$modname] = array();
649 // Create an object for a default representation of this module type in the activity chooser. It will be used
650 // if module does not implement callback get_shortcuts() and it will also be passed to the callback if it exists.
651 $defaultmodule = new stdClass();
652 $defaultmodule->title = $modnamestr;
653 $defaultmodule->name = $modname;
654 $defaultmodule->link = new moodle_url($urlbase, array('add' => $modname));
655 $defaultmodule->icon = $OUTPUT->pix_icon('icon', '', $defaultmodule->name, array('class' => 'icon'));
656 $sm = get_string_manager();
657 if ($sm->string_exists('modulename_help', $modname)) {
658 $defaultmodule->help = get_string('modulename_help', $modname);
659 if ($sm->string_exists('modulename_link', $modname)) { // Link to further info in Moodle docs.
660 $link = get_string('modulename_link', $modname);
661 $linktext = get_string('morehelp');
662 $defaultmodule->help .= html_writer::tag('div',
663 $OUTPUT->doc_link($link, $linktext, true), array('class' => 'helpdoclink'));
666 $defaultmodule->archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
668 // Legacy support for callback get_types() - do not use any more, use get_shortcuts() instead!
669 $typescallbackexists = component_callback_exists($modname, 'get_types');
671 // Each module can implement callback modulename_get_shortcuts() in its lib.php and return the list
672 // of elements to be added to activity chooser.
673 $items = component_callback($modname, 'get_shortcuts', array($defaultmodule), null);
674 if ($items !== null) {
675 foreach ($items as $item) {
676 // Add all items to the return array. All items must have different links, use them as a key in the return array.
677 if (!isset($item->archetype)) {
678 $item->archetype = $defaultmodule->archetype;
680 if (!isset($item->icon)) {
681 $item->icon = $defaultmodule->icon;
683 // If plugin returned the only one item with the same link as default item - cache it as $modname,
684 // otherwise append the link url to the module name.
685 $item->name = (count($items) == 1 &&
686 $item->link->out() === $defaultmodule->link->out()) ? $modname : $modname . ':' . $item->link;
688 // If the module provides the helptext property, append it to the help text to match the look and feel
689 // of the default course modules.
690 if (isset($item->help) && isset($item->helplink)) {
691 $linktext = get_string('morehelp');
692 $item->help .= html_writer::tag('div',
693 $OUTPUT->doc_link($item->helplink, $linktext, true), array('class' => 'helpdoclink'));
695 $modlist[$course->id][$modname][$item->name] = $item;
697 $return += $modlist[$course->id][$modname];
698 if ($typescallbackexists) {
699 debugging('Both callbacks get_shortcuts() and get_types() are found in module ' . $modname .
700 '. Callback get_types() will be completely ignored', DEBUG_DEVELOPER);
702 // If get_shortcuts() callback is defined, the default module action is not added.
703 // It is a responsibility of the callback to add it to the return value unless it is not needed.
707 if ($typescallbackexists) {
708 debugging('Callback get_types() is found in module ' . $modname . ', this functionality is deprecated, ' .
709 'please use callback get_shortcuts() instead', DEBUG_DEVELOPER);
711 $types = component_callback($modname, 'get_types', array(), MOD_SUBTYPE_NO_CHILDREN);
712 if ($types !== MOD_SUBTYPE_NO_CHILDREN) {
713 // Legacy support for deprecated callback get_types(). To be removed in Moodle 3.5. TODO MDL-53697.
714 if (is_array($types) && count($types) > 0) {
715 $grouptitle = $modnamestr;
716 $icon = $OUTPUT->pix_icon('icon', '', $modname, array('class' => 'icon'));
717 foreach($types as $type) {
718 if ($type->typestr === '--') {
721 if (strpos($type->typestr, '--') === 0) {
722 $grouptitle = str_replace('--', '', $type->typestr);
725 // Set the Sub Type metadata.
726 $subtype = new stdClass();
727 $subtype->title = get_string('activitytypetitle', '',
728 (object)['activity' => $grouptitle, 'type' => $type->typestr]);
729 $subtype->type = str_replace('&', '&', $type->type);
730 $typename = preg_replace('/.*type=/', '', $subtype->type);
731 $subtype->archetype = $type->modclass;
733 if (!empty($type->help)) {
734 $subtype->help = $type->help;
735 } else if (get_string_manager()->string_exists('help' . $subtype->name, $modname)) {
736 $subtype->help = get_string('help' . $subtype->name, $modname);
738 $subtype->link = new moodle_url($urlbase, array('add' => $modname, 'type' => $typename));
739 $subtype->name = $modname . ':' . $subtype->link;
740 $subtype->icon = $icon;
741 $modlist[$course->id][$modname][$subtype->name] = $subtype;
743 $return += $modlist[$course->id][$modname];
746 // Neither get_shortcuts() nor get_types() callbacks found, use the default item for the activity chooser.
747 $modlist[$course->id][$modname][$modname] = $defaultmodule;
748 $return[$modname] = $defaultmodule;
752 core_collator::asort_objects_by_property($return, 'title');
757 * Return the course category context for the category with id $categoryid, except
758 * that if $categoryid is 0, return the system context.
760 * @param integer $categoryid a category id or 0.
761 * @return context the corresponding context
763 function get_category_or_system_context($categoryid) {
765 return context_coursecat::instance($categoryid, IGNORE_MISSING);
767 return context_system::instance();
772 * Returns full course categories trees to be used in html_writer::select()
774 * Calls {@link coursecat::make_categories_list()} to build the tree and
775 * adds whitespace to denote nesting
777 * @return array array mapping coursecat id to the display name
779 function make_categories_options() {
781 require_once($CFG->libdir. '/coursecatlib.php');
782 $cats = coursecat::make_categories_list('', 0, ' / ');
783 foreach ($cats as $key => $value) {
784 // Prefix the value with the number of spaces equal to category depth (number of separators in the value).
785 $cats[$key] = str_repeat(' ', substr_count($value, ' / ')). $value;
791 * Print the buttons relating to course requests.
793 * @param object $context current page context.
795 function print_course_request_buttons($context) {
796 global $CFG, $DB, $OUTPUT;
797 if (empty($CFG->enablecourserequests)) {
800 if (!has_capability('moodle/course:create', $context) && has_capability('moodle/course:request', $context)) {
801 /// Print a button to request a new course
802 echo $OUTPUT->single_button(new moodle_url('/course/request.php'), get_string('requestcourse'), 'get');
804 /// Print a button to manage pending requests
805 if ($context->contextlevel == CONTEXT_SYSTEM && has_capability('moodle/site:approvecourse', $context)) {
806 $disabled = !$DB->record_exists('course_request', array());
807 echo $OUTPUT->single_button(new moodle_url('/course/pending.php'), get_string('coursespending'), 'get', array('disabled' => $disabled));
812 * Does the user have permission to edit things in this category?
814 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
815 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
817 function can_edit_in_category($categoryid = 0) {
818 $context = get_category_or_system_context($categoryid);
819 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
822 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
824 function add_course_module($mod) {
827 $mod->added = time();
830 $cmid = $DB->insert_record("course_modules", $mod);
831 rebuild_course_cache($mod->course, true);
836 * Creates a course section and adds it to the specified position
838 * @param int|stdClass $courseorid course id or course object
839 * @param int $position position to add to, 0 means to the end. If position is greater than
840 * number of existing secitons, the section is added to the end. This will become sectionnum of the
841 * new section. All existing sections at this or bigger position will be shifted down.
842 * @param bool $skipcheck the check has already been made and we know that the section with this position does not exist
843 * @return stdClass created section object
845 function course_create_section($courseorid, $position = 0, $skipcheck = false) {
847 $courseid = is_object($courseorid) ? $courseorid->id : $courseorid;
849 // Find the last sectionnum among existing sections.
851 $lastsection = $position - 1;
853 $lastsection = (int)$DB->get_field_sql('SELECT max(section) from {course_sections} WHERE course = ?', [$courseid]);
856 // First add section to the end.
857 $cw = new stdClass();
858 $cw->course = $courseid;
859 $cw->section = $lastsection + 1;
861 $cw->summaryformat = FORMAT_HTML;
865 $cw->availability = null;
866 $cw->id = $DB->insert_record("course_sections", $cw);
868 // Now move it to the specified position.
869 if ($position > 0 && $position <= $lastsection) {
870 $course = is_object($courseorid) ? $courseorid : get_course($courseorid);
871 move_section_to($course, $cw->section, $position, true);
872 $cw->section = $position;
875 core\event\course_section_created::create_from_section($cw)->trigger();
877 rebuild_course_cache($courseid, true);
882 * Creates missing course section(s) and rebuilds course cache
884 * @param int|stdClass $courseorid course id or course object
885 * @param int|array $sections list of relative section numbers to create
886 * @return bool if there were any sections created
888 function course_create_sections_if_missing($courseorid, $sections) {
889 if (!is_array($sections)) {
890 $sections = array($sections);
892 $existing = array_keys(get_fast_modinfo($courseorid)->get_section_info_all());
893 if ($newsections = array_diff($sections, $existing)) {
894 foreach ($newsections as $sectionnum) {
895 course_create_section($courseorid, $sectionnum, true);
903 * Adds an existing module to the section
905 * Updates both tables {course_sections} and {course_modules}
907 * Note: This function does not use modinfo PROVIDED that the section you are
908 * adding the module to already exists. If the section does not exist, it will
909 * build modinfo if necessary and create the section.
911 * @param int|stdClass $courseorid course id or course object
912 * @param int $cmid id of the module already existing in course_modules table
913 * @param int $sectionnum relative number of the section (field course_sections.section)
914 * If section does not exist it will be created
915 * @param int|stdClass $beforemod id or object with field id corresponding to the module
916 * before which the module needs to be included. Null for inserting in the
918 * @return int The course_sections ID where the module is inserted
920 function course_add_cm_to_section($courseorid, $cmid, $sectionnum, $beforemod = null) {
922 if (is_object($beforemod)) {
923 $beforemod = $beforemod->id;
925 if (is_object($courseorid)) {
926 $courseid = $courseorid->id;
928 $courseid = $courseorid;
930 // Do not try to use modinfo here, there is no guarantee it is valid!
931 $section = $DB->get_record('course_sections',
932 array('course' => $courseid, 'section' => $sectionnum), '*', IGNORE_MISSING);
934 // This function call requires modinfo.
935 course_create_sections_if_missing($courseorid, $sectionnum);
936 $section = $DB->get_record('course_sections',
937 array('course' => $courseid, 'section' => $sectionnum), '*', MUST_EXIST);
940 $modarray = explode(",", trim($section->sequence));
941 if (empty($section->sequence)) {
942 $newsequence = "$cmid";
943 } else if ($beforemod && ($key = array_keys($modarray, $beforemod))) {
944 $insertarray = array($cmid, $beforemod);
945 array_splice($modarray, $key[0], 1, $insertarray);
946 $newsequence = implode(",", $modarray);
948 $newsequence = "$section->sequence,$cmid";
950 $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id));
951 $DB->set_field('course_modules', 'section', $section->id, array('id' => $cmid));
952 if (is_object($courseorid)) {
953 rebuild_course_cache($courseorid->id, true);
955 rebuild_course_cache($courseorid, true);
957 return $section->id; // Return course_sections ID that was used.
961 * Change the group mode of a course module.
963 * Note: Do not forget to trigger the event \core\event\course_module_updated as it needs
964 * to be triggered manually, refer to {@link \core\event\course_module_updated::create_from_cm()}.
966 * @param int $id course module ID.
967 * @param int $groupmode the new groupmode value.
968 * @return bool True if the $groupmode was updated.
970 function set_coursemodule_groupmode($id, $groupmode) {
972 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST);
973 if ($cm->groupmode != $groupmode) {
974 $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id));
975 rebuild_course_cache($cm->course, true);
977 return ($cm->groupmode != $groupmode);
980 function set_coursemodule_idnumber($id, $idnumber) {
982 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST);
983 if ($cm->idnumber != $idnumber) {
984 $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id));
985 rebuild_course_cache($cm->course, true);
987 return ($cm->idnumber != $idnumber);
991 * Set the visibility of a module and inherent properties.
993 * Note: Do not forget to trigger the event \core\event\course_module_updated as it needs
994 * to be triggered manually, refer to {@link \core\event\course_module_updated::create_from_cm()}.
996 * From 2.4 the parameter $prevstateoverrides has been removed, the logic it triggered
997 * has been moved to {@link set_section_visible()} which was the only place from which
998 * the parameter was used.
1000 * @param int $id of the module
1001 * @param int $visible state of the module
1002 * @param int $visibleoncoursepage state of the module on the course page
1003 * @return bool false when the module was not found, true otherwise
1005 function set_coursemodule_visible($id, $visible, $visibleoncoursepage = 1) {
1007 require_once($CFG->libdir.'/gradelib.php');
1008 require_once($CFG->dirroot.'/calendar/lib.php');
1010 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
1014 // Create events and propagate visibility to associated grade items if the value has changed.
1015 // Only do this if it's changed to avoid accidently overwriting manual showing/hiding of student grades.
1016 if ($cm->visible == $visible && $cm->visibleoncoursepage == $visibleoncoursepage) {
1020 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
1023 if (($cm->visible != $visible) &&
1024 ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename)))) {
1025 foreach($events as $event) {
1027 $event = new calendar_event($event);
1028 $event->toggle_visibility(true);
1030 $event = new calendar_event($event);
1031 $event->toggle_visibility(false);
1036 // Updating visible and visibleold to keep them in sync. Only changing a section visibility will
1037 // affect visibleold to allow for an original visibility restore. See set_section_visible().
1038 $cminfo = new stdClass();
1040 $cminfo->visible = $visible;
1041 $cminfo->visibleoncoursepage = $visibleoncoursepage;
1042 $cminfo->visibleold = $visible;
1043 $DB->update_record('course_modules', $cminfo);
1045 // Hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there.
1046 // Note that this must be done after updating the row in course_modules, in case
1047 // the modules grade_item_update function needs to access $cm->visible.
1048 if ($cm->visible != $visible &&
1049 plugin_supports('mod', $modulename, FEATURE_CONTROLS_GRADE_VISIBILITY) &&
1050 component_callback_exists('mod_' . $modulename, 'grade_item_update')) {
1051 $instance = $DB->get_record($modulename, array('id' => $cm->instance), '*', MUST_EXIST);
1052 component_callback('mod_' . $modulename, 'grade_item_update', array($instance));
1053 } else if ($cm->visible != $visible) {
1054 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
1056 foreach ($grade_items as $grade_item) {
1057 $grade_item->set_hidden(!$visible);
1062 rebuild_course_cache($cm->course, true);
1067 * Changes the course module name
1069 * @param int $id course module id
1070 * @param string $name new value for a name
1071 * @return bool whether a change was made
1073 function set_coursemodule_name($id, $name) {
1075 require_once($CFG->libdir . '/gradelib.php');
1077 $cm = get_coursemodule_from_id('', $id, 0, false, MUST_EXIST);
1079 $module = new \stdClass();
1080 $module->id = $cm->instance;
1082 // Escape strings as they would be by mform.
1083 if (!empty($CFG->formatstringstriptags)) {
1084 $module->name = clean_param($name, PARAM_TEXT);
1086 $module->name = clean_param($name, PARAM_CLEANHTML);
1088 if ($module->name === $cm->name || strval($module->name) === '') {
1091 if (\core_text::strlen($module->name) > 255) {
1092 throw new \moodle_exception('maximumchars', 'moodle', '', 255);
1095 $module->timemodified = time();
1096 $DB->update_record($cm->modname, $module);
1097 $cm->name = $module->name;
1098 \core\event\course_module_updated::create_from_cm($cm)->trigger();
1099 rebuild_course_cache($cm->course, true);
1101 // Attempt to update the grade item if relevant.
1102 $grademodule = $DB->get_record($cm->modname, array('id' => $cm->instance));
1103 $grademodule->cmidnumber = $cm->idnumber;
1104 $grademodule->modname = $cm->modname;
1105 grade_update_mod_grades($grademodule);
1107 // Update calendar events with the new name.
1108 $refresheventsfunction = $cm->modname . '_refresh_events';
1109 if (function_exists($refresheventsfunction)) {
1110 call_user_func($refresheventsfunction, $cm->course);
1117 * This function will handle the whole deletion process of a module. This includes calling
1118 * the modules delete_instance function, deleting files, events, grades, conditional data,
1119 * the data in the course_module and course_sections table and adding a module deletion
1122 * @param int $cmid the course module id
1123 * @param bool $async whether or not to try to delete the module using an adhoc task. Async also depends on a plugin hook.
1124 * @throws moodle_exception
1127 function course_delete_module($cmid, $async = false) {
1128 // Check the 'course_module_background_deletion_recommended' hook first.
1129 // Only use asynchronous deletion if at least one plugin returns true and if async deletion has been requested.
1130 // Both are checked because plugins should not be allowed to dictate the deletion behaviour, only support/decline it.
1131 // It's up to plugins to handle things like whether or not they are enabled.
1132 if ($async && $pluginsfunction = get_plugins_with_function('course_module_background_deletion_recommended')) {
1133 foreach ($pluginsfunction as $plugintype => $plugins) {
1134 foreach ($plugins as $pluginfunction) {
1135 if ($pluginfunction()) {
1136 return course_module_flag_for_async_deletion($cmid);
1144 require_once($CFG->libdir.'/gradelib.php');
1145 require_once($CFG->libdir.'/questionlib.php');
1146 require_once($CFG->dirroot.'/blog/lib.php');
1147 require_once($CFG->dirroot.'/calendar/lib.php');
1149 // Get the course module.
1150 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
1154 // Get the module context.
1155 $modcontext = context_module::instance($cm->id);
1157 // Get the course module name.
1158 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
1160 // Get the file location of the delete_instance function for this module.
1161 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
1163 // Include the file required to call the delete_instance function for this module.
1164 if (file_exists($modlib)) {
1165 require_once($modlib);
1167 throw new moodle_exception('cannotdeletemodulemissinglib', '', '', null,
1168 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
1171 $deleteinstancefunction = $modulename . '_delete_instance';
1173 // Ensure the delete_instance function exists for this module.
1174 if (!function_exists($deleteinstancefunction)) {
1175 throw new moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
1176 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
1179 // Allow plugins to use this course module before we completely delete it.
1180 if ($pluginsfunction = get_plugins_with_function('pre_course_module_delete')) {
1181 foreach ($pluginsfunction as $plugintype => $plugins) {
1182 foreach ($plugins as $pluginfunction) {
1183 $pluginfunction($cm);
1188 // Delete activity context questions and question categories.
1189 question_delete_activity($cm);
1191 // Call the delete_instance function, if it returns false throw an exception.
1192 if (!$deleteinstancefunction($cm->instance)) {
1193 throw new moodle_exception('cannotdeletemoduleinstance', '', '', null,
1194 "Cannot delete the module $modulename (instance).");
1197 // Remove all module files in case modules forget to do that.
1198 $fs = get_file_storage();
1199 $fs->delete_area_files($modcontext->id);
1201 // Delete events from calendar.
1202 if ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename))) {
1203 foreach($events as $event) {
1204 $calendarevent = calendar_event::load($event->id);
1205 $calendarevent->delete();
1209 // Delete grade items, outcome items and grades attached to modules.
1210 if ($grade_items = grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $modulename,
1211 'iteminstance' => $cm->instance, 'courseid' => $cm->course))) {
1212 foreach ($grade_items as $grade_item) {
1213 $grade_item->delete('moddelete');
1217 // Delete completion and availability data; it is better to do this even if the
1218 // features are not turned on, in case they were turned on previously (these will be
1219 // very quick on an empty table).
1220 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
1221 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
1222 'course' => $cm->course,
1223 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
1225 // Delete all tag instances associated with the instance of this module.
1226 core_tag_tag::delete_instances('mod_' . $modulename, null, $modcontext->id);
1227 core_tag_tag::remove_all_item_tags('core', 'course_modules', $cm->id);
1229 // Notify the competency subsystem.
1230 \core_competency\api::hook_course_module_deleted($cm);
1232 // Delete the context.
1233 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
1235 // Delete the module from the course_modules table.
1236 $DB->delete_records('course_modules', array('id' => $cm->id));
1238 // Delete module from that section.
1239 if (!delete_mod_from_section($cm->id, $cm->section)) {
1240 throw new moodle_exception('cannotdeletemodulefromsection', '', '', null,
1241 "Cannot delete the module $modulename (instance) from section.");
1244 // Trigger event for course module delete action.
1245 $event = \core\event\course_module_deleted::create(array(
1246 'courseid' => $cm->course,
1247 'context' => $modcontext,
1248 'objectid' => $cm->id,
1250 'modulename' => $modulename,
1251 'instanceid' => $cm->instance,
1254 $event->add_record_snapshot('course_modules', $cm);
1256 rebuild_course_cache($cm->course, true);
1260 * Schedule a course module for deletion in the background using an adhoc task.
1262 * This method should not be called directly. Instead, please use course_delete_module($cmid, true), to denote async deletion.
1263 * The real deletion of the module is handled by the task, which calls 'course_delete_module($cmid)'.
1265 * @param int $cmid the course module id.
1266 * @return bool whether the module was successfully scheduled for deletion.
1267 * @throws \moodle_exception
1269 function course_module_flag_for_async_deletion($cmid) {
1270 global $CFG, $DB, $USER;
1271 require_once($CFG->libdir.'/gradelib.php');
1272 require_once($CFG->libdir.'/questionlib.php');
1273 require_once($CFG->dirroot.'/blog/lib.php');
1274 require_once($CFG->dirroot.'/calendar/lib.php');
1276 // Get the course module.
1277 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
1281 // We need to be reasonably certain the deletion is going to succeed before we background the process.
1282 // Make the necessary delete_instance checks, etc. before proceeding further. Throw exceptions if required.
1284 // Get the course module name.
1285 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
1287 // Get the file location of the delete_instance function for this module.
1288 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
1290 // Include the file required to call the delete_instance function for this module.
1291 if (file_exists($modlib)) {
1292 require_once($modlib);
1294 throw new \moodle_exception('cannotdeletemodulemissinglib', '', '', null,
1295 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
1298 $deleteinstancefunction = $modulename . '_delete_instance';
1300 // Ensure the delete_instance function exists for this module.
1301 if (!function_exists($deleteinstancefunction)) {
1302 throw new \moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
1303 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
1306 // We are going to defer the deletion as we can't be sure how long the module's pre_delete code will run for.
1307 $cm->deletioninprogress = '1';
1308 $DB->update_record('course_modules', $cm);
1310 // Create an adhoc task for the deletion of the course module. The task takes an array of course modules for removal.
1311 $removaltask = new \core_course\task\course_delete_modules();
1312 $removaltask->set_custom_data(array(
1313 'cms' => array($cm),
1314 'userid' => $USER->id,
1315 'realuserid' => \core\session\manager::get_realuser()->id
1318 // Queue the task for the next run.
1319 \core\task\manager::queue_adhoc_task($removaltask);
1321 // Reset the course cache to hide the module.
1322 rebuild_course_cache($cm->course, true);
1326 * Checks whether the given course has any course modules scheduled for adhoc deletion.
1328 * @param int $courseid the id of the course.
1329 * @return bool true if the course contains any modules pending deletion, false otherwise.
1331 function course_modules_pending_deletion($courseid) {
1332 if (empty($courseid)) {
1335 $modinfo = get_fast_modinfo($courseid);
1336 foreach ($modinfo->get_cms() as $module) {
1337 if ($module->deletioninprogress == '1') {
1345 * Checks whether the course module, as defined by modulename and instanceid, is scheduled for deletion within the given course.
1347 * @param int $courseid the course id.
1348 * @param string $modulename the module name. E.g. 'assign', 'book', etc.
1349 * @param int $instanceid the module instance id.
1350 * @return bool true if the course module is pending deletion, false otherwise.
1352 function course_module_instance_pending_deletion($courseid, $modulename, $instanceid) {
1353 if (empty($courseid) || empty($modulename) || empty($instanceid)) {
1356 $modinfo = get_fast_modinfo($courseid);
1357 $instances = $modinfo->get_instances_of($modulename);
1358 return isset($instances[$instanceid]) && $instances[$instanceid]->deletioninprogress;
1361 function delete_mod_from_section($modid, $sectionid) {
1364 if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
1366 $modarray = explode(",", $section->sequence);
1368 if ($key = array_keys ($modarray, $modid)) {
1369 array_splice($modarray, $key[0], 1);
1370 $newsequence = implode(",", $modarray);
1371 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
1372 rebuild_course_cache($section->course, true);
1383 * Moves a section within a course, from a position to another.
1384 * Be very careful: $section and $destination refer to section number,
1387 * @param object $course
1388 * @param int $section Section number (not id!!!)
1389 * @param int $destination
1390 * @param bool $ignorenumsections
1391 * @return boolean Result
1393 function move_section_to($course, $section, $destination, $ignorenumsections = false) {
1394 /// Moves a whole course section up and down within the course
1397 if (!$destination && $destination != 0) {
1401 // compartibility with course formats using field 'numsections'
1402 $courseformatoptions = course_get_format($course)->get_format_options();
1403 if ((!$ignorenumsections && array_key_exists('numsections', $courseformatoptions) &&
1404 ($destination > $courseformatoptions['numsections'])) || ($destination < 1)) {
1408 // Get all sections for this course and re-order them (2 of them should now share the same section number)
1409 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
1410 'section ASC, id ASC', 'id, section')) {
1414 $movedsections = reorder_sections($sections, $section, $destination);
1416 // Update all sections. Do this in 2 steps to avoid breaking database
1417 // uniqueness constraint
1418 $transaction = $DB->start_delegated_transaction();
1419 foreach ($movedsections as $id => $position) {
1420 if ($sections[$id] !== $position) {
1421 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
1424 foreach ($movedsections as $id => $position) {
1425 if ($sections[$id] !== $position) {
1426 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
1430 // If we move the highlighted section itself, then just highlight the destination.
1431 // Adjust the higlighted section location if we move something over it either direction.
1432 if ($section == $course->marker) {
1433 course_set_marker($course->id, $destination);
1434 } elseif ($section > $course->marker && $course->marker >= $destination) {
1435 course_set_marker($course->id, $course->marker+1);
1436 } elseif ($section < $course->marker && $course->marker <= $destination) {
1437 course_set_marker($course->id, $course->marker-1);
1440 $transaction->allow_commit();
1441 rebuild_course_cache($course->id, true);
1446 * This method will delete a course section and may delete all modules inside it.
1448 * No permissions are checked here, use {@link course_can_delete_section()} to
1449 * check if section can actually be deleted.
1451 * @param int|stdClass $course
1452 * @param int|stdClass|section_info $section
1453 * @param bool $forcedeleteifnotempty if set to false section will not be deleted if it has modules in it.
1454 * @param bool $async whether or not to try to delete the section using an adhoc task. Async also depends on a plugin hook.
1455 * @return bool whether section was deleted
1457 function course_delete_section($course, $section, $forcedeleteifnotempty = true, $async = false) {
1460 // Prepare variables.
1461 $courseid = (is_object($course)) ? $course->id : (int)$course;
1462 $sectionnum = (is_object($section)) ? $section->section : (int)$section;
1463 $section = $DB->get_record('course_sections', array('course' => $courseid, 'section' => $sectionnum));
1465 // No section exists, can't proceed.
1469 // Check the 'course_module_background_deletion_recommended' hook first.
1470 // Only use asynchronous deletion if at least one plugin returns true and if async deletion has been requested.
1471 // Both are checked because plugins should not be allowed to dictate the deletion behaviour, only support/decline it.
1472 // It's up to plugins to handle things like whether or not they are enabled.
1473 if ($async && $pluginsfunction = get_plugins_with_function('course_module_background_deletion_recommended')) {
1474 foreach ($pluginsfunction as $plugintype => $plugins) {
1475 foreach ($plugins as $pluginfunction) {
1476 if ($pluginfunction()) {
1477 return course_delete_section_async($section, $forcedeleteifnotempty);
1483 $format = course_get_format($course);
1484 $sectionname = $format->get_section_name($section);
1487 $result = $format->delete_section($section, $forcedeleteifnotempty);
1489 // Trigger an event for course section deletion.
1491 $context = context_course::instance($courseid);
1492 $event = \core\event\course_section_deleted::create(
1494 'objectid' => $section->id,
1495 'courseid' => $courseid,
1496 'context' => $context,
1498 'sectionnum' => $section->section,
1499 'sectionname' => $sectionname,
1503 $event->add_record_snapshot('course_sections', $section);
1510 * Course section deletion, using an adhoc task for deletion of the modules it contains.
1511 * 1. Schedule all modules within the section for adhoc removal.
1512 * 2. Move all modules to course section 0.
1513 * 3. Delete the resulting empty section.
1515 * @param \stdClass $section the section to schedule for deletion.
1516 * @param bool $forcedeleteifnotempty whether to force section deletion if it contains modules.
1517 * @return bool true if the section was scheduled for deletion, false otherwise.
1519 function course_delete_section_async($section, $forcedeleteifnotempty = true) {
1522 // Objects only, and only valid ones.
1523 if (!is_object($section) || empty($section->id)) {
1527 // Does the object currently exist in the DB for removal (check for stale objects).
1528 $section = $DB->get_record('course_sections', array('id' => $section->id));
1529 if (!$section || !$section->section) {
1530 // No section exists, or the section is 0. Can't proceed.
1534 // Check whether the section can be removed.
1535 if (!$forcedeleteifnotempty && (!empty($section->sequence) || !empty($section->summary))) {
1539 $format = course_get_format($section->course);
1540 $sectionname = $format->get_section_name($section);
1542 // Flag those modules having no existing deletion flag. Some modules may have been scheduled for deletion manually, and we don't
1543 // want to create additional adhoc deletion tasks for these. Moving them to section 0 will suffice.
1544 $affectedmods = $DB->get_records_select('course_modules', 'course = ? AND section = ? AND deletioninprogress <> ?',
1545 [$section->course, $section->id, 1], '', 'id');
1546 $DB->set_field('course_modules', 'deletioninprogress', '1', ['course' => $section->course, 'section' => $section->id]);
1548 // Move all modules to section 0.
1549 $modules = $DB->get_records('course_modules', ['section' => $section->id], '');
1550 $sectionzero = $DB->get_record('course_sections', ['course' => $section->course, 'section' => '0']);
1551 foreach ($modules as $mod) {
1552 moveto_module($mod, $sectionzero);
1555 // Create and queue an adhoc task for the deletion of the modules.
1556 $removaltask = new \core_course\task\course_delete_modules();
1558 'cms' => $affectedmods,
1559 'userid' => $USER->id,
1560 'realuserid' => \core\session\manager::get_realuser()->id
1562 $removaltask->set_custom_data($data);
1563 \core\task\manager::queue_adhoc_task($removaltask);
1565 // Delete the now empty section, passing in only the section number, which forces the function to fetch a new object.
1566 // The refresh is needed because the section->sequence is now stale.
1567 $result = $format->delete_section($section->section, $forcedeleteifnotempty);
1569 // Trigger an event for course section deletion.
1571 $context = \context_course::instance($section->course);
1572 $event = \core\event\course_section_deleted::create(
1574 'objectid' => $section->id,
1575 'courseid' => $section->course,
1576 'context' => $context,
1578 'sectionnum' => $section->section,
1579 'sectionname' => $sectionname,
1583 $event->add_record_snapshot('course_sections', $section);
1586 rebuild_course_cache($section->course, true);
1592 * Updates the course section
1594 * This function does not check permissions or clean values - this has to be done prior to calling it.
1596 * @param int|stdClass $course
1597 * @param stdClass $section record from course_sections table - it will be updated with the new values
1598 * @param array|stdClass $data
1600 function course_update_section($course, $section, $data) {
1603 $courseid = (is_object($course)) ? $course->id : (int)$course;
1605 // Some fields can not be updated using this method.
1606 $data = array_diff_key((array)$data, array('id', 'course', 'section', 'sequence'));
1607 $changevisibility = (array_key_exists('visible', $data) && (bool)$data['visible'] != (bool)$section->visible);
1608 if (array_key_exists('name', $data) && \core_text::strlen($data['name']) > 255) {
1609 throw new moodle_exception('maximumchars', 'moodle', '', 255);
1612 // Update record in the DB and course format options.
1613 $data['id'] = $section->id;
1614 $DB->update_record('course_sections', $data);
1615 rebuild_course_cache($courseid, true);
1616 course_get_format($courseid)->update_section_format_options($data);
1618 // Update fields of the $section object.
1619 foreach ($data as $key => $value) {
1620 if (property_exists($section, $key)) {
1621 $section->$key = $value;
1625 // Trigger an event for course section update.
1626 $event = \core\event\course_section_updated::create(
1628 'objectid' => $section->id,
1629 'courseid' => $courseid,
1630 'context' => context_course::instance($courseid),
1631 'other' => array('sectionnum' => $section->section)
1636 // If section visibility was changed, hide the modules in this section too.
1637 if ($changevisibility && !empty($section->sequence)) {
1638 $modules = explode(',', $section->sequence);
1639 foreach ($modules as $moduleid) {
1640 if ($cm = get_coursemodule_from_id(null, $moduleid, $courseid)) {
1641 if ($data['visible']) {
1642 // As we unhide the section, we use the previously saved visibility stored in visibleold.
1643 set_coursemodule_visible($moduleid, $cm->visibleold, $cm->visibleoncoursepage);
1645 // We hide the section, so we hide the module but we store the original state in visibleold.
1646 set_coursemodule_visible($moduleid, 0, $cm->visibleoncoursepage);
1647 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id' => $moduleid));
1649 \core\event\course_module_updated::create_from_cm($cm)->trigger();
1656 * Checks if the current user can delete a section (if course format allows it and user has proper permissions).
1658 * @param int|stdClass $course
1659 * @param int|stdClass|section_info $section
1662 function course_can_delete_section($course, $section) {
1663 if (is_object($section)) {
1664 $section = $section->section;
1667 // Not possible to delete 0-section.
1670 // Course format should allow to delete sections.
1671 if (!course_get_format($course)->can_delete_section($section)) {
1674 // Make sure user has capability to update course and move sections.
1675 $context = context_course::instance(is_object($course) ? $course->id : $course);
1676 if (!has_all_capabilities(array('moodle/course:movesections', 'moodle/course:update'), $context)) {
1679 // Make sure user has capability to delete each activity in this section.
1680 $modinfo = get_fast_modinfo($course);
1681 if (!empty($modinfo->sections[$section])) {
1682 foreach ($modinfo->sections[$section] as $cmid) {
1683 if (!has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
1692 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
1693 * an original position number and a target position number, rebuilds the array so that the
1694 * move is made without any duplication of section positions.
1695 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
1696 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
1698 * @param array $sections
1699 * @param int $origin_position
1700 * @param int $target_position
1703 function reorder_sections($sections, $origin_position, $target_position) {
1704 if (!is_array($sections)) {
1708 // We can't move section position 0
1709 if ($origin_position < 1) {
1710 echo "We can't move section position 0";
1714 // Locate origin section in sections array
1715 if (!$origin_key = array_search($origin_position, $sections)) {
1716 echo "searched position not in sections array";
1717 return false; // searched position not in sections array
1720 // Extract origin section
1721 $origin_section = $sections[$origin_key];
1722 unset($sections[$origin_key]);
1724 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
1726 $append_array = array();
1727 foreach ($sections as $id => $position) {
1729 $append_array[$id] = $position;
1730 unset($sections[$id]);
1732 if ($position == $target_position) {
1733 if ($target_position < $origin_position) {
1734 $append_array[$id] = $position;
1735 unset($sections[$id]);
1741 // Append moved section
1742 $sections[$origin_key] = $origin_section;
1744 // Append rest of array (if applicable)
1745 if (!empty($append_array)) {
1746 foreach ($append_array as $id => $position) {
1747 $sections[$id] = $position;
1751 // Renumber positions
1753 foreach ($sections as $id => $p) {
1754 $sections[$id] = $position;
1763 * Move the module object $mod to the specified $section
1764 * If $beforemod exists then that is the module
1765 * before which $modid should be inserted
1767 * @param stdClass|cm_info $mod
1768 * @param stdClass|section_info $section
1769 * @param int|stdClass $beforemod id or object with field id corresponding to the module
1770 * before which the module needs to be included. Null for inserting in the
1771 * end of the section
1772 * @return int new value for module visibility (0 or 1)
1774 function moveto_module($mod, $section, $beforemod=NULL) {
1775 global $OUTPUT, $DB;
1777 // Current module visibility state - return value of this function.
1778 $modvisible = $mod->visible;
1780 // Remove original module from original section.
1781 if (! delete_mod_from_section($mod->id, $mod->section)) {
1782 echo $OUTPUT->notification("Could not delete module from existing section");
1785 // If moving to a hidden section then hide module.
1786 if ($mod->section != $section->id) {
1787 if (!$section->visible && $mod->visible) {
1788 // Module was visible but must become hidden after moving to hidden section.
1790 set_coursemodule_visible($mod->id, 0);
1791 // Set visibleold to 1 so module will be visible when section is made visible.
1792 $DB->set_field('course_modules', 'visibleold', 1, array('id' => $mod->id));
1794 if ($section->visible && !$mod->visible) {
1795 // Hidden module was moved to the visible section, restore the module visibility from visibleold.
1796 set_coursemodule_visible($mod->id, $mod->visibleold);
1797 $modvisible = $mod->visibleold;
1801 // Add the module into the new section.
1802 course_add_cm_to_section($section->course, $mod->id, $section->section, $beforemod);
1807 * Returns the list of all editing actions that current user can perform on the module
1809 * @param cm_info $mod The module to produce editing buttons for
1810 * @param int $indent The current indenting (default -1 means no move left-right actions)
1811 * @param int $sr The section to link back to (used for creating the links)
1812 * @return array array of action_link or pix_icon objects
1814 function course_get_cm_edit_actions(cm_info $mod, $indent = -1, $sr = null) {
1815 global $COURSE, $SITE, $CFG;
1819 $coursecontext = context_course::instance($mod->course);
1820 $modcontext = context_module::instance($mod->id);
1821 $courseformat = course_get_format($mod->get_course());
1823 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
1824 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
1826 // No permission to edit anything.
1827 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
1831 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
1834 $str = get_strings(array('delete', 'move', 'moveright', 'moveleft',
1835 'editsettings', 'duplicate', 'modhide', 'makeavailable', 'makeunavailable', 'modshow'), 'moodle');
1836 $str->assign = get_string('assignroles', 'role');
1837 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
1838 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
1839 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
1842 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
1845 $baseurl->param('sr', $sr);
1850 if ($hasmanageactivities) {
1851 $actions['update'] = new action_menu_link_secondary(
1852 new moodle_url($baseurl, array('update' => $mod->id)),
1853 new pix_icon('t/edit', $str->editsettings, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1855 array('class' => 'editing_update', 'data-action' => 'update')
1860 if ($hasmanageactivities && $indent >= 0) {
1861 $indentlimits = new stdClass();
1862 $indentlimits->min = 0;
1863 $indentlimits->max = 16;
1864 if (right_to_left()) { // Exchange arrows on RTL
1865 $rightarrow = 't/left';
1866 $leftarrow = 't/right';
1868 $rightarrow = 't/right';
1869 $leftarrow = 't/left';
1872 if ($indent >= $indentlimits->max) {
1873 $enabledclass = 'hidden';
1877 $actions['moveright'] = new action_menu_link_secondary(
1878 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
1879 new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1881 array('class' => 'editing_moveright ' . $enabledclass, 'data-action' => 'moveright',
1882 'data-keepopen' => true, 'data-sectionreturn' => $sr)
1885 if ($indent <= $indentlimits->min) {
1886 $enabledclass = 'hidden';
1890 $actions['moveleft'] = new action_menu_link_secondary(
1891 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
1892 new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1894 array('class' => 'editing_moveleft ' . $enabledclass, 'data-action' => 'moveleft',
1895 'data-keepopen' => true, 'data-sectionreturn' => $sr)
1900 // Hide/Show/Available/Unavailable.
1901 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
1902 $allowstealth = !empty($CFG->allowstealth) && $courseformat->allow_stealth_module_visibility($mod, $mod->get_section_info());
1904 $sectionvisible = $mod->get_section_info()->visible;
1905 // The module on the course page may be in one of the following states:
1906 // - Available and displayed on the course page ($displayedoncoursepage);
1907 // - Not available and not displayed on the course page ($unavailable);
1908 // - Available but not displayed on the course page ($stealth) - this can also be a visible activity in a hidden section.
1909 $displayedoncoursepage = $mod->visible && $mod->visibleoncoursepage && $sectionvisible;
1910 $unavailable = !$mod->visible;
1911 $stealth = $mod->visible && (!$mod->visibleoncoursepage || !$sectionvisible);
1912 if ($displayedoncoursepage) {
1913 $actions['hide'] = new action_menu_link_secondary(
1914 new moodle_url($baseurl, array('hide' => $mod->id)),
1915 new pix_icon('t/hide', $str->modhide, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1917 array('class' => 'editing_hide', 'data-action' => 'hide')
1919 } else if (!$displayedoncoursepage && $sectionvisible) {
1920 // Offer to "show" only if the section is visible.
1921 $actions['show'] = new action_menu_link_secondary(
1922 new moodle_url($baseurl, array('show' => $mod->id)),
1923 new pix_icon('t/show', $str->modshow, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1925 array('class' => 'editing_show', 'data-action' => 'show')
1930 // When making the "stealth" module unavailable we perform the same action as hiding the visible module.
1931 $actions['hide'] = new action_menu_link_secondary(
1932 new moodle_url($baseurl, array('hide' => $mod->id)),
1933 new pix_icon('t/unblock', $str->makeunavailable, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1934 $str->makeunavailable,
1935 array('class' => 'editing_makeunavailable', 'data-action' => 'hide', 'data-sectionreturn' => $sr)
1937 } else if ($unavailable && (!$sectionvisible || $allowstealth) && $mod->has_view()) {
1938 // Allow to make visually hidden module available in gradebook and other reports by making it a "stealth" module.
1939 // When the section is hidden it is an equivalent of "showing" the module.
1940 // Activities without the link (i.e. labels) can not be made available but hidden on course page.
1941 $action = $sectionvisible ? 'stealth' : 'show';
1942 $actions[$action] = new action_menu_link_secondary(
1943 new moodle_url($baseurl, array($action => $mod->id)),
1944 new pix_icon('t/block', $str->makeavailable, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1945 $str->makeavailable,
1946 array('class' => 'editing_makeavailable', 'data-action' => $action, 'data-sectionreturn' => $sr)
1951 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
1952 if (has_all_capabilities($dupecaps, $coursecontext) &&
1953 plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2) &&
1954 course_allowed_module($mod->get_course(), $mod->modname)) {
1955 $actions['duplicate'] = new action_menu_link_secondary(
1956 new moodle_url($baseurl, array('duplicate' => $mod->id)),
1957 new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1959 array('class' => 'editing_duplicate', 'data-action' => 'duplicate', 'data-sectionreturn' => $sr)
1964 if ($hasmanageactivities && !$mod->coursegroupmodeforce) {
1965 if (plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
1966 if ($mod->effectivegroupmode == SEPARATEGROUPS) {
1967 $nextgroupmode = VISIBLEGROUPS;
1968 $grouptitle = $str->groupsseparate;
1969 $actionname = 'groupsseparate';
1970 $nextactionname = 'groupsvisible';
1971 $groupimage = 'i/groups';
1972 } else if ($mod->effectivegroupmode == VISIBLEGROUPS) {
1973 $nextgroupmode = NOGROUPS;
1974 $grouptitle = $str->groupsvisible;
1975 $actionname = 'groupsvisible';
1976 $nextactionname = 'groupsnone';
1977 $groupimage = 'i/groupv';
1979 $nextgroupmode = SEPARATEGROUPS;
1980 $grouptitle = $str->groupsnone;
1981 $actionname = 'groupsnone';
1982 $nextactionname = 'groupsseparate';
1983 $groupimage = 'i/groupn';
1986 $actions[$actionname] = new action_menu_link_primary(
1987 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $nextgroupmode)),
1988 new pix_icon($groupimage, $grouptitle, 'moodle', array('class' => 'iconsmall')),
1990 array('class' => 'editing_'. $actionname, 'data-action' => $nextactionname,
1991 'aria-live' => 'assertive', 'data-sectionreturn' => $sr)
1994 $actions['nogroupsupport'] = new action_menu_filler();
1999 if (has_capability('moodle/role:assign', $modcontext)){
2000 $actions['assign'] = new action_menu_link_secondary(
2001 new moodle_url('/admin/roles/assign.php', array('contextid' => $modcontext->id)),
2002 new pix_icon('t/assignroles', $str->assign, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2004 array('class' => 'editing_assign', 'data-action' => 'assignroles', 'data-sectionreturn' => $sr)
2009 if ($hasmanageactivities) {
2010 $actions['delete'] = new action_menu_link_secondary(
2011 new moodle_url($baseurl, array('delete' => $mod->id)),
2012 new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2014 array('class' => 'editing_delete', 'data-action' => 'delete', 'data-sectionreturn' => $sr)
2022 * Returns the move action.
2024 * @param cm_info $mod The module to produce a move button for
2025 * @param int $sr The section to link back to (used for creating the links)
2026 * @return The markup for the move action, or an empty string if not available.
2028 function course_get_cm_move(cm_info $mod, $sr = null) {
2034 $modcontext = context_module::instance($mod->id);
2035 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
2038 $str = get_strings(array('move'));
2041 if (!isset($baseurl)) {
2042 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
2045 $baseurl->param('sr', $sr);
2049 if ($hasmanageactivities) {
2050 $pixicon = 'i/dragdrop';
2052 if (!course_ajax_enabled($mod->get_course())) {
2053 // Override for course frontpage until we get drag/drop working there.
2054 $pixicon = 't/move';
2057 return html_writer::link(
2058 new moodle_url($baseurl, array('copy' => $mod->id)),
2059 $OUTPUT->pix_icon($pixicon, $str->move, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2060 array('class' => 'editing_move', 'data-action' => 'move', 'data-sectionreturn' => $sr)
2067 * given a course object with shortname & fullname, this function will
2068 * truncate the the number of chars allowed and add ... if it was too long
2070 function course_format_name ($course,$max=100) {
2072 $context = context_course::instance($course->id);
2073 $shortname = format_string($course->shortname, true, array('context' => $context));
2074 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
2075 $str = $shortname.': '. $fullname;
2076 if (core_text::strlen($str) <= $max) {
2080 return core_text::substr($str,0,$max-3).'...';
2085 * Is the user allowed to add this type of module to this course?
2086 * @param object $course the course settings. Only $course->id is used.
2087 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
2088 * @return bool whether the current user is allowed to add this type of module to this course.
2090 function course_allowed_module($course, $modname) {
2091 if (is_numeric($modname)) {
2092 throw new coding_exception('Function course_allowed_module no longer
2093 supports numeric module ids. Please update your code to pass the module name.');
2096 $capability = 'mod/' . $modname . ':addinstance';
2097 if (!get_capability_info($capability)) {
2098 // Debug warning that the capability does not exist, but no more than once per page.
2099 static $warned = array();
2100 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
2101 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
2102 debugging('The module ' . $modname . ' does not define the standard capability ' .
2103 $capability , DEBUG_DEVELOPER);
2104 $warned[$modname] = 1;
2107 // If the capability does not exist, the module can always be added.
2111 $coursecontext = context_course::instance($course->id);
2112 return has_capability($capability, $coursecontext);
2116 * Efficiently moves many courses around while maintaining
2117 * sortorder in order.
2119 * @param array $courseids is an array of course ids
2120 * @param int $categoryid
2121 * @return bool success
2123 function move_courses($courseids, $categoryid) {
2126 if (empty($courseids)) {
2131 if (!$category = $DB->get_record('course_categories', array('id' => $categoryid))) {
2135 $courseids = array_reverse($courseids);
2136 $newparent = context_coursecat::instance($category->id);
2139 list($where, $params) = $DB->get_in_or_equal($courseids);
2140 $dbcourses = $DB->get_records_select('course', 'id ' . $where, $params, '', 'id, category, shortname, fullname');
2141 foreach ($dbcourses as $dbcourse) {
2142 $course = new stdClass();
2143 $course->id = $dbcourse->id;
2144 $course->category = $category->id;
2145 $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
2146 if ($category->visible == 0) {
2147 // Hide the course when moving into hidden category, do not update the visibleold flag - we want to get
2148 // to previous state if somebody unhides the category.
2149 $course->visible = 0;
2152 $DB->update_record('course', $course);
2154 // Update context, so it can be passed to event.
2155 $context = context_course::instance($course->id);
2156 $context->update_moved($newparent);
2158 // Trigger a course updated event.
2159 $event = \core\event\course_updated::create(array(
2160 'objectid' => $course->id,
2161 'context' => context_course::instance($course->id),
2162 'other' => array('shortname' => $dbcourse->shortname,
2163 'fullname' => $dbcourse->fullname)
2165 $event->set_legacy_logdata(array($course->id, 'course', 'move', 'edit.php?id=' . $course->id, $course->id));
2168 fix_course_sortorder();
2169 cache_helper::purge_by_event('changesincourse');
2175 * Returns the display name of the given section that the course prefers
2177 * Implementation of this function is provided by course format
2178 * @see format_base::get_section_name()
2180 * @param int|stdClass $courseorid The course to get the section name for (object or just course id)
2181 * @param int|stdClass $section Section object from database or just field course_sections.section
2182 * @return string Display name that the course format prefers, e.g. "Week 2"
2184 function get_section_name($courseorid, $section) {
2185 return course_get_format($courseorid)->get_section_name($section);
2189 * Tells if current course format uses sections
2191 * @param string $format Course format ID e.g. 'weeks' $course->format
2194 function course_format_uses_sections($format) {
2195 $course = new stdClass();
2196 $course->format = $format;
2197 return course_get_format($course)->uses_sections();
2201 * Returns the information about the ajax support in the given source format
2203 * The returned object's property (boolean)capable indicates that
2204 * the course format supports Moodle course ajax features.
2206 * @param string $format
2209 function course_format_ajax_support($format) {
2210 $course = new stdClass();
2211 $course->format = $format;
2212 return course_get_format($course)->supports_ajax();
2216 * Can the current user delete this course?
2217 * Course creators have exception,
2218 * 1 day after the creation they can sill delete the course.
2219 * @param int $courseid
2222 function can_delete_course($courseid) {
2225 $context = context_course::instance($courseid);
2227 if (has_capability('moodle/course:delete', $context)) {
2231 // hack: now try to find out if creator created this course recently (1 day)
2232 if (!has_capability('moodle/course:create', $context)) {
2236 $since = time() - 60*60*24;
2237 $course = get_course($courseid);
2239 if ($course->timecreated < $since) {
2240 return false; // Return if the course was not created in last 24 hours.
2243 $logmanger = get_log_manager();
2244 $readers = $logmanger->get_readers('\core\log\sql_reader');
2245 $reader = reset($readers);
2247 if (empty($reader)) {
2248 return false; // No log reader found.
2252 $select = "userid = :userid AND courseid = :courseid AND eventname = :eventname AND timecreated > :since";
2253 $params = array('userid' => $USER->id, 'since' => $since, 'courseid' => $course->id, 'eventname' => '\core\event\course_created');
2255 return (bool)$reader->get_events_select_count($select, $params);
2259 * Save the Your name for 'Some role' strings.
2261 * @param integer $courseid the id of this course.
2262 * @param array $data the data that came from the course settings form.
2264 function save_local_role_names($courseid, $data) {
2266 $context = context_course::instance($courseid);
2268 foreach ($data as $fieldname => $value) {
2269 if (strpos($fieldname, 'role_') !== 0) {
2272 list($ignored, $roleid) = explode('_', $fieldname);
2274 // make up our mind whether we want to delete, update or insert
2276 $DB->delete_records('role_names', array('contextid' => $context->id, 'roleid' => $roleid));
2278 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id, 'roleid' => $roleid))) {
2279 $rolename->name = $value;
2280 $DB->update_record('role_names', $rolename);
2283 $rolename = new stdClass;
2284 $rolename->contextid = $context->id;
2285 $rolename->roleid = $roleid;
2286 $rolename->name = $value;
2287 $DB->insert_record('role_names', $rolename);
2289 // This will ensure the course contacts cache is purged..
2290 coursecat::role_assignment_changed($roleid, $context);
2295 * Returns options to use in course overviewfiles filemanager
2297 * @param null|stdClass|course_in_list|int $course either object that has 'id' property or just the course id;
2298 * may be empty if course does not exist yet (course create form)
2299 * @return array|null array of options such as maxfiles, maxbytes, accepted_types, etc.
2300 * or null if overviewfiles are disabled
2302 function course_overviewfiles_options($course) {
2304 if (empty($CFG->courseoverviewfileslimit)) {
2307 $accepted_types = preg_split('/\s*,\s*/', trim($CFG->courseoverviewfilesext), -1, PREG_SPLIT_NO_EMPTY);
2308 if (in_array('*', $accepted_types) || empty($accepted_types)) {
2309 $accepted_types = '*';
2311 // Since config for $CFG->courseoverviewfilesext is a text box, human factor must be considered.
2312 // Make sure extensions are prefixed with dot unless they are valid typegroups
2313 foreach ($accepted_types as $i => $type) {
2314 if (substr($type, 0, 1) !== '.') {
2315 require_once($CFG->libdir. '/filelib.php');
2316 if (!count(file_get_typegroup('extension', $type))) {
2317 // It does not start with dot and is not a valid typegroup, this is most likely extension.
2318 $accepted_types[$i] = '.'. $type;
2323 if (!empty($corrected)) {
2324 set_config('courseoverviewfilesext', join(',', $accepted_types));
2328 'maxfiles' => $CFG->courseoverviewfileslimit,
2329 'maxbytes' => $CFG->maxbytes,
2331 'accepted_types' => $accepted_types
2333 if (!empty($course->id)) {
2334 $options['context'] = context_course::instance($course->id);
2335 } else if (is_int($course) && $course > 0) {
2336 $options['context'] = context_course::instance($course);
2342 * Create a course and either return a $course object
2344 * Please note this functions does not verify any access control,
2345 * the calling code is responsible for all validation (usually it is the form definition).
2347 * @param array $editoroptions course description editor options
2348 * @param object $data - all the data needed for an entry in the 'course' table
2349 * @return object new course instance
2351 function create_course($data, $editoroptions = NULL) {
2354 //check the categoryid - must be given for all new courses
2355 $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
2357 // Check if the shortname already exists.
2358 if (!empty($data->shortname)) {
2359 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
2360 throw new moodle_exception('shortnametaken', '', '', $data->shortname);
2364 // Check if the idnumber already exists.
2365 if (!empty($data->idnumber)) {
2366 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
2367 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber);
2371 if ($errorcode = course_validate_dates((array)$data)) {
2372 throw new moodle_exception($errorcode);
2375 // Check if timecreated is given.
2376 $data->timecreated = !empty($data->timecreated) ? $data->timecreated : time();
2377 $data->timemodified = $data->timecreated;
2379 // place at beginning of any category
2380 $data->sortorder = 0;
2382 if ($editoroptions) {
2383 // summary text is updated later, we need context to store the files first
2384 $data->summary = '';
2385 $data->summary_format = FORMAT_HTML;
2388 if (!isset($data->visible)) {
2389 // data not from form, add missing visibility info
2390 $data->visible = $category->visible;
2392 $data->visibleold = $data->visible;
2394 $newcourseid = $DB->insert_record('course', $data);
2395 $context = context_course::instance($newcourseid, MUST_EXIST);
2397 if ($editoroptions) {
2398 // Save the files used in the summary editor and store
2399 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2400 $DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid));
2401 $DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid));
2403 if ($overviewfilesoptions = course_overviewfiles_options($newcourseid)) {
2404 // Save the course overviewfiles
2405 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2408 // update course format options
2409 course_get_format($newcourseid)->update_course_format_options($data);
2411 $course = course_get_format($newcourseid)->get_course();
2413 fix_course_sortorder();
2414 // purge appropriate caches in case fix_course_sortorder() did not change anything
2415 cache_helper::purge_by_event('changesincourse');
2417 // new context created - better mark it as dirty
2418 $context->mark_dirty();
2420 // Trigger a course created event.
2421 $event = \core\event\course_created::create(array(
2422 'objectid' => $course->id,
2423 'context' => context_course::instance($course->id),
2424 'other' => array('shortname' => $course->shortname,
2425 'fullname' => $course->fullname)
2431 blocks_add_default_course_blocks($course);
2433 // Create default section and initial sections if specified (unless they've already been created earlier).
2434 // We do not want to call course_create_sections_if_missing() because to avoid creating course cache.
2435 $numsections = isset($data->numsections) ? $data->numsections : 0;
2436 $existingsections = $DB->get_fieldset_sql('SELECT section from {course_sections} WHERE course = ?', [$newcourseid]);
2437 $newsections = array_diff(range(0, $numsections), $existingsections);
2438 foreach ($newsections as $sectionnum) {
2439 course_create_section($newcourseid, $sectionnum, true);
2442 // Save any custom role names.
2443 save_local_role_names($course->id, (array)$data);
2445 // set up enrolments
2446 enrol_course_updated(true, $course, $data);
2448 // Update course tags.
2449 if (isset($data->tags)) {
2450 core_tag_tag::set_item_tags('core', 'course', $course->id, context_course::instance($course->id), $data->tags);
2459 * Please note this functions does not verify any access control,
2460 * the calling code is responsible for all validation (usually it is the form definition).
2462 * @param object $data - all the data needed for an entry in the 'course' table
2463 * @param array $editoroptions course description editor options
2466 function update_course($data, $editoroptions = NULL) {
2469 $data->timemodified = time();
2471 // Prevent changes on front page course.
2472 if ($data->id == SITEID) {
2473 throw new moodle_exception('invalidcourse', 'error');
2476 $oldcourse = course_get_format($data->id)->get_course();
2477 $context = context_course::instance($oldcourse->id);
2479 if ($editoroptions) {
2480 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2482 if ($overviewfilesoptions = course_overviewfiles_options($data->id)) {
2483 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2486 // Check we don't have a duplicate shortname.
2487 if (!empty($data->shortname) && $oldcourse->shortname != $data->shortname) {
2488 if ($DB->record_exists_sql('SELECT id from {course} WHERE shortname = ? AND id <> ?', array($data->shortname, $data->id))) {
2489 throw new moodle_exception('shortnametaken', '', '', $data->shortname);
2493 // Check we don't have a duplicate idnumber.
2494 if (!empty($data->idnumber) && $oldcourse->idnumber != $data->idnumber) {
2495 if ($DB->record_exists_sql('SELECT id from {course} WHERE idnumber = ? AND id <> ?', array($data->idnumber, $data->id))) {
2496 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber);
2500 if ($errorcode = course_validate_dates((array)$data)) {
2501 throw new moodle_exception($errorcode);
2504 if (!isset($data->category) or empty($data->category)) {
2505 // prevent nulls and 0 in category field
2506 unset($data->category);
2508 $changesincoursecat = $movecat = (isset($data->category) and $oldcourse->category != $data->category);
2510 if (!isset($data->visible)) {
2511 // data not from form, add missing visibility info
2512 $data->visible = $oldcourse->visible;
2515 if ($data->visible != $oldcourse->visible) {
2516 // reset the visibleold flag when manually hiding/unhiding course
2517 $data->visibleold = $data->visible;
2518 $changesincoursecat = true;
2521 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category));
2522 if (empty($newcategory->visible)) {
2523 // make sure when moving into hidden category the course is hidden automatically
2529 // Set newsitems to 0 if format does not support announcements.
2530 if (isset($data->format)) {
2531 $newcourseformat = course_get_format((object)['format' => $data->format]);
2532 if (!$newcourseformat->supports_news()) {
2533 $data->newsitems = 0;
2537 // Update with the new data
2538 $DB->update_record('course', $data);
2539 // make sure the modinfo cache is reset
2540 rebuild_course_cache($data->id);
2542 // update course format options with full course data
2543 course_get_format($data->id)->update_course_format_options($data, $oldcourse);
2545 $course = $DB->get_record('course', array('id'=>$data->id));
2548 $newparent = context_coursecat::instance($course->category);
2549 $context->update_moved($newparent);
2551 $fixcoursesortorder = $movecat || (isset($data->sortorder) && ($oldcourse->sortorder != $data->sortorder));
2552 if ($fixcoursesortorder) {
2553 fix_course_sortorder();
2556 // purge appropriate caches in case fix_course_sortorder() did not change anything
2557 cache_helper::purge_by_event('changesincourse');
2558 if ($changesincoursecat) {
2559 cache_helper::purge_by_event('changesincoursecat');
2562 // Test for and remove blocks which aren't appropriate anymore
2563 blocks_remove_inappropriate($course);
2565 // Save any custom role names.
2566 save_local_role_names($course->id, $data);
2568 // update enrol settings
2569 enrol_course_updated(false, $course, $data);
2571 // Update course tags.
2572 if (isset($data->tags)) {
2573 core_tag_tag::set_item_tags('core', 'course', $course->id, context_course::instance($course->id), $data->tags);
2576 // Trigger a course updated event.
2577 $event = \core\event\course_updated::create(array(
2578 'objectid' => $course->id,
2579 'context' => context_course::instance($course->id),
2580 'other' => array('shortname' => $course->shortname,
2581 'fullname' => $course->fullname)
2584 $event->set_legacy_logdata(array($course->id, 'course', 'update', 'edit.php?id=' . $course->id, $course->id));
2587 if ($oldcourse->format !== $course->format) {
2588 // Remove all options stored for the previous format
2589 // We assume that new course format migrated everything it needed watching trigger
2590 // 'course_updated' and in method format_XXX::update_course_format_options()
2591 $DB->delete_records('course_format_options',
2592 array('courseid' => $course->id, 'format' => $oldcourse->format));
2597 * Average number of participants
2600 function average_number_of_participants() {
2603 //count total of enrolments for visible course (except front page)
2604 $sql = 'SELECT COUNT(*) FROM (
2605 SELECT DISTINCT ue.userid, e.courseid
2606 FROM {user_enrolments} ue, {enrol} e, {course} c
2607 WHERE ue.enrolid = e.id
2608 AND e.courseid <> :siteid
2609 AND c.id = e.courseid
2610 AND c.visible = 1) total';
2611 $params = array('siteid' => $SITE->id);
2612 $enrolmenttotal = $DB->count_records_sql($sql, $params);
2615 //count total of visible courses (minus front page)
2616 $coursetotal = $DB->count_records('course', array('visible' => 1));
2617 $coursetotal = $coursetotal - 1 ;
2619 //average of enrolment
2620 if (empty($coursetotal)) {
2621 $participantaverage = 0;
2623 $participantaverage = $enrolmenttotal / $coursetotal;
2626 return $participantaverage;
2630 * Average number of course modules
2633 function average_number_of_courses_modules() {
2636 //count total of visible course module (except front page)
2637 $sql = 'SELECT COUNT(*) FROM (
2638 SELECT cm.course, cm.module
2639 FROM {course} c, {course_modules} cm
2640 WHERE c.id = cm.course
2643 AND c.visible = 1) total';
2644 $params = array('siteid' => $SITE->id);
2645 $moduletotal = $DB->count_records_sql($sql, $params);
2648 //count total of visible courses (minus front page)
2649 $coursetotal = $DB->count_records('course', array('visible' => 1));
2650 $coursetotal = $coursetotal - 1 ;
2652 //average of course module
2653 if (empty($coursetotal)) {
2654 $coursemoduleaverage = 0;
2656 $coursemoduleaverage = $moduletotal / $coursetotal;
2659 return $coursemoduleaverage;
2663 * This class pertains to course requests and contains methods associated with
2664 * create, approving, and removing course requests.
2666 * Please note we do not allow embedded images here because there is no context
2667 * to store them with proper access control.
2669 * @copyright 2009 Sam Hemelryk
2670 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2673 * @property-read int $id
2674 * @property-read string $fullname
2675 * @property-read string $shortname
2676 * @property-read string $summary
2677 * @property-read int $summaryformat
2678 * @property-read int $summarytrust
2679 * @property-read string $reason
2680 * @property-read int $requester
2682 class course_request {
2685 * This is the stdClass that stores the properties for the course request
2686 * and is externally accessed through the __get magic method
2689 protected $properties;
2692 * An array of options for the summary editor used by course request forms.
2693 * This is initially set by {@link summary_editor_options()}
2697 protected static $summaryeditoroptions;
2700 * Static function to prepare the summary editor for working with a course
2704 * @param null|stdClass $data Optional, an object containing the default values
2705 * for the form, these may be modified when preparing the
2706 * editor so this should be called before creating the form
2707 * @return stdClass An object that can be used to set the default values for
2710 public static function prepare($data=null) {
2711 if ($data === null) {
2712 $data = new stdClass;
2714 $data = file_prepare_standard_editor($data, 'summary', self::summary_editor_options());
2719 * Static function to create a new course request when passed an array of properties
2722 * This function also handles saving any files that may have been used in the editor
2725 * @param stdClass $data
2726 * @return course_request The newly created course request
2728 public static function create($data) {
2729 global $USER, $DB, $CFG;
2730 $data->requester = $USER->id;
2732 // Setting the default category if none set.
2733 if (empty($data->category) || empty($CFG->requestcategoryselection)) {
2734 $data->category = $CFG->defaultrequestcategory;
2737 // Summary is a required field so copy the text over
2738 $data->summary = $data->summary_editor['text'];
2739 $data->summaryformat = $data->summary_editor['format'];
2741 $data->id = $DB->insert_record('course_request', $data);
2743 // Create a new course_request object and return it
2744 $request = new course_request($data);
2746 // Notify the admin if required.
2747 if ($users = get_users_from_config($CFG->courserequestnotify, 'moodle/site:approvecourse')) {
2750 $a->link = "$CFG->wwwroot/course/pending.php";
2751 $a->user = fullname($USER);
2752 $subject = get_string('courserequest');
2753 $message = get_string('courserequestnotifyemail', 'admin', $a);
2754 foreach ($users as $user) {
2755 $request->notify($user, $USER, 'courserequested', $subject, $message);
2763 * Returns an array of options to use with a summary editor
2765 * @uses course_request::$summaryeditoroptions
2766 * @return array An array of options to use with the editor
2768 public static function summary_editor_options() {
2770 if (self::$summaryeditoroptions === null) {
2771 self::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
2773 return self::$summaryeditoroptions;
2777 * Loads the properties for this course request object. Id is required and if
2778 * only id is provided then we load the rest of the properties from the database
2780 * @param stdClass|int $properties Either an object containing properties
2781 * or the course_request id to load
2783 public function __construct($properties) {
2785 if (empty($properties->id)) {
2786 if (empty($properties)) {
2787 throw new coding_exception('You must provide a course request id when creating a course_request object');
2790 $properties = new stdClass;
2791 $properties->id = (int)$id;
2794 if (empty($properties->requester)) {
2795 if (!($this->properties = $DB->get_record('course_request', array('id' => $properties->id)))) {
2796 print_error('unknowncourserequest');
2799 $this->properties = $properties;
2801 $this->properties->collision = null;
2805 * Returns the requested property
2807 * @param string $key
2810 public function __get($key) {
2811 return $this->properties->$key;
2815 * Override this to ensure empty($request->blah) calls return a reliable answer...
2817 * This is required because we define the __get method
2820 * @return bool True is it not empty, false otherwise
2822 public function __isset($key) {
2823 return (!empty($this->properties->$key));
2827 * Returns the user who requested this course
2829 * Uses a static var to cache the results and cut down the number of db queries
2831 * @staticvar array $requesters An array of cached users
2832 * @return stdClass The user who requested the course
2834 public function get_requester() {
2836 static $requesters= array();
2837 if (!array_key_exists($this->properties->requester, $requesters)) {
2838 $requesters[$this->properties->requester] = $DB->get_record('user', array('id'=>$this->properties->requester));
2840 return $requesters[$this->properties->requester];
2844 * Checks that the shortname used by the course does not conflict with any other
2845 * courses that exist
2847 * @param string|null $shortnamemark The string to append to the requests shortname
2848 * should a conflict be found
2849 * @return bool true is there is a conflict, false otherwise
2851 public function check_shortname_collision($shortnamemark = '[*]') {
2854 if ($this->properties->collision !== null) {
2855 return $this->properties->collision;
2858 if (empty($this->properties->shortname)) {
2859 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER);
2860 $this->properties->collision = false;
2861 } else if ($DB->record_exists('course', array('shortname' => $this->properties->shortname))) {
2862 if (!empty($shortnamemark)) {
2863 $this->properties->shortname .= ' '.$shortnamemark;
2865 $this->properties->collision = true;
2867 $this->properties->collision = false;
2869 return $this->properties->collision;
2873 * Returns the category where this course request should be created
2875 * Note that we don't check here that user has a capability to view
2876 * hidden categories if he has capabilities 'moodle/site:approvecourse' and
2877 * 'moodle/course:changecategory'
2881 public function get_category() {
2883 require_once($CFG->libdir.'/coursecatlib.php');
2884 // If the category is not set, if the current user does not have the rights to change the category, or if the
2885 // category does not exist, we set the default category to the course to be approved.
2886 // The system level is used because the capability moodle/site:approvecourse is based on a system level.
2887 if (empty($this->properties->category) || !has_capability('moodle/course:changecategory', context_system::instance()) ||
2888 (!$category = coursecat::get($this->properties->category, IGNORE_MISSING, true))) {
2889 $category = coursecat::get($CFG->defaultrequestcategory, IGNORE_MISSING, true);
2892 $category = coursecat::get_default();
2898 * This function approves the request turning it into a course
2900 * This function converts the course request into a course, at the same time
2901 * transferring any files used in the summary to the new course and then removing
2902 * the course request and the files associated with it.
2904 * @return int The id of the course that was created from this request
2906 public function approve() {
2907 global $CFG, $DB, $USER;
2909 $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted'=>0), '*', MUST_EXIST);
2911 $courseconfig = get_config('moodlecourse');
2913 // Transfer appropriate settings
2914 $data = clone($this->properties);
2916 unset($data->reason);
2917 unset($data->requester);
2920 $category = $this->get_category();
2921 $data->category = $category->id;
2922 // Set misc settings
2923 $data->requested = 1;
2925 // Apply course default settings
2926 $data->format = $courseconfig->format;
2927 $data->newsitems = $courseconfig->newsitems;
2928 $data->showgrades = $courseconfig->showgrades;
2929 $data->showreports = $courseconfig->showreports;
2930 $data->maxbytes = $courseconfig->maxbytes;
2931 $data->groupmode = $courseconfig->groupmode;
2932 $data->groupmodeforce = $courseconfig->groupmodeforce;
2933 $data->visible = $courseconfig->visible;
2934 $data->visibleold = $data->visible;
2935 $data->lang = $courseconfig->lang;
2936 $data->enablecompletion = $courseconfig->enablecompletion;
2938 $course = create_course($data);
2939 $context = context_course::instance($course->id, MUST_EXIST);
2941 // add enrol instances
2942 if (!$DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
2943 if ($manual = enrol_get_plugin('manual')) {
2944 $manual->add_default_instance($course);
2948 // enrol the requester as teacher if necessary
2949 if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
2950 enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid);
2955 $a = new stdClass();
2956 $a->name = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
2957 $a->url = $CFG->wwwroot.'/course/view.php?id=' . $course->id;
2958 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a), $course->id);
2964 * Reject a course request
2966 * This function rejects a course request, emailing the requesting user the
2967 * provided notice and then removing the request from the database
2969 * @param string $notice The message to display to the user
2971 public function reject($notice) {
2973 $user = $DB->get_record('user', array('id' => $this->properties->requester), '*', MUST_EXIST);
2974 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
2979 * Deletes the course request and any associated files
2981 public function delete() {
2983 $DB->delete_records('course_request', array('id' => $this->properties->id));
2987 * Send a message from one user to another using events_trigger
2989 * @param object $touser
2990 * @param object $fromuser
2991 * @param string $name
2992 * @param string $subject
2993 * @param string $message
2994 * @param int|null $courseid
2996 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message, $courseid = null) {
2997 $eventdata = new \core\message\message();
2998 $eventdata->courseid = empty($courseid) ? SITEID : $courseid;
2999 $eventdata->component = 'moodle';
3000 $eventdata->name = $name;
3001 $eventdata->userfrom = $fromuser;
3002 $eventdata->userto = $touser;
3003 $eventdata->subject = $subject;
3004 $eventdata->fullmessage = $message;
3005 $eventdata->fullmessageformat = FORMAT_PLAIN;
3006 $eventdata->fullmessagehtml = '';
3007 $eventdata->smallmessage = '';
3008 $eventdata->notification = 1;
3009 message_send($eventdata);
3014 * Return a list of page types
3015 * @param string $pagetype current page type
3016 * @param context $parentcontext Block's parent context
3017 * @param context $currentcontext Current context of block
3018 * @return array array of page types
3020 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
3021 if ($pagetype === 'course-index' || $pagetype === 'course-index-category') {
3022 // For courses and categories browsing pages (/course/index.php) add option to show on ANY category page
3023 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
3024 'course-index-*' => get_string('page-course-index-x', 'pagetype'),
3026 } else if ($currentcontext && (!($coursecontext = $currentcontext->get_course_context(false)) || $coursecontext->instanceid == SITEID)) {
3027 // We know for sure that despite pagetype starts with 'course-' this is not a page in course context (i.e. /course/search.php, etc.)
3028 $pagetypes = array('*' => get_string('page-x', 'pagetype'));
3030 // Otherwise consider it a page inside a course even if $currentcontext is null
3031 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
3032 'course-*' => get_string('page-course-x', 'pagetype'),
3033 'course-view-*' => get_string('page-course-view-x', 'pagetype')
3040 * Determine whether course ajax should be enabled for the specified course
3042 * @param stdClass $course The course to test against
3043 * @return boolean Whether course ajax is enabled or note
3045 function course_ajax_enabled($course) {
3046 global $CFG, $PAGE, $SITE;
3048 // The user must be editing for AJAX to be included
3049 if (!$PAGE->user_is_editing()) {
3053 // Check that the theme suports
3054 if (!$PAGE->theme->enablecourseajax) {
3058 // Check that the course format supports ajax functionality
3059 // The site 'format' doesn't have information on course format support
3060 if ($SITE->id !== $course->id) {
3061 $courseformatajaxsupport = course_format_ajax_support($course->format);
3062 if (!$courseformatajaxsupport->capable) {
3067 // All conditions have been met so course ajax should be enabled
3072 * Include the relevant javascript and language strings for the resource
3073 * toolbox YUI module
3075 * @param integer $id The ID of the course being applied to
3076 * @param array $usedmodules An array containing the names of the modules in use on the page
3077 * @param array $enabledmodules An array containing the names of the enabled (visible) modules on this site
3078 * @param stdClass $config An object containing configuration parameters for ajax modules including:
3079 * * resourceurl The URL to post changes to for resource changes
3080 * * sectionurl The URL to post changes to for section changes
3081 * * pageparams Additional parameters to pass through in the post
3084 function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) {
3085 global $CFG, $PAGE, $SITE;
3087 // Ensure that ajax should be included
3088 if (!course_ajax_enabled($course)) {
3093 $config = new stdClass();
3096 // The URL to use for resource changes
3097 if (!isset($config->resourceurl)) {
3098 $config->resourceurl = '/course/rest.php';
3101 // The URL to use for section changes
3102 if (!isset($config->sectionurl)) {
3103 $config->sectionurl = '/course/rest.php';
3106 // Any additional parameters which need to be included on page submission
3107 if (!isset($config->pageparams)) {
3108 $config->pageparams = array();
3111 // Include course dragdrop
3112 if (course_format_uses_sections($course->format)) {
3113 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_section_dragdrop',
3115 'courseid' => $course->id,
3116 'ajaxurl' => $config->sectionurl,
3117 'config' => $config,
3120 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_resource_dragdrop',
3122 'courseid' => $course->id,
3123 'ajaxurl' => $config->resourceurl,
3124 'config' => $config,
3128 // Require various strings for the command toolbox
3129 $PAGE->requires->strings_for_js(array(
3132 'deletechecktypename',
3134 'edittitleinstructions',
3142 'clicktochangeinbrackets',
3147 'movecoursesection',
3150 'emptydragdropregion',
3156 // Include section-specific strings for formats which support sections.
3157 if (course_format_uses_sections($course->format)) {
3158 $PAGE->requires->strings_for_js(array(
3161 ), 'format_' . $course->format);
3164 // For confirming resource deletion we need the name of the module in question
3165 foreach ($usedmodules as $module => $modname) {
3166 $PAGE->requires->string_for_js('pluginname', $module);
3169 // Load drag and drop upload AJAX.
3170 require_once($CFG->dirroot.'/course/dnduploadlib.php');
3171 dndupload_add_to_course($course, $enabledmodules);
3173 $PAGE->requires->js_call_amd('core_course/actions', 'initCoursePage', array($course->format));
3179 * Returns the sorted list of available course formats, filtered by enabled if necessary
3181 * @param bool $enabledonly return only formats that are enabled
3182 * @return array array of sorted format names
3184 function get_sorted_course_formats($enabledonly = false) {
3186 $formats = core_component::get_plugin_list('format');
3188 if (!empty($CFG->format_plugins_sortorder)) {
3189 $order = explode(',', $CFG->format_plugins_sortorder);
3190 $order = array_merge(array_intersect($order, array_keys($formats)),
3191 array_diff(array_keys($formats), $order));
3193 $order = array_keys($formats);
3195 if (!$enabledonly) {
3198 $sortedformats = array();
3199 foreach ($order as $formatname) {
3200 if (!get_config('format_'.$formatname, 'disabled')) {
3201 $sortedformats[] = $formatname;
3204 return $sortedformats;
3208 * The URL to use for the specified course (with section)
3210 * @param int|stdClass $courseorid The course to get the section name for (either object or just course id)
3211 * @param int|stdClass $section Section object from database or just field course_sections.section
3212 * if omitted the course view page is returned
3213 * @param array $options options for view URL. At the moment core uses:
3214 * 'navigation' (bool) if true and section has no separate page, the function returns null
3215 * 'sr' (int) used by multipage formats to specify to which section to return
3216 * @return moodle_url The url of course
3218 function course_get_url($courseorid, $section = null, $options = array()) {
3219 return course_get_format($courseorid)->get_view_url($section, $options);
3226 * - capability checks and other checks
3227 * - create the module from the module info
3229 * @param object $module
3230 * @return object the created module info
3231 * @throws moodle_exception if user is not allowed to perform the action or module is not allowed in this course
3233 function create_module($moduleinfo) {
3236 require_once($CFG->dirroot . '/course/modlib.php');
3238 // Check manadatory attributs.
3239 $mandatoryfields = array('modulename', 'course', 'section', 'visible');
3240 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
3241 $mandatoryfields[] = 'introeditor';
3243 foreach($mandatoryfields as $mandatoryfield) {
3244 if (!isset($moduleinfo->{$mandatoryfield})) {
3245 throw new moodle_exception('createmodulemissingattribut', '', '', $mandatoryfield);
3249 // Some additional checks (capability / existing instances).
3250 $course = $DB->get_record('course', array('id'=>$moduleinfo->course), '*', MUST_EXIST);
3251 list($module, $context, $cw) = can_add_moduleinfo($course, $moduleinfo->modulename, $moduleinfo->section);
3254 $moduleinfo->module = $module->id;
3255 $moduleinfo = add_moduleinfo($moduleinfo, $course, null);
3264 * - capability and other checks
3265 * - update the module
3267 * @param object $module
3268 * @return object the updated module info
3269 * @throws moodle_exception if current user is not allowed to update the module
3271 function update_module($moduleinfo) {
3274 require_once($CFG->dirroot . '/course/modlib.php');
3276 // Check the course module exists.
3277 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule, 0, false, MUST_EXIST);
3279 // Check the course exists.
3280 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
3282 // Some checks (capaibility / existing instances).
3283 list($cm, $context, $module, $data, $cw) = can_update_moduleinfo($cm);
3285 // Retrieve few information needed by update_moduleinfo.
3286 $moduleinfo->modulename = $cm->modname;
3287 if (!isset($moduleinfo->scale)) {
3288 $moduleinfo->scale = 0;
3290 $moduleinfo->type = 'mod';
3292 // Update the module.
3293 list($cm, $moduleinfo) = update_moduleinfo($cm, $moduleinfo, $course, null);
3299 * Duplicate a module on the course for ajax.
3301 * @see mod_duplicate_module()
3302 * @param object $course The course
3303 * @param object $cm The course module to duplicate
3304 * @param int $sr The section to link back to (used for creating the links)
3305 * @throws moodle_exception if the plugin doesn't support duplication
3306 * @return Object containing:
3307 * - fullcontent: The HTML markup for the created CM
3308 * - cmid: The CMID of the newly created CM
3309 * - redirect: Whether to trigger a redirect following this change
3311 function mod_duplicate_activity($course, $cm, $sr = null) {
3314 $newcm = duplicate_module($course, $cm);
3316 $resp = new stdClass();
3318 $courserenderer = $PAGE->get_renderer('core', 'course');
3319 $completioninfo = new completion_info($course);
3320 $modulehtml = $courserenderer->course_section_cm($course, $completioninfo,
3321 $newcm, null, array());
3323 $resp->fullcontent = $courserenderer->course_section_cm_list_item($course, $completioninfo, $newcm, $sr);
3324 $resp->cmid = $newcm->id;
3326 // Trigger a redirect.
3327 $resp->redirect = true;
3333 * Api to duplicate a module.
3335 * @param object $course course object.
3336 * @param object $cm course module object to be duplicated.
3340 * @throws coding_exception
3341 * @throws moodle_exception
3342 * @throws restore_controller_exception
3344 * @return cm_info|null cminfo object if we sucessfully duplicated the mod and found the new cm.
3346 function duplicate_module($course, $cm) {
3347 global $CFG, $DB, $USER;
3348 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
3349 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
3350 require_once($CFG->libdir . '/filelib.php');
3352 $a = new stdClass();
3353 $a->modtype = get_string('modulename', $cm->modname);
3354 $a->modname = format_string($cm->name);
3356 if (!plugin_supports('mod', $cm->modname, FEATURE_BACKUP_MOODLE2)) {
3357 throw new moodle_exception('duplicatenosupport', 'error', '', $a);
3360 // Backup the activity.
3362 $bc = new backup_controller(backup::TYPE_1ACTIVITY, $cm->id, backup::FORMAT_MOODLE,
3363 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
3365 $backupid = $bc->get_backupid();
3366 $backupbasepath = $bc->get_plan()->get_basepath();
3368 $bc->execute_plan();
3372 // Restore the backup immediately.
3374 $rc = new restore_controller($backupid, $course->id,
3375 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, backup::TARGET_CURRENT_ADDING);
3377 $cmcontext = context_module::instance($cm->id);
3378 if (!$rc->execute_precheck()) {
3379 $precheckresults = $rc->get_precheck_results();
3380 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
3381 if (empty($CFG->keeptempdirectoriesonbackup)) {
3382 fulldelete($backupbasepath);
3387 $rc->execute_plan();
3389 // Now a bit hacky part follows - we try to get the cmid of the newly
3390 // restored copy of the module.
3392 $tasks = $rc->get_plan()->get_tasks();
3393 foreach ($tasks as $task) {
3394 if (is_subclass_of($task, 'restore_activity_task')) {
3395 if ($task->get_old_contextid() == $cmcontext->id) {
3396 $newcmid = $task->get_moduleid();
3402 // If we know the cmid of the new course module, let us move it
3403 // right below the original one. otherwise it will stay at the
3404 // end of the section.
3406 $info = get_fast_modinfo($course);
3407 $newcm = $info->get_cm($newcmid);
3408 $section = $DB->get_record('course_sections', array('id' => $cm->section, 'course' => $cm->course));
3409 moveto_module($newcm, $section, $cm);
3410 moveto_module($cm, $section, $newcm);
3412 // Update calendar events with the duplicated module.
3413 $refresheventsfunction = $newcm->modname . '_refresh_events';
3414 if (function_exists($refresheventsfunction)) {
3415 call_user_func($refresheventsfunction, $newcm->course);
3418 // Trigger course module created event. We can trigger the event only if we know the newcmid.
3419 $event = \core\event\course_module_created::create_from_cm($newcm);
3422 rebuild_course_cache($cm->course);
3426 if (empty($CFG->keeptempdirectoriesonbackup)) {
3427 fulldelete($backupbasepath);
3430 return isset($newcm) ? $newcm : null;
3434 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3435 * Sorts by descending order of time.
3437 * @param stdClass $a First object
3438 * @param stdClass $b Second object
3439 * @return int 0,1,-1 representing the order
3441 function compare_activities_by_time_desc($a, $b) {
3442 // Make sure the activities actually have a timestamp property.
3443 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3446 // We treat instances without timestamp as if they have a timestamp of 0.
3447 if ((!property_exists($a, 'timestamp')) && (property_exists($b,'timestamp'))) {
3450 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3453 if ($a->timestamp == $b->timestamp) {
3456 return ($a->timestamp > $b->timestamp) ? -1 : 1;
3460 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3461 * Sorts by ascending order of time.
3463 * @param stdClass $a First object
3464 * @param stdClass $b Second object
3465 * @return int 0,1,-1 representing the order
3467 function compare_activities_by_time_asc($a, $b) {
3468 // Make sure the activities actually have a timestamp property.
3469 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3472 // We treat instances without timestamp as if they have a timestamp of 0.
3473 if ((!property_exists($a, 'timestamp')) && (property_exists($b, 'timestamp'))) {
3476 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3479 if ($a->timestamp == $b->timestamp) {
3482 return ($a->timestamp < $b->timestamp) ? -1 : 1;
3486 * Changes the visibility of a course.
3488 * @param int $courseid The course to change.
3489 * @param bool $show True to make it visible, false otherwise.
3492 function course_change_visibility($courseid, $show = true) {
3493 $course = new stdClass;
3494 $course->id = $courseid;
3495 $course->visible = ($show) ? '1' : '0';
3496 $course->visibleold = $course->visible;
3497 update_course($course);
3502 * Changes the course sortorder by one, moving it up or down one in respect to sort order.
3504 * @param stdClass|course_in_list $course
3505 * @param bool $up If set to true the course will be moved up one. Otherwise down one.
3508 function course_change_sortorder_by_one($course, $up) {
3510 $params = array($course->sortorder, $course->category);
3512 $select = 'sortorder < ? AND category = ?';
3513 $sort = 'sortorder DESC';
3515 $select = 'sortorder > ? AND category = ?';
3516 $sort = 'sortorder ASC';
3518 fix_course_sortorder();
3519 $swapcourse = $DB->get_records_select('course', $select, $params, $sort, '*', 0, 1);
3521 $swapcourse = reset($swapcourse);
3522 $DB->set_field('course', 'sortorder', $swapcourse->sortorder, array('id' => $course->id));
3523 $DB->set_field('course', 'sortorder', $course->sortorder, array('id' => $swapcourse->id));
3524 // Finally reorder courses.
3525 fix_course_sortorder();
3526 cache_helper::purge_by_event('changesincourse');
3533 * Changes the sort order of courses in a category so that the first course appears after the second.
3535 * @param int|stdClass $courseorid The course to focus on.
3536 * @param int $moveaftercourseid The course to shifter after or 0 if you want it to be the first course in the category.
3539 function course_change_sortorder_after_course($courseorid, $moveaftercourseid) {
3542 if (!is_object($courseorid)) {
3543 $course = get_course($courseorid);
3545 $course = $courseorid;
3548 if ((int)$moveaftercourseid === 0) {
3549 // We've moving the course to the start of the queue.
3550 $sql = 'SELECT sortorder
3552 WHERE category = :categoryid
3553 ORDER BY sortorder';
3555 'categoryid' => $course->category
3557 $sortorder = $DB->get_field_sql($sql, $params, IGNORE_MULTIPLE);
3559 $sql = 'UPDATE {course}
3560 SET sortorder = sortorder + 1
3561 WHERE category = :categoryid
3564 'categoryid' => $course->category,
3565 'id' => $course->id,
3567 $DB->execute($sql, $params);
3568 $DB->set_field('course', 'sortorder', $sortorder, array('id' => $course->id));
3569 } else if ($course->id === $moveaftercourseid) {
3570 // They're the same - moronic.
3571 debugging("Invalid move after&