MDL-61410 question: support course tags on export
[moodle.git] / course / lib.php
blobb2d0b1d3551fb5a1856ffde0bfa70c81c990edb0
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Library of useful functions
20 * @copyright 1999 Martin Dougiamas http://dougiamas.com
21 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
22 * @package core_course
25 defined('MOODLE_INTERNAL') || die;
27 require_once($CFG->libdir.'/completionlib.php');
28 require_once($CFG->libdir.'/filelib.php');
29 require_once($CFG->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.
34 /**
35 * Number of courses to display when summaries are included.
36 * @var int
37 * @deprecated since 2.4, use $CFG->courseswithsummarieslimit instead.
39 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10);
41 // Max courses in log dropdown before switching to optional.
42 define('COURSE_MAX_COURSES_PER_DROPDOWN', 1000);
43 // Max users in log dropdown before switching to optional.
44 define('COURSE_MAX_USERS_PER_DROPDOWN', 1000);
45 define('FRONTPAGENEWS', '0');
46 define('FRONTPAGECATEGORYNAMES', '2');
47 define('FRONTPAGECATEGORYCOMBO', '4');
48 define('FRONTPAGEENROLLEDCOURSELIST', '5');
49 define('FRONTPAGEALLCOURSELIST', '6');
50 define('FRONTPAGECOURSESEARCH', '7');
51 // Important! Replaced with $CFG->frontpagecourselimit - maximum number of courses displayed on the frontpage.
52 define('EXCELROWS', 65535);
53 define('FIRSTUSEDEXCELROW', 3);
55 define('MOD_CLASS_ACTIVITY', 0);
56 define('MOD_CLASS_RESOURCE', 1);
58 define('COURSE_TIMELINE_PAST', 'past');
59 define('COURSE_TIMELINE_INPROGRESS', 'inprogress');
60 define('COURSE_TIMELINE_FUTURE', 'future');
62 function make_log_url($module, $url) {
63 switch ($module) {
64 case 'course':
65 if (strpos($url, 'report/') === 0) {
66 // there is only one report type, course reports are deprecated
67 $url = "/$url";
68 break;
70 case 'file':
71 case 'login':
72 case 'lib':
73 case 'admin':
74 case 'category':
75 case 'mnet course':
76 if (strpos($url, '../') === 0) {
77 $url = ltrim($url, '.');
78 } else {
79 $url = "/course/$url";
81 break;
82 case 'calendar':
83 $url = "/calendar/$url";
84 break;
85 case 'user':
86 case 'blog':
87 $url = "/$module/$url";
88 break;
89 case 'upload':
90 $url = $url;
91 break;
92 case 'coursetags':
93 $url = '/'.$url;
94 break;
95 case 'library':
96 case '':
97 $url = '/';
98 break;
99 case 'message':
100 $url = "/message/$url";
101 break;
102 case 'notes':
103 $url = "/notes/$url";
104 break;
105 case 'tag':
106 $url = "/tag/$url";
107 break;
108 case 'role':
109 $url = '/'.$url;
110 break;
111 case 'grade':
112 $url = "/grade/$url";
113 break;
114 default:
115 $url = "/mod/$module/$url";
116 break;
119 //now let's sanitise urls - there might be some ugly nasties:-(
120 $parts = explode('?', $url);
121 $script = array_shift($parts);
122 if (strpos($script, 'http') === 0) {
123 $script = clean_param($script, PARAM_URL);
124 } else {
125 $script = clean_param($script, PARAM_PATH);
128 $query = '';
129 if ($parts) {
130 $query = implode('', $parts);
131 $query = str_replace('&amp;', '&', $query); // both & and &amp; are stored in db :-|
132 $parts = explode('&', $query);
133 $eq = urlencode('=');
134 foreach ($parts as $key=>$part) {
135 $part = urlencode(urldecode($part));
136 $part = str_replace($eq, '=', $part);
137 $parts[$key] = $part;
139 $query = '?'.implode('&amp;', $parts);
142 return $script.$query;
146 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
147 $modname="", $modid=0, $modaction="", $groupid=0) {
148 global $CFG, $DB;
150 // It is assumed that $date is the GMT time of midnight for that day,
151 // and so the next 86400 seconds worth of logs are printed.
153 /// Setup for group handling.
155 // TODO: I don't understand group/context/etc. enough to be able to do
156 // something interesting with it here
157 // What is the context of a remote course?
159 /// If the group mode is separate, and this user does not have editing privileges,
160 /// then only the user's group can be viewed.
161 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
162 // $groupid = get_current_group($course->id);
164 /// If this course doesn't have groups, no groupid can be specified.
165 //else if (!$course->groupmode) {
166 // $groupid = 0;
169 $groupid = 0;
171 $joins = array();
172 $where = '';
174 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
175 FROM {mnet_log} l
176 LEFT JOIN {user} u ON l.userid = u.id
177 WHERE ";
178 $params = array();
180 $where .= "l.hostid = :hostid";
181 $params['hostid'] = $hostid;
183 // TODO: Is 1 really a magic number referring to the sitename?
184 if ($course != SITEID || $modid != 0) {
185 $where .= " AND l.course=:courseid";
186 $params['courseid'] = $course;
189 if ($modname) {
190 $where .= " AND l.module = :modname";
191 $params['modname'] = $modname;
194 if ('site_errors' === $modid) {
195 $where .= " AND ( l.action='error' OR l.action='infected' )";
196 } else if ($modid) {
197 //TODO: This assumes that modids are the same across sites... probably
198 //not true
199 $where .= " AND l.cmid = :modid";
200 $params['modid'] = $modid;
203 if ($modaction) {
204 $firstletter = substr($modaction, 0, 1);
205 if ($firstletter == '-') {
206 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
207 $params['modaction'] = '%'.substr($modaction, 1).'%';
208 } else {
209 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
210 $params['modaction'] = '%'.$modaction.'%';
214 if ($user) {
215 $where .= " AND l.userid = :user";
216 $params['user'] = $user;
219 if ($date) {
220 $enddate = $date + 86400;
221 $where .= " AND l.time > :date AND l.time < :enddate";
222 $params['date'] = $date;
223 $params['enddate'] = $enddate;
226 $result = array();
227 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
228 if(!empty($result['totalcount'])) {
229 $where .= " ORDER BY $order";
230 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
231 } else {
232 $result['logs'] = array();
234 return $result;
238 * Checks the integrity of the course data.
240 * In summary - compares course_sections.sequence and course_modules.section.
242 * More detailed, checks that:
243 * - course_sections.sequence contains each module id not more than once in the course
244 * - for each moduleid from course_sections.sequence the field course_modules.section
245 * refers to the same section id (this means course_sections.sequence is more
246 * important if they are different)
247 * - ($fullcheck only) each module in the course is present in one of
248 * course_sections.sequence
249 * - ($fullcheck only) removes non-existing course modules from section sequences
251 * If there are any mismatches, the changes are made and records are updated in DB.
253 * Course cache is NOT rebuilt if there are any errors!
255 * This function is used each time when course cache is being rebuilt with $fullcheck = false
256 * and in CLI script admin/cli/fix_course_sequence.php with $fullcheck = true
258 * @param int $courseid id of the course
259 * @param array $rawmods result of funciton {@link get_course_mods()} - containst
260 * the list of enabled course modules in the course. Retrieved from DB if not specified.
261 * Argument ignored in cashe of $fullcheck, the list is retrieved form DB anyway.
262 * @param array $sections records from course_sections table for this course.
263 * Retrieved from DB if not specified
264 * @param bool $fullcheck Will add orphaned modules to their sections and remove non-existing
265 * course modules from sequences. Only to be used in site maintenance mode when we are
266 * sure that another user is not in the middle of the process of moving/removing a module.
267 * @param bool $checkonly Only performs the check without updating DB, outputs all errors as debug messages.
268 * @return array array of messages with found problems. Empty output means everything is ok
270 function course_integrity_check($courseid, $rawmods = null, $sections = null, $fullcheck = false, $checkonly = false) {
271 global $DB;
272 $messages = array();
273 if ($sections === null) {
274 $sections = $DB->get_records('course_sections', array('course' => $courseid), 'section', 'id,section,sequence');
276 if ($fullcheck) {
277 // Retrieve all records from course_modules regardless of module type visibility.
278 $rawmods = $DB->get_records('course_modules', array('course' => $courseid), 'id', 'id,section');
280 if ($rawmods === null) {
281 $rawmods = get_course_mods($courseid);
283 if (!$fullcheck && (empty($sections) || empty($rawmods))) {
284 // If either of the arrays is empty, no modules are displayed anyway.
285 return true;
287 $debuggingprefix = 'Failed integrity check for course ['.$courseid.']. ';
289 // First make sure that each module id appears in section sequences only once.
290 // If it appears in several section sequences the last section wins.
291 // If it appears twice in one section sequence, the first occurence wins.
292 $modsection = array();
293 foreach ($sections as $sectionid => $section) {
294 $sections[$sectionid]->newsequence = $section->sequence;
295 if (!empty($section->sequence)) {
296 $sequence = explode(",", $section->sequence);
297 $sequenceunique = array_unique($sequence);
298 if (count($sequenceunique) != count($sequence)) {
299 // Some course module id appears in this section sequence more than once.
300 ksort($sequenceunique); // Preserve initial order of modules.
301 $sequence = array_values($sequenceunique);
302 $sections[$sectionid]->newsequence = join(',', $sequence);
303 $messages[] = $debuggingprefix.'Sequence for course section ['.
304 $sectionid.'] is "'.$sections[$sectionid]->sequence.'", must be "'.$sections[$sectionid]->newsequence.'"';
306 foreach ($sequence as $cmid) {
307 if (array_key_exists($cmid, $modsection) && isset($rawmods[$cmid])) {
308 // Some course module id appears to be in more than one section's sequences.
309 $wrongsectionid = $modsection[$cmid];
310 $sections[$wrongsectionid]->newsequence = trim(preg_replace("/,$cmid,/", ',', ','.$sections[$wrongsectionid]->newsequence. ','), ',');
311 $messages[] = $debuggingprefix.'Course module ['.$cmid.'] must be removed from sequence of section ['.
312 $wrongsectionid.'] because it is also present in sequence of section ['.$sectionid.']';
314 $modsection[$cmid] = $sectionid;
319 // Add orphaned modules to their sections if they exist or to section 0 otherwise.
320 if ($fullcheck) {
321 foreach ($rawmods as $cmid => $mod) {
322 if (!isset($modsection[$cmid])) {
323 // This is a module that is not mentioned in course_section.sequence at all.
324 // Add it to the section $mod->section or to the last available section.
325 if ($mod->section && isset($sections[$mod->section])) {
326 $modsection[$cmid] = $mod->section;
327 } else {
328 $firstsection = reset($sections);
329 $modsection[$cmid] = $firstsection->id;
331 $sections[$modsection[$cmid]]->newsequence = trim($sections[$modsection[$cmid]]->newsequence.','.$cmid, ',');
332 $messages[] = $debuggingprefix.'Course module ['.$cmid.'] is missing from sequence of section ['.
333 $modsection[$cmid].']';
336 foreach ($modsection as $cmid => $sectionid) {
337 if (!isset($rawmods[$cmid])) {
338 // Section $sectionid refers to module id that does not exist.
339 $sections[$sectionid]->newsequence = trim(preg_replace("/,$cmid,/", ',', ','.$sections[$sectionid]->newsequence.','), ',');
340 $messages[] = $debuggingprefix.'Course module ['.$cmid.
341 '] does not exist but is present in the sequence of section ['.$sectionid.']';
346 // Update changed sections.
347 if (!$checkonly && !empty($messages)) {
348 foreach ($sections as $sectionid => $section) {
349 if ($section->newsequence !== $section->sequence) {
350 $DB->update_record('course_sections', array('id' => $sectionid, 'sequence' => $section->newsequence));
355 // Now make sure that all modules point to the correct sections.
356 foreach ($rawmods as $cmid => $mod) {
357 if (isset($modsection[$cmid]) && $modsection[$cmid] != $mod->section) {
358 if (!$checkonly) {
359 $DB->update_record('course_modules', array('id' => $cmid, 'section' => $modsection[$cmid]));
361 $messages[] = $debuggingprefix.'Course module ['.$cmid.
362 '] points to section ['.$mod->section.'] instead of ['.$modsection[$cmid].']';
366 return $messages;
370 * For a given course, returns an array of course activity objects
371 * Each item in the array contains he following properties:
373 function get_array_of_activities($courseid) {
374 // cm - course module id
375 // mod - name of the module (eg forum)
376 // section - the number of the section (eg week or topic)
377 // name - the name of the instance
378 // visible - is the instance visible or not
379 // groupingid - grouping id
380 // extra - contains extra string to include in any link
381 global $CFG, $DB;
383 $course = $DB->get_record('course', array('id'=>$courseid));
385 if (empty($course)) {
386 throw new moodle_exception('courseidnotfound');
389 $mod = array();
391 $rawmods = get_course_mods($courseid);
392 if (empty($rawmods)) {
393 return $mod; // always return array
395 $courseformat = course_get_format($course);
397 if ($sections = $DB->get_records('course_sections', array('course' => $courseid),
398 'section ASC', 'id,section,sequence,visible')) {
399 // First check and correct obvious mismatches between course_sections.sequence and course_modules.section.
400 if ($errormessages = course_integrity_check($courseid, $rawmods, $sections)) {
401 debugging(join('<br>', $errormessages));
402 $rawmods = get_course_mods($courseid);
403 $sections = $DB->get_records('course_sections', array('course' => $courseid),
404 'section ASC', 'id,section,sequence,visible');
406 // Build array of activities.
407 foreach ($sections as $section) {
408 if (!empty($section->sequence)) {
409 $sequence = explode(",", $section->sequence);
410 foreach ($sequence as $seq) {
411 if (empty($rawmods[$seq])) {
412 continue;
414 // Adjust visibleoncoursepage, value in DB may not respect format availability.
415 $rawmods[$seq]->visibleoncoursepage = (!$rawmods[$seq]->visible
416 || $rawmods[$seq]->visibleoncoursepage
417 || empty($CFG->allowstealth)
418 || !$courseformat->allow_stealth_module_visibility($rawmods[$seq], $section)) ? 1 : 0;
420 // Create an object that will be cached.
421 $mod[$seq] = new stdClass();
422 $mod[$seq]->id = $rawmods[$seq]->instance;
423 $mod[$seq]->cm = $rawmods[$seq]->id;
424 $mod[$seq]->mod = $rawmods[$seq]->modname;
426 // Oh dear. Inconsistent names left here for backward compatibility.
427 $mod[$seq]->section = $section->section;
428 $mod[$seq]->sectionid = $rawmods[$seq]->section;
430 $mod[$seq]->module = $rawmods[$seq]->module;
431 $mod[$seq]->added = $rawmods[$seq]->added;
432 $mod[$seq]->score = $rawmods[$seq]->score;
433 $mod[$seq]->idnumber = $rawmods[$seq]->idnumber;
434 $mod[$seq]->visible = $rawmods[$seq]->visible;
435 $mod[$seq]->visibleoncoursepage = $rawmods[$seq]->visibleoncoursepage;
436 $mod[$seq]->visibleold = $rawmods[$seq]->visibleold;
437 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
438 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
439 $mod[$seq]->indent = $rawmods[$seq]->indent;
440 $mod[$seq]->completion = $rawmods[$seq]->completion;
441 $mod[$seq]->extra = "";
442 $mod[$seq]->completiongradeitemnumber =
443 $rawmods[$seq]->completiongradeitemnumber;
444 $mod[$seq]->completionview = $rawmods[$seq]->completionview;
445 $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected;
446 $mod[$seq]->showdescription = $rawmods[$seq]->showdescription;
447 $mod[$seq]->availability = $rawmods[$seq]->availability;
448 $mod[$seq]->deletioninprogress = $rawmods[$seq]->deletioninprogress;
450 $modname = $mod[$seq]->mod;
451 $functionname = $modname."_get_coursemodule_info";
453 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
454 continue;
457 include_once("$CFG->dirroot/mod/$modname/lib.php");
459 if ($hasfunction = function_exists($functionname)) {
460 if ($info = $functionname($rawmods[$seq])) {
461 if (!empty($info->icon)) {
462 $mod[$seq]->icon = $info->icon;
464 if (!empty($info->iconcomponent)) {
465 $mod[$seq]->iconcomponent = $info->iconcomponent;
467 if (!empty($info->name)) {
468 $mod[$seq]->name = $info->name;
470 if ($info instanceof cached_cm_info) {
471 // When using cached_cm_info you can include three new fields
472 // that aren't available for legacy code
473 if (!empty($info->content)) {
474 $mod[$seq]->content = $info->content;
476 if (!empty($info->extraclasses)) {
477 $mod[$seq]->extraclasses = $info->extraclasses;
479 if (!empty($info->iconurl)) {
480 // Convert URL to string as it's easier to store. Also serialized object contains \0 byte and can not be written to Postgres DB.
481 $url = new moodle_url($info->iconurl);
482 $mod[$seq]->iconurl = $url->out(false);
484 if (!empty($info->onclick)) {
485 $mod[$seq]->onclick = $info->onclick;
487 if (!empty($info->customdata)) {
488 $mod[$seq]->customdata = $info->customdata;
490 } else {
491 // When using a stdclass, the (horrible) deprecated ->extra field
492 // is available for BC
493 if (!empty($info->extra)) {
494 $mod[$seq]->extra = $info->extra;
499 // When there is no modname_get_coursemodule_info function,
500 // but showdescriptions is enabled, then we use the 'intro'
501 // and 'introformat' fields in the module table
502 if (!$hasfunction && $rawmods[$seq]->showdescription) {
503 if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
504 array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
505 // Set content from intro and introformat. Filters are disabled
506 // because we filter it with format_text at display time
507 $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
508 $modvalues, $rawmods[$seq]->id, false);
510 // To save making another query just below, put name in here
511 $mod[$seq]->name = $modvalues->name;
514 if (!isset($mod[$seq]->name)) {
515 $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
518 // Minimise the database size by unsetting default options when they are
519 // 'empty'. This list corresponds to code in the cm_info constructor.
520 foreach (array('idnumber', 'groupmode', 'groupingid',
521 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
522 'icon', 'iconcomponent', 'customdata', 'availability', 'completionview',
523 'completionexpected', 'score', 'showdescription', 'deletioninprogress') as $property) {
524 if (property_exists($mod[$seq], $property) &&
525 empty($mod[$seq]->{$property})) {
526 unset($mod[$seq]->{$property});
529 // Special case: this value is usually set to null, but may be 0
530 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
531 is_null($mod[$seq]->completiongradeitemnumber)) {
532 unset($mod[$seq]->completiongradeitemnumber);
538 return $mod;
542 * Returns the localised human-readable names of all used modules
544 * @param bool $plural if true returns the plural forms of the names
545 * @return array where key is the module name (component name without 'mod_') and
546 * the value is the human-readable string. Array sorted alphabetically by value
548 function get_module_types_names($plural = false) {
549 static $modnames = null;
550 global $DB, $CFG;
551 if ($modnames === null) {
552 $modnames = array(0 => array(), 1 => array());
553 if ($allmods = $DB->get_records("modules")) {
554 foreach ($allmods as $mod) {
555 if (file_exists("$CFG->dirroot/mod/$mod->name/lib.php") && $mod->visible) {
556 $modnames[0][$mod->name] = get_string("modulename", "$mod->name");
557 $modnames[1][$mod->name] = get_string("modulenameplural", "$mod->name");
560 core_collator::asort($modnames[0]);
561 core_collator::asort($modnames[1]);
564 return $modnames[(int)$plural];
568 * Set highlighted section. Only one section can be highlighted at the time.
570 * @param int $courseid course id
571 * @param int $marker highlight section with this number, 0 means remove higlightin
572 * @return void
574 function course_set_marker($courseid, $marker) {
575 global $DB, $COURSE;
576 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
577 if ($COURSE && $COURSE->id == $courseid) {
578 $COURSE->marker = $marker;
580 if (class_exists('format_base')) {
581 format_base::reset_course_cache($courseid);
583 course_modinfo::clear_instance_cache($courseid);
587 * For a given course section, marks it visible or hidden,
588 * and does the same for every activity in that section
590 * @param int $courseid course id
591 * @param int $sectionnumber The section number to adjust
592 * @param int $visibility The new visibility
593 * @return array A list of resources which were hidden in the section
595 function set_section_visible($courseid, $sectionnumber, $visibility) {
596 global $DB;
598 $resourcestotoggle = array();
599 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
600 course_update_section($courseid, $section, array('visible' => $visibility));
602 // Determine which modules are visible for AJAX update
603 $modules = !empty($section->sequence) ? explode(',', $section->sequence) : array();
604 if (!empty($modules)) {
605 list($insql, $params) = $DB->get_in_or_equal($modules);
606 $select = 'id ' . $insql . ' AND visible = ?';
607 array_push($params, $visibility);
608 if (!$visibility) {
609 $select .= ' AND visibleold = 1';
611 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
614 return $resourcestotoggle;
618 * Retrieve all metadata for the requested modules
620 * @param object $course The Course
621 * @param array $modnames An array containing the list of modules and their
622 * names
623 * @param int $sectionreturn The section to return to
624 * @return array A list of stdClass objects containing metadata about each
625 * module
627 function get_module_metadata($course, $modnames, $sectionreturn = null) {
628 global $OUTPUT;
630 // get_module_metadata will be called once per section on the page and courses may show
631 // different modules to one another
632 static $modlist = array();
633 if (!isset($modlist[$course->id])) {
634 $modlist[$course->id] = array();
637 $return = array();
638 $urlbase = new moodle_url('/course/mod.php', array('id' => $course->id, 'sesskey' => sesskey()));
639 if ($sectionreturn !== null) {
640 $urlbase->param('sr', $sectionreturn);
642 foreach($modnames as $modname => $modnamestr) {
643 if (!course_allowed_module($course, $modname)) {
644 continue;
646 if (isset($modlist[$course->id][$modname])) {
647 // This module is already cached
648 $return += $modlist[$course->id][$modname];
649 continue;
651 $modlist[$course->id][$modname] = array();
653 // Create an object for a default representation of this module type in the activity chooser. It will be used
654 // if module does not implement callback get_shortcuts() and it will also be passed to the callback if it exists.
655 $defaultmodule = new stdClass();
656 $defaultmodule->title = $modnamestr;
657 $defaultmodule->name = $modname;
658 $defaultmodule->link = new moodle_url($urlbase, array('add' => $modname));
659 $defaultmodule->icon = $OUTPUT->pix_icon('icon', '', $defaultmodule->name, array('class' => 'icon'));
660 $sm = get_string_manager();
661 if ($sm->string_exists('modulename_help', $modname)) {
662 $defaultmodule->help = get_string('modulename_help', $modname);
663 if ($sm->string_exists('modulename_link', $modname)) { // Link to further info in Moodle docs.
664 $link = get_string('modulename_link', $modname);
665 $linktext = get_string('morehelp');
666 $defaultmodule->help .= html_writer::tag('div',
667 $OUTPUT->doc_link($link, $linktext, true), array('class' => 'helpdoclink'));
670 $defaultmodule->archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
672 // Legacy support for callback get_types() - do not use any more, use get_shortcuts() instead!
673 $typescallbackexists = component_callback_exists($modname, 'get_types');
675 // Each module can implement callback modulename_get_shortcuts() in its lib.php and return the list
676 // of elements to be added to activity chooser.
677 $items = component_callback($modname, 'get_shortcuts', array($defaultmodule), null);
678 if ($items !== null) {
679 foreach ($items as $item) {
680 // Add all items to the return array. All items must have different links, use them as a key in the return array.
681 if (!isset($item->archetype)) {
682 $item->archetype = $defaultmodule->archetype;
684 if (!isset($item->icon)) {
685 $item->icon = $defaultmodule->icon;
687 // If plugin returned the only one item with the same link as default item - cache it as $modname,
688 // otherwise append the link url to the module name.
689 $item->name = (count($items) == 1 &&
690 $item->link->out() === $defaultmodule->link->out()) ? $modname : $modname . ':' . $item->link;
692 // If the module provides the helptext property, append it to the help text to match the look and feel
693 // of the default course modules.
694 if (isset($item->help) && isset($item->helplink)) {
695 $linktext = get_string('morehelp');
696 $item->help .= html_writer::tag('div',
697 $OUTPUT->doc_link($item->helplink, $linktext, true), array('class' => 'helpdoclink'));
699 $modlist[$course->id][$modname][$item->name] = $item;
701 $return += $modlist[$course->id][$modname];
702 if ($typescallbackexists) {
703 debugging('Both callbacks get_shortcuts() and get_types() are found in module ' . $modname .
704 '. Callback get_types() will be completely ignored', DEBUG_DEVELOPER);
706 // If get_shortcuts() callback is defined, the default module action is not added.
707 // It is a responsibility of the callback to add it to the return value unless it is not needed.
708 continue;
711 if ($typescallbackexists) {
712 debugging('Callback get_types() is found in module ' . $modname . ', this functionality is deprecated, ' .
713 'please use callback get_shortcuts() instead', DEBUG_DEVELOPER);
715 $types = component_callback($modname, 'get_types', array(), MOD_SUBTYPE_NO_CHILDREN);
716 if ($types !== MOD_SUBTYPE_NO_CHILDREN) {
717 // Legacy support for deprecated callback get_types(). To be removed in Moodle 3.5. TODO MDL-53697.
718 if (is_array($types) && count($types) > 0) {
719 $grouptitle = $modnamestr;
720 $icon = $OUTPUT->pix_icon('icon', '', $modname, array('class' => 'icon'));
721 foreach($types as $type) {
722 if ($type->typestr === '--') {
723 continue;
725 if (strpos($type->typestr, '--') === 0) {
726 $grouptitle = str_replace('--', '', $type->typestr);
727 continue;
729 // Set the Sub Type metadata.
730 $subtype = new stdClass();
731 $subtype->title = get_string('activitytypetitle', '',
732 (object)['activity' => $grouptitle, 'type' => $type->typestr]);
733 $subtype->type = str_replace('&amp;', '&', $type->type);
734 $typename = preg_replace('/.*type=/', '', $subtype->type);
735 $subtype->archetype = $type->modclass;
737 if (!empty($type->help)) {
738 $subtype->help = $type->help;
739 } else if (get_string_manager()->string_exists('help' . $subtype->name, $modname)) {
740 $subtype->help = get_string('help' . $subtype->name, $modname);
742 $subtype->link = new moodle_url($urlbase, array('add' => $modname, 'type' => $typename));
743 $subtype->name = $modname . ':' . $subtype->link;
744 $subtype->icon = $icon;
745 $modlist[$course->id][$modname][$subtype->name] = $subtype;
747 $return += $modlist[$course->id][$modname];
749 } else {
750 // Neither get_shortcuts() nor get_types() callbacks found, use the default item for the activity chooser.
751 $modlist[$course->id][$modname][$modname] = $defaultmodule;
752 $return[$modname] = $defaultmodule;
756 core_collator::asort_objects_by_property($return, 'title');
757 return $return;
761 * Return the course category context for the category with id $categoryid, except
762 * that if $categoryid is 0, return the system context.
764 * @param integer $categoryid a category id or 0.
765 * @return context the corresponding context
767 function get_category_or_system_context($categoryid) {
768 if ($categoryid) {
769 return context_coursecat::instance($categoryid, IGNORE_MISSING);
770 } else {
771 return context_system::instance();
776 * Returns full course categories trees to be used in html_writer::select()
778 * Calls {@link coursecat::make_categories_list()} to build the tree and
779 * adds whitespace to denote nesting
781 * @return array array mapping coursecat id to the display name
783 function make_categories_options() {
784 global $CFG;
785 require_once($CFG->libdir. '/coursecatlib.php');
786 $cats = coursecat::make_categories_list('', 0, ' / ');
787 foreach ($cats as $key => $value) {
788 // Prefix the value with the number of spaces equal to category depth (number of separators in the value).
789 $cats[$key] = str_repeat('&nbsp;', substr_count($value, ' / ')). $value;
791 return $cats;
795 * Print the buttons relating to course requests.
797 * @param object $context current page context.
799 function print_course_request_buttons($context) {
800 global $CFG, $DB, $OUTPUT;
801 if (empty($CFG->enablecourserequests)) {
802 return;
804 if (!has_capability('moodle/course:create', $context) && has_capability('moodle/course:request', $context)) {
805 /// Print a button to request a new course
806 echo $OUTPUT->single_button(new moodle_url('/course/request.php'), get_string('requestcourse'), 'get');
808 /// Print a button to manage pending requests
809 if ($context->contextlevel == CONTEXT_SYSTEM && has_capability('moodle/site:approvecourse', $context)) {
810 $disabled = !$DB->record_exists('course_request', array());
811 echo $OUTPUT->single_button(new moodle_url('/course/pending.php'), get_string('coursespending'), 'get', array('disabled' => $disabled));
816 * Does the user have permission to edit things in this category?
818 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
819 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
821 function can_edit_in_category($categoryid = 0) {
822 $context = get_category_or_system_context($categoryid);
823 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
826 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
828 function add_course_module($mod) {
829 global $DB;
831 $mod->added = time();
832 unset($mod->id);
834 $cmid = $DB->insert_record("course_modules", $mod);
835 rebuild_course_cache($mod->course, true);
836 return $cmid;
840 * Creates a course section and adds it to the specified position
842 * @param int|stdClass $courseorid course id or course object
843 * @param int $position position to add to, 0 means to the end. If position is greater than
844 * number of existing secitons, the section is added to the end. This will become sectionnum of the
845 * new section. All existing sections at this or bigger position will be shifted down.
846 * @param bool $skipcheck the check has already been made and we know that the section with this position does not exist
847 * @return stdClass created section object
849 function course_create_section($courseorid, $position = 0, $skipcheck = false) {
850 global $DB;
851 $courseid = is_object($courseorid) ? $courseorid->id : $courseorid;
853 // Find the last sectionnum among existing sections.
854 if ($skipcheck) {
855 $lastsection = $position - 1;
856 } else {
857 $lastsection = (int)$DB->get_field_sql('SELECT max(section) from {course_sections} WHERE course = ?', [$courseid]);
860 // First add section to the end.
861 $cw = new stdClass();
862 $cw->course = $courseid;
863 $cw->section = $lastsection + 1;
864 $cw->summary = '';
865 $cw->summaryformat = FORMAT_HTML;
866 $cw->sequence = '';
867 $cw->name = null;
868 $cw->visible = 1;
869 $cw->availability = null;
870 $cw->timemodified = time();
871 $cw->id = $DB->insert_record("course_sections", $cw);
873 // Now move it to the specified position.
874 if ($position > 0 && $position <= $lastsection) {
875 $course = is_object($courseorid) ? $courseorid : get_course($courseorid);
876 move_section_to($course, $cw->section, $position, true);
877 $cw->section = $position;
880 core\event\course_section_created::create_from_section($cw)->trigger();
882 rebuild_course_cache($courseid, true);
883 return $cw;
887 * Creates missing course section(s) and rebuilds course cache
889 * @param int|stdClass $courseorid course id or course object
890 * @param int|array $sections list of relative section numbers to create
891 * @return bool if there were any sections created
893 function course_create_sections_if_missing($courseorid, $sections) {
894 if (!is_array($sections)) {
895 $sections = array($sections);
897 $existing = array_keys(get_fast_modinfo($courseorid)->get_section_info_all());
898 if ($newsections = array_diff($sections, $existing)) {
899 foreach ($newsections as $sectionnum) {
900 course_create_section($courseorid, $sectionnum, true);
902 return true;
904 return false;
908 * Adds an existing module to the section
910 * Updates both tables {course_sections} and {course_modules}
912 * Note: This function does not use modinfo PROVIDED that the section you are
913 * adding the module to already exists. If the section does not exist, it will
914 * build modinfo if necessary and create the section.
916 * @param int|stdClass $courseorid course id or course object
917 * @param int $cmid id of the module already existing in course_modules table
918 * @param int $sectionnum relative number of the section (field course_sections.section)
919 * If section does not exist it will be created
920 * @param int|stdClass $beforemod id or object with field id corresponding to the module
921 * before which the module needs to be included. Null for inserting in the
922 * end of the section
923 * @return int The course_sections ID where the module is inserted
925 function course_add_cm_to_section($courseorid, $cmid, $sectionnum, $beforemod = null) {
926 global $DB, $COURSE;
927 if (is_object($beforemod)) {
928 $beforemod = $beforemod->id;
930 if (is_object($courseorid)) {
931 $courseid = $courseorid->id;
932 } else {
933 $courseid = $courseorid;
935 // Do not try to use modinfo here, there is no guarantee it is valid!
936 $section = $DB->get_record('course_sections',
937 array('course' => $courseid, 'section' => $sectionnum), '*', IGNORE_MISSING);
938 if (!$section) {
939 // This function call requires modinfo.
940 course_create_sections_if_missing($courseorid, $sectionnum);
941 $section = $DB->get_record('course_sections',
942 array('course' => $courseid, 'section' => $sectionnum), '*', MUST_EXIST);
945 $modarray = explode(",", trim($section->sequence));
946 if (empty($section->sequence)) {
947 $newsequence = "$cmid";
948 } else if ($beforemod && ($key = array_keys($modarray, $beforemod))) {
949 $insertarray = array($cmid, $beforemod);
950 array_splice($modarray, $key[0], 1, $insertarray);
951 $newsequence = implode(",", $modarray);
952 } else {
953 $newsequence = "$section->sequence,$cmid";
955 $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id));
956 $DB->set_field('course_modules', 'section', $section->id, array('id' => $cmid));
957 if (is_object($courseorid)) {
958 rebuild_course_cache($courseorid->id, true);
959 } else {
960 rebuild_course_cache($courseorid, true);
962 return $section->id; // Return course_sections ID that was used.
966 * Change the group mode of a course module.
968 * Note: Do not forget to trigger the event \core\event\course_module_updated as it needs
969 * to be triggered manually, refer to {@link \core\event\course_module_updated::create_from_cm()}.
971 * @param int $id course module ID.
972 * @param int $groupmode the new groupmode value.
973 * @return bool True if the $groupmode was updated.
975 function set_coursemodule_groupmode($id, $groupmode) {
976 global $DB;
977 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST);
978 if ($cm->groupmode != $groupmode) {
979 $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id));
980 rebuild_course_cache($cm->course, true);
982 return ($cm->groupmode != $groupmode);
985 function set_coursemodule_idnumber($id, $idnumber) {
986 global $DB;
987 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST);
988 if ($cm->idnumber != $idnumber) {
989 $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id));
990 rebuild_course_cache($cm->course, true);
992 return ($cm->idnumber != $idnumber);
996 * Set the visibility of a module and inherent properties.
998 * Note: Do not forget to trigger the event \core\event\course_module_updated as it needs
999 * to be triggered manually, refer to {@link \core\event\course_module_updated::create_from_cm()}.
1001 * From 2.4 the parameter $prevstateoverrides has been removed, the logic it triggered
1002 * has been moved to {@link set_section_visible()} which was the only place from which
1003 * the parameter was used.
1005 * @param int $id of the module
1006 * @param int $visible state of the module
1007 * @param int $visibleoncoursepage state of the module on the course page
1008 * @return bool false when the module was not found, true otherwise
1010 function set_coursemodule_visible($id, $visible, $visibleoncoursepage = 1) {
1011 global $DB, $CFG;
1012 require_once($CFG->libdir.'/gradelib.php');
1013 require_once($CFG->dirroot.'/calendar/lib.php');
1015 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
1016 return false;
1019 // Create events and propagate visibility to associated grade items if the value has changed.
1020 // Only do this if it's changed to avoid accidently overwriting manual showing/hiding of student grades.
1021 if ($cm->visible == $visible && $cm->visibleoncoursepage == $visibleoncoursepage) {
1022 return true;
1025 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
1026 return false;
1028 if (($cm->visible != $visible) &&
1029 ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename)))) {
1030 foreach($events as $event) {
1031 if ($visible) {
1032 $event = new calendar_event($event);
1033 $event->toggle_visibility(true);
1034 } else {
1035 $event = new calendar_event($event);
1036 $event->toggle_visibility(false);
1041 // Updating visible and visibleold to keep them in sync. Only changing a section visibility will
1042 // affect visibleold to allow for an original visibility restore. See set_section_visible().
1043 $cminfo = new stdClass();
1044 $cminfo->id = $id;
1045 $cminfo->visible = $visible;
1046 $cminfo->visibleoncoursepage = $visibleoncoursepage;
1047 $cminfo->visibleold = $visible;
1048 $DB->update_record('course_modules', $cminfo);
1050 // Hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there.
1051 // Note that this must be done after updating the row in course_modules, in case
1052 // the modules grade_item_update function needs to access $cm->visible.
1053 if ($cm->visible != $visible &&
1054 plugin_supports('mod', $modulename, FEATURE_CONTROLS_GRADE_VISIBILITY) &&
1055 component_callback_exists('mod_' . $modulename, 'grade_item_update')) {
1056 $instance = $DB->get_record($modulename, array('id' => $cm->instance), '*', MUST_EXIST);
1057 component_callback('mod_' . $modulename, 'grade_item_update', array($instance));
1058 } else if ($cm->visible != $visible) {
1059 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
1060 if ($grade_items) {
1061 foreach ($grade_items as $grade_item) {
1062 $grade_item->set_hidden(!$visible);
1067 rebuild_course_cache($cm->course, true);
1068 return true;
1072 * Changes the course module name
1074 * @param int $id course module id
1075 * @param string $name new value for a name
1076 * @return bool whether a change was made
1078 function set_coursemodule_name($id, $name) {
1079 global $CFG, $DB;
1080 require_once($CFG->libdir . '/gradelib.php');
1082 $cm = get_coursemodule_from_id('', $id, 0, false, MUST_EXIST);
1084 $module = new \stdClass();
1085 $module->id = $cm->instance;
1087 // Escape strings as they would be by mform.
1088 if (!empty($CFG->formatstringstriptags)) {
1089 $module->name = clean_param($name, PARAM_TEXT);
1090 } else {
1091 $module->name = clean_param($name, PARAM_CLEANHTML);
1093 if ($module->name === $cm->name || strval($module->name) === '') {
1094 return false;
1096 if (\core_text::strlen($module->name) > 255) {
1097 throw new \moodle_exception('maximumchars', 'moodle', '', 255);
1100 $module->timemodified = time();
1101 $DB->update_record($cm->modname, $module);
1102 $cm->name = $module->name;
1103 \core\event\course_module_updated::create_from_cm($cm)->trigger();
1104 rebuild_course_cache($cm->course, true);
1106 // Attempt to update the grade item if relevant.
1107 $grademodule = $DB->get_record($cm->modname, array('id' => $cm->instance));
1108 $grademodule->cmidnumber = $cm->idnumber;
1109 $grademodule->modname = $cm->modname;
1110 grade_update_mod_grades($grademodule);
1112 // Update calendar events with the new name.
1113 course_module_update_calendar_events($cm->modname, $grademodule, $cm);
1115 return true;
1119 * This function will handle the whole deletion process of a module. This includes calling
1120 * the modules delete_instance function, deleting files, events, grades, conditional data,
1121 * the data in the course_module and course_sections table and adding a module deletion
1122 * event to the DB.
1124 * @param int $cmid the course module id
1125 * @param bool $async whether or not to try to delete the module using an adhoc task. Async also depends on a plugin hook.
1126 * @throws moodle_exception
1127 * @since Moodle 2.5
1129 function course_delete_module($cmid, $async = false) {
1130 // Check the 'course_module_background_deletion_recommended' hook first.
1131 // Only use asynchronous deletion if at least one plugin returns true and if async deletion has been requested.
1132 // Both are checked because plugins should not be allowed to dictate the deletion behaviour, only support/decline it.
1133 // It's up to plugins to handle things like whether or not they are enabled.
1134 if ($async && $pluginsfunction = get_plugins_with_function('course_module_background_deletion_recommended')) {
1135 foreach ($pluginsfunction as $plugintype => $plugins) {
1136 foreach ($plugins as $pluginfunction) {
1137 if ($pluginfunction()) {
1138 return course_module_flag_for_async_deletion($cmid);
1144 global $CFG, $DB;
1146 require_once($CFG->libdir.'/gradelib.php');
1147 require_once($CFG->libdir.'/questionlib.php');
1148 require_once($CFG->dirroot.'/blog/lib.php');
1149 require_once($CFG->dirroot.'/calendar/lib.php');
1151 // Get the course module.
1152 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
1153 return true;
1156 // Get the module context.
1157 $modcontext = context_module::instance($cm->id);
1159 // Get the course module name.
1160 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
1162 // Get the file location of the delete_instance function for this module.
1163 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
1165 // Include the file required to call the delete_instance function for this module.
1166 if (file_exists($modlib)) {
1167 require_once($modlib);
1168 } else {
1169 throw new moodle_exception('cannotdeletemodulemissinglib', '', '', null,
1170 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
1173 $deleteinstancefunction = $modulename . '_delete_instance';
1175 // Ensure the delete_instance function exists for this module.
1176 if (!function_exists($deleteinstancefunction)) {
1177 throw new moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
1178 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
1181 // Allow plugins to use this course module before we completely delete it.
1182 if ($pluginsfunction = get_plugins_with_function('pre_course_module_delete')) {
1183 foreach ($pluginsfunction as $plugintype => $plugins) {
1184 foreach ($plugins as $pluginfunction) {
1185 $pluginfunction($cm);
1190 // Delete activity context questions and question categories.
1191 question_delete_activity($cm);
1193 // Call the delete_instance function, if it returns false throw an exception.
1194 if (!$deleteinstancefunction($cm->instance)) {
1195 throw new moodle_exception('cannotdeletemoduleinstance', '', '', null,
1196 "Cannot delete the module $modulename (instance).");
1199 // Remove all module files in case modules forget to do that.
1200 $fs = get_file_storage();
1201 $fs->delete_area_files($modcontext->id);
1203 // Delete events from calendar.
1204 if ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename))) {
1205 $coursecontext = context_course::instance($cm->course);
1206 foreach($events as $event) {
1207 $event->context = $coursecontext;
1208 $calendarevent = calendar_event::load($event);
1209 $calendarevent->delete();
1213 // Delete grade items, outcome items and grades attached to modules.
1214 if ($grade_items = grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $modulename,
1215 'iteminstance' => $cm->instance, 'courseid' => $cm->course))) {
1216 foreach ($grade_items as $grade_item) {
1217 $grade_item->delete('moddelete');
1221 // Delete completion and availability data; it is better to do this even if the
1222 // features are not turned on, in case they were turned on previously (these will be
1223 // very quick on an empty table).
1224 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
1225 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
1226 'course' => $cm->course,
1227 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
1229 // Delete all tag instances associated with the instance of this module.
1230 core_tag_tag::delete_instances('mod_' . $modulename, null, $modcontext->id);
1231 core_tag_tag::remove_all_item_tags('core', 'course_modules', $cm->id);
1233 // Notify the competency subsystem.
1234 \core_competency\api::hook_course_module_deleted($cm);
1236 // Delete the context.
1237 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
1239 // Delete the module from the course_modules table.
1240 $DB->delete_records('course_modules', array('id' => $cm->id));
1242 // Delete module from that section.
1243 if (!delete_mod_from_section($cm->id, $cm->section)) {
1244 throw new moodle_exception('cannotdeletemodulefromsection', '', '', null,
1245 "Cannot delete the module $modulename (instance) from section.");
1248 // Trigger event for course module delete action.
1249 $event = \core\event\course_module_deleted::create(array(
1250 'courseid' => $cm->course,
1251 'context' => $modcontext,
1252 'objectid' => $cm->id,
1253 'other' => array(
1254 'modulename' => $modulename,
1255 'instanceid' => $cm->instance,
1258 $event->add_record_snapshot('course_modules', $cm);
1259 $event->trigger();
1260 rebuild_course_cache($cm->course, true);
1264 * Schedule a course module for deletion in the background using an adhoc task.
1266 * This method should not be called directly. Instead, please use course_delete_module($cmid, true), to denote async deletion.
1267 * The real deletion of the module is handled by the task, which calls 'course_delete_module($cmid)'.
1269 * @param int $cmid the course module id.
1270 * @return bool whether the module was successfully scheduled for deletion.
1271 * @throws \moodle_exception
1273 function course_module_flag_for_async_deletion($cmid) {
1274 global $CFG, $DB, $USER;
1275 require_once($CFG->libdir.'/gradelib.php');
1276 require_once($CFG->libdir.'/questionlib.php');
1277 require_once($CFG->dirroot.'/blog/lib.php');
1278 require_once($CFG->dirroot.'/calendar/lib.php');
1280 // Get the course module.
1281 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
1282 return true;
1285 // We need to be reasonably certain the deletion is going to succeed before we background the process.
1286 // Make the necessary delete_instance checks, etc. before proceeding further. Throw exceptions if required.
1288 // Get the course module name.
1289 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
1291 // Get the file location of the delete_instance function for this module.
1292 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
1294 // Include the file required to call the delete_instance function for this module.
1295 if (file_exists($modlib)) {
1296 require_once($modlib);
1297 } else {
1298 throw new \moodle_exception('cannotdeletemodulemissinglib', '', '', null,
1299 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
1302 $deleteinstancefunction = $modulename . '_delete_instance';
1304 // Ensure the delete_instance function exists for this module.
1305 if (!function_exists($deleteinstancefunction)) {
1306 throw new \moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
1307 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
1310 // We are going to defer the deletion as we can't be sure how long the module's pre_delete code will run for.
1311 $cm->deletioninprogress = '1';
1312 $DB->update_record('course_modules', $cm);
1314 // Create an adhoc task for the deletion of the course module. The task takes an array of course modules for removal.
1315 $removaltask = new \core_course\task\course_delete_modules();
1316 $removaltask->set_custom_data(array(
1317 'cms' => array($cm),
1318 'userid' => $USER->id,
1319 'realuserid' => \core\session\manager::get_realuser()->id
1322 // Queue the task for the next run.
1323 \core\task\manager::queue_adhoc_task($removaltask);
1325 // Reset the course cache to hide the module.
1326 rebuild_course_cache($cm->course, true);
1330 * Checks whether the given course has any course modules scheduled for adhoc deletion.
1332 * @param int $courseid the id of the course.
1333 * @return bool true if the course contains any modules pending deletion, false otherwise.
1335 function course_modules_pending_deletion($courseid) {
1336 if (empty($courseid)) {
1337 return false;
1339 $modinfo = get_fast_modinfo($courseid);
1340 foreach ($modinfo->get_cms() as $module) {
1341 if ($module->deletioninprogress == '1') {
1342 return true;
1345 return false;
1349 * Checks whether the course module, as defined by modulename and instanceid, is scheduled for deletion within the given course.
1351 * @param int $courseid the course id.
1352 * @param string $modulename the module name. E.g. 'assign', 'book', etc.
1353 * @param int $instanceid the module instance id.
1354 * @return bool true if the course module is pending deletion, false otherwise.
1356 function course_module_instance_pending_deletion($courseid, $modulename, $instanceid) {
1357 if (empty($courseid) || empty($modulename) || empty($instanceid)) {
1358 return false;
1360 $modinfo = get_fast_modinfo($courseid);
1361 $instances = $modinfo->get_instances_of($modulename);
1362 return isset($instances[$instanceid]) && $instances[$instanceid]->deletioninprogress;
1365 function delete_mod_from_section($modid, $sectionid) {
1366 global $DB;
1368 if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
1370 $modarray = explode(",", $section->sequence);
1372 if ($key = array_keys ($modarray, $modid)) {
1373 array_splice($modarray, $key[0], 1);
1374 $newsequence = implode(",", $modarray);
1375 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
1376 rebuild_course_cache($section->course, true);
1377 return true;
1378 } else {
1379 return false;
1383 return false;
1387 * This function updates the calendar events from the information stored in the module table and the course
1388 * module table.
1390 * @param string $modulename Module name
1391 * @param stdClass $instance Module object. Either the $instance or the $cm must be supplied.
1392 * @param stdClass $cm Course module object. Either the $instance or the $cm must be supplied.
1393 * @return bool Returns true if calendar events are updated.
1394 * @since Moodle 3.3.4
1396 function course_module_update_calendar_events($modulename, $instance = null, $cm = null) {
1397 global $DB;
1399 if (isset($instance) || isset($cm)) {
1401 if (!isset($instance)) {
1402 $instance = $DB->get_record($modulename, array('id' => $cm->instance), '*', MUST_EXIST);
1404 if (!isset($cm)) {
1405 $cm = get_coursemodule_from_instance($modulename, $instance->id, $instance->course);
1407 if (!empty($cm)) {
1408 course_module_calendar_event_update_process($instance, $cm);
1410 return true;
1412 return false;
1416 * Update all instances through out the site or in a course.
1418 * @param string $modulename Module type to update.
1419 * @param integer $courseid Course id to update events. 0 for the whole site.
1420 * @return bool Returns True if the update was successful.
1421 * @since Moodle 3.3.4
1423 function course_module_bulk_update_calendar_events($modulename, $courseid = 0) {
1424 global $DB;
1426 $instances = null;
1427 if ($courseid) {
1428 if (!$instances = $DB->get_records($modulename, array('course' => $courseid))) {
1429 return false;
1431 } else {
1432 if (!$instances = $DB->get_records($modulename)) {
1433 return false;
1437 foreach ($instances as $instance) {
1438 if ($cm = get_coursemodule_from_instance($modulename, $instance->id, $instance->course)) {
1439 course_module_calendar_event_update_process($instance, $cm);
1442 return true;
1446 * Calendar events for a module instance are updated.
1448 * @param stdClass $instance Module instance object.
1449 * @param stdClass $cm Course Module object.
1450 * @since Moodle 3.3.4
1452 function course_module_calendar_event_update_process($instance, $cm) {
1453 // We need to call *_refresh_events() first because some modules delete 'old' events at the end of the code which
1454 // will remove the completion events.
1455 $refresheventsfunction = $cm->modname . '_refresh_events';
1456 if (function_exists($refresheventsfunction)) {
1457 call_user_func($refresheventsfunction, $cm->course, $instance, $cm);
1459 $completionexpected = (!empty($cm->completionexpected)) ? $cm->completionexpected : null;
1460 \core_completion\api::update_completion_date_event($cm->id, $cm->modname, $instance, $completionexpected);
1464 * Moves a section within a course, from a position to another.
1465 * Be very careful: $section and $destination refer to section number,
1466 * not id!.
1468 * @param object $course
1469 * @param int $section Section number (not id!!!)
1470 * @param int $destination
1471 * @param bool $ignorenumsections
1472 * @return boolean Result
1474 function move_section_to($course, $section, $destination, $ignorenumsections = false) {
1475 /// Moves a whole course section up and down within the course
1476 global $USER, $DB;
1478 if (!$destination && $destination != 0) {
1479 return true;
1482 // compartibility with course formats using field 'numsections'
1483 $courseformatoptions = course_get_format($course)->get_format_options();
1484 if ((!$ignorenumsections && array_key_exists('numsections', $courseformatoptions) &&
1485 ($destination > $courseformatoptions['numsections'])) || ($destination < 1)) {
1486 return false;
1489 // Get all sections for this course and re-order them (2 of them should now share the same section number)
1490 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
1491 'section ASC, id ASC', 'id, section')) {
1492 return false;
1495 $movedsections = reorder_sections($sections, $section, $destination);
1497 // Update all sections. Do this in 2 steps to avoid breaking database
1498 // uniqueness constraint
1499 $transaction = $DB->start_delegated_transaction();
1500 foreach ($movedsections as $id => $position) {
1501 if ($sections[$id] !== $position) {
1502 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
1505 foreach ($movedsections as $id => $position) {
1506 if ($sections[$id] !== $position) {
1507 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
1511 // If we move the highlighted section itself, then just highlight the destination.
1512 // Adjust the higlighted section location if we move something over it either direction.
1513 if ($section == $course->marker) {
1514 course_set_marker($course->id, $destination);
1515 } elseif ($section > $course->marker && $course->marker >= $destination) {
1516 course_set_marker($course->id, $course->marker+1);
1517 } elseif ($section < $course->marker && $course->marker <= $destination) {
1518 course_set_marker($course->id, $course->marker-1);
1521 $transaction->allow_commit();
1522 rebuild_course_cache($course->id, true);
1523 return true;
1527 * This method will delete a course section and may delete all modules inside it.
1529 * No permissions are checked here, use {@link course_can_delete_section()} to
1530 * check if section can actually be deleted.
1532 * @param int|stdClass $course
1533 * @param int|stdClass|section_info $section
1534 * @param bool $forcedeleteifnotempty if set to false section will not be deleted if it has modules in it.
1535 * @param bool $async whether or not to try to delete the section using an adhoc task. Async also depends on a plugin hook.
1536 * @return bool whether section was deleted
1538 function course_delete_section($course, $section, $forcedeleteifnotempty = true, $async = false) {
1539 global $DB;
1541 // Prepare variables.
1542 $courseid = (is_object($course)) ? $course->id : (int)$course;
1543 $sectionnum = (is_object($section)) ? $section->section : (int)$section;
1544 $section = $DB->get_record('course_sections', array('course' => $courseid, 'section' => $sectionnum));
1545 if (!$section) {
1546 // No section exists, can't proceed.
1547 return false;
1550 // Check the 'course_module_background_deletion_recommended' hook first.
1551 // Only use asynchronous deletion if at least one plugin returns true and if async deletion has been requested.
1552 // Both are checked because plugins should not be allowed to dictate the deletion behaviour, only support/decline it.
1553 // It's up to plugins to handle things like whether or not they are enabled.
1554 if ($async && $pluginsfunction = get_plugins_with_function('course_module_background_deletion_recommended')) {
1555 foreach ($pluginsfunction as $plugintype => $plugins) {
1556 foreach ($plugins as $pluginfunction) {
1557 if ($pluginfunction()) {
1558 return course_delete_section_async($section, $forcedeleteifnotempty);
1564 $format = course_get_format($course);
1565 $sectionname = $format->get_section_name($section);
1567 // Delete section.
1568 $result = $format->delete_section($section, $forcedeleteifnotempty);
1570 // Trigger an event for course section deletion.
1571 if ($result) {
1572 $context = context_course::instance($courseid);
1573 $event = \core\event\course_section_deleted::create(
1574 array(
1575 'objectid' => $section->id,
1576 'courseid' => $courseid,
1577 'context' => $context,
1578 'other' => array(
1579 'sectionnum' => $section->section,
1580 'sectionname' => $sectionname,
1584 $event->add_record_snapshot('course_sections', $section);
1585 $event->trigger();
1587 return $result;
1591 * Course section deletion, using an adhoc task for deletion of the modules it contains.
1592 * 1. Schedule all modules within the section for adhoc removal.
1593 * 2. Move all modules to course section 0.
1594 * 3. Delete the resulting empty section.
1596 * @param \stdClass $section the section to schedule for deletion.
1597 * @param bool $forcedeleteifnotempty whether to force section deletion if it contains modules.
1598 * @return bool true if the section was scheduled for deletion, false otherwise.
1600 function course_delete_section_async($section, $forcedeleteifnotempty = true) {
1601 global $DB, $USER;
1603 // Objects only, and only valid ones.
1604 if (!is_object($section) || empty($section->id)) {
1605 return false;
1608 // Does the object currently exist in the DB for removal (check for stale objects).
1609 $section = $DB->get_record('course_sections', array('id' => $section->id));
1610 if (!$section || !$section->section) {
1611 // No section exists, or the section is 0. Can't proceed.
1612 return false;
1615 // Check whether the section can be removed.
1616 if (!$forcedeleteifnotempty && (!empty($section->sequence) || !empty($section->summary))) {
1617 return false;
1620 $format = course_get_format($section->course);
1621 $sectionname = $format->get_section_name($section);
1623 // Flag those modules having no existing deletion flag. Some modules may have been scheduled for deletion manually, and we don't
1624 // want to create additional adhoc deletion tasks for these. Moving them to section 0 will suffice.
1625 $affectedmods = $DB->get_records_select('course_modules', 'course = ? AND section = ? AND deletioninprogress <> ?',
1626 [$section->course, $section->id, 1], '', 'id');
1627 $DB->set_field('course_modules', 'deletioninprogress', '1', ['course' => $section->course, 'section' => $section->id]);
1629 // Move all modules to section 0.
1630 $modules = $DB->get_records('course_modules', ['section' => $section->id], '');
1631 $sectionzero = $DB->get_record('course_sections', ['course' => $section->course, 'section' => '0']);
1632 foreach ($modules as $mod) {
1633 moveto_module($mod, $sectionzero);
1636 // Create and queue an adhoc task for the deletion of the modules.
1637 $removaltask = new \core_course\task\course_delete_modules();
1638 $data = array(
1639 'cms' => $affectedmods,
1640 'userid' => $USER->id,
1641 'realuserid' => \core\session\manager::get_realuser()->id
1643 $removaltask->set_custom_data($data);
1644 \core\task\manager::queue_adhoc_task($removaltask);
1646 // Delete the now empty section, passing in only the section number, which forces the function to fetch a new object.
1647 // The refresh is needed because the section->sequence is now stale.
1648 $result = $format->delete_section($section->section, $forcedeleteifnotempty);
1650 // Trigger an event for course section deletion.
1651 if ($result) {
1652 $context = \context_course::instance($section->course);
1653 $event = \core\event\course_section_deleted::create(
1654 array(
1655 'objectid' => $section->id,
1656 'courseid' => $section->course,
1657 'context' => $context,
1658 'other' => array(
1659 'sectionnum' => $section->section,
1660 'sectionname' => $sectionname,
1664 $event->add_record_snapshot('course_sections', $section);
1665 $event->trigger();
1667 rebuild_course_cache($section->course, true);
1669 return $result;
1673 * Updates the course section
1675 * This function does not check permissions or clean values - this has to be done prior to calling it.
1677 * @param int|stdClass $course
1678 * @param stdClass $section record from course_sections table - it will be updated with the new values
1679 * @param array|stdClass $data
1681 function course_update_section($course, $section, $data) {
1682 global $DB;
1684 $courseid = (is_object($course)) ? $course->id : (int)$course;
1686 // Some fields can not be updated using this method.
1687 $data = array_diff_key((array)$data, array('id', 'course', 'section', 'sequence'));
1688 $changevisibility = (array_key_exists('visible', $data) && (bool)$data['visible'] != (bool)$section->visible);
1689 if (array_key_exists('name', $data) && \core_text::strlen($data['name']) > 255) {
1690 throw new moodle_exception('maximumchars', 'moodle', '', 255);
1693 // Update record in the DB and course format options.
1694 $data['id'] = $section->id;
1695 $data['timemodified'] = time();
1696 $DB->update_record('course_sections', $data);
1697 rebuild_course_cache($courseid, true);
1698 course_get_format($courseid)->update_section_format_options($data);
1700 // Update fields of the $section object.
1701 foreach ($data as $key => $value) {
1702 if (property_exists($section, $key)) {
1703 $section->$key = $value;
1707 // Trigger an event for course section update.
1708 $event = \core\event\course_section_updated::create(
1709 array(
1710 'objectid' => $section->id,
1711 'courseid' => $courseid,
1712 'context' => context_course::instance($courseid),
1713 'other' => array('sectionnum' => $section->section)
1716 $event->trigger();
1718 // If section visibility was changed, hide the modules in this section too.
1719 if ($changevisibility && !empty($section->sequence)) {
1720 $modules = explode(',', $section->sequence);
1721 foreach ($modules as $moduleid) {
1722 if ($cm = get_coursemodule_from_id(null, $moduleid, $courseid)) {
1723 if ($data['visible']) {
1724 // As we unhide the section, we use the previously saved visibility stored in visibleold.
1725 set_coursemodule_visible($moduleid, $cm->visibleold, $cm->visibleoncoursepage);
1726 } else {
1727 // We hide the section, so we hide the module but we store the original state in visibleold.
1728 set_coursemodule_visible($moduleid, 0, $cm->visibleoncoursepage);
1729 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id' => $moduleid));
1731 \core\event\course_module_updated::create_from_cm($cm)->trigger();
1738 * Checks if the current user can delete a section (if course format allows it and user has proper permissions).
1740 * @param int|stdClass $course
1741 * @param int|stdClass|section_info $section
1742 * @return bool
1744 function course_can_delete_section($course, $section) {
1745 if (is_object($section)) {
1746 $section = $section->section;
1748 if (!$section) {
1749 // Not possible to delete 0-section.
1750 return false;
1752 // Course format should allow to delete sections.
1753 if (!course_get_format($course)->can_delete_section($section)) {
1754 return false;
1756 // Make sure user has capability to update course and move sections.
1757 $context = context_course::instance(is_object($course) ? $course->id : $course);
1758 if (!has_all_capabilities(array('moodle/course:movesections', 'moodle/course:update'), $context)) {
1759 return false;
1761 // Make sure user has capability to delete each activity in this section.
1762 $modinfo = get_fast_modinfo($course);
1763 if (!empty($modinfo->sections[$section])) {
1764 foreach ($modinfo->sections[$section] as $cmid) {
1765 if (!has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
1766 return false;
1770 return true;
1774 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
1775 * an original position number and a target position number, rebuilds the array so that the
1776 * move is made without any duplication of section positions.
1777 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
1778 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
1780 * @param array $sections
1781 * @param int $origin_position
1782 * @param int $target_position
1783 * @return array
1785 function reorder_sections($sections, $origin_position, $target_position) {
1786 if (!is_array($sections)) {
1787 return false;
1790 // We can't move section position 0
1791 if ($origin_position < 1) {
1792 echo "We can't move section position 0";
1793 return false;
1796 // Locate origin section in sections array
1797 if (!$origin_key = array_search($origin_position, $sections)) {
1798 echo "searched position not in sections array";
1799 return false; // searched position not in sections array
1802 // Extract origin section
1803 $origin_section = $sections[$origin_key];
1804 unset($sections[$origin_key]);
1806 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
1807 $found = false;
1808 $append_array = array();
1809 foreach ($sections as $id => $position) {
1810 if ($found) {
1811 $append_array[$id] = $position;
1812 unset($sections[$id]);
1814 if ($position == $target_position) {
1815 if ($target_position < $origin_position) {
1816 $append_array[$id] = $position;
1817 unset($sections[$id]);
1819 $found = true;
1823 // Append moved section
1824 $sections[$origin_key] = $origin_section;
1826 // Append rest of array (if applicable)
1827 if (!empty($append_array)) {
1828 foreach ($append_array as $id => $position) {
1829 $sections[$id] = $position;
1833 // Renumber positions
1834 $position = 0;
1835 foreach ($sections as $id => $p) {
1836 $sections[$id] = $position;
1837 $position++;
1840 return $sections;
1845 * Move the module object $mod to the specified $section
1846 * If $beforemod exists then that is the module
1847 * before which $modid should be inserted
1849 * @param stdClass|cm_info $mod
1850 * @param stdClass|section_info $section
1851 * @param int|stdClass $beforemod id or object with field id corresponding to the module
1852 * before which the module needs to be included. Null for inserting in the
1853 * end of the section
1854 * @return int new value for module visibility (0 or 1)
1856 function moveto_module($mod, $section, $beforemod=NULL) {
1857 global $OUTPUT, $DB;
1859 // Current module visibility state - return value of this function.
1860 $modvisible = $mod->visible;
1862 // Remove original module from original section.
1863 if (! delete_mod_from_section($mod->id, $mod->section)) {
1864 echo $OUTPUT->notification("Could not delete module from existing section");
1867 // If moving to a hidden section then hide module.
1868 if ($mod->section != $section->id) {
1869 if (!$section->visible && $mod->visible) {
1870 // Module was visible but must become hidden after moving to hidden section.
1871 $modvisible = 0;
1872 set_coursemodule_visible($mod->id, 0);
1873 // Set visibleold to 1 so module will be visible when section is made visible.
1874 $DB->set_field('course_modules', 'visibleold', 1, array('id' => $mod->id));
1876 if ($section->visible && !$mod->visible) {
1877 // Hidden module was moved to the visible section, restore the module visibility from visibleold.
1878 set_coursemodule_visible($mod->id, $mod->visibleold);
1879 $modvisible = $mod->visibleold;
1883 // Add the module into the new section.
1884 course_add_cm_to_section($section->course, $mod->id, $section->section, $beforemod);
1885 return $modvisible;
1889 * Returns the list of all editing actions that current user can perform on the module
1891 * @param cm_info $mod The module to produce editing buttons for
1892 * @param int $indent The current indenting (default -1 means no move left-right actions)
1893 * @param int $sr The section to link back to (used for creating the links)
1894 * @return array array of action_link or pix_icon objects
1896 function course_get_cm_edit_actions(cm_info $mod, $indent = -1, $sr = null) {
1897 global $COURSE, $SITE, $CFG;
1899 static $str;
1901 $coursecontext = context_course::instance($mod->course);
1902 $modcontext = context_module::instance($mod->id);
1903 $courseformat = course_get_format($mod->get_course());
1905 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
1906 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
1908 // No permission to edit anything.
1909 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
1910 return array();
1913 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
1915 if (!isset($str)) {
1916 $str = get_strings(array('delete', 'move', 'moveright', 'moveleft',
1917 'editsettings', 'duplicate', 'modhide', 'makeavailable', 'makeunavailable', 'modshow'), 'moodle');
1918 $str->assign = get_string('assignroles', 'role');
1919 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
1920 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
1921 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
1924 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
1926 if ($sr !== null) {
1927 $baseurl->param('sr', $sr);
1929 $actions = array();
1931 // Update.
1932 if ($hasmanageactivities) {
1933 $actions['update'] = new action_menu_link_secondary(
1934 new moodle_url($baseurl, array('update' => $mod->id)),
1935 new pix_icon('t/edit', $str->editsettings, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1936 $str->editsettings,
1937 array('class' => 'editing_update', 'data-action' => 'update')
1941 // Indent.
1942 if ($hasmanageactivities && $indent >= 0) {
1943 $indentlimits = new stdClass();
1944 $indentlimits->min = 0;
1945 $indentlimits->max = 16;
1946 if (right_to_left()) { // Exchange arrows on RTL
1947 $rightarrow = 't/left';
1948 $leftarrow = 't/right';
1949 } else {
1950 $rightarrow = 't/right';
1951 $leftarrow = 't/left';
1954 if ($indent >= $indentlimits->max) {
1955 $enabledclass = 'hidden';
1956 } else {
1957 $enabledclass = '';
1959 $actions['moveright'] = new action_menu_link_secondary(
1960 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
1961 new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1962 $str->moveright,
1963 array('class' => 'editing_moveright ' . $enabledclass, 'data-action' => 'moveright',
1964 'data-keepopen' => true, 'data-sectionreturn' => $sr)
1967 if ($indent <= $indentlimits->min) {
1968 $enabledclass = 'hidden';
1969 } else {
1970 $enabledclass = '';
1972 $actions['moveleft'] = new action_menu_link_secondary(
1973 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
1974 new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1975 $str->moveleft,
1976 array('class' => 'editing_moveleft ' . $enabledclass, 'data-action' => 'moveleft',
1977 'data-keepopen' => true, 'data-sectionreturn' => $sr)
1982 // Hide/Show/Available/Unavailable.
1983 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
1984 $allowstealth = !empty($CFG->allowstealth) && $courseformat->allow_stealth_module_visibility($mod, $mod->get_section_info());
1986 $sectionvisible = $mod->get_section_info()->visible;
1987 // The module on the course page may be in one of the following states:
1988 // - Available and displayed on the course page ($displayedoncoursepage);
1989 // - Not available and not displayed on the course page ($unavailable);
1990 // - Available but not displayed on the course page ($stealth) - this can also be a visible activity in a hidden section.
1991 $displayedoncoursepage = $mod->visible && $mod->visibleoncoursepage && $sectionvisible;
1992 $unavailable = !$mod->visible;
1993 $stealth = $mod->visible && (!$mod->visibleoncoursepage || !$sectionvisible);
1994 if ($displayedoncoursepage) {
1995 $actions['hide'] = new action_menu_link_secondary(
1996 new moodle_url($baseurl, array('hide' => $mod->id)),
1997 new pix_icon('t/hide', $str->modhide, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1998 $str->modhide,
1999 array('class' => 'editing_hide', 'data-action' => 'hide')
2001 } else if (!$displayedoncoursepage && $sectionvisible) {
2002 // Offer to "show" only if the section is visible.
2003 $actions['show'] = new action_menu_link_secondary(
2004 new moodle_url($baseurl, array('show' => $mod->id)),
2005 new pix_icon('t/show', $str->modshow, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2006 $str->modshow,
2007 array('class' => 'editing_show', 'data-action' => 'show')
2011 if ($stealth) {
2012 // When making the "stealth" module unavailable we perform the same action as hiding the visible module.
2013 $actions['hide'] = new action_menu_link_secondary(
2014 new moodle_url($baseurl, array('hide' => $mod->id)),
2015 new pix_icon('t/unblock', $str->makeunavailable, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2016 $str->makeunavailable,
2017 array('class' => 'editing_makeunavailable', 'data-action' => 'hide', 'data-sectionreturn' => $sr)
2019 } else if ($unavailable && (!$sectionvisible || $allowstealth) && $mod->has_view()) {
2020 // Allow to make visually hidden module available in gradebook and other reports by making it a "stealth" module.
2021 // When the section is hidden it is an equivalent of "showing" the module.
2022 // Activities without the link (i.e. labels) can not be made available but hidden on course page.
2023 $action = $sectionvisible ? 'stealth' : 'show';
2024 $actions[$action] = new action_menu_link_secondary(
2025 new moodle_url($baseurl, array($action => $mod->id)),
2026 new pix_icon('t/block', $str->makeavailable, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2027 $str->makeavailable,
2028 array('class' => 'editing_makeavailable', 'data-action' => $action, 'data-sectionreturn' => $sr)
2033 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
2034 if (has_all_capabilities($dupecaps, $coursecontext) &&
2035 plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2) &&
2036 course_allowed_module($mod->get_course(), $mod->modname)) {
2037 $actions['duplicate'] = new action_menu_link_secondary(
2038 new moodle_url($baseurl, array('duplicate' => $mod->id)),
2039 new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2040 $str->duplicate,
2041 array('class' => 'editing_duplicate', 'data-action' => 'duplicate', 'data-sectionreturn' => $sr)
2045 // Groupmode.
2046 if ($hasmanageactivities && !$mod->coursegroupmodeforce) {
2047 if (plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
2048 if ($mod->effectivegroupmode == SEPARATEGROUPS) {
2049 $nextgroupmode = VISIBLEGROUPS;
2050 $grouptitle = $str->groupsseparate;
2051 $actionname = 'groupsseparate';
2052 $nextactionname = 'groupsvisible';
2053 $groupimage = 'i/groups';
2054 } else if ($mod->effectivegroupmode == VISIBLEGROUPS) {
2055 $nextgroupmode = NOGROUPS;
2056 $grouptitle = $str->groupsvisible;
2057 $actionname = 'groupsvisible';
2058 $nextactionname = 'groupsnone';
2059 $groupimage = 'i/groupv';
2060 } else {
2061 $nextgroupmode = SEPARATEGROUPS;
2062 $grouptitle = $str->groupsnone;
2063 $actionname = 'groupsnone';
2064 $nextactionname = 'groupsseparate';
2065 $groupimage = 'i/groupn';
2068 $actions[$actionname] = new action_menu_link_primary(
2069 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $nextgroupmode)),
2070 new pix_icon($groupimage, $grouptitle, 'moodle', array('class' => 'iconsmall')),
2071 $grouptitle,
2072 array('class' => 'editing_'. $actionname, 'data-action' => $nextactionname,
2073 'aria-live' => 'assertive', 'data-sectionreturn' => $sr)
2075 } else {
2076 $actions['nogroupsupport'] = new action_menu_filler();
2080 // Assign.
2081 if (has_capability('moodle/role:assign', $modcontext)){
2082 $actions['assign'] = new action_menu_link_secondary(
2083 new moodle_url('/admin/roles/assign.php', array('contextid' => $modcontext->id)),
2084 new pix_icon('t/assignroles', $str->assign, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2085 $str->assign,
2086 array('class' => 'editing_assign', 'data-action' => 'assignroles', 'data-sectionreturn' => $sr)
2090 // Delete.
2091 if ($hasmanageactivities) {
2092 $actions['delete'] = new action_menu_link_secondary(
2093 new moodle_url($baseurl, array('delete' => $mod->id)),
2094 new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2095 $str->delete,
2096 array('class' => 'editing_delete', 'data-action' => 'delete', 'data-sectionreturn' => $sr)
2100 return $actions;
2104 * Returns the move action.
2106 * @param cm_info $mod The module to produce a move button for
2107 * @param int $sr The section to link back to (used for creating the links)
2108 * @return The markup for the move action, or an empty string if not available.
2110 function course_get_cm_move(cm_info $mod, $sr = null) {
2111 global $OUTPUT;
2113 static $str;
2114 static $baseurl;
2116 $modcontext = context_module::instance($mod->id);
2117 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
2119 if (!isset($str)) {
2120 $str = get_strings(array('move'));
2123 if (!isset($baseurl)) {
2124 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
2126 if ($sr !== null) {
2127 $baseurl->param('sr', $sr);
2131 if ($hasmanageactivities) {
2132 $pixicon = 'i/dragdrop';
2134 if (!course_ajax_enabled($mod->get_course())) {
2135 // Override for course frontpage until we get drag/drop working there.
2136 $pixicon = 't/move';
2139 return html_writer::link(
2140 new moodle_url($baseurl, array('copy' => $mod->id)),
2141 $OUTPUT->pix_icon($pixicon, $str->move, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2142 array('class' => 'editing_move', 'data-action' => 'move', 'data-sectionreturn' => $sr)
2145 return '';
2149 * given a course object with shortname & fullname, this function will
2150 * truncate the the number of chars allowed and add ... if it was too long
2152 function course_format_name ($course,$max=100) {
2154 $context = context_course::instance($course->id);
2155 $shortname = format_string($course->shortname, true, array('context' => $context));
2156 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
2157 $str = $shortname.': '. $fullname;
2158 if (core_text::strlen($str) <= $max) {
2159 return $str;
2161 else {
2162 return core_text::substr($str,0,$max-3).'...';
2167 * Is the user allowed to add this type of module to this course?
2168 * @param object $course the course settings. Only $course->id is used.
2169 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
2170 * @return bool whether the current user is allowed to add this type of module to this course.
2172 function course_allowed_module($course, $modname) {
2173 if (is_numeric($modname)) {
2174 throw new coding_exception('Function course_allowed_module no longer
2175 supports numeric module ids. Please update your code to pass the module name.');
2178 $capability = 'mod/' . $modname . ':addinstance';
2179 if (!get_capability_info($capability)) {
2180 // Debug warning that the capability does not exist, but no more than once per page.
2181 static $warned = array();
2182 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
2183 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
2184 debugging('The module ' . $modname . ' does not define the standard capability ' .
2185 $capability , DEBUG_DEVELOPER);
2186 $warned[$modname] = 1;
2189 // If the capability does not exist, the module can always be added.
2190 return true;
2193 $coursecontext = context_course::instance($course->id);
2194 return has_capability($capability, $coursecontext);
2198 * Efficiently moves many courses around while maintaining
2199 * sortorder in order.
2201 * @param array $courseids is an array of course ids
2202 * @param int $categoryid
2203 * @return bool success
2205 function move_courses($courseids, $categoryid) {
2206 global $DB;
2208 if (empty($courseids)) {
2209 // Nothing to do.
2210 return false;
2213 if (!$category = $DB->get_record('course_categories', array('id' => $categoryid))) {
2214 return false;
2217 $courseids = array_reverse($courseids);
2218 $newparent = context_coursecat::instance($category->id);
2219 $i = 1;
2221 list($where, $params) = $DB->get_in_or_equal($courseids);
2222 $dbcourses = $DB->get_records_select('course', 'id ' . $where, $params, '', 'id, category, shortname, fullname');
2223 foreach ($dbcourses as $dbcourse) {
2224 $course = new stdClass();
2225 $course->id = $dbcourse->id;
2226 $course->category = $category->id;
2227 $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
2228 if ($category->visible == 0) {
2229 // Hide the course when moving into hidden category, do not update the visibleold flag - we want to get
2230 // to previous state if somebody unhides the category.
2231 $course->visible = 0;
2234 $DB->update_record('course', $course);
2236 // Update context, so it can be passed to event.
2237 $context = context_course::instance($course->id);
2238 $context->update_moved($newparent);
2240 // Trigger a course updated event.
2241 $event = \core\event\course_updated::create(array(
2242 'objectid' => $course->id,
2243 'context' => context_course::instance($course->id),
2244 'other' => array('shortname' => $dbcourse->shortname,
2245 'fullname' => $dbcourse->fullname)
2247 $event->set_legacy_logdata(array($course->id, 'course', 'move', 'edit.php?id=' . $course->id, $course->id));
2248 $event->trigger();
2250 fix_course_sortorder();
2251 cache_helper::purge_by_event('changesincourse');
2253 return true;
2257 * Returns the display name of the given section that the course prefers
2259 * Implementation of this function is provided by course format
2260 * @see format_base::get_section_name()
2262 * @param int|stdClass $courseorid The course to get the section name for (object or just course id)
2263 * @param int|stdClass $section Section object from database or just field course_sections.section
2264 * @return string Display name that the course format prefers, e.g. "Week 2"
2266 function get_section_name($courseorid, $section) {
2267 return course_get_format($courseorid)->get_section_name($section);
2271 * Tells if current course format uses sections
2273 * @param string $format Course format ID e.g. 'weeks' $course->format
2274 * @return bool
2276 function course_format_uses_sections($format) {
2277 $course = new stdClass();
2278 $course->format = $format;
2279 return course_get_format($course)->uses_sections();
2283 * Returns the information about the ajax support in the given source format
2285 * The returned object's property (boolean)capable indicates that
2286 * the course format supports Moodle course ajax features.
2288 * @param string $format
2289 * @return stdClass
2291 function course_format_ajax_support($format) {
2292 $course = new stdClass();
2293 $course->format = $format;
2294 return course_get_format($course)->supports_ajax();
2298 * Can the current user delete this course?
2299 * Course creators have exception,
2300 * 1 day after the creation they can sill delete the course.
2301 * @param int $courseid
2302 * @return boolean
2304 function can_delete_course($courseid) {
2305 global $USER;
2307 $context = context_course::instance($courseid);
2309 if (has_capability('moodle/course:delete', $context)) {
2310 return true;
2313 // hack: now try to find out if creator created this course recently (1 day)
2314 if (!has_capability('moodle/course:create', $context)) {
2315 return false;
2318 $since = time() - 60*60*24;
2319 $course = get_course($courseid);
2321 if ($course->timecreated < $since) {
2322 return false; // Return if the course was not created in last 24 hours.
2325 $logmanger = get_log_manager();
2326 $readers = $logmanger->get_readers('\core\log\sql_reader');
2327 $reader = reset($readers);
2329 if (empty($reader)) {
2330 return false; // No log reader found.
2333 // A proper reader.
2334 $select = "userid = :userid AND courseid = :courseid AND eventname = :eventname AND timecreated > :since";
2335 $params = array('userid' => $USER->id, 'since' => $since, 'courseid' => $course->id, 'eventname' => '\core\event\course_created');
2337 return (bool)$reader->get_events_select_count($select, $params);
2341 * Save the Your name for 'Some role' strings.
2343 * @param integer $courseid the id of this course.
2344 * @param array $data the data that came from the course settings form.
2346 function save_local_role_names($courseid, $data) {
2347 global $DB;
2348 $context = context_course::instance($courseid);
2350 foreach ($data as $fieldname => $value) {
2351 if (strpos($fieldname, 'role_') !== 0) {
2352 continue;
2354 list($ignored, $roleid) = explode('_', $fieldname);
2356 // make up our mind whether we want to delete, update or insert
2357 if (!$value) {
2358 $DB->delete_records('role_names', array('contextid' => $context->id, 'roleid' => $roleid));
2360 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id, 'roleid' => $roleid))) {
2361 $rolename->name = $value;
2362 $DB->update_record('role_names', $rolename);
2364 } else {
2365 $rolename = new stdClass;
2366 $rolename->contextid = $context->id;
2367 $rolename->roleid = $roleid;
2368 $rolename->name = $value;
2369 $DB->insert_record('role_names', $rolename);
2371 // This will ensure the course contacts cache is purged..
2372 coursecat::role_assignment_changed($roleid, $context);
2377 * Returns options to use in course overviewfiles filemanager
2379 * @param null|stdClass|course_in_list|int $course either object that has 'id' property or just the course id;
2380 * may be empty if course does not exist yet (course create form)
2381 * @return array|null array of options such as maxfiles, maxbytes, accepted_types, etc.
2382 * or null if overviewfiles are disabled
2384 function course_overviewfiles_options($course) {
2385 global $CFG;
2386 if (empty($CFG->courseoverviewfileslimit)) {
2387 return null;
2389 $accepted_types = preg_split('/\s*,\s*/', trim($CFG->courseoverviewfilesext), -1, PREG_SPLIT_NO_EMPTY);
2390 if (in_array('*', $accepted_types) || empty($accepted_types)) {
2391 $accepted_types = '*';
2392 } else {
2393 // Since config for $CFG->courseoverviewfilesext is a text box, human factor must be considered.
2394 // Make sure extensions are prefixed with dot unless they are valid typegroups
2395 foreach ($accepted_types as $i => $type) {
2396 if (substr($type, 0, 1) !== '.') {
2397 require_once($CFG->libdir. '/filelib.php');
2398 if (!count(file_get_typegroup('extension', $type))) {
2399 // It does not start with dot and is not a valid typegroup, this is most likely extension.
2400 $accepted_types[$i] = '.'. $type;
2401 $corrected = true;
2405 if (!empty($corrected)) {
2406 set_config('courseoverviewfilesext', join(',', $accepted_types));
2409 $options = array(
2410 'maxfiles' => $CFG->courseoverviewfileslimit,
2411 'maxbytes' => $CFG->maxbytes,
2412 'subdirs' => 0,
2413 'accepted_types' => $accepted_types
2415 if (!empty($course->id)) {
2416 $options['context'] = context_course::instance($course->id);
2417 } else if (is_int($course) && $course > 0) {
2418 $options['context'] = context_course::instance($course);
2420 return $options;
2424 * Create a course and either return a $course object
2426 * Please note this functions does not verify any access control,
2427 * the calling code is responsible for all validation (usually it is the form definition).
2429 * @param array $editoroptions course description editor options
2430 * @param object $data - all the data needed for an entry in the 'course' table
2431 * @return object new course instance
2433 function create_course($data, $editoroptions = NULL) {
2434 global $DB, $CFG;
2436 //check the categoryid - must be given for all new courses
2437 $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
2439 // Check if the shortname already exists.
2440 if (!empty($data->shortname)) {
2441 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
2442 throw new moodle_exception('shortnametaken', '', '', $data->shortname);
2446 // Check if the idnumber already exists.
2447 if (!empty($data->idnumber)) {
2448 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
2449 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber);
2453 if ($errorcode = course_validate_dates((array)$data)) {
2454 throw new moodle_exception($errorcode);
2457 // Check if timecreated is given.
2458 $data->timecreated = !empty($data->timecreated) ? $data->timecreated : time();
2459 $data->timemodified = $data->timecreated;
2461 // place at beginning of any category
2462 $data->sortorder = 0;
2464 if ($editoroptions) {
2465 // summary text is updated later, we need context to store the files first
2466 $data->summary = '';
2467 $data->summary_format = FORMAT_HTML;
2470 if (!isset($data->visible)) {
2471 // data not from form, add missing visibility info
2472 $data->visible = $category->visible;
2474 $data->visibleold = $data->visible;
2476 $newcourseid = $DB->insert_record('course', $data);
2477 $context = context_course::instance($newcourseid, MUST_EXIST);
2479 if ($editoroptions) {
2480 // Save the files used in the summary editor and store
2481 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2482 $DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid));
2483 $DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid));
2485 if ($overviewfilesoptions = course_overviewfiles_options($newcourseid)) {
2486 // Save the course overviewfiles
2487 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2490 // update course format options
2491 course_get_format($newcourseid)->update_course_format_options($data);
2493 $course = course_get_format($newcourseid)->get_course();
2495 fix_course_sortorder();
2496 // purge appropriate caches in case fix_course_sortorder() did not change anything
2497 cache_helper::purge_by_event('changesincourse');
2499 // new context created - better mark it as dirty
2500 $context->mark_dirty();
2502 // Trigger a course created event.
2503 $event = \core\event\course_created::create(array(
2504 'objectid' => $course->id,
2505 'context' => context_course::instance($course->id),
2506 'other' => array('shortname' => $course->shortname,
2507 'fullname' => $course->fullname)
2510 $event->trigger();
2512 // Setup the blocks
2513 blocks_add_default_course_blocks($course);
2515 // Create default section and initial sections if specified (unless they've already been created earlier).
2516 // We do not want to call course_create_sections_if_missing() because to avoid creating course cache.
2517 $numsections = isset($data->numsections) ? $data->numsections : 0;
2518 $existingsections = $DB->get_fieldset_sql('SELECT section from {course_sections} WHERE course = ?', [$newcourseid]);
2519 $newsections = array_diff(range(0, $numsections), $existingsections);
2520 foreach ($newsections as $sectionnum) {
2521 course_create_section($newcourseid, $sectionnum, true);
2524 // Save any custom role names.
2525 save_local_role_names($course->id, (array)$data);
2527 // set up enrolments
2528 enrol_course_updated(true, $course, $data);
2530 // Update course tags.
2531 if (isset($data->tags)) {
2532 core_tag_tag::set_item_tags('core', 'course', $course->id, context_course::instance($course->id), $data->tags);
2535 return $course;
2539 * Update a course.
2541 * Please note this functions does not verify any access control,
2542 * the calling code is responsible for all validation (usually it is the form definition).
2544 * @param object $data - all the data needed for an entry in the 'course' table
2545 * @param array $editoroptions course description editor options
2546 * @return void
2548 function update_course($data, $editoroptions = NULL) {
2549 global $DB, $CFG;
2551 $data->timemodified = time();
2553 // Prevent changes on front page course.
2554 if ($data->id == SITEID) {
2555 throw new moodle_exception('invalidcourse', 'error');
2558 $oldcourse = course_get_format($data->id)->get_course();
2559 $context = context_course::instance($oldcourse->id);
2561 if ($editoroptions) {
2562 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2564 if ($overviewfilesoptions = course_overviewfiles_options($data->id)) {
2565 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2568 // Check we don't have a duplicate shortname.
2569 if (!empty($data->shortname) && $oldcourse->shortname != $data->shortname) {
2570 if ($DB->record_exists_sql('SELECT id from {course} WHERE shortname = ? AND id <> ?', array($data->shortname, $data->id))) {
2571 throw new moodle_exception('shortnametaken', '', '', $data->shortname);
2575 // Check we don't have a duplicate idnumber.
2576 if (!empty($data->idnumber) && $oldcourse->idnumber != $data->idnumber) {
2577 if ($DB->record_exists_sql('SELECT id from {course} WHERE idnumber = ? AND id <> ?', array($data->idnumber, $data->id))) {
2578 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber);
2582 if ($errorcode = course_validate_dates((array)$data)) {
2583 throw new moodle_exception($errorcode);
2586 if (!isset($data->category) or empty($data->category)) {
2587 // prevent nulls and 0 in category field
2588 unset($data->category);
2590 $changesincoursecat = $movecat = (isset($data->category) and $oldcourse->category != $data->category);
2592 if (!isset($data->visible)) {
2593 // data not from form, add missing visibility info
2594 $data->visible = $oldcourse->visible;
2597 if ($data->visible != $oldcourse->visible) {
2598 // reset the visibleold flag when manually hiding/unhiding course
2599 $data->visibleold = $data->visible;
2600 $changesincoursecat = true;
2601 } else {
2602 if ($movecat) {
2603 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category));
2604 if (empty($newcategory->visible)) {
2605 // make sure when moving into hidden category the course is hidden automatically
2606 $data->visible = 0;
2611 // Set newsitems to 0 if format does not support announcements.
2612 if (isset($data->format)) {
2613 $newcourseformat = course_get_format((object)['format' => $data->format]);
2614 if (!$newcourseformat->supports_news()) {
2615 $data->newsitems = 0;
2619 // Update with the new data
2620 $DB->update_record('course', $data);
2621 // make sure the modinfo cache is reset
2622 rebuild_course_cache($data->id);
2624 // update course format options with full course data
2625 course_get_format($data->id)->update_course_format_options($data, $oldcourse);
2627 $course = $DB->get_record('course', array('id'=>$data->id));
2629 if ($movecat) {
2630 $newparent = context_coursecat::instance($course->category);
2631 $context->update_moved($newparent);
2633 $fixcoursesortorder = $movecat || (isset($data->sortorder) && ($oldcourse->sortorder != $data->sortorder));
2634 if ($fixcoursesortorder) {
2635 fix_course_sortorder();
2638 // purge appropriate caches in case fix_course_sortorder() did not change anything
2639 cache_helper::purge_by_event('changesincourse');
2640 if ($changesincoursecat) {
2641 cache_helper::purge_by_event('changesincoursecat');
2644 // Test for and remove blocks which aren't appropriate anymore
2645 blocks_remove_inappropriate($course);
2647 // Save any custom role names.
2648 save_local_role_names($course->id, $data);
2650 // update enrol settings
2651 enrol_course_updated(false, $course, $data);
2653 // Update course tags.
2654 if (isset($data->tags)) {
2655 core_tag_tag::set_item_tags('core', 'course', $course->id, context_course::instance($course->id), $data->tags);
2658 // Trigger a course updated event.
2659 $event = \core\event\course_updated::create(array(
2660 'objectid' => $course->id,
2661 'context' => context_course::instance($course->id),
2662 'other' => array('shortname' => $course->shortname,
2663 'fullname' => $course->fullname)
2666 $event->set_legacy_logdata(array($course->id, 'course', 'update', 'edit.php?id=' . $course->id, $course->id));
2667 $event->trigger();
2669 if ($oldcourse->format !== $course->format) {
2670 // Remove all options stored for the previous format
2671 // We assume that new course format migrated everything it needed watching trigger
2672 // 'course_updated' and in method format_XXX::update_course_format_options()
2673 $DB->delete_records('course_format_options',
2674 array('courseid' => $course->id, 'format' => $oldcourse->format));
2679 * Average number of participants
2680 * @return integer
2682 function average_number_of_participants() {
2683 global $DB, $SITE;
2685 //count total of enrolments for visible course (except front page)
2686 $sql = 'SELECT COUNT(*) FROM (
2687 SELECT DISTINCT ue.userid, e.courseid
2688 FROM {user_enrolments} ue, {enrol} e, {course} c
2689 WHERE ue.enrolid = e.id
2690 AND e.courseid <> :siteid
2691 AND c.id = e.courseid
2692 AND c.visible = 1) total';
2693 $params = array('siteid' => $SITE->id);
2694 $enrolmenttotal = $DB->count_records_sql($sql, $params);
2697 //count total of visible courses (minus front page)
2698 $coursetotal = $DB->count_records('course', array('visible' => 1));
2699 $coursetotal = $coursetotal - 1 ;
2701 //average of enrolment
2702 if (empty($coursetotal)) {
2703 $participantaverage = 0;
2704 } else {
2705 $participantaverage = $enrolmenttotal / $coursetotal;
2708 return $participantaverage;
2712 * Average number of course modules
2713 * @return integer
2715 function average_number_of_courses_modules() {
2716 global $DB, $SITE;
2718 //count total of visible course module (except front page)
2719 $sql = 'SELECT COUNT(*) FROM (
2720 SELECT cm.course, cm.module
2721 FROM {course} c, {course_modules} cm
2722 WHERE c.id = cm.course
2723 AND c.id <> :siteid
2724 AND cm.visible = 1
2725 AND c.visible = 1) total';
2726 $params = array('siteid' => $SITE->id);
2727 $moduletotal = $DB->count_records_sql($sql, $params);
2730 //count total of visible courses (minus front page)
2731 $coursetotal = $DB->count_records('course', array('visible' => 1));
2732 $coursetotal = $coursetotal - 1 ;
2734 //average of course module
2735 if (empty($coursetotal)) {
2736 $coursemoduleaverage = 0;
2737 } else {
2738 $coursemoduleaverage = $moduletotal / $coursetotal;
2741 return $coursemoduleaverage;
2745 * This class pertains to course requests and contains methods associated with
2746 * create, approving, and removing course requests.
2748 * Please note we do not allow embedded images here because there is no context
2749 * to store them with proper access control.
2751 * @copyright 2009 Sam Hemelryk
2752 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2753 * @since Moodle 2.0
2755 * @property-read int $id
2756 * @property-read string $fullname
2757 * @property-read string $shortname
2758 * @property-read string $summary
2759 * @property-read int $summaryformat
2760 * @property-read int $summarytrust
2761 * @property-read string $reason
2762 * @property-read int $requester
2764 class course_request {
2767 * This is the stdClass that stores the properties for the course request
2768 * and is externally accessed through the __get magic method
2769 * @var stdClass
2771 protected $properties;
2774 * An array of options for the summary editor used by course request forms.
2775 * This is initially set by {@link summary_editor_options()}
2776 * @var array
2777 * @static
2779 protected static $summaryeditoroptions;
2782 * Static function to prepare the summary editor for working with a course
2783 * request.
2785 * @static
2786 * @param null|stdClass $data Optional, an object containing the default values
2787 * for the form, these may be modified when preparing the
2788 * editor so this should be called before creating the form
2789 * @return stdClass An object that can be used to set the default values for
2790 * an mforms form
2792 public static function prepare($data=null) {
2793 if ($data === null) {
2794 $data = new stdClass;
2796 $data = file_prepare_standard_editor($data, 'summary', self::summary_editor_options());
2797 return $data;
2801 * Static function to create a new course request when passed an array of properties
2802 * for it.
2804 * This function also handles saving any files that may have been used in the editor
2806 * @static
2807 * @param stdClass $data
2808 * @return course_request The newly created course request
2810 public static function create($data) {
2811 global $USER, $DB, $CFG;
2812 $data->requester = $USER->id;
2814 // Setting the default category if none set.
2815 if (empty($data->category) || empty($CFG->requestcategoryselection)) {
2816 $data->category = $CFG->defaultrequestcategory;
2819 // Summary is a required field so copy the text over
2820 $data->summary = $data->summary_editor['text'];
2821 $data->summaryformat = $data->summary_editor['format'];
2823 $data->id = $DB->insert_record('course_request', $data);
2825 // Create a new course_request object and return it
2826 $request = new course_request($data);
2828 // Notify the admin if required.
2829 if ($users = get_users_from_config($CFG->courserequestnotify, 'moodle/site:approvecourse')) {
2831 $a = new stdClass;
2832 $a->link = "$CFG->wwwroot/course/pending.php";
2833 $a->user = fullname($USER);
2834 $subject = get_string('courserequest');
2835 $message = get_string('courserequestnotifyemail', 'admin', $a);
2836 foreach ($users as $user) {
2837 $request->notify($user, $USER, 'courserequested', $subject, $message);
2841 return $request;
2845 * Returns an array of options to use with a summary editor
2847 * @uses course_request::$summaryeditoroptions
2848 * @return array An array of options to use with the editor
2850 public static function summary_editor_options() {
2851 global $CFG;
2852 if (self::$summaryeditoroptions === null) {
2853 self::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
2855 return self::$summaryeditoroptions;
2859 * Loads the properties for this course request object. Id is required and if
2860 * only id is provided then we load the rest of the properties from the database
2862 * @param stdClass|int $properties Either an object containing properties
2863 * or the course_request id to load
2865 public function __construct($properties) {
2866 global $DB;
2867 if (empty($properties->id)) {
2868 if (empty($properties)) {
2869 throw new coding_exception('You must provide a course request id when creating a course_request object');
2871 $id = $properties;
2872 $properties = new stdClass;
2873 $properties->id = (int)$id;
2874 unset($id);
2876 if (empty($properties->requester)) {
2877 if (!($this->properties = $DB->get_record('course_request', array('id' => $properties->id)))) {
2878 print_error('unknowncourserequest');
2880 } else {
2881 $this->properties = $properties;
2883 $this->properties->collision = null;
2887 * Returns the requested property
2889 * @param string $key
2890 * @return mixed
2892 public function __get($key) {
2893 return $this->properties->$key;
2897 * Override this to ensure empty($request->blah) calls return a reliable answer...
2899 * This is required because we define the __get method
2901 * @param mixed $key
2902 * @return bool True is it not empty, false otherwise
2904 public function __isset($key) {
2905 return (!empty($this->properties->$key));
2909 * Returns the user who requested this course
2911 * Uses a static var to cache the results and cut down the number of db queries
2913 * @staticvar array $requesters An array of cached users
2914 * @return stdClass The user who requested the course
2916 public function get_requester() {
2917 global $DB;
2918 static $requesters= array();
2919 if (!array_key_exists($this->properties->requester, $requesters)) {
2920 $requesters[$this->properties->requester] = $DB->get_record('user', array('id'=>$this->properties->requester));
2922 return $requesters[$this->properties->requester];
2926 * Checks that the shortname used by the course does not conflict with any other
2927 * courses that exist
2929 * @param string|null $shortnamemark The string to append to the requests shortname
2930 * should a conflict be found
2931 * @return bool true is there is a conflict, false otherwise
2933 public function check_shortname_collision($shortnamemark = '[*]') {
2934 global $DB;
2936 if ($this->properties->collision !== null) {
2937 return $this->properties->collision;
2940 if (empty($this->properties->shortname)) {
2941 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER);
2942 $this->properties->collision = false;
2943 } else if ($DB->record_exists('course', array('shortname' => $this->properties->shortname))) {
2944 if (!empty($shortnamemark)) {
2945 $this->properties->shortname .= ' '.$shortnamemark;
2947 $this->properties->collision = true;
2948 } else {
2949 $this->properties->collision = false;
2951 return $this->properties->collision;
2955 * Returns the category where this course request should be created
2957 * Note that we don't check here that user has a capability to view
2958 * hidden categories if he has capabilities 'moodle/site:approvecourse' and
2959 * 'moodle/course:changecategory'
2961 * @return coursecat
2963 public function get_category() {
2964 global $CFG;
2965 require_once($CFG->libdir.'/coursecatlib.php');
2966 // If the category is not set, if the current user does not have the rights to change the category, or if the
2967 // category does not exist, we set the default category to the course to be approved.
2968 // The system level is used because the capability moodle/site:approvecourse is based on a system level.
2969 if (empty($this->properties->category) || !has_capability('moodle/course:changecategory', context_system::instance()) ||
2970 (!$category = coursecat::get($this->properties->category, IGNORE_MISSING, true))) {
2971 $category = coursecat::get($CFG->defaultrequestcategory, IGNORE_MISSING, true);
2973 if (!$category) {
2974 $category = coursecat::get_default();
2976 return $category;
2980 * This function approves the request turning it into a course
2982 * This function converts the course request into a course, at the same time
2983 * transferring any files used in the summary to the new course and then removing
2984 * the course request and the files associated with it.
2986 * @return int The id of the course that was created from this request
2988 public function approve() {
2989 global $CFG, $DB, $USER;
2991 $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted'=>0), '*', MUST_EXIST);
2993 $courseconfig = get_config('moodlecourse');
2995 // Transfer appropriate settings
2996 $data = clone($this->properties);
2997 unset($data->id);
2998 unset($data->reason);
2999 unset($data->requester);
3001 // Set category
3002 $category = $this->get_category();
3003 $data->category = $category->id;
3004 // Set misc settings
3005 $data->requested = 1;
3007 // Apply course default settings
3008 $data->format = $courseconfig->format;
3009 $data->newsitems = $courseconfig->newsitems;
3010 $data->showgrades = $courseconfig->showgrades;
3011 $data->showreports = $courseconfig->showreports;
3012 $data->maxbytes = $courseconfig->maxbytes;
3013 $data->groupmode = $courseconfig->groupmode;
3014 $data->groupmodeforce = $courseconfig->groupmodeforce;
3015 $data->visible = $courseconfig->visible;
3016 $data->visibleold = $data->visible;
3017 $data->lang = $courseconfig->lang;
3018 $data->enablecompletion = $courseconfig->enablecompletion;
3019 $data->numsections = $courseconfig->numsections;
3020 $data->startdate = usergetmidnight(time());
3021 if ($courseconfig->courseenddateenabled) {
3022 $data->enddate = usergetmidnight(time()) + $courseconfig->courseduration;
3025 $course = create_course($data);
3026 $context = context_course::instance($course->id, MUST_EXIST);
3028 // add enrol instances
3029 if (!$DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
3030 if ($manual = enrol_get_plugin('manual')) {
3031 $manual->add_default_instance($course);
3035 // enrol the requester as teacher if necessary
3036 if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
3037 enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid);
3040 $this->delete();
3042 $a = new stdClass();
3043 $a->name = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
3044 $a->url = $CFG->wwwroot.'/course/view.php?id=' . $course->id;
3045 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a), $course->id);
3047 return $course->id;
3051 * Reject a course request
3053 * This function rejects a course request, emailing the requesting user the
3054 * provided notice and then removing the request from the database
3056 * @param string $notice The message to display to the user
3058 public function reject($notice) {
3059 global $USER, $DB;
3060 $user = $DB->get_record('user', array('id' => $this->properties->requester), '*', MUST_EXIST);
3061 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
3062 $this->delete();
3066 * Deletes the course request and any associated files
3068 public function delete() {
3069 global $DB;
3070 $DB->delete_records('course_request', array('id' => $this->properties->id));
3074 * Send a message from one user to another using events_trigger
3076 * @param object $touser
3077 * @param object $fromuser
3078 * @param string $name
3079 * @param string $subject
3080 * @param string $message
3081 * @param int|null $courseid
3083 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message, $courseid = null) {
3084 $eventdata = new \core\message\message();
3085 $eventdata->courseid = empty($courseid) ? SITEID : $courseid;
3086 $eventdata->component = 'moodle';
3087 $eventdata->name = $name;
3088 $eventdata->userfrom = $fromuser;
3089 $eventdata->userto = $touser;
3090 $eventdata->subject = $subject;
3091 $eventdata->fullmessage = $message;
3092 $eventdata->fullmessageformat = FORMAT_PLAIN;
3093 $eventdata->fullmessagehtml = '';
3094 $eventdata->smallmessage = '';
3095 $eventdata->notification = 1;
3096 message_send($eventdata);
3101 * Return a list of page types
3102 * @param string $pagetype current page type
3103 * @param context $parentcontext Block's parent context
3104 * @param context $currentcontext Current context of block
3105 * @return array array of page types
3107 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
3108 if ($pagetype === 'course-index' || $pagetype === 'course-index-category') {
3109 // For courses and categories browsing pages (/course/index.php) add option to show on ANY category page
3110 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
3111 'course-index-*' => get_string('page-course-index-x', 'pagetype'),
3113 } else if ($currentcontext && (!($coursecontext = $currentcontext->get_course_context(false)) || $coursecontext->instanceid == SITEID)) {
3114 // We know for sure that despite pagetype starts with 'course-' this is not a page in course context (i.e. /course/search.php, etc.)
3115 $pagetypes = array('*' => get_string('page-x', 'pagetype'));
3116 } else {
3117 // Otherwise consider it a page inside a course even if $currentcontext is null
3118 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
3119 'course-*' => get_string('page-course-x', 'pagetype'),
3120 'course-view-*' => get_string('page-course-view-x', 'pagetype')
3123 return $pagetypes;
3127 * Determine whether course ajax should be enabled for the specified course
3129 * @param stdClass $course The course to test against
3130 * @return boolean Whether course ajax is enabled or note
3132 function course_ajax_enabled($course) {
3133 global $CFG, $PAGE, $SITE;
3135 // The user must be editing for AJAX to be included
3136 if (!$PAGE->user_is_editing()) {
3137 return false;
3140 // Check that the theme suports
3141 if (!$PAGE->theme->enablecourseajax) {
3142 return false;
3145 // Check that the course format supports ajax functionality
3146 // The site 'format' doesn't have information on course format support
3147 if ($SITE->id !== $course->id) {
3148 $courseformatajaxsupport = course_format_ajax_support($course->format);
3149 if (!$courseformatajaxsupport->capable) {
3150 return false;
3154 // All conditions have been met so course ajax should be enabled
3155 return true;
3159 * Include the relevant javascript and language strings for the resource
3160 * toolbox YUI module
3162 * @param integer $id The ID of the course being applied to
3163 * @param array $usedmodules An array containing the names of the modules in use on the page
3164 * @param array $enabledmodules An array containing the names of the enabled (visible) modules on this site
3165 * @param stdClass $config An object containing configuration parameters for ajax modules including:
3166 * * resourceurl The URL to post changes to for resource changes
3167 * * sectionurl The URL to post changes to for section changes
3168 * * pageparams Additional parameters to pass through in the post
3169 * @return bool
3171 function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) {
3172 global $CFG, $PAGE, $SITE;
3174 // Ensure that ajax should be included
3175 if (!course_ajax_enabled($course)) {
3176 return false;
3179 if (!$config) {
3180 $config = new stdClass();
3183 // The URL to use for resource changes
3184 if (!isset($config->resourceurl)) {
3185 $config->resourceurl = '/course/rest.php';
3188 // The URL to use for section changes
3189 if (!isset($config->sectionurl)) {
3190 $config->sectionurl = '/course/rest.php';
3193 // Any additional parameters which need to be included on page submission
3194 if (!isset($config->pageparams)) {
3195 $config->pageparams = array();
3198 // Include course dragdrop
3199 if (course_format_uses_sections($course->format)) {
3200 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_section_dragdrop',
3201 array(array(
3202 'courseid' => $course->id,
3203 'ajaxurl' => $config->sectionurl,
3204 'config' => $config,
3205 )), null, true);
3207 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_resource_dragdrop',
3208 array(array(
3209 'courseid' => $course->id,
3210 'ajaxurl' => $config->resourceurl,
3211 'config' => $config,
3212 )), null, true);
3215 // Require various strings for the command toolbox
3216 $PAGE->requires->strings_for_js(array(
3217 'moveleft',
3218 'deletechecktype',
3219 'deletechecktypename',
3220 'edittitle',
3221 'edittitleinstructions',
3222 'show',
3223 'hide',
3224 'highlight',
3225 'highlightoff',
3226 'groupsnone',
3227 'groupsvisible',
3228 'groupsseparate',
3229 'clicktochangeinbrackets',
3230 'markthistopic',
3231 'markedthistopic',
3232 'movesection',
3233 'movecoursemodule',
3234 'movecoursesection',
3235 'movecontent',
3236 'tocontent',
3237 'emptydragdropregion',
3238 'afterresource',
3239 'aftersection',
3240 'totopofsection',
3241 ), 'moodle');
3243 // Include section-specific strings for formats which support sections.
3244 if (course_format_uses_sections($course->format)) {
3245 $PAGE->requires->strings_for_js(array(
3246 'showfromothers',
3247 'hidefromothers',
3248 ), 'format_' . $course->format);
3251 // For confirming resource deletion we need the name of the module in question
3252 foreach ($usedmodules as $module => $modname) {
3253 $PAGE->requires->string_for_js('pluginname', $module);
3256 // Load drag and drop upload AJAX.
3257 require_once($CFG->dirroot.'/course/dnduploadlib.php');
3258 dndupload_add_to_course($course, $enabledmodules);
3260 $PAGE->requires->js_call_amd('core_course/actions', 'initCoursePage', array($course->format));
3262 return true;
3266 * Returns the sorted list of available course formats, filtered by enabled if necessary
3268 * @param bool $enabledonly return only formats that are enabled
3269 * @return array array of sorted format names
3271 function get_sorted_course_formats($enabledonly = false) {
3272 global $CFG;
3273 $formats = core_component::get_plugin_list('format');
3275 if (!empty($CFG->format_plugins_sortorder)) {
3276 $order = explode(',', $CFG->format_plugins_sortorder);
3277 $order = array_merge(array_intersect($order, array_keys($formats)),
3278 array_diff(array_keys($formats), $order));
3279 } else {
3280 $order = array_keys($formats);
3282 if (!$enabledonly) {
3283 return $order;
3285 $sortedformats = array();
3286 foreach ($order as $formatname) {
3287 if (!get_config('format_'.$formatname, 'disabled')) {
3288 $sortedformats[] = $formatname;
3291 return $sortedformats;
3295 * The URL to use for the specified course (with section)
3297 * @param int|stdClass $courseorid The course to get the section name for (either object or just course id)
3298 * @param int|stdClass $section Section object from database or just field course_sections.section
3299 * if omitted the course view page is returned
3300 * @param array $options options for view URL. At the moment core uses:
3301 * 'navigation' (bool) if true and section has no separate page, the function returns null
3302 * 'sr' (int) used by multipage formats to specify to which section to return
3303 * @return moodle_url The url of course
3305 function course_get_url($courseorid, $section = null, $options = array()) {
3306 return course_get_format($courseorid)->get_view_url($section, $options);
3310 * Create a module.
3312 * It includes:
3313 * - capability checks and other checks
3314 * - create the module from the module info
3316 * @param object $module
3317 * @return object the created module info
3318 * @throws moodle_exception if user is not allowed to perform the action or module is not allowed in this course
3320 function create_module($moduleinfo) {
3321 global $DB, $CFG;
3323 require_once($CFG->dirroot . '/course/modlib.php');
3325 // Check manadatory attributs.
3326 $mandatoryfields = array('modulename', 'course', 'section', 'visible');
3327 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
3328 $mandatoryfields[] = 'introeditor';
3330 foreach($mandatoryfields as $mandatoryfield) {
3331 if (!isset($moduleinfo->{$mandatoryfield})) {
3332 throw new moodle_exception('createmodulemissingattribut', '', '', $mandatoryfield);
3336 // Some additional checks (capability / existing instances).
3337 $course = $DB->get_record('course', array('id'=>$moduleinfo->course), '*', MUST_EXIST);
3338 list($module, $context, $cw) = can_add_moduleinfo($course, $moduleinfo->modulename, $moduleinfo->section);
3340 // Add the module.
3341 $moduleinfo->module = $module->id;
3342 $moduleinfo = add_moduleinfo($moduleinfo, $course, null);
3344 return $moduleinfo;
3348 * Update a module.
3350 * It includes:
3351 * - capability and other checks
3352 * - update the module
3354 * @param object $module
3355 * @return object the updated module info
3356 * @throws moodle_exception if current user is not allowed to update the module
3358 function update_module($moduleinfo) {
3359 global $DB, $CFG;
3361 require_once($CFG->dirroot . '/course/modlib.php');
3363 // Check the course module exists.
3364 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule, 0, false, MUST_EXIST);
3366 // Check the course exists.
3367 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
3369 // Some checks (capaibility / existing instances).
3370 list($cm, $context, $module, $data, $cw) = can_update_moduleinfo($cm);
3372 // Retrieve few information needed by update_moduleinfo.
3373 $moduleinfo->modulename = $cm->modname;
3374 if (!isset($moduleinfo->scale)) {
3375 $moduleinfo->scale = 0;
3377 $moduleinfo->type = 'mod';
3379 // Update the module.
3380 list($cm, $moduleinfo) = update_moduleinfo($cm, $moduleinfo, $course, null);
3382 return $moduleinfo;
3386 * Duplicate a module on the course for ajax.
3388 * @see mod_duplicate_module()
3389 * @param object $course The course
3390 * @param object $cm The course module to duplicate
3391 * @param int $sr The section to link back to (used for creating the links)
3392 * @throws moodle_exception if the plugin doesn't support duplication
3393 * @return Object containing:
3394 * - fullcontent: The HTML markup for the created CM
3395 * - cmid: The CMID of the newly created CM
3396 * - redirect: Whether to trigger a redirect following this change
3398 function mod_duplicate_activity($course, $cm, $sr = null) {
3399 global $PAGE;
3401 $newcm = duplicate_module($course, $cm);
3403 $resp = new stdClass();
3404 if ($newcm) {
3405 $courserenderer = $PAGE->get_renderer('core', 'course');
3406 $completioninfo = new completion_info($course);
3407 $modulehtml = $courserenderer->course_section_cm($course, $completioninfo,
3408 $newcm, null, array());
3410 $resp->fullcontent = $courserenderer->course_section_cm_list_item($course, $completioninfo, $newcm, $sr);
3411 $resp->cmid = $newcm->id;
3412 } else {
3413 // Trigger a redirect.
3414 $resp->redirect = true;
3416 return $resp;
3420 * Api to duplicate a module.
3422 * @param object $course course object.
3423 * @param object $cm course module object to be duplicated.
3424 * @since Moodle 2.8
3426 * @throws Exception
3427 * @throws coding_exception
3428 * @throws moodle_exception
3429 * @throws restore_controller_exception
3431 * @return cm_info|null cminfo object if we sucessfully duplicated the mod and found the new cm.
3433 function duplicate_module($course, $cm) {
3434 global $CFG, $DB, $USER;
3435 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
3436 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
3437 require_once($CFG->libdir . '/filelib.php');
3439 $a = new stdClass();
3440 $a->modtype = get_string('modulename', $cm->modname);
3441 $a->modname = format_string($cm->name);
3443 if (!plugin_supports('mod', $cm->modname, FEATURE_BACKUP_MOODLE2)) {
3444 throw new moodle_exception('duplicatenosupport', 'error', '', $a);
3447 // Backup the activity.
3449 $bc = new backup_controller(backup::TYPE_1ACTIVITY, $cm->id, backup::FORMAT_MOODLE,
3450 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
3452 $backupid = $bc->get_backupid();
3453 $backupbasepath = $bc->get_plan()->get_basepath();
3455 $bc->execute_plan();
3457 $bc->destroy();
3459 // Restore the backup immediately.
3461 $rc = new restore_controller($backupid, $course->id,
3462 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, backup::TARGET_CURRENT_ADDING);
3464 $cmcontext = context_module::instance($cm->id);
3465 if (!$rc->execute_precheck()) {
3466 $precheckresults = $rc->get_precheck_results();
3467 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
3468 if (empty($CFG->keeptempdirectoriesonbackup)) {
3469 fulldelete($backupbasepath);
3474 $rc->execute_plan();
3476 // Now a bit hacky part follows - we try to get the cmid of the newly
3477 // restored copy of the module.
3478 $newcmid = null;
3479 $tasks = $rc->get_plan()->get_tasks();
3480 foreach ($tasks as $task) {
3481 if (is_subclass_of($task, 'restore_activity_task')) {
3482 if ($task->get_old_contextid() == $cmcontext->id) {
3483 $newcmid = $task->get_moduleid();
3484 break;
3489 $rc->destroy();
3491 if (empty($CFG->keeptempdirectoriesonbackup)) {
3492 fulldelete($backupbasepath);
3495 // If we know the cmid of the new course module, let us move it
3496 // right below the original one. otherwise it will stay at the
3497 // end of the section.
3498 if ($newcmid) {
3499 $section = $DB->get_record('course_sections', array('id' => $cm->section, 'course' => $cm->course));
3500 $modarray = explode(",", trim($section->sequence));
3501 $cmindex = array_search($cm->id, $modarray);
3502 if ($cmindex !== false && $cmindex < count($modarray) - 1) {
3503 $newcm = get_coursemodule_from_id($cm->modname, $newcmid, $cm->course);
3504 moveto_module($newcm, $section, $modarray[$cmindex + 1]);
3507 // Update calendar events with the duplicated module.
3508 // The following line is to be removed in MDL-58906.
3509 course_module_update_calendar_events($newcm->modname, null, $newcm);
3511 // Trigger course module created event. We can trigger the event only if we know the newcmid.
3512 $newcm = get_fast_modinfo($cm->course)->get_cm($newcmid);
3513 $event = \core\event\course_module_created::create_from_cm($newcm);
3514 $event->trigger();
3517 return isset($newcm) ? $newcm : null;
3521 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3522 * Sorts by descending order of time.
3524 * @param stdClass $a First object
3525 * @param stdClass $b Second object
3526 * @return int 0,1,-1 representing the order
3528 function compare_activities_by_time_desc($a, $b) {
3529 // Make sure the activities actually have a timestamp property.
3530 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3531 return 0;
3533 // We treat instances without timestamp as if they have a timestamp of 0.
3534 if ((!property_exists($a, 'timestamp')) && (property_exists($b,'timestamp'))) {
3535 return 1;
3537 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3538 return -1;
3540 if ($a->timestamp == $b->timestamp) {
3541 return 0;
3543 return ($a->timestamp > $b->timestamp) ? -1 : 1;
3547 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3548 * Sorts by ascending order of time.
3550 * @param stdClass $a First object
3551 * @param stdClass $b Second object
3552 * @return int 0,1,-1 representing the order
3554 function compare_activities_by_time_asc($a, $b) {
3555 // Make sure the activities actually have a timestamp property.
3556 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3557 return 0;
3559 // We treat instances without timestamp as if they have a timestamp of 0.
3560 if ((!property_exists($a, 'timestamp')) && (property_exists($b, 'timestamp'))) {
3561 return -1;
3563 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3564 return 1;
3566 if ($a->timestamp == $b->timestamp) {
3567 return 0;
3569 return ($a->timestamp < $b->timestamp) ? -1 : 1;
3573 * Changes the visibility of a course.
3575 * @param int $courseid The course to change.
3576 * @param bool $show True to make it visible, false otherwise.
3577 * @return bool
3579 function course_change_visibility($courseid, $show = true) {
3580 $course = new stdClass;
3581 $course->id = $courseid;
3582 $course->visible = ($show) ? '1' : '0';
3583 $course->visibleold = $course->visible;
3584 update_course($course);
3585 return true;
3589 * Changes the course sortorder by one, moving it up or down one in respect to sort order.
3591 * @param stdClass|course_in_list $course
3592 * @param bool $up If set to true the course will be moved up one. Otherwise down one.
3593 * @return bool
3595 function course_change_sortorder_by_one($course, $up) {
3596 global $DB;
3597 $params = array($course->sortorder, $course->category);
3598 if ($up) {
3599 $select = 'sortorder < ? AND category = ?';
3600 $sort = 'sortorder DESC';
3601 } else {
3602 $select = 'sortorder > ? AND category = ?';
3603 $sort = 'sortorder ASC';
3605 fix_course_sortorder();
3606 $swapcourse = $DB->get_records_select('course', $select, $params, $sort, '*', 0, 1);
3607 if ($swapcourse) {
3608 $swapcourse = reset($swapcourse);
3609 $DB->set_field('course', 'sortorder', $swapcourse->sortorder, array('id' => $course->id));
3610 $DB->set_field('course', 'sortorder', $course->sortorder, array('id' => $swapcourse->id));
3611 // Finally reorder courses.
3612 fix_course_sortorder();
3613 cache_helper::purge_by_event('changesincourse');
3614 return true;
3616 return false;
3620 * Changes the sort order of courses in a category so that the first course appears after the second.
3622 * @param int|stdClass $courseorid The course to focus on.
3623 * @param int $moveaftercourseid The course to shifter after or 0 if you want it to be the first course in the category.
3624 * @return bool
3626 function course_change_sortorder_after_course($courseorid, $moveaftercourseid) {
3627 global $DB;
3629 if (!is_object($courseorid)) {
3630 $course = get_course($courseorid);
3631 } else {
3632 $course = $courseorid;
3635 if ((int)$moveaftercourseid === 0) {
3636 // We've moving the course to the start of the queue.
3637 $sql = 'SELECT sortorder
3638 FROM {course}
3639 WHERE category = :categoryid
3640 ORDER BY sortorder';
3641 $params = array(
3642 'categoryid' => $course->category
3644 $sortorder = $DB->get_field_sql($sql, $params, IGNORE_MULTIPLE);
3646 $sql = 'UPDATE {course}
3647 SET sortorder = sortorder + 1
3648 WHERE category = :categoryid
3649 AND id <> :id';
3650 $params = array(
3651 'categoryid' => $course->category,
3652 'id' => $course->id,
3654 $DB->execute($sql, $params);
3655 $DB->set_field('course', 'sortorder', $sortorder, array('id' => $course->id));
3656 } else if ($course->id === $moveaftercourseid) {
3657 // They're the same - moronic.
3658 debugging("Invalid move after course given.", DEBUG_DEVELOPER);
3659 return false;
3660 } else {
3661 // Moving this course after the given course. It could be before it could be after.
3662 $moveaftercourse = get_course($moveaftercourseid);
3663 if ($course->category !== $moveaftercourse->category) {
3664 debugging("Cannot re-order courses. The given courses do not belong to the same category.", DEBUG_DEVELOPER);
3665 return false;
3667 // Increment all courses in the same category that are ordered after the moveafter course.
3668 // This makes a space for the course we're moving.
3669 $sql = 'UPDATE {course}
3670 SET sortorder = sortorder + 1
3671 WHERE category = :categoryid
3672 AND sortorder > :sortorder';
3673 $params = array(
3674 'categoryid' => $moveaftercourse->category,
3675 'sortorder' => $moveaftercourse->sortorder
3677 $DB->execute($sql, $params);
3678 $DB->set_field('course', 'sortorder', $moveaftercourse->sortorder + 1, array('id' => $course->id));
3680 fix_course_sortorder();
3681 cache_helper::purge_by_event('changesincourse');
3682 return true;
3686 * Trigger course viewed event. This API function is used when course view actions happens,
3687 * usually in course/view.php but also in external functions.
3689 * @param stdClass $context course context object
3690 * @param int $sectionnumber section number
3691 * @since Moodle 2.9
3693 function course_view($context, $sectionnumber = 0) {
3695 $eventdata = array('context' => $context);
3697 if (!empty($sectionnumber)) {
3698 $eventdata['other']['coursesectionnumber'] = $sectionnumber;
3701 $event = \core\event\course_viewed::create($eventdata);
3702 $event->trigger();
3706 * Returns courses tagged with a specified tag.
3708 * @param core_tag_tag $tag
3709 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
3710 * are displayed on the page and the per-page limit may be bigger
3711 * @param int $fromctx context id where the link was displayed, may be used by callbacks
3712 * to display items in the same context first
3713 * @param int $ctx context id where to search for records
3714 * @param bool $rec search in subcontexts as well
3715 * @param int $page 0-based number of page being displayed
3716 * @return \core_tag\output\tagindex
3718 function course_get_tagged_courses($tag, $exclusivemode = false, $fromctx = 0, $ctx = 0, $rec = 1, $page = 0) {
3719 global $CFG, $PAGE;
3720 require_once($CFG->libdir . '/coursecatlib.php');
3722 $perpage = $exclusivemode ? $CFG->coursesperpage : 5;
3723 $displayoptions = array(
3724 'limit' => $perpage,
3725 'offset' => $page * $perpage,
3726 'viewmoreurl' => null,
3729 $courserenderer = $PAGE->get_renderer('core', 'course');
3730 $totalcount = coursecat::search_courses_count(array('tagid' => $tag->id, 'ctx' => $ctx, 'rec' => $rec));
3731 $content = $courserenderer->tagged_courses($tag->id, $exclusivemode, $ctx, $rec, $displayoptions);
3732 $totalpages = ceil($totalcount / $perpage);
3734 return new core_tag\output\tagindex($tag, 'core', 'course', $content,
3735 $exclusivemode, $fromctx, $ctx, $rec, $page, $totalpages);
3739 * Implements callback inplace_editable() allowing to edit values in-place
3741 * @param string $itemtype
3742 * @param int $itemid
3743 * @param mixed $newvalue
3744 * @return \core\output\inplace_editable
3746 function core_course_inplace_editable($itemtype, $itemid, $newvalue) {
3747 if ($itemtype === 'activityname') {
3748 return \core_course\output\course_module_name::update($itemid, $newvalue);
3753 * Returns course modules tagged with a specified tag ready for output on tag/index.php page
3755 * This is a callback used by the tag area core/course_modules to search for course modules
3756 * tagged with a specific tag.
3758 * @param core_tag_tag $tag
3759 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
3760 * are displayed on the page and the per-page limit may be bigger
3761 * @param int $fromcontextid context id where the link was displayed, may be used by callbacks
3762 * to display items in the same context first
3763 * @param int $contextid context id where to search for records
3764 * @param bool $recursivecontext search in subcontexts as well
3765 * @param int $page 0-based number of page being displayed
3766 * @return \core_tag\output\tagindex
3768 function course_get_tagged_course_modules($tag, $exclusivemode = false, $fromcontextid = 0, $contextid = 0,
3769 $recursivecontext = 1, $page = 0) {
3770 global $OUTPUT;
3771 $perpage = $exclusivemode ? 20 : 5;
3773 // Build select query.
3774 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
3775 $query = "SELECT cm.id AS cmid, c.id AS courseid, $ctxselect
3776 FROM {course_modules} cm
3777 JOIN {tag_instance} tt ON cm.id = tt.itemid
3778 JOIN {course} c ON cm.course = c.id
3779 JOIN {context} ctx ON ctx.instanceid = cm.id AND ctx.contextlevel = :coursemodulecontextlevel
3780 WHERE tt.itemtype = :itemtype AND tt.tagid = :tagid AND tt.component = :component
3781 AND cm.deletioninprogress = 0
3782 AND c.id %COURSEFILTER% AND cm.id %ITEMFILTER%";
3784 $params = array('itemtype' => 'course_modules', 'tagid' => $tag->id, 'component' => 'core',
3785 'coursemodulecontextlevel' => CONTEXT_MODULE);
3786 if ($contextid) {
3787 $context = context::instance_by_id($contextid);
3788 $query .= $recursivecontext ? ' AND (ctx.id = :contextid OR ctx.path LIKE :path)' : ' AND ctx.id = :contextid';
3789 $params['contextid'] = $context->id;
3790 $params['path'] = $context->path.'/%';
3793 $query .= ' ORDER BY';
3794 if ($fromcontextid) {
3795 // In order-clause specify that modules from inside "fromctx" context should be returned first.
3796 $fromcontext = context::instance_by_id($fromcontextid);
3797 $query .= ' (CASE WHEN ctx.id = :fromcontextid OR ctx.path LIKE :frompath THEN 0 ELSE 1 END),';
3798 $params['fromcontextid'] = $fromcontext->id;
3799 $params['frompath'] = $fromcontext->path.'/%';
3801 $query .= ' c.sortorder, cm.id';
3802 $totalpages = $page + 1;
3804 // Use core_tag_index_builder to build and filter the list of items.
3805 // Request one item more than we need so we know if next page exists.
3806 $builder = new core_tag_index_builder('core', 'course_modules', $query, $params, $page * $perpage, $perpage + 1);
3807 while ($item = $builder->has_item_that_needs_access_check()) {
3808 context_helper::preload_from_record($item);
3809 $courseid = $item->courseid;
3810 if (!$builder->can_access_course($courseid)) {
3811 $builder->set_accessible($item, false);
3812 continue;
3814 $modinfo = get_fast_modinfo($builder->get_course($courseid));
3815 // Set accessibility of this item and all other items in the same course.
3816 $builder->walk(function ($taggeditem) use ($courseid, $modinfo, $builder) {
3817 if ($taggeditem->courseid == $courseid) {
3818 $cm = $modinfo->get_cm($taggeditem->cmid);
3819 $builder->set_accessible($taggeditem, $cm->uservisible);
3824 $items = $builder->get_items();
3825 if (count($items) > $perpage) {
3826 $totalpages = $page + 2; // We don't need exact page count, just indicate that the next page exists.
3827 array_pop($items);
3830 // Build the display contents.
3831 if ($items) {
3832 $tagfeed = new core_tag\output\tagfeed();
3833 foreach ($items as $item) {
3834 context_helper::preload_from_record($item);
3835 $course = $builder->get_course($item->courseid);
3836 $modinfo = get_fast_modinfo($course);
3837 $cm = $modinfo->get_cm($item->cmid);
3838 $courseurl = course_get_url($item->courseid, $cm->sectionnum);
3839 $cmname = $cm->get_formatted_name();
3840 if (!$exclusivemode) {
3841 $cmname = shorten_text($cmname, 100);
3843 $cmname = html_writer::link($cm->url?:$courseurl, $cmname);
3844 $coursename = format_string($course->fullname, true,
3845 array('context' => context_course::instance($item->courseid)));
3846 $coursename = html_writer::link($courseurl, $coursename);
3847 $icon = html_writer::empty_tag('img', array('src' => $cm->get_icon_url()));
3848 $tagfeed->add($icon, $cmname, $coursename);
3851 $content = $OUTPUT->render_from_template('core_tag/tagfeed',
3852 $tagfeed->export_for_template($OUTPUT));
3854 return new core_tag\output\tagindex($tag, 'core', 'course_modules', $content,
3855 $exclusivemode, $fromcontextid, $contextid, $recursivecontext, $page, $totalpages);
3860 * Return an object with the list of navigation options in a course that are avaialable or not for the current user.
3861 * This function also handles the frontpage course.
3863 * @param stdClass $context context object (it can be a course context or the system context for frontpage settings)
3864 * @param stdClass $course the course where the settings are being rendered
3865 * @return stdClass the navigation options in a course and their availability status
3866 * @since Moodle 3.2
3868 function course_get_user_navigation_options($context, $course = null) {
3869 global $CFG;
3871 $isloggedin = isloggedin();
3872 $isguestuser = isguestuser();
3873 $isfrontpage = $context->contextlevel == CONTEXT_SYSTEM;
3875 if ($isfrontpage) {
3876 $sitecontext = $context;
3877 } else {
3878 $sitecontext = context_system::instance();
3881 // Sets defaults for all options.
3882 $options = (object) [
3883 'badges' => false,
3884 'blogs' => false,
3885 'calendar' => false,
3886 'competencies' => false,
3887 'grades' => false,
3888 'notes' => false,
3889 'participants' => false,
3890 'search' => false,
3891 'tags' => false,
3894 $options->blogs = !empty($CFG->enableblogs) &&
3895 ($CFG->bloglevel == BLOG_GLOBAL_LEVEL ||
3896 ($CFG->bloglevel == BLOG_SITE_LEVEL and ($isloggedin and !$isguestuser)))
3897 && has_capability('moodle/blog:view', $sitecontext);
3899 $options->notes = !empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $context);
3901 // Frontpage settings?
3902 if ($isfrontpage) {
3903 // We are on the front page, so make sure we use the proper capability (site:viewparticipants).
3904 $options->participants = course_can_view_participants($sitecontext);
3905 $options->badges = !empty($CFG->enablebadges) && has_capability('moodle/badges:viewbadges', $sitecontext);
3906 $options->tags = !empty($CFG->usetags) && $isloggedin;
3907 $options->search = !empty($CFG->enableglobalsearch) && has_capability('moodle/search:query', $sitecontext);
3908 $options->calendar = $isloggedin;
3909 } else {
3910 // We are in a course, so make sure we use the proper capability (course:viewparticipants).
3911 $options->participants = course_can_view_participants($context);
3912 $options->badges = !empty($CFG->enablebadges) && !empty($CFG->badges_allowcoursebadges) &&
3913 has_capability('moodle/badges:viewbadges', $context);
3914 // Add view grade report is permitted.
3915 $grades = false;
3917 if (has_capability('moodle/grade:viewall', $context)) {
3918 $grades = true;
3919 } else if (!empty($course->showgrades)) {
3920 $reports = core_component::get_plugin_list('gradereport');
3921 if (is_array($reports) && count($reports) > 0) { // Get all installed reports.
3922 arsort($reports); // User is last, we want to test it first.
3923 foreach ($reports as $plugin => $plugindir) {
3924 if (has_capability('gradereport/'.$plugin.':view', $context)) {
3925 // Stop when the first visible plugin is found.
3926 $grades = true;
3927 break;
3932 $options->grades = $grades;
3935 if (\core_competency\api::is_enabled()) {
3936 $capabilities = array('moodle/competency:coursecompetencyview', 'moodle/competency:coursecompetencymanage');
3937 $options->competencies = has_any_capability($capabilities, $context);
3939 return $options;
3943 * Return an object with the list of administration options in a course that are available or not for the current user.
3944 * This function also handles the frontpage settings.
3946 * @param stdClass $course course object (for frontpage it should be a clone of $SITE)
3947 * @param stdClass $context context object (course context)
3948 * @return stdClass the administration options in a course and their availability status
3949 * @since Moodle 3.2
3951 function course_get_user_administration_options($course, $context) {
3952 global $CFG;
3953 $isfrontpage = $course->id == SITEID;
3954 $completionenabled = $CFG->enablecompletion && $course->enablecompletion;
3955 $hascompletiontabs = count(core_completion\manager::get_available_completion_tabs($course, $context)) > 0;
3957 $options = new stdClass;
3958 $options->update = has_capability('moodle/course:update', $context);
3959 $options->editcompletion = $CFG->enablecompletion &&
3960 $course->enablecompletion &&
3961 ($options->update || $hascompletiontabs);
3962 $options->filters = has_capability('moodle/filter:manage', $context) &&
3963 count(filter_get_available_in_context($context)) > 0;
3964 $options->reports = has_capability('moodle/site:viewreports', $context);
3965 $options->backup = has_capability('moodle/backup:backupcourse', $context);
3966 $options->restore = has_capability('moodle/restore:restorecourse', $context);
3967 $options->files = ($course->legacyfiles == 2 && has_capability('moodle/course:managefiles', $context));
3969 if (!$isfrontpage) {
3970 $options->tags = has_capability('moodle/course:tag', $context);
3971 $options->gradebook = has_capability('moodle/grade:manage', $context);
3972 $options->outcomes = !empty($CFG->enableoutcomes) && has_capability('moodle/course:update', $context);
3973 $options->badges = !empty($CFG->enablebadges);
3974 $options->import = has_capability('moodle/restore:restoretargetimport', $context);
3975 $options->publish = has_capability('moodle/course:publish', $context);
3976 $options->reset = has_capability('moodle/course:reset', $context);
3977 $options->roles = has_capability('moodle/role:switchroles', $context);
3978 } else {
3979 // Set default options to false.
3980 $listofoptions = array('tags', 'gradebook', 'outcomes', 'badges', 'import', 'publish', 'reset', 'roles', 'grades');
3982 foreach ($listofoptions as $option) {
3983 $options->$option = false;
3987 return $options;
3991 * Validates course start and end dates.
3993 * Checks that the end course date is not greater than the start course date.
3995 * $coursedata['startdate'] or $coursedata['enddate'] may not be set, it depends on the form and user input.
3997 * @param array $coursedata May contain startdate and enddate timestamps, depends on the user input.
3998 * @return mixed False if everything alright, error codes otherwise.
4000 function course_validate_dates($coursedata) {
4002 // If both start and end dates are set end date should be later than the start date.
4003 if (!empty($coursedata['startdate']) && !empty($coursedata['enddate']) &&
4004 ($coursedata['enddate'] < $coursedata['startdate'])) {
4005 return 'enddatebeforestartdate';
4008 // If start date is not set end date can not be set.
4009 if (empty($coursedata['startdate']) && !empty($coursedata['enddate'])) {
4010 return 'nostartdatenoenddate';
4013 return false;
4017 * Check for course updates in the given context level instances (only modules supported right Now)
4019 * @param stdClass $course course object
4020 * @param array $tocheck instances to check for updates
4021 * @param array $filter check only for updates in these areas
4022 * @return array list of warnings and instances with updates information
4023 * @since Moodle 3.2
4025 function course_check_updates($course, $tocheck, $filter = array()) {
4026 global $CFG, $DB;
4028 $instances = array();
4029 $warnings = array();
4030 $modulescallbacksupport = array();
4031 $modinfo = get_fast_modinfo($course);
4033 $supportedplugins = get_plugin_list_with_function('mod', 'check_updates_since');
4035 // Check instances.
4036 foreach ($tocheck as $instance) {
4037 if ($instance['contextlevel'] == 'module') {
4038 // Check module visibility.
4039 try {
4040 $cm = $modinfo->get_cm($instance['id']);
4041 } catch (Exception $e) {
4042 $warnings[] = array(
4043 'item' => 'module',
4044 'itemid' => $instance['id'],
4045 'warningcode' => 'cmidnotincourse',
4046 'message' => 'This module id does not belong to this course.'
4048 continue;
4051 if (!$cm->uservisible) {
4052 $warnings[] = array(
4053 'item' => 'module',
4054 'itemid' => $instance['id'],
4055 'warningcode' => 'nonuservisible',
4056 'message' => 'You don\'t have access to this module.'
4058 continue;
4060 if (empty($supportedplugins['mod_' . $cm->modname])) {
4061 $warnings[] = array(
4062 'item' => 'module',
4063 'itemid' => $instance['id'],
4064 'warningcode' => 'missingcallback',
4065 'message' => 'This module does not implement the check_updates_since callback: ' . $instance['contextlevel'],
4067 continue;
4069 // Retrieve the module instance.
4070 $instances[] = array(
4071 'contextlevel' => $instance['contextlevel'],
4072 'id' => $instance['id'],
4073 'updates' => call_user_func($cm->modname . '_check_updates_since', $cm, $instance['since'], $filter)
4076 } else {
4077 $warnings[] = array(
4078 'item' => 'contextlevel',
4079 'itemid' => $instance['id'],
4080 'warningcode' => 'contextlevelnotsupported',
4081 'message' => 'Context level not yet supported ' . $instance['contextlevel'],
4085 return array($instances, $warnings);
4089 * This function classifies a course as past, in progress or future.
4091 * This function may incur a DB hit to calculate course completion.
4092 * @param stdClass $course Course record
4093 * @param stdClass $user User record (optional - defaults to $USER).
4094 * @param completion_info $completioninfo Completion record for the user (optional - will be fetched if required).
4095 * @return string (one of COURSE_TIMELINE_FUTURE, COURSE_TIMELINE_INPROGRESS or COURSE_TIMELINE_PAST)
4097 function course_classify_for_timeline($course, $user = null, $completioninfo = null) {
4098 global $USER;
4100 if ($user == null) {
4101 $user = $USER;
4104 $today = time();
4105 // End date past.
4106 if (!empty($course->enddate) && $course->enddate < $today) {
4107 return COURSE_TIMELINE_PAST;
4110 if ($completioninfo == null) {
4111 $completioninfo = new completion_info($course);
4114 // Course was completed.
4115 if ($completioninfo->is_enabled() && $completioninfo->is_course_complete($user->id)) {
4116 return COURSE_TIMELINE_PAST;
4119 // Start date not reached.
4120 if (!empty($course->startdate) && $course->startdate > $today) {
4121 return COURSE_TIMELINE_FUTURE;
4124 // Everything else is in progress.
4125 return COURSE_TIMELINE_INPROGRESS;
4129 * Check module updates since a given time.
4130 * This function checks for updates in the module config, file areas, completion, grades, comments and ratings.
4132 * @param cm_info $cm course module data
4133 * @param int $from the time to check
4134 * @param array $fileareas additional file ares to check
4135 * @param array $filter if we need to filter and return only selected updates
4136 * @return stdClass object with the different updates
4137 * @since Moodle 3.2
4139 function course_check_module_updates_since($cm, $from, $fileareas = array(), $filter = array()) {
4140 global $DB, $CFG, $USER;
4142 $context = $cm->context;
4143 $mod = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
4145 $updates = new stdClass();
4146 $course = get_course($cm->course);
4147 $component = 'mod_' . $cm->modname;
4149 // Check changes in the module configuration.
4150 if (isset($mod->timemodified) and (empty($filter) or in_array('configuration', $filter))) {
4151 $updates->configuration = (object) array('updated' => false);
4152 if ($updates->configuration->updated = $mod->timemodified > $from) {
4153 $updates->configuration->timeupdated = $mod->timemodified;
4157 // Check for updates in files.
4158 if (plugin_supports('mod', $cm->modname, FEATURE_MOD_INTRO)) {
4159 $fileareas[] = 'intro';
4161 if (!empty($fileareas) and (empty($filter) or in_array('fileareas', $filter))) {
4162 $fs = get_file_storage();
4163 $files = $fs->get_area_files($context->id, $component, $fileareas, false, "filearea, timemodified DESC", false, $from);
4164 foreach ($fileareas as $filearea) {
4165 $updates->{$filearea . 'files'} = (object) array('updated' => false);
4167 foreach ($files as $file) {
4168 $updates->{$file->get_filearea() . 'files'}->updated = true;
4169 $updates->{$file->get_filearea() . 'files'}->itemids[] = $file->get_id();
4173 // Check completion.
4174 $supportcompletion = plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_HAS_RULES);
4175 $supportcompletion = $supportcompletion or plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_TRACKS_VIEWS);
4176 if ($supportcompletion and (empty($filter) or in_array('completion', $filter))) {
4177 $updates->completion = (object) array('updated' => false);
4178 $completion = new completion_info($course);
4179 // Use wholecourse to cache all the modules the first time.
4180 $completiondata = $completion->get_data($cm, true);
4181 if ($updates->completion->updated = !empty($completiondata->timemodified) && $completiondata->timemodified > $from) {
4182 $updates->completion->timemodified = $completiondata->timemodified;
4186 // Check grades.
4187 $supportgrades = plugin_supports('mod', $cm->modname, FEATURE_GRADE_HAS_GRADE);
4188 $supportgrades = $supportgrades or plugin_supports('mod', $cm->modname, FEATURE_GRADE_OUTCOMES);
4189 if ($supportgrades and (empty($filter) or (in_array('gradeitems', $filter) or in_array('outcomes', $filter)))) {
4190 require_once($CFG->libdir . '/gradelib.php');
4191 $grades = grade_get_grades($course->id, 'mod', $cm->modname, $mod->id, $USER->id);
4193 if (empty($filter) or in_array('gradeitems', $filter)) {
4194 $updates->gradeitems = (object) array('updated' => false);
4195 foreach ($grades->items as $gradeitem) {
4196 foreach ($gradeitem->grades as $grade) {
4197 if ($grade->datesubmitted > $from or $grade->dategraded > $from) {
4198 $updates->gradeitems->updated = true;
4199 $updates->gradeitems->itemids[] = $gradeitem->id;
4205 if (empty($filter) or in_array('outcomes', $filter)) {
4206 $updates->outcomes = (object) array('updated' => false);
4207 foreach ($grades->outcomes as $outcome) {
4208 foreach ($outcome->grades as $grade) {
4209 if ($grade->datesubmitted > $from or $grade->dategraded > $from) {
4210 $updates->outcomes->updated = true;
4211 $updates->outcomes->itemids[] = $outcome->id;
4218 // Check comments.
4219 if (plugin_supports('mod', $cm->modname, FEATURE_COMMENT) and (empty($filter) or in_array('comments', $filter))) {
4220 $updates->comments = (object) array('updated' => false);
4221 require_once($CFG->dirroot . '/comment/lib.php');
4222 require_once($CFG->dirroot . '/comment/locallib.php');
4223 $manager = new comment_manager();
4224 $comments = $manager->get_component_comments_since($course, $context, $component, $from, $cm);
4225 if (!empty($comments)) {
4226 $updates->comments->updated = true;
4227 $updates->comments->itemids = array_keys($comments);
4231 // Check ratings.
4232 if (plugin_supports('mod', $cm->modname, FEATURE_RATE) and (empty($filter) or in_array('ratings', $filter))) {
4233 $updates->ratings = (object) array('updated' => false);
4234 require_once($CFG->dirroot . '/rating/lib.php');
4235 $manager = new rating_manager();
4236 $ratings = $manager->get_component_ratings_since($context, $component, $from);
4237 if (!empty($ratings)) {
4238 $updates->ratings->updated = true;
4239 $updates->ratings->itemids = array_keys($ratings);
4243 return $updates;
4247 * Returns true if the user can view the participant page, false otherwise,
4249 * @param context $context The context we are checking.
4250 * @return bool
4252 function course_can_view_participants($context) {
4253 $viewparticipantscap = 'moodle/course:viewparticipants';
4254 if ($context->contextlevel == CONTEXT_SYSTEM) {
4255 $viewparticipantscap = 'moodle/site:viewparticipants';
4258 return has_any_capability([$viewparticipantscap, 'moodle/course:enrolreview'], $context);
4262 * Checks if a user can view the participant page, if not throws an exception.
4264 * @param context $context The context we are checking.
4265 * @throws required_capability_exception
4267 function course_require_view_participants($context) {
4268 if (!course_can_view_participants($context)) {
4269 $viewparticipantscap = 'moodle/course:viewparticipants';
4270 if ($context->contextlevel == CONTEXT_SYSTEM) {
4271 $viewparticipantscap = 'moodle/site:viewparticipants';
4273 throw new required_capability_exception($context, $viewparticipantscap, 'nopermissions', '');
4278 * Return whether the user can download from the specified backup file area in the given context.
4280 * @param string $filearea the backup file area. E.g. 'course', 'backup' or 'automated'.
4281 * @param \context $context
4282 * @param stdClass $user the user object. If not provided, the current user will be checked.
4283 * @return bool true if the user is allowed to download in the context, false otherwise.
4285 function can_download_from_backup_filearea($filearea, \context $context, stdClass $user = null) {
4286 $candownload = false;
4287 switch ($filearea) {
4288 case 'course':
4289 case 'backup':
4290 $candownload = has_capability('moodle/backup:downloadfile', $context, $user);
4291 break;
4292 case 'automated':
4293 // Given the automated backups may contain userinfo, we restrict access such that only users who are able to
4294 // restore with userinfo are able to download the file. Users can't create these backups, so checking 'backup:userinfo'
4295 // doesn't make sense here.
4296 $candownload = has_capability('moodle/backup:downloadfile', $context, $user) &&
4297 has_capability('moodle/restore:userinfo', $context, $user);
4298 break;
4299 default:
4300 break;
4303 return $candownload;