MDL-57411 groups: New helper functions
[moodle.git] / course / lib.php
blob980173f8307dad6ca1df86a5041ebf67ae9b74d7
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 function make_log_url($module, $url) {
59 switch ($module) {
60 case 'course':
61 if (strpos($url, 'report/') === 0) {
62 // there is only one report type, course reports are deprecated
63 $url = "/$url";
64 break;
66 case 'file':
67 case 'login':
68 case 'lib':
69 case 'admin':
70 case 'category':
71 case 'mnet course':
72 if (strpos($url, '../') === 0) {
73 $url = ltrim($url, '.');
74 } else {
75 $url = "/course/$url";
77 break;
78 case 'calendar':
79 $url = "/calendar/$url";
80 break;
81 case 'user':
82 case 'blog':
83 $url = "/$module/$url";
84 break;
85 case 'upload':
86 $url = $url;
87 break;
88 case 'coursetags':
89 $url = '/'.$url;
90 break;
91 case 'library':
92 case '':
93 $url = '/';
94 break;
95 case 'message':
96 $url = "/message/$url";
97 break;
98 case 'notes':
99 $url = "/notes/$url";
100 break;
101 case 'tag':
102 $url = "/tag/$url";
103 break;
104 case 'role':
105 $url = '/'.$url;
106 break;
107 case 'grade':
108 $url = "/grade/$url";
109 break;
110 default:
111 $url = "/mod/$module/$url";
112 break;
115 //now let's sanitise urls - there might be some ugly nasties:-(
116 $parts = explode('?', $url);
117 $script = array_shift($parts);
118 if (strpos($script, 'http') === 0) {
119 $script = clean_param($script, PARAM_URL);
120 } else {
121 $script = clean_param($script, PARAM_PATH);
124 $query = '';
125 if ($parts) {
126 $query = implode('', $parts);
127 $query = str_replace('&amp;', '&', $query); // both & and &amp; are stored in db :-|
128 $parts = explode('&', $query);
129 $eq = urlencode('=');
130 foreach ($parts as $key=>$part) {
131 $part = urlencode(urldecode($part));
132 $part = str_replace($eq, '=', $part);
133 $parts[$key] = $part;
135 $query = '?'.implode('&amp;', $parts);
138 return $script.$query;
142 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
143 $modname="", $modid=0, $modaction="", $groupid=0) {
144 global $CFG, $DB;
146 // It is assumed that $date is the GMT time of midnight for that day,
147 // and so the next 86400 seconds worth of logs are printed.
149 /// Setup for group handling.
151 // TODO: I don't understand group/context/etc. enough to be able to do
152 // something interesting with it here
153 // What is the context of a remote course?
155 /// If the group mode is separate, and this user does not have editing privileges,
156 /// then only the user's group can be viewed.
157 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
158 // $groupid = get_current_group($course->id);
160 /// If this course doesn't have groups, no groupid can be specified.
161 //else if (!$course->groupmode) {
162 // $groupid = 0;
165 $groupid = 0;
167 $joins = array();
168 $where = '';
170 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
171 FROM {mnet_log} l
172 LEFT JOIN {user} u ON l.userid = u.id
173 WHERE ";
174 $params = array();
176 $where .= "l.hostid = :hostid";
177 $params['hostid'] = $hostid;
179 // TODO: Is 1 really a magic number referring to the sitename?
180 if ($course != SITEID || $modid != 0) {
181 $where .= " AND l.course=:courseid";
182 $params['courseid'] = $course;
185 if ($modname) {
186 $where .= " AND l.module = :modname";
187 $params['modname'] = $modname;
190 if ('site_errors' === $modid) {
191 $where .= " AND ( l.action='error' OR l.action='infected' )";
192 } else if ($modid) {
193 //TODO: This assumes that modids are the same across sites... probably
194 //not true
195 $where .= " AND l.cmid = :modid";
196 $params['modid'] = $modid;
199 if ($modaction) {
200 $firstletter = substr($modaction, 0, 1);
201 if ($firstletter == '-') {
202 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
203 $params['modaction'] = '%'.substr($modaction, 1).'%';
204 } else {
205 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
206 $params['modaction'] = '%'.$modaction.'%';
210 if ($user) {
211 $where .= " AND l.userid = :user";
212 $params['user'] = $user;
215 if ($date) {
216 $enddate = $date + 86400;
217 $where .= " AND l.time > :date AND l.time < :enddate";
218 $params['date'] = $date;
219 $params['enddate'] = $enddate;
222 $result = array();
223 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
224 if(!empty($result['totalcount'])) {
225 $where .= " ORDER BY $order";
226 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
227 } else {
228 $result['logs'] = array();
230 return $result;
234 * Checks the integrity of the course data.
236 * In summary - compares course_sections.sequence and course_modules.section.
238 * More detailed, checks that:
239 * - course_sections.sequence contains each module id not more than once in the course
240 * - for each moduleid from course_sections.sequence the field course_modules.section
241 * refers to the same section id (this means course_sections.sequence is more
242 * important if they are different)
243 * - ($fullcheck only) each module in the course is present in one of
244 * course_sections.sequence
245 * - ($fullcheck only) removes non-existing course modules from section sequences
247 * If there are any mismatches, the changes are made and records are updated in DB.
249 * Course cache is NOT rebuilt if there are any errors!
251 * This function is used each time when course cache is being rebuilt with $fullcheck = false
252 * and in CLI script admin/cli/fix_course_sequence.php with $fullcheck = true
254 * @param int $courseid id of the course
255 * @param array $rawmods result of funciton {@link get_course_mods()} - containst
256 * the list of enabled course modules in the course. Retrieved from DB if not specified.
257 * Argument ignored in cashe of $fullcheck, the list is retrieved form DB anyway.
258 * @param array $sections records from course_sections table for this course.
259 * Retrieved from DB if not specified
260 * @param bool $fullcheck Will add orphaned modules to their sections and remove non-existing
261 * course modules from sequences. Only to be used in site maintenance mode when we are
262 * sure that another user is not in the middle of the process of moving/removing a module.
263 * @param bool $checkonly Only performs the check without updating DB, outputs all errors as debug messages.
264 * @return array array of messages with found problems. Empty output means everything is ok
266 function course_integrity_check($courseid, $rawmods = null, $sections = null, $fullcheck = false, $checkonly = false) {
267 global $DB;
268 $messages = array();
269 if ($sections === null) {
270 $sections = $DB->get_records('course_sections', array('course' => $courseid), 'section', 'id,section,sequence');
272 if ($fullcheck) {
273 // Retrieve all records from course_modules regardless of module type visibility.
274 $rawmods = $DB->get_records('course_modules', array('course' => $courseid), 'id', 'id,section');
276 if ($rawmods === null) {
277 $rawmods = get_course_mods($courseid);
279 if (!$fullcheck && (empty($sections) || empty($rawmods))) {
280 // If either of the arrays is empty, no modules are displayed anyway.
281 return true;
283 $debuggingprefix = 'Failed integrity check for course ['.$courseid.']. ';
285 // First make sure that each module id appears in section sequences only once.
286 // If it appears in several section sequences the last section wins.
287 // If it appears twice in one section sequence, the first occurence wins.
288 $modsection = array();
289 foreach ($sections as $sectionid => $section) {
290 $sections[$sectionid]->newsequence = $section->sequence;
291 if (!empty($section->sequence)) {
292 $sequence = explode(",", $section->sequence);
293 $sequenceunique = array_unique($sequence);
294 if (count($sequenceunique) != count($sequence)) {
295 // Some course module id appears in this section sequence more than once.
296 ksort($sequenceunique); // Preserve initial order of modules.
297 $sequence = array_values($sequenceunique);
298 $sections[$sectionid]->newsequence = join(',', $sequence);
299 $messages[] = $debuggingprefix.'Sequence for course section ['.
300 $sectionid.'] is "'.$sections[$sectionid]->sequence.'", must be "'.$sections[$sectionid]->newsequence.'"';
302 foreach ($sequence as $cmid) {
303 if (array_key_exists($cmid, $modsection) && isset($rawmods[$cmid])) {
304 // Some course module id appears to be in more than one section's sequences.
305 $wrongsectionid = $modsection[$cmid];
306 $sections[$wrongsectionid]->newsequence = trim(preg_replace("/,$cmid,/", ',', ','.$sections[$wrongsectionid]->newsequence. ','), ',');
307 $messages[] = $debuggingprefix.'Course module ['.$cmid.'] must be removed from sequence of section ['.
308 $wrongsectionid.'] because it is also present in sequence of section ['.$sectionid.']';
310 $modsection[$cmid] = $sectionid;
315 // Add orphaned modules to their sections if they exist or to section 0 otherwise.
316 if ($fullcheck) {
317 foreach ($rawmods as $cmid => $mod) {
318 if (!isset($modsection[$cmid])) {
319 // This is a module that is not mentioned in course_section.sequence at all.
320 // Add it to the section $mod->section or to the last available section.
321 if ($mod->section && isset($sections[$mod->section])) {
322 $modsection[$cmid] = $mod->section;
323 } else {
324 $firstsection = reset($sections);
325 $modsection[$cmid] = $firstsection->id;
327 $sections[$modsection[$cmid]]->newsequence = trim($sections[$modsection[$cmid]]->newsequence.','.$cmid, ',');
328 $messages[] = $debuggingprefix.'Course module ['.$cmid.'] is missing from sequence of section ['.
329 $modsection[$cmid].']';
332 foreach ($modsection as $cmid => $sectionid) {
333 if (!isset($rawmods[$cmid])) {
334 // Section $sectionid refers to module id that does not exist.
335 $sections[$sectionid]->newsequence = trim(preg_replace("/,$cmid,/", ',', ','.$sections[$sectionid]->newsequence.','), ',');
336 $messages[] = $debuggingprefix.'Course module ['.$cmid.
337 '] does not exist but is present in the sequence of section ['.$sectionid.']';
342 // Update changed sections.
343 if (!$checkonly && !empty($messages)) {
344 foreach ($sections as $sectionid => $section) {
345 if ($section->newsequence !== $section->sequence) {
346 $DB->update_record('course_sections', array('id' => $sectionid, 'sequence' => $section->newsequence));
351 // Now make sure that all modules point to the correct sections.
352 foreach ($rawmods as $cmid => $mod) {
353 if (isset($modsection[$cmid]) && $modsection[$cmid] != $mod->section) {
354 if (!$checkonly) {
355 $DB->update_record('course_modules', array('id' => $cmid, 'section' => $modsection[$cmid]));
357 $messages[] = $debuggingprefix.'Course module ['.$cmid.
358 '] points to section ['.$mod->section.'] instead of ['.$modsection[$cmid].']';
362 return $messages;
366 * For a given course, returns an array of course activity objects
367 * Each item in the array contains he following properties:
369 function get_array_of_activities($courseid) {
370 // cm - course module id
371 // mod - name of the module (eg forum)
372 // section - the number of the section (eg week or topic)
373 // name - the name of the instance
374 // visible - is the instance visible or not
375 // groupingid - grouping id
376 // extra - contains extra string to include in any link
377 global $CFG, $DB;
379 $course = $DB->get_record('course', array('id'=>$courseid));
381 if (empty($course)) {
382 throw new moodle_exception('courseidnotfound');
385 $mod = array();
387 $rawmods = get_course_mods($courseid);
388 if (empty($rawmods)) {
389 return $mod; // always return array
391 $courseformat = course_get_format($course);
393 if ($sections = $DB->get_records('course_sections', array('course' => $courseid),
394 'section ASC', 'id,section,sequence,visible')) {
395 // First check and correct obvious mismatches between course_sections.sequence and course_modules.section.
396 if ($errormessages = course_integrity_check($courseid, $rawmods, $sections)) {
397 debugging(join('<br>', $errormessages));
398 $rawmods = get_course_mods($courseid);
399 $sections = $DB->get_records('course_sections', array('course' => $courseid),
400 'section ASC', 'id,section,sequence,visible');
402 // Build array of activities.
403 foreach ($sections as $section) {
404 if (!empty($section->sequence)) {
405 $sequence = explode(",", $section->sequence);
406 foreach ($sequence as $seq) {
407 if (empty($rawmods[$seq])) {
408 continue;
410 // Adjust visibleoncoursepage, value in DB may not respect format availability.
411 $rawmods[$seq]->visibleoncoursepage = (!$rawmods[$seq]->visible
412 || $rawmods[$seq]->visibleoncoursepage
413 || empty($CFG->allowstealth)
414 || !$courseformat->allow_stealth_module_visibility($rawmods[$seq], $section)) ? 1 : 0;
416 // Create an object that will be cached.
417 $mod[$seq] = new stdClass();
418 $mod[$seq]->id = $rawmods[$seq]->instance;
419 $mod[$seq]->cm = $rawmods[$seq]->id;
420 $mod[$seq]->mod = $rawmods[$seq]->modname;
422 // Oh dear. Inconsistent names left here for backward compatibility.
423 $mod[$seq]->section = $section->section;
424 $mod[$seq]->sectionid = $rawmods[$seq]->section;
426 $mod[$seq]->module = $rawmods[$seq]->module;
427 $mod[$seq]->added = $rawmods[$seq]->added;
428 $mod[$seq]->score = $rawmods[$seq]->score;
429 $mod[$seq]->idnumber = $rawmods[$seq]->idnumber;
430 $mod[$seq]->visible = $rawmods[$seq]->visible;
431 $mod[$seq]->visibleoncoursepage = $rawmods[$seq]->visibleoncoursepage;
432 $mod[$seq]->visibleold = $rawmods[$seq]->visibleold;
433 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
434 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
435 $mod[$seq]->indent = $rawmods[$seq]->indent;
436 $mod[$seq]->completion = $rawmods[$seq]->completion;
437 $mod[$seq]->extra = "";
438 $mod[$seq]->completiongradeitemnumber =
439 $rawmods[$seq]->completiongradeitemnumber;
440 $mod[$seq]->completionview = $rawmods[$seq]->completionview;
441 $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected;
442 $mod[$seq]->showdescription = $rawmods[$seq]->showdescription;
443 $mod[$seq]->availability = $rawmods[$seq]->availability;
444 $mod[$seq]->deletioninprogress = $rawmods[$seq]->deletioninprogress;
446 $modname = $mod[$seq]->mod;
447 $functionname = $modname."_get_coursemodule_info";
449 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
450 continue;
453 include_once("$CFG->dirroot/mod/$modname/lib.php");
455 if ($hasfunction = function_exists($functionname)) {
456 if ($info = $functionname($rawmods[$seq])) {
457 if (!empty($info->icon)) {
458 $mod[$seq]->icon = $info->icon;
460 if (!empty($info->iconcomponent)) {
461 $mod[$seq]->iconcomponent = $info->iconcomponent;
463 if (!empty($info->name)) {
464 $mod[$seq]->name = $info->name;
466 if ($info instanceof cached_cm_info) {
467 // When using cached_cm_info you can include three new fields
468 // that aren't available for legacy code
469 if (!empty($info->content)) {
470 $mod[$seq]->content = $info->content;
472 if (!empty($info->extraclasses)) {
473 $mod[$seq]->extraclasses = $info->extraclasses;
475 if (!empty($info->iconurl)) {
476 // Convert URL to string as it's easier to store. Also serialized object contains \0 byte and can not be written to Postgres DB.
477 $url = new moodle_url($info->iconurl);
478 $mod[$seq]->iconurl = $url->out(false);
480 if (!empty($info->onclick)) {
481 $mod[$seq]->onclick = $info->onclick;
483 if (!empty($info->customdata)) {
484 $mod[$seq]->customdata = $info->customdata;
486 } else {
487 // When using a stdclass, the (horrible) deprecated ->extra field
488 // is available for BC
489 if (!empty($info->extra)) {
490 $mod[$seq]->extra = $info->extra;
495 // When there is no modname_get_coursemodule_info function,
496 // but showdescriptions is enabled, then we use the 'intro'
497 // and 'introformat' fields in the module table
498 if (!$hasfunction && $rawmods[$seq]->showdescription) {
499 if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
500 array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
501 // Set content from intro and introformat. Filters are disabled
502 // because we filter it with format_text at display time
503 $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
504 $modvalues, $rawmods[$seq]->id, false);
506 // To save making another query just below, put name in here
507 $mod[$seq]->name = $modvalues->name;
510 if (!isset($mod[$seq]->name)) {
511 $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
514 // Minimise the database size by unsetting default options when they are
515 // 'empty'. This list corresponds to code in the cm_info constructor.
516 foreach (array('idnumber', 'groupmode', 'groupingid',
517 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
518 'icon', 'iconcomponent', 'customdata', 'availability', 'completionview',
519 'completionexpected', 'score', 'showdescription', 'deletioninprogress') as $property) {
520 if (property_exists($mod[$seq], $property) &&
521 empty($mod[$seq]->{$property})) {
522 unset($mod[$seq]->{$property});
525 // Special case: this value is usually set to null, but may be 0
526 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
527 is_null($mod[$seq]->completiongradeitemnumber)) {
528 unset($mod[$seq]->completiongradeitemnumber);
534 return $mod;
538 * Returns the localised human-readable names of all used modules
540 * @param bool $plural if true returns the plural forms of the names
541 * @return array where key is the module name (component name without 'mod_') and
542 * the value is the human-readable string. Array sorted alphabetically by value
544 function get_module_types_names($plural = false) {
545 static $modnames = null;
546 global $DB, $CFG;
547 if ($modnames === null) {
548 $modnames = array(0 => array(), 1 => array());
549 if ($allmods = $DB->get_records("modules")) {
550 foreach ($allmods as $mod) {
551 if (file_exists("$CFG->dirroot/mod/$mod->name/lib.php") && $mod->visible) {
552 $modnames[0][$mod->name] = get_string("modulename", "$mod->name");
553 $modnames[1][$mod->name] = get_string("modulenameplural", "$mod->name");
556 core_collator::asort($modnames[0]);
557 core_collator::asort($modnames[1]);
560 return $modnames[(int)$plural];
564 * Set highlighted section. Only one section can be highlighted at the time.
566 * @param int $courseid course id
567 * @param int $marker highlight section with this number, 0 means remove higlightin
568 * @return void
570 function course_set_marker($courseid, $marker) {
571 global $DB, $COURSE;
572 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
573 if ($COURSE && $COURSE->id == $courseid) {
574 $COURSE->marker = $marker;
576 if (class_exists('format_base')) {
577 format_base::reset_course_cache($courseid);
579 course_modinfo::clear_instance_cache($courseid);
583 * For a given course section, marks it visible or hidden,
584 * and does the same for every activity in that section
586 * @param int $courseid course id
587 * @param int $sectionnumber The section number to adjust
588 * @param int $visibility The new visibility
589 * @return array A list of resources which were hidden in the section
591 function set_section_visible($courseid, $sectionnumber, $visibility) {
592 global $DB;
594 $resourcestotoggle = array();
595 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
596 course_update_section($courseid, $section, array('visible' => $visibility));
598 // Determine which modules are visible for AJAX update
599 $modules = !empty($section->sequence) ? explode(',', $section->sequence) : array();
600 if (!empty($modules)) {
601 list($insql, $params) = $DB->get_in_or_equal($modules);
602 $select = 'id ' . $insql . ' AND visible = ?';
603 array_push($params, $visibility);
604 if (!$visibility) {
605 $select .= ' AND visibleold = 1';
607 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
610 return $resourcestotoggle;
614 * Retrieve all metadata for the requested modules
616 * @param object $course The Course
617 * @param array $modnames An array containing the list of modules and their
618 * names
619 * @param int $sectionreturn The section to return to
620 * @return array A list of stdClass objects containing metadata about each
621 * module
623 function get_module_metadata($course, $modnames, $sectionreturn = null) {
624 global $OUTPUT;
626 // get_module_metadata will be called once per section on the page and courses may show
627 // different modules to one another
628 static $modlist = array();
629 if (!isset($modlist[$course->id])) {
630 $modlist[$course->id] = array();
633 $return = array();
634 $urlbase = new moodle_url('/course/mod.php', array('id' => $course->id, 'sesskey' => sesskey()));
635 if ($sectionreturn !== null) {
636 $urlbase->param('sr', $sectionreturn);
638 foreach($modnames as $modname => $modnamestr) {
639 if (!course_allowed_module($course, $modname)) {
640 continue;
642 if (isset($modlist[$course->id][$modname])) {
643 // This module is already cached
644 $return += $modlist[$course->id][$modname];
645 continue;
647 $modlist[$course->id][$modname] = array();
649 // Create an object for a default representation of this module type in the activity chooser. It will be used
650 // if module does not implement callback get_shortcuts() and it will also be passed to the callback if it exists.
651 $defaultmodule = new stdClass();
652 $defaultmodule->title = $modnamestr;
653 $defaultmodule->name = $modname;
654 $defaultmodule->link = new moodle_url($urlbase, array('add' => $modname));
655 $defaultmodule->icon = $OUTPUT->pix_icon('icon', '', $defaultmodule->name, array('class' => 'icon'));
656 $sm = get_string_manager();
657 if ($sm->string_exists('modulename_help', $modname)) {
658 $defaultmodule->help = get_string('modulename_help', $modname);
659 if ($sm->string_exists('modulename_link', $modname)) { // Link to further info in Moodle docs.
660 $link = get_string('modulename_link', $modname);
661 $linktext = get_string('morehelp');
662 $defaultmodule->help .= html_writer::tag('div',
663 $OUTPUT->doc_link($link, $linktext, true), array('class' => 'helpdoclink'));
666 $defaultmodule->archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
668 // Legacy support for callback get_types() - do not use any more, use get_shortcuts() instead!
669 $typescallbackexists = component_callback_exists($modname, 'get_types');
671 // Each module can implement callback modulename_get_shortcuts() in its lib.php and return the list
672 // of elements to be added to activity chooser.
673 $items = component_callback($modname, 'get_shortcuts', array($defaultmodule), null);
674 if ($items !== null) {
675 foreach ($items as $item) {
676 // Add all items to the return array. All items must have different links, use them as a key in the return array.
677 if (!isset($item->archetype)) {
678 $item->archetype = $defaultmodule->archetype;
680 if (!isset($item->icon)) {
681 $item->icon = $defaultmodule->icon;
683 // If plugin returned the only one item with the same link as default item - cache it as $modname,
684 // otherwise append the link url to the module name.
685 $item->name = (count($items) == 1 &&
686 $item->link->out() === $defaultmodule->link->out()) ? $modname : $modname . ':' . $item->link;
688 // If the module provides the helptext property, append it to the help text to match the look and feel
689 // of the default course modules.
690 if (isset($item->help) && isset($item->helplink)) {
691 $linktext = get_string('morehelp');
692 $item->help .= html_writer::tag('div',
693 $OUTPUT->doc_link($item->helplink, $linktext, true), array('class' => 'helpdoclink'));
695 $modlist[$course->id][$modname][$item->name] = $item;
697 $return += $modlist[$course->id][$modname];
698 if ($typescallbackexists) {
699 debugging('Both callbacks get_shortcuts() and get_types() are found in module ' . $modname .
700 '. Callback get_types() will be completely ignored', DEBUG_DEVELOPER);
702 // If get_shortcuts() callback is defined, the default module action is not added.
703 // It is a responsibility of the callback to add it to the return value unless it is not needed.
704 continue;
707 if ($typescallbackexists) {
708 debugging('Callback get_types() is found in module ' . $modname . ', this functionality is deprecated, ' .
709 'please use callback get_shortcuts() instead', DEBUG_DEVELOPER);
711 $types = component_callback($modname, 'get_types', array(), MOD_SUBTYPE_NO_CHILDREN);
712 if ($types !== MOD_SUBTYPE_NO_CHILDREN) {
713 // Legacy support for deprecated callback get_types(). To be removed in Moodle 3.5. TODO MDL-53697.
714 if (is_array($types) && count($types) > 0) {
715 $grouptitle = $modnamestr;
716 $icon = $OUTPUT->pix_icon('icon', '', $modname, array('class' => 'icon'));
717 foreach($types as $type) {
718 if ($type->typestr === '--') {
719 continue;
721 if (strpos($type->typestr, '--') === 0) {
722 $grouptitle = str_replace('--', '', $type->typestr);
723 continue;
725 // Set the Sub Type metadata.
726 $subtype = new stdClass();
727 $subtype->title = get_string('activitytypetitle', '',
728 (object)['activity' => $grouptitle, 'type' => $type->typestr]);
729 $subtype->type = str_replace('&amp;', '&', $type->type);
730 $typename = preg_replace('/.*type=/', '', $subtype->type);
731 $subtype->archetype = $type->modclass;
733 if (!empty($type->help)) {
734 $subtype->help = $type->help;
735 } else if (get_string_manager()->string_exists('help' . $subtype->name, $modname)) {
736 $subtype->help = get_string('help' . $subtype->name, $modname);
738 $subtype->link = new moodle_url($urlbase, array('add' => $modname, 'type' => $typename));
739 $subtype->name = $modname . ':' . $subtype->link;
740 $subtype->icon = $icon;
741 $modlist[$course->id][$modname][$subtype->name] = $subtype;
743 $return += $modlist[$course->id][$modname];
745 } else {
746 // Neither get_shortcuts() nor get_types() callbacks found, use the default item for the activity chooser.
747 $modlist[$course->id][$modname][$modname] = $defaultmodule;
748 $return[$modname] = $defaultmodule;
752 core_collator::asort_objects_by_property($return, 'title');
753 return $return;
757 * Return the course category context for the category with id $categoryid, except
758 * that if $categoryid is 0, return the system context.
760 * @param integer $categoryid a category id or 0.
761 * @return context the corresponding context
763 function get_category_or_system_context($categoryid) {
764 if ($categoryid) {
765 return context_coursecat::instance($categoryid, IGNORE_MISSING);
766 } else {
767 return context_system::instance();
772 * Returns full course categories trees to be used in html_writer::select()
774 * Calls {@link coursecat::make_categories_list()} to build the tree and
775 * adds whitespace to denote nesting
777 * @return array array mapping coursecat id to the display name
779 function make_categories_options() {
780 global $CFG;
781 require_once($CFG->libdir. '/coursecatlib.php');
782 $cats = coursecat::make_categories_list('', 0, ' / ');
783 foreach ($cats as $key => $value) {
784 // Prefix the value with the number of spaces equal to category depth (number of separators in the value).
785 $cats[$key] = str_repeat('&nbsp;', substr_count($value, ' / ')). $value;
787 return $cats;
791 * Print the buttons relating to course requests.
793 * @param object $context current page context.
795 function print_course_request_buttons($context) {
796 global $CFG, $DB, $OUTPUT;
797 if (empty($CFG->enablecourserequests)) {
798 return;
800 if (!has_capability('moodle/course:create', $context) && has_capability('moodle/course:request', $context)) {
801 /// Print a button to request a new course
802 echo $OUTPUT->single_button(new moodle_url('/course/request.php'), get_string('requestcourse'), 'get');
804 /// Print a button to manage pending requests
805 if ($context->contextlevel == CONTEXT_SYSTEM && has_capability('moodle/site:approvecourse', $context)) {
806 $disabled = !$DB->record_exists('course_request', array());
807 echo $OUTPUT->single_button(new moodle_url('/course/pending.php'), get_string('coursespending'), 'get', array('disabled' => $disabled));
812 * Does the user have permission to edit things in this category?
814 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
815 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
817 function can_edit_in_category($categoryid = 0) {
818 $context = get_category_or_system_context($categoryid);
819 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
822 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
824 function add_course_module($mod) {
825 global $DB;
827 $mod->added = time();
828 unset($mod->id);
830 $cmid = $DB->insert_record("course_modules", $mod);
831 rebuild_course_cache($mod->course, true);
832 return $cmid;
836 * Creates missing course section(s) and rebuilds course cache
838 * @param int|stdClass $courseorid course id or course object
839 * @param int|array $sections list of relative section numbers to create
840 * @return bool if there were any sections created
842 function course_create_sections_if_missing($courseorid, $sections) {
843 global $DB;
844 if (!is_array($sections)) {
845 $sections = array($sections);
847 $existing = array_keys(get_fast_modinfo($courseorid)->get_section_info_all());
848 if (is_object($courseorid)) {
849 $courseorid = $courseorid->id;
851 $coursechanged = false;
852 foreach ($sections as $sectionnum) {
853 if (!in_array($sectionnum, $existing)) {
854 $cw = new stdClass();
855 $cw->course = $courseorid;
856 $cw->section = $sectionnum;
857 $cw->summary = '';
858 $cw->summaryformat = FORMAT_HTML;
859 $cw->sequence = '';
860 $id = $DB->insert_record("course_sections", $cw);
861 $coursechanged = true;
864 if ($coursechanged) {
865 rebuild_course_cache($courseorid, true);
867 return $coursechanged;
871 * Adds an existing module to the section
873 * Updates both tables {course_sections} and {course_modules}
875 * Note: This function does not use modinfo PROVIDED that the section you are
876 * adding the module to already exists. If the section does not exist, it will
877 * build modinfo if necessary and create the section.
879 * @param int|stdClass $courseorid course id or course object
880 * @param int $cmid id of the module already existing in course_modules table
881 * @param int $sectionnum relative number of the section (field course_sections.section)
882 * If section does not exist it will be created
883 * @param int|stdClass $beforemod id or object with field id corresponding to the module
884 * before which the module needs to be included. Null for inserting in the
885 * end of the section
886 * @return int The course_sections ID where the module is inserted
888 function course_add_cm_to_section($courseorid, $cmid, $sectionnum, $beforemod = null) {
889 global $DB, $COURSE;
890 if (is_object($beforemod)) {
891 $beforemod = $beforemod->id;
893 if (is_object($courseorid)) {
894 $courseid = $courseorid->id;
895 } else {
896 $courseid = $courseorid;
898 // Do not try to use modinfo here, there is no guarantee it is valid!
899 $section = $DB->get_record('course_sections',
900 array('course' => $courseid, 'section' => $sectionnum), '*', IGNORE_MISSING);
901 if (!$section) {
902 // This function call requires modinfo.
903 course_create_sections_if_missing($courseorid, $sectionnum);
904 $section = $DB->get_record('course_sections',
905 array('course' => $courseid, 'section' => $sectionnum), '*', MUST_EXIST);
908 $modarray = explode(",", trim($section->sequence));
909 if (empty($section->sequence)) {
910 $newsequence = "$cmid";
911 } else if ($beforemod && ($key = array_keys($modarray, $beforemod))) {
912 $insertarray = array($cmid, $beforemod);
913 array_splice($modarray, $key[0], 1, $insertarray);
914 $newsequence = implode(",", $modarray);
915 } else {
916 $newsequence = "$section->sequence,$cmid";
918 $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id));
919 $DB->set_field('course_modules', 'section', $section->id, array('id' => $cmid));
920 if (is_object($courseorid)) {
921 rebuild_course_cache($courseorid->id, true);
922 } else {
923 rebuild_course_cache($courseorid, true);
925 return $section->id; // Return course_sections ID that was used.
929 * Change the group mode of a course module.
931 * Note: Do not forget to trigger the event \core\event\course_module_updated as it needs
932 * to be triggered manually, refer to {@link \core\event\course_module_updated::create_from_cm()}.
934 * @param int $id course module ID.
935 * @param int $groupmode the new groupmode value.
936 * @return bool True if the $groupmode was updated.
938 function set_coursemodule_groupmode($id, $groupmode) {
939 global $DB;
940 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST);
941 if ($cm->groupmode != $groupmode) {
942 $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id));
943 rebuild_course_cache($cm->course, true);
945 return ($cm->groupmode != $groupmode);
948 function set_coursemodule_idnumber($id, $idnumber) {
949 global $DB;
950 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST);
951 if ($cm->idnumber != $idnumber) {
952 $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id));
953 rebuild_course_cache($cm->course, true);
955 return ($cm->idnumber != $idnumber);
959 * Set the visibility of a module and inherent properties.
961 * Note: Do not forget to trigger the event \core\event\course_module_updated as it needs
962 * to be triggered manually, refer to {@link \core\event\course_module_updated::create_from_cm()}.
964 * From 2.4 the parameter $prevstateoverrides has been removed, the logic it triggered
965 * has been moved to {@link set_section_visible()} which was the only place from which
966 * the parameter was used.
968 * @param int $id of the module
969 * @param int $visible state of the module
970 * @param int $visibleoncoursepage state of the module on the course page
971 * @return bool false when the module was not found, true otherwise
973 function set_coursemodule_visible($id, $visible, $visibleoncoursepage = 1) {
974 global $DB, $CFG;
975 require_once($CFG->libdir.'/gradelib.php');
976 require_once($CFG->dirroot.'/calendar/lib.php');
978 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
979 return false;
982 // Create events and propagate visibility to associated grade items if the value has changed.
983 // Only do this if it's changed to avoid accidently overwriting manual showing/hiding of student grades.
984 if ($cm->visible == $visible && $cm->visibleoncoursepage == $visibleoncoursepage) {
985 return true;
988 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
989 return false;
991 if (($cm->visible != $visible) &&
992 ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename)))) {
993 foreach($events as $event) {
994 if ($visible) {
995 $event = new calendar_event($event);
996 $event->toggle_visibility(true);
997 } else {
998 $event = new calendar_event($event);
999 $event->toggle_visibility(false);
1004 // Updating visible and visibleold to keep them in sync. Only changing a section visibility will
1005 // affect visibleold to allow for an original visibility restore. See set_section_visible().
1006 $cminfo = new stdClass();
1007 $cminfo->id = $id;
1008 $cminfo->visible = $visible;
1009 $cminfo->visibleoncoursepage = $visibleoncoursepage;
1010 $cminfo->visibleold = $visible;
1011 $DB->update_record('course_modules', $cminfo);
1013 // Hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there.
1014 // Note that this must be done after updating the row in course_modules, in case
1015 // the modules grade_item_update function needs to access $cm->visible.
1016 if ($cm->visible != $visible &&
1017 plugin_supports('mod', $modulename, FEATURE_CONTROLS_GRADE_VISIBILITY) &&
1018 component_callback_exists('mod_' . $modulename, 'grade_item_update')) {
1019 $instance = $DB->get_record($modulename, array('id' => $cm->instance), '*', MUST_EXIST);
1020 component_callback('mod_' . $modulename, 'grade_item_update', array($instance));
1021 } else if ($cm->visible != $visible) {
1022 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
1023 if ($grade_items) {
1024 foreach ($grade_items as $grade_item) {
1025 $grade_item->set_hidden(!$visible);
1030 rebuild_course_cache($cm->course, true);
1031 return true;
1035 * Changes the course module name
1037 * @param int $id course module id
1038 * @param string $name new value for a name
1039 * @return bool whether a change was made
1041 function set_coursemodule_name($id, $name) {
1042 global $CFG, $DB;
1043 require_once($CFG->libdir . '/gradelib.php');
1045 $cm = get_coursemodule_from_id('', $id, 0, false, MUST_EXIST);
1047 $module = new \stdClass();
1048 $module->id = $cm->instance;
1050 // Escape strings as they would be by mform.
1051 if (!empty($CFG->formatstringstriptags)) {
1052 $module->name = clean_param($name, PARAM_TEXT);
1053 } else {
1054 $module->name = clean_param($name, PARAM_CLEANHTML);
1056 if ($module->name === $cm->name || strval($module->name) === '') {
1057 return false;
1059 if (\core_text::strlen($module->name) > 255) {
1060 throw new \moodle_exception('maximumchars', 'moodle', '', 255);
1063 $module->timemodified = time();
1064 $DB->update_record($cm->modname, $module);
1065 $cm->name = $module->name;
1066 \core\event\course_module_updated::create_from_cm($cm)->trigger();
1067 rebuild_course_cache($cm->course, true);
1069 // Attempt to update the grade item if relevant.
1070 $grademodule = $DB->get_record($cm->modname, array('id' => $cm->instance));
1071 $grademodule->cmidnumber = $cm->idnumber;
1072 $grademodule->modname = $cm->modname;
1073 grade_update_mod_grades($grademodule);
1075 // Update calendar events with the new name.
1076 $refresheventsfunction = $cm->modname . '_refresh_events';
1077 if (function_exists($refresheventsfunction)) {
1078 call_user_func($refresheventsfunction, $cm->course);
1081 return true;
1085 * This function will handle the whole deletion process of a module. This includes calling
1086 * the modules delete_instance function, deleting files, events, grades, conditional data,
1087 * the data in the course_module and course_sections table and adding a module deletion
1088 * event to the DB.
1090 * @param int $cmid the course module id
1091 * @param bool $async whether or not to try to delete the module using an adhoc task. Async also depends on a plugin hook.
1092 * @throws moodle_exception
1093 * @since Moodle 2.5
1095 function course_delete_module($cmid, $async = false) {
1096 // Check the 'course_module_background_deletion_recommended' hook first.
1097 // Only use asynchronous deletion if at least one plugin returns true and if async deletion has been requested.
1098 // Both are checked because plugins should not be allowed to dictate the deletion behaviour, only support/decline it.
1099 // It's up to plugins to handle things like whether or not they are enabled.
1100 if ($async && $pluginsfunction = get_plugins_with_function('course_module_background_deletion_recommended')) {
1101 foreach ($pluginsfunction as $plugintype => $plugins) {
1102 foreach ($plugins as $pluginfunction) {
1103 if ($pluginfunction()) {
1104 return course_module_flag_for_async_deletion($cmid);
1110 global $CFG, $DB;
1112 require_once($CFG->libdir.'/gradelib.php');
1113 require_once($CFG->libdir.'/questionlib.php');
1114 require_once($CFG->dirroot.'/blog/lib.php');
1115 require_once($CFG->dirroot.'/calendar/lib.php');
1117 // Get the course module.
1118 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
1119 return true;
1122 // Get the module context.
1123 $modcontext = context_module::instance($cm->id);
1125 // Get the course module name.
1126 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
1128 // Get the file location of the delete_instance function for this module.
1129 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
1131 // Include the file required to call the delete_instance function for this module.
1132 if (file_exists($modlib)) {
1133 require_once($modlib);
1134 } else {
1135 throw new moodle_exception('cannotdeletemodulemissinglib', '', '', null,
1136 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
1139 $deleteinstancefunction = $modulename . '_delete_instance';
1141 // Ensure the delete_instance function exists for this module.
1142 if (!function_exists($deleteinstancefunction)) {
1143 throw new moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
1144 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
1147 // Allow plugins to use this course module before we completely delete it.
1148 if ($pluginsfunction = get_plugins_with_function('pre_course_module_delete')) {
1149 foreach ($pluginsfunction as $plugintype => $plugins) {
1150 foreach ($plugins as $pluginfunction) {
1151 $pluginfunction($cm);
1156 // Delete activity context questions and question categories.
1157 question_delete_activity($cm);
1159 // Call the delete_instance function, if it returns false throw an exception.
1160 if (!$deleteinstancefunction($cm->instance)) {
1161 throw new moodle_exception('cannotdeletemoduleinstance', '', '', null,
1162 "Cannot delete the module $modulename (instance).");
1165 // Remove all module files in case modules forget to do that.
1166 $fs = get_file_storage();
1167 $fs->delete_area_files($modcontext->id);
1169 // Delete events from calendar.
1170 if ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename))) {
1171 foreach($events as $event) {
1172 $calendarevent = calendar_event::load($event->id);
1173 $calendarevent->delete();
1177 // Delete grade items, outcome items and grades attached to modules.
1178 if ($grade_items = grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $modulename,
1179 'iteminstance' => $cm->instance, 'courseid' => $cm->course))) {
1180 foreach ($grade_items as $grade_item) {
1181 $grade_item->delete('moddelete');
1185 // Delete completion and availability data; it is better to do this even if the
1186 // features are not turned on, in case they were turned on previously (these will be
1187 // very quick on an empty table).
1188 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
1189 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
1190 'course' => $cm->course,
1191 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
1193 // Delete all tag instances associated with the instance of this module.
1194 core_tag_tag::delete_instances('mod_' . $modulename, null, $modcontext->id);
1195 core_tag_tag::remove_all_item_tags('core', 'course_modules', $cm->id);
1197 // Notify the competency subsystem.
1198 \core_competency\api::hook_course_module_deleted($cm);
1200 // Delete the context.
1201 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
1203 // Delete the module from the course_modules table.
1204 $DB->delete_records('course_modules', array('id' => $cm->id));
1206 // Delete module from that section.
1207 if (!delete_mod_from_section($cm->id, $cm->section)) {
1208 throw new moodle_exception('cannotdeletemodulefromsection', '', '', null,
1209 "Cannot delete the module $modulename (instance) from section.");
1212 // Trigger event for course module delete action.
1213 $event = \core\event\course_module_deleted::create(array(
1214 'courseid' => $cm->course,
1215 'context' => $modcontext,
1216 'objectid' => $cm->id,
1217 'other' => array(
1218 'modulename' => $modulename,
1219 'instanceid' => $cm->instance,
1222 $event->add_record_snapshot('course_modules', $cm);
1223 $event->trigger();
1224 rebuild_course_cache($cm->course, true);
1228 * Schedule a course module for deletion in the background using an adhoc task.
1230 * This method should not be called directly. Instead, please use course_delete_module($cmid, true), to denote async deletion.
1231 * The real deletion of the module is handled by the task, which calls 'course_delete_module($cmid)'.
1233 * @param int $cmid the course module id.
1234 * @return bool whether the module was successfully scheduled for deletion.
1235 * @throws \moodle_exception
1237 function course_module_flag_for_async_deletion($cmid) {
1238 global $CFG, $DB, $USER;
1239 require_once($CFG->libdir.'/gradelib.php');
1240 require_once($CFG->libdir.'/questionlib.php');
1241 require_once($CFG->dirroot.'/blog/lib.php');
1242 require_once($CFG->dirroot.'/calendar/lib.php');
1244 // Get the course module.
1245 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
1246 return true;
1249 // We need to be reasonably certain the deletion is going to succeed before we background the process.
1250 // Make the necessary delete_instance checks, etc. before proceeding further. Throw exceptions if required.
1252 // Get the course module name.
1253 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
1255 // Get the file location of the delete_instance function for this module.
1256 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
1258 // Include the file required to call the delete_instance function for this module.
1259 if (file_exists($modlib)) {
1260 require_once($modlib);
1261 } else {
1262 throw new \moodle_exception('cannotdeletemodulemissinglib', '', '', null,
1263 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
1266 $deleteinstancefunction = $modulename . '_delete_instance';
1268 // Ensure the delete_instance function exists for this module.
1269 if (!function_exists($deleteinstancefunction)) {
1270 throw new \moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
1271 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
1274 // We are going to defer the deletion as we can't be sure how long the module's pre_delete code will run for.
1275 $cm->deletioninprogress = '1';
1276 $DB->update_record('course_modules', $cm);
1278 // Create an adhoc task for the deletion of the course module. The task takes an array of course modules for removal.
1279 $removaltask = new \core_course\task\course_delete_modules();
1280 $removaltask->set_custom_data(array(
1281 'cms' => array($cm),
1282 'userid' => $USER->id,
1283 'realuserid' => \core\session\manager::get_realuser()->id
1286 // Queue the task for the next run.
1287 \core\task\manager::queue_adhoc_task($removaltask);
1289 // Reset the course cache to hide the module.
1290 rebuild_course_cache($cm->course, true);
1294 * Checks whether the given course has any course modules scheduled for adhoc deletion.
1296 * @param int $courseid the id of the course.
1297 * @return bool true if the course contains any modules pending deletion, false otherwise.
1299 function course_modules_pending_deletion($courseid) {
1300 if (empty($courseid)) {
1301 return false;
1303 $modinfo = get_fast_modinfo($courseid);
1304 foreach ($modinfo->get_cms() as $module) {
1305 if ($module->deletioninprogress == '1') {
1306 return true;
1309 return false;
1313 * Checks whether the course module, as defined by modulename and instanceid, is scheduled for deletion within the given course.
1315 * @param int $courseid the course id.
1316 * @param string $modulename the module name. E.g. 'assign', 'book', etc.
1317 * @param int $instanceid the module instance id.
1318 * @return bool true if the course module is pending deletion, false otherwise.
1320 function course_module_instance_pending_deletion($courseid, $modulename, $instanceid) {
1321 if (empty($courseid) || empty($modulename) || empty($instanceid)) {
1322 return false;
1324 $modinfo = get_fast_modinfo($courseid);
1325 $instances = $modinfo->get_instances_of($modulename);
1326 return isset($instances[$instanceid]) && $instances[$instanceid]->deletioninprogress;
1329 function delete_mod_from_section($modid, $sectionid) {
1330 global $DB;
1332 if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
1334 $modarray = explode(",", $section->sequence);
1336 if ($key = array_keys ($modarray, $modid)) {
1337 array_splice($modarray, $key[0], 1);
1338 $newsequence = implode(",", $modarray);
1339 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
1340 rebuild_course_cache($section->course, true);
1341 return true;
1342 } else {
1343 return false;
1347 return false;
1351 * Moves a section within a course, from a position to another.
1352 * Be very careful: $section and $destination refer to section number,
1353 * not id!.
1355 * @param object $course
1356 * @param int $section Section number (not id!!!)
1357 * @param int $destination
1358 * @param bool $ignorenumsections
1359 * @return boolean Result
1361 function move_section_to($course, $section, $destination, $ignorenumsections = false) {
1362 /// Moves a whole course section up and down within the course
1363 global $USER, $DB;
1365 if (!$destination && $destination != 0) {
1366 return true;
1369 // compartibility with course formats using field 'numsections'
1370 $courseformatoptions = course_get_format($course)->get_format_options();
1371 if ((!$ignorenumsections && array_key_exists('numsections', $courseformatoptions) &&
1372 ($destination > $courseformatoptions['numsections'])) || ($destination < 1)) {
1373 return false;
1376 // Get all sections for this course and re-order them (2 of them should now share the same section number)
1377 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
1378 'section ASC, id ASC', 'id, section')) {
1379 return false;
1382 $movedsections = reorder_sections($sections, $section, $destination);
1384 // Update all sections. Do this in 2 steps to avoid breaking database
1385 // uniqueness constraint
1386 $transaction = $DB->start_delegated_transaction();
1387 foreach ($movedsections as $id => $position) {
1388 if ($sections[$id] !== $position) {
1389 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
1392 foreach ($movedsections as $id => $position) {
1393 if ($sections[$id] !== $position) {
1394 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
1398 // If we move the highlighted section itself, then just highlight the destination.
1399 // Adjust the higlighted section location if we move something over it either direction.
1400 if ($section == $course->marker) {
1401 course_set_marker($course->id, $destination);
1402 } elseif ($section > $course->marker && $course->marker >= $destination) {
1403 course_set_marker($course->id, $course->marker+1);
1404 } elseif ($section < $course->marker && $course->marker <= $destination) {
1405 course_set_marker($course->id, $course->marker-1);
1408 $transaction->allow_commit();
1409 rebuild_course_cache($course->id, true);
1410 return true;
1414 * This method will delete a course section and may delete all modules inside it.
1416 * No permissions are checked here, use {@link course_can_delete_section()} to
1417 * check if section can actually be deleted.
1419 * @param int|stdClass $course
1420 * @param int|stdClass|section_info $section
1421 * @param bool $forcedeleteifnotempty if set to false section will not be deleted if it has modules in it.
1422 * @param bool $async whether or not to try to delete the section using an adhoc task. Async also depends on a plugin hook.
1423 * @return bool whether section was deleted
1425 function course_delete_section($course, $section, $forcedeleteifnotempty = true, $async = false) {
1426 global $DB;
1428 // Prepare variables.
1429 $courseid = (is_object($course)) ? $course->id : (int)$course;
1430 $sectionnum = (is_object($section)) ? $section->section : (int)$section;
1431 $section = $DB->get_record('course_sections', array('course' => $courseid, 'section' => $sectionnum));
1432 if (!$section) {
1433 // No section exists, can't proceed.
1434 return false;
1437 // Check the 'course_module_background_deletion_recommended' hook first.
1438 // Only use asynchronous deletion if at least one plugin returns true and if async deletion has been requested.
1439 // Both are checked because plugins should not be allowed to dictate the deletion behaviour, only support/decline it.
1440 // It's up to plugins to handle things like whether or not they are enabled.
1441 if ($async && $pluginsfunction = get_plugins_with_function('course_module_background_deletion_recommended')) {
1442 foreach ($pluginsfunction as $plugintype => $plugins) {
1443 foreach ($plugins as $pluginfunction) {
1444 if ($pluginfunction()) {
1445 return course_delete_section_async($section, $forcedeleteifnotempty);
1451 $format = course_get_format($course);
1452 $sectionname = $format->get_section_name($section);
1454 // Delete section.
1455 $result = $format->delete_section($section, $forcedeleteifnotempty);
1457 // Trigger an event for course section deletion.
1458 if ($result) {
1459 $context = context_course::instance($courseid);
1460 $event = \core\event\course_section_deleted::create(
1461 array(
1462 'objectid' => $section->id,
1463 'courseid' => $courseid,
1464 'context' => $context,
1465 'other' => array(
1466 'sectionnum' => $section->section,
1467 'sectionname' => $sectionname,
1471 $event->add_record_snapshot('course_sections', $section);
1472 $event->trigger();
1474 return $result;
1478 * Course section deletion, using an adhoc task for deletion of the modules it contains.
1479 * 1. Schedule all modules within the section for adhoc removal.
1480 * 2. Move all modules to course section 0.
1481 * 3. Delete the resulting empty section.
1483 * @param \stdClass $section the section to schedule for deletion.
1484 * @param bool $forcedeleteifnotempty whether to force section deletion if it contains modules.
1485 * @return bool true if the section was scheduled for deletion, false otherwise.
1487 function course_delete_section_async($section, $forcedeleteifnotempty = true) {
1488 global $DB, $USER;
1490 // Objects only, and only valid ones.
1491 if (!is_object($section) || empty($section->id)) {
1492 return false;
1495 // Does the object currently exist in the DB for removal (check for stale objects).
1496 $section = $DB->get_record('course_sections', array('id' => $section->id));
1497 if (!$section || !$section->section) {
1498 // No section exists, or the section is 0. Can't proceed.
1499 return false;
1502 // Check whether the section can be removed.
1503 if (!$forcedeleteifnotempty && (!empty($section->sequence) || !empty($section->summary))) {
1504 return false;
1507 $format = course_get_format($section->course);
1508 $sectionname = $format->get_section_name($section);
1510 // Flag those modules having no existing deletion flag. Some modules may have been scheduled for deletion manually, and we don't
1511 // want to create additional adhoc deletion tasks for these. Moving them to section 0 will suffice.
1512 $affectedmods = $DB->get_records_select('course_modules', 'course = ? AND section = ? AND deletioninprogress <> ?',
1513 [$section->course, $section->id, 1], '', 'id');
1514 $DB->set_field('course_modules', 'deletioninprogress', '1', ['course' => $section->course, 'section' => $section->id]);
1516 // Move all modules to section 0.
1517 $modules = $DB->get_records('course_modules', ['section' => $section->id], '');
1518 $sectionzero = $DB->get_record('course_sections', ['course' => $section->course, 'section' => '0']);
1519 foreach ($modules as $mod) {
1520 moveto_module($mod, $sectionzero);
1523 // Create and queue an adhoc task for the deletion of the modules.
1524 $removaltask = new \core_course\task\course_delete_modules();
1525 $data = array(
1526 'cms' => $affectedmods,
1527 'userid' => $USER->id,
1528 'realuserid' => \core\session\manager::get_realuser()->id
1530 $removaltask->set_custom_data($data);
1531 \core\task\manager::queue_adhoc_task($removaltask);
1533 // Delete the now empty section, passing in only the section number, which forces the function to fetch a new object.
1534 // The refresh is needed because the section->sequence is now stale.
1535 $result = $format->delete_section($section->section, $forcedeleteifnotempty);
1537 // Trigger an event for course section deletion.
1538 if ($result) {
1539 $context = \context_course::instance($section->course);
1540 $event = \core\event\course_section_deleted::create(
1541 array(
1542 'objectid' => $section->id,
1543 'courseid' => $section->course,
1544 'context' => $context,
1545 'other' => array(
1546 'sectionnum' => $section->section,
1547 'sectionname' => $sectionname,
1551 $event->add_record_snapshot('course_sections', $section);
1552 $event->trigger();
1554 rebuild_course_cache($section->course, true);
1556 return $result;
1560 * Updates the course section
1562 * This function does not check permissions or clean values - this has to be done prior to calling it.
1564 * @param int|stdClass $course
1565 * @param stdClass $section record from course_sections table - it will be updated with the new values
1566 * @param array|stdClass $data
1568 function course_update_section($course, $section, $data) {
1569 global $DB;
1571 $courseid = (is_object($course)) ? $course->id : (int)$course;
1573 // Some fields can not be updated using this method.
1574 $data = array_diff_key((array)$data, array('id', 'course', 'section', 'sequence'));
1575 $changevisibility = (array_key_exists('visible', $data) && (bool)$data['visible'] != (bool)$section->visible);
1576 if (array_key_exists('name', $data) && \core_text::strlen($data['name']) > 255) {
1577 throw new moodle_exception('maximumchars', 'moodle', '', 255);
1580 // Update record in the DB and course format options.
1581 $data['id'] = $section->id;
1582 $DB->update_record('course_sections', $data);
1583 rebuild_course_cache($courseid, true);
1584 course_get_format($courseid)->update_section_format_options($data);
1586 // Update fields of the $section object.
1587 foreach ($data as $key => $value) {
1588 if (property_exists($section, $key)) {
1589 $section->$key = $value;
1593 // Trigger an event for course section update.
1594 $event = \core\event\course_section_updated::create(
1595 array(
1596 'objectid' => $section->id,
1597 'courseid' => $courseid,
1598 'context' => context_course::instance($courseid),
1599 'other' => array('sectionnum' => $section->section)
1602 $event->trigger();
1604 // If section visibility was changed, hide the modules in this section too.
1605 if ($changevisibility && !empty($section->sequence)) {
1606 $modules = explode(',', $section->sequence);
1607 foreach ($modules as $moduleid) {
1608 if ($cm = get_coursemodule_from_id(null, $moduleid, $courseid)) {
1609 if ($data['visible']) {
1610 // As we unhide the section, we use the previously saved visibility stored in visibleold.
1611 set_coursemodule_visible($moduleid, $cm->visibleold, $cm->visibleoncoursepage);
1612 } else {
1613 // We hide the section, so we hide the module but we store the original state in visibleold.
1614 set_coursemodule_visible($moduleid, 0, $cm->visibleoncoursepage);
1615 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id' => $moduleid));
1617 \core\event\course_module_updated::create_from_cm($cm)->trigger();
1624 * Checks if the current user can delete a section (if course format allows it and user has proper permissions).
1626 * @param int|stdClass $course
1627 * @param int|stdClass|section_info $section
1628 * @return bool
1630 function course_can_delete_section($course, $section) {
1631 if (is_object($section)) {
1632 $section = $section->section;
1634 if (!$section) {
1635 // Not possible to delete 0-section.
1636 return false;
1638 // Course format should allow to delete sections.
1639 if (!course_get_format($course)->can_delete_section($section)) {
1640 return false;
1642 // Make sure user has capability to update course and move sections.
1643 $context = context_course::instance(is_object($course) ? $course->id : $course);
1644 if (!has_all_capabilities(array('moodle/course:movesections', 'moodle/course:update'), $context)) {
1645 return false;
1647 // Make sure user has capability to delete each activity in this section.
1648 $modinfo = get_fast_modinfo($course);
1649 if (!empty($modinfo->sections[$section])) {
1650 foreach ($modinfo->sections[$section] as $cmid) {
1651 if (!has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
1652 return false;
1656 return true;
1660 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
1661 * an original position number and a target position number, rebuilds the array so that the
1662 * move is made without any duplication of section positions.
1663 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
1664 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
1666 * @param array $sections
1667 * @param int $origin_position
1668 * @param int $target_position
1669 * @return array
1671 function reorder_sections($sections, $origin_position, $target_position) {
1672 if (!is_array($sections)) {
1673 return false;
1676 // We can't move section position 0
1677 if ($origin_position < 1) {
1678 echo "We can't move section position 0";
1679 return false;
1682 // Locate origin section in sections array
1683 if (!$origin_key = array_search($origin_position, $sections)) {
1684 echo "searched position not in sections array";
1685 return false; // searched position not in sections array
1688 // Extract origin section
1689 $origin_section = $sections[$origin_key];
1690 unset($sections[$origin_key]);
1692 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
1693 $found = false;
1694 $append_array = array();
1695 foreach ($sections as $id => $position) {
1696 if ($found) {
1697 $append_array[$id] = $position;
1698 unset($sections[$id]);
1700 if ($position == $target_position) {
1701 if ($target_position < $origin_position) {
1702 $append_array[$id] = $position;
1703 unset($sections[$id]);
1705 $found = true;
1709 // Append moved section
1710 $sections[$origin_key] = $origin_section;
1712 // Append rest of array (if applicable)
1713 if (!empty($append_array)) {
1714 foreach ($append_array as $id => $position) {
1715 $sections[$id] = $position;
1719 // Renumber positions
1720 $position = 0;
1721 foreach ($sections as $id => $p) {
1722 $sections[$id] = $position;
1723 $position++;
1726 return $sections;
1731 * Move the module object $mod to the specified $section
1732 * If $beforemod exists then that is the module
1733 * before which $modid should be inserted
1735 * @param stdClass|cm_info $mod
1736 * @param stdClass|section_info $section
1737 * @param int|stdClass $beforemod id or object with field id corresponding to the module
1738 * before which the module needs to be included. Null for inserting in the
1739 * end of the section
1740 * @return int new value for module visibility (0 or 1)
1742 function moveto_module($mod, $section, $beforemod=NULL) {
1743 global $OUTPUT, $DB;
1745 // Current module visibility state - return value of this function.
1746 $modvisible = $mod->visible;
1748 // Remove original module from original section.
1749 if (! delete_mod_from_section($mod->id, $mod->section)) {
1750 echo $OUTPUT->notification("Could not delete module from existing section");
1753 // If moving to a hidden section then hide module.
1754 if ($mod->section != $section->id) {
1755 if (!$section->visible && $mod->visible) {
1756 // Module was visible but must become hidden after moving to hidden section.
1757 $modvisible = 0;
1758 set_coursemodule_visible($mod->id, 0);
1759 // Set visibleold to 1 so module will be visible when section is made visible.
1760 $DB->set_field('course_modules', 'visibleold', 1, array('id' => $mod->id));
1762 if ($section->visible && !$mod->visible) {
1763 // Hidden module was moved to the visible section, restore the module visibility from visibleold.
1764 set_coursemodule_visible($mod->id, $mod->visibleold);
1765 $modvisible = $mod->visibleold;
1769 // Add the module into the new section.
1770 course_add_cm_to_section($section->course, $mod->id, $section->section, $beforemod);
1771 return $modvisible;
1775 * Returns the list of all editing actions that current user can perform on the module
1777 * @param cm_info $mod The module to produce editing buttons for
1778 * @param int $indent The current indenting (default -1 means no move left-right actions)
1779 * @param int $sr The section to link back to (used for creating the links)
1780 * @return array array of action_link or pix_icon objects
1782 function course_get_cm_edit_actions(cm_info $mod, $indent = -1, $sr = null) {
1783 global $COURSE, $SITE, $CFG;
1785 static $str;
1787 $coursecontext = context_course::instance($mod->course);
1788 $modcontext = context_module::instance($mod->id);
1789 $courseformat = course_get_format($mod->get_course());
1791 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
1792 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
1794 // No permission to edit anything.
1795 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
1796 return array();
1799 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
1801 if (!isset($str)) {
1802 $str = get_strings(array('delete', 'move', 'moveright', 'moveleft',
1803 'editsettings', 'duplicate', 'hide', 'makeavailable', 'makeunavailable', 'show'), 'moodle');
1804 $str->assign = get_string('assignroles', 'role');
1805 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
1806 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
1807 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
1810 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
1812 if ($sr !== null) {
1813 $baseurl->param('sr', $sr);
1815 $actions = array();
1817 // Update.
1818 if ($hasmanageactivities) {
1819 $actions['update'] = new action_menu_link_secondary(
1820 new moodle_url($baseurl, array('update' => $mod->id)),
1821 new pix_icon('t/edit', $str->editsettings, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1822 $str->editsettings,
1823 array('class' => 'editing_update', 'data-action' => 'update')
1827 // Indent.
1828 if ($hasmanageactivities && $indent >= 0) {
1829 $indentlimits = new stdClass();
1830 $indentlimits->min = 0;
1831 $indentlimits->max = 16;
1832 if (right_to_left()) { // Exchange arrows on RTL
1833 $rightarrow = 't/left';
1834 $leftarrow = 't/right';
1835 } else {
1836 $rightarrow = 't/right';
1837 $leftarrow = 't/left';
1840 if ($indent >= $indentlimits->max) {
1841 $enabledclass = 'hidden';
1842 } else {
1843 $enabledclass = '';
1845 $actions['moveright'] = new action_menu_link_secondary(
1846 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
1847 new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1848 $str->moveright,
1849 array('class' => 'editing_moveright ' . $enabledclass, 'data-action' => 'moveright',
1850 'data-keepopen' => true, 'data-sectionreturn' => $sr)
1853 if ($indent <= $indentlimits->min) {
1854 $enabledclass = 'hidden';
1855 } else {
1856 $enabledclass = '';
1858 $actions['moveleft'] = new action_menu_link_secondary(
1859 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
1860 new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1861 $str->moveleft,
1862 array('class' => 'editing_moveleft ' . $enabledclass, 'data-action' => 'moveleft',
1863 'data-keepopen' => true, 'data-sectionreturn' => $sr)
1868 // Hide/Show/Available/Unavailable.
1869 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
1870 $allowstealth = !empty($CFG->allowstealth) && $courseformat->allow_stealth_module_visibility($mod, $mod->get_section_info());
1872 $sectionvisible = $mod->get_section_info()->visible;
1873 // The module on the course page may be in one of the following states:
1874 // - Available and displayed on the course page ($displayedoncoursepage);
1875 // - Not available and not displayed on the course page ($unavailable);
1876 // - Available but not displayed on the course page ($stealth) - this can also be a visible activity in a hidden section.
1877 $displayedoncoursepage = $mod->visible && $mod->visibleoncoursepage && $sectionvisible;
1878 $unavailable = !$mod->visible;
1879 $stealth = $mod->visible && (!$mod->visibleoncoursepage || !$sectionvisible);
1880 if ($displayedoncoursepage) {
1881 $actions['hide'] = new action_menu_link_secondary(
1882 new moodle_url($baseurl, array('hide' => $mod->id)),
1883 new pix_icon('t/hide', $str->hide, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1884 $str->hide,
1885 array('class' => 'editing_hide', 'data-action' => 'hide')
1887 } else if (!$displayedoncoursepage && $sectionvisible) {
1888 // Offer to "show" only if the section is visible.
1889 $actions['show'] = new action_menu_link_secondary(
1890 new moodle_url($baseurl, array('show' => $mod->id)),
1891 new pix_icon('t/show', $str->show, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1892 $str->show,
1893 array('class' => 'editing_show', 'data-action' => 'show')
1897 if ($stealth) {
1898 // When making the "stealth" module unavailable we perform the same action as hiding the visible module.
1899 $actions['hide'] = new action_menu_link_secondary(
1900 new moodle_url($baseurl, array('hide' => $mod->id)),
1901 new pix_icon('t/unblock', $str->makeunavailable, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1902 $str->makeunavailable,
1903 array('class' => 'editing_makeunavailable', 'data-action' => 'hide', 'data-sectionreturn' => $sr)
1905 } else if ($unavailable && (!$sectionvisible || $allowstealth) && $mod->has_view()) {
1906 // Allow to make visually hidden module available in gradebook and other reports by making it a "stealth" module.
1907 // When the section is hidden it is an equivalent of "showing" the module.
1908 // Activities without the link (i.e. labels) can not be made available but hidden on course page.
1909 $action = $sectionvisible ? 'stealth' : 'show';
1910 $actions[$action] = new action_menu_link_secondary(
1911 new moodle_url($baseurl, array($action => $mod->id)),
1912 new pix_icon('t/block', $str->makeavailable, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1913 $str->makeavailable,
1914 array('class' => 'editing_makeavailable', 'data-action' => $action, 'data-sectionreturn' => $sr)
1919 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
1920 if (has_all_capabilities($dupecaps, $coursecontext) &&
1921 plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2) &&
1922 course_allowed_module($mod->get_course(), $mod->modname)) {
1923 $actions['duplicate'] = new action_menu_link_secondary(
1924 new moodle_url($baseurl, array('duplicate' => $mod->id)),
1925 new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1926 $str->duplicate,
1927 array('class' => 'editing_duplicate', 'data-action' => 'duplicate', 'data-sectionreturn' => $sr)
1931 // Groupmode.
1932 if ($hasmanageactivities && !$mod->coursegroupmodeforce) {
1933 if (plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
1934 if ($mod->effectivegroupmode == SEPARATEGROUPS) {
1935 $nextgroupmode = VISIBLEGROUPS;
1936 $grouptitle = $str->groupsseparate;
1937 $actionname = 'groupsseparate';
1938 $nextactionname = 'groupsvisible';
1939 $groupimage = 'i/groups';
1940 } else if ($mod->effectivegroupmode == VISIBLEGROUPS) {
1941 $nextgroupmode = NOGROUPS;
1942 $grouptitle = $str->groupsvisible;
1943 $actionname = 'groupsvisible';
1944 $nextactionname = 'groupsnone';
1945 $groupimage = 'i/groupv';
1946 } else {
1947 $nextgroupmode = SEPARATEGROUPS;
1948 $grouptitle = $str->groupsnone;
1949 $actionname = 'groupsnone';
1950 $nextactionname = 'groupsseparate';
1951 $groupimage = 'i/groupn';
1954 $actions[$actionname] = new action_menu_link_primary(
1955 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $nextgroupmode)),
1956 new pix_icon($groupimage, $grouptitle, 'moodle', array('class' => 'iconsmall')),
1957 $grouptitle,
1958 array('class' => 'editing_'. $actionname, 'data-action' => $nextactionname,
1959 'aria-live' => 'assertive', 'data-sectionreturn' => $sr)
1961 } else {
1962 $actions['nogroupsupport'] = new action_menu_filler();
1966 // Assign.
1967 if (has_capability('moodle/role:assign', $modcontext)){
1968 $actions['assign'] = new action_menu_link_secondary(
1969 new moodle_url('/admin/roles/assign.php', array('contextid' => $modcontext->id)),
1970 new pix_icon('t/assignroles', $str->assign, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1971 $str->assign,
1972 array('class' => 'editing_assign', 'data-action' => 'assignroles', 'data-sectionreturn' => $sr)
1976 // Delete.
1977 if ($hasmanageactivities) {
1978 $actions['delete'] = new action_menu_link_secondary(
1979 new moodle_url($baseurl, array('delete' => $mod->id)),
1980 new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1981 $str->delete,
1982 array('class' => 'editing_delete', 'data-action' => 'delete', 'data-sectionreturn' => $sr)
1986 return $actions;
1990 * Returns the move action.
1992 * @param cm_info $mod The module to produce a move button for
1993 * @param int $sr The section to link back to (used for creating the links)
1994 * @return The markup for the move action, or an empty string if not available.
1996 function course_get_cm_move(cm_info $mod, $sr = null) {
1997 global $OUTPUT;
1999 static $str;
2000 static $baseurl;
2002 $modcontext = context_module::instance($mod->id);
2003 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
2005 if (!isset($str)) {
2006 $str = get_strings(array('move'));
2009 if (!isset($baseurl)) {
2010 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
2012 if ($sr !== null) {
2013 $baseurl->param('sr', $sr);
2017 if ($hasmanageactivities) {
2018 $pixicon = 'i/dragdrop';
2020 if (!course_ajax_enabled($mod->get_course())) {
2021 // Override for course frontpage until we get drag/drop working there.
2022 $pixicon = 't/move';
2025 return html_writer::link(
2026 new moodle_url($baseurl, array('copy' => $mod->id)),
2027 $OUTPUT->pix_icon($pixicon, $str->move, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2028 array('class' => 'editing_move', 'data-action' => 'move', 'data-sectionreturn' => $sr)
2031 return '';
2035 * given a course object with shortname & fullname, this function will
2036 * truncate the the number of chars allowed and add ... if it was too long
2038 function course_format_name ($course,$max=100) {
2040 $context = context_course::instance($course->id);
2041 $shortname = format_string($course->shortname, true, array('context' => $context));
2042 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
2043 $str = $shortname.': '. $fullname;
2044 if (core_text::strlen($str) <= $max) {
2045 return $str;
2047 else {
2048 return core_text::substr($str,0,$max-3).'...';
2053 * Is the user allowed to add this type of module to this course?
2054 * @param object $course the course settings. Only $course->id is used.
2055 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
2056 * @return bool whether the current user is allowed to add this type of module to this course.
2058 function course_allowed_module($course, $modname) {
2059 if (is_numeric($modname)) {
2060 throw new coding_exception('Function course_allowed_module no longer
2061 supports numeric module ids. Please update your code to pass the module name.');
2064 $capability = 'mod/' . $modname . ':addinstance';
2065 if (!get_capability_info($capability)) {
2066 // Debug warning that the capability does not exist, but no more than once per page.
2067 static $warned = array();
2068 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
2069 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
2070 debugging('The module ' . $modname . ' does not define the standard capability ' .
2071 $capability , DEBUG_DEVELOPER);
2072 $warned[$modname] = 1;
2075 // If the capability does not exist, the module can always be added.
2076 return true;
2079 $coursecontext = context_course::instance($course->id);
2080 return has_capability($capability, $coursecontext);
2084 * Efficiently moves many courses around while maintaining
2085 * sortorder in order.
2087 * @param array $courseids is an array of course ids
2088 * @param int $categoryid
2089 * @return bool success
2091 function move_courses($courseids, $categoryid) {
2092 global $DB;
2094 if (empty($courseids)) {
2095 // Nothing to do.
2096 return false;
2099 if (!$category = $DB->get_record('course_categories', array('id' => $categoryid))) {
2100 return false;
2103 $courseids = array_reverse($courseids);
2104 $newparent = context_coursecat::instance($category->id);
2105 $i = 1;
2107 list($where, $params) = $DB->get_in_or_equal($courseids);
2108 $dbcourses = $DB->get_records_select('course', 'id ' . $where, $params, '', 'id, category, shortname, fullname');
2109 foreach ($dbcourses as $dbcourse) {
2110 $course = new stdClass();
2111 $course->id = $dbcourse->id;
2112 $course->category = $category->id;
2113 $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
2114 if ($category->visible == 0) {
2115 // Hide the course when moving into hidden category, do not update the visibleold flag - we want to get
2116 // to previous state if somebody unhides the category.
2117 $course->visible = 0;
2120 $DB->update_record('course', $course);
2122 // Update context, so it can be passed to event.
2123 $context = context_course::instance($course->id);
2124 $context->update_moved($newparent);
2126 // Trigger a course updated event.
2127 $event = \core\event\course_updated::create(array(
2128 'objectid' => $course->id,
2129 'context' => context_course::instance($course->id),
2130 'other' => array('shortname' => $dbcourse->shortname,
2131 'fullname' => $dbcourse->fullname)
2133 $event->set_legacy_logdata(array($course->id, 'course', 'move', 'edit.php?id=' . $course->id, $course->id));
2134 $event->trigger();
2136 fix_course_sortorder();
2137 cache_helper::purge_by_event('changesincourse');
2139 return true;
2143 * Returns the display name of the given section that the course prefers
2145 * Implementation of this function is provided by course format
2146 * @see format_base::get_section_name()
2148 * @param int|stdClass $courseorid The course to get the section name for (object or just course id)
2149 * @param int|stdClass $section Section object from database or just field course_sections.section
2150 * @return string Display name that the course format prefers, e.g. "Week 2"
2152 function get_section_name($courseorid, $section) {
2153 return course_get_format($courseorid)->get_section_name($section);
2157 * Tells if current course format uses sections
2159 * @param string $format Course format ID e.g. 'weeks' $course->format
2160 * @return bool
2162 function course_format_uses_sections($format) {
2163 $course = new stdClass();
2164 $course->format = $format;
2165 return course_get_format($course)->uses_sections();
2169 * Returns the information about the ajax support in the given source format
2171 * The returned object's property (boolean)capable indicates that
2172 * the course format supports Moodle course ajax features.
2174 * @param string $format
2175 * @return stdClass
2177 function course_format_ajax_support($format) {
2178 $course = new stdClass();
2179 $course->format = $format;
2180 return course_get_format($course)->supports_ajax();
2184 * Can the current user delete this course?
2185 * Course creators have exception,
2186 * 1 day after the creation they can sill delete the course.
2187 * @param int $courseid
2188 * @return boolean
2190 function can_delete_course($courseid) {
2191 global $USER;
2193 $context = context_course::instance($courseid);
2195 if (has_capability('moodle/course:delete', $context)) {
2196 return true;
2199 // hack: now try to find out if creator created this course recently (1 day)
2200 if (!has_capability('moodle/course:create', $context)) {
2201 return false;
2204 $since = time() - 60*60*24;
2205 $course = get_course($courseid);
2207 if ($course->timecreated < $since) {
2208 return false; // Return if the course was not created in last 24 hours.
2211 $logmanger = get_log_manager();
2212 $readers = $logmanger->get_readers('\core\log\sql_reader');
2213 $reader = reset($readers);
2215 if (empty($reader)) {
2216 return false; // No log reader found.
2219 // A proper reader.
2220 $select = "userid = :userid AND courseid = :courseid AND eventname = :eventname AND timecreated > :since";
2221 $params = array('userid' => $USER->id, 'since' => $since, 'courseid' => $course->id, 'eventname' => '\core\event\course_created');
2223 return (bool)$reader->get_events_select_count($select, $params);
2227 * Save the Your name for 'Some role' strings.
2229 * @param integer $courseid the id of this course.
2230 * @param array $data the data that came from the course settings form.
2232 function save_local_role_names($courseid, $data) {
2233 global $DB;
2234 $context = context_course::instance($courseid);
2236 foreach ($data as $fieldname => $value) {
2237 if (strpos($fieldname, 'role_') !== 0) {
2238 continue;
2240 list($ignored, $roleid) = explode('_', $fieldname);
2242 // make up our mind whether we want to delete, update or insert
2243 if (!$value) {
2244 $DB->delete_records('role_names', array('contextid' => $context->id, 'roleid' => $roleid));
2246 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id, 'roleid' => $roleid))) {
2247 $rolename->name = $value;
2248 $DB->update_record('role_names', $rolename);
2250 } else {
2251 $rolename = new stdClass;
2252 $rolename->contextid = $context->id;
2253 $rolename->roleid = $roleid;
2254 $rolename->name = $value;
2255 $DB->insert_record('role_names', $rolename);
2257 // This will ensure the course contacts cache is purged..
2258 coursecat::role_assignment_changed($roleid, $context);
2263 * Returns options to use in course overviewfiles filemanager
2265 * @param null|stdClass|course_in_list|int $course either object that has 'id' property or just the course id;
2266 * may be empty if course does not exist yet (course create form)
2267 * @return array|null array of options such as maxfiles, maxbytes, accepted_types, etc.
2268 * or null if overviewfiles are disabled
2270 function course_overviewfiles_options($course) {
2271 global $CFG;
2272 if (empty($CFG->courseoverviewfileslimit)) {
2273 return null;
2275 $accepted_types = preg_split('/\s*,\s*/', trim($CFG->courseoverviewfilesext), -1, PREG_SPLIT_NO_EMPTY);
2276 if (in_array('*', $accepted_types) || empty($accepted_types)) {
2277 $accepted_types = '*';
2278 } else {
2279 // Since config for $CFG->courseoverviewfilesext is a text box, human factor must be considered.
2280 // Make sure extensions are prefixed with dot unless they are valid typegroups
2281 foreach ($accepted_types as $i => $type) {
2282 if (substr($type, 0, 1) !== '.') {
2283 require_once($CFG->libdir. '/filelib.php');
2284 if (!count(file_get_typegroup('extension', $type))) {
2285 // It does not start with dot and is not a valid typegroup, this is most likely extension.
2286 $accepted_types[$i] = '.'. $type;
2287 $corrected = true;
2291 if (!empty($corrected)) {
2292 set_config('courseoverviewfilesext', join(',', $accepted_types));
2295 $options = array(
2296 'maxfiles' => $CFG->courseoverviewfileslimit,
2297 'maxbytes' => $CFG->maxbytes,
2298 'subdirs' => 0,
2299 'accepted_types' => $accepted_types
2301 if (!empty($course->id)) {
2302 $options['context'] = context_course::instance($course->id);
2303 } else if (is_int($course) && $course > 0) {
2304 $options['context'] = context_course::instance($course);
2306 return $options;
2310 * Create a course and either return a $course object
2312 * Please note this functions does not verify any access control,
2313 * the calling code is responsible for all validation (usually it is the form definition).
2315 * @param array $editoroptions course description editor options
2316 * @param object $data - all the data needed for an entry in the 'course' table
2317 * @return object new course instance
2319 function create_course($data, $editoroptions = NULL) {
2320 global $DB, $CFG;
2322 //check the categoryid - must be given for all new courses
2323 $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
2325 // Check if the shortname already exists.
2326 if (!empty($data->shortname)) {
2327 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
2328 throw new moodle_exception('shortnametaken', '', '', $data->shortname);
2332 // Check if the idnumber already exists.
2333 if (!empty($data->idnumber)) {
2334 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
2335 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber);
2339 if ($errorcode = course_validate_dates((array)$data)) {
2340 throw new moodle_exception($errorcode);
2343 // Check if timecreated is given.
2344 $data->timecreated = !empty($data->timecreated) ? $data->timecreated : time();
2345 $data->timemodified = $data->timecreated;
2347 // place at beginning of any category
2348 $data->sortorder = 0;
2350 if ($editoroptions) {
2351 // summary text is updated later, we need context to store the files first
2352 $data->summary = '';
2353 $data->summary_format = FORMAT_HTML;
2356 if (!isset($data->visible)) {
2357 // data not from form, add missing visibility info
2358 $data->visible = $category->visible;
2360 $data->visibleold = $data->visible;
2362 $newcourseid = $DB->insert_record('course', $data);
2363 $context = context_course::instance($newcourseid, MUST_EXIST);
2365 if ($editoroptions) {
2366 // Save the files used in the summary editor and store
2367 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2368 $DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid));
2369 $DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid));
2371 if ($overviewfilesoptions = course_overviewfiles_options($newcourseid)) {
2372 // Save the course overviewfiles
2373 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2376 // update course format options
2377 course_get_format($newcourseid)->update_course_format_options($data);
2379 $course = course_get_format($newcourseid)->get_course();
2381 fix_course_sortorder();
2382 // purge appropriate caches in case fix_course_sortorder() did not change anything
2383 cache_helper::purge_by_event('changesincourse');
2385 // new context created - better mark it as dirty
2386 $context->mark_dirty();
2388 // Trigger a course created event.
2389 $event = \core\event\course_created::create(array(
2390 'objectid' => $course->id,
2391 'context' => context_course::instance($course->id),
2392 'other' => array('shortname' => $course->shortname,
2393 'fullname' => $course->fullname)
2396 $event->trigger();
2398 // Setup the blocks
2399 blocks_add_default_course_blocks($course);
2401 // Create a default section.
2402 course_create_sections_if_missing($course, 0);
2404 // Save any custom role names.
2405 save_local_role_names($course->id, (array)$data);
2407 // set up enrolments
2408 enrol_course_updated(true, $course, $data);
2410 // Update course tags.
2411 if (isset($data->tags)) {
2412 core_tag_tag::set_item_tags('core', 'course', $course->id, context_course::instance($course->id), $data->tags);
2415 return $course;
2419 * Update a course.
2421 * Please note this functions does not verify any access control,
2422 * the calling code is responsible for all validation (usually it is the form definition).
2424 * @param object $data - all the data needed for an entry in the 'course' table
2425 * @param array $editoroptions course description editor options
2426 * @return void
2428 function update_course($data, $editoroptions = NULL) {
2429 global $DB, $CFG;
2431 $data->timemodified = time();
2433 // Prevent changes on front page course.
2434 if ($data->id == SITEID) {
2435 throw new moodle_exception('invalidcourse', 'error');
2438 $oldcourse = course_get_format($data->id)->get_course();
2439 $context = context_course::instance($oldcourse->id);
2441 if ($editoroptions) {
2442 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2444 if ($overviewfilesoptions = course_overviewfiles_options($data->id)) {
2445 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2448 // Check we don't have a duplicate shortname.
2449 if (!empty($data->shortname) && $oldcourse->shortname != $data->shortname) {
2450 if ($DB->record_exists_sql('SELECT id from {course} WHERE shortname = ? AND id <> ?', array($data->shortname, $data->id))) {
2451 throw new moodle_exception('shortnametaken', '', '', $data->shortname);
2455 // Check we don't have a duplicate idnumber.
2456 if (!empty($data->idnumber) && $oldcourse->idnumber != $data->idnumber) {
2457 if ($DB->record_exists_sql('SELECT id from {course} WHERE idnumber = ? AND id <> ?', array($data->idnumber, $data->id))) {
2458 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber);
2462 if ($errorcode = course_validate_dates((array)$data)) {
2463 throw new moodle_exception($errorcode);
2466 if (!isset($data->category) or empty($data->category)) {
2467 // prevent nulls and 0 in category field
2468 unset($data->category);
2470 $changesincoursecat = $movecat = (isset($data->category) and $oldcourse->category != $data->category);
2472 if (!isset($data->visible)) {
2473 // data not from form, add missing visibility info
2474 $data->visible = $oldcourse->visible;
2477 if ($data->visible != $oldcourse->visible) {
2478 // reset the visibleold flag when manually hiding/unhiding course
2479 $data->visibleold = $data->visible;
2480 $changesincoursecat = true;
2481 } else {
2482 if ($movecat) {
2483 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category));
2484 if (empty($newcategory->visible)) {
2485 // make sure when moving into hidden category the course is hidden automatically
2486 $data->visible = 0;
2491 // Set newsitems to 0 if format does not support announcements.
2492 if (isset($data->format)) {
2493 $newcourseformat = course_get_format((object)['format' => $data->format]);
2494 if (!$newcourseformat->supports_news()) {
2495 $data->newsitems = 0;
2499 // Update with the new data
2500 $DB->update_record('course', $data);
2501 // make sure the modinfo cache is reset
2502 rebuild_course_cache($data->id);
2504 // update course format options with full course data
2505 course_get_format($data->id)->update_course_format_options($data, $oldcourse);
2507 $course = $DB->get_record('course', array('id'=>$data->id));
2509 if ($movecat) {
2510 $newparent = context_coursecat::instance($course->category);
2511 $context->update_moved($newparent);
2513 $fixcoursesortorder = $movecat || (isset($data->sortorder) && ($oldcourse->sortorder != $data->sortorder));
2514 if ($fixcoursesortorder) {
2515 fix_course_sortorder();
2518 // purge appropriate caches in case fix_course_sortorder() did not change anything
2519 cache_helper::purge_by_event('changesincourse');
2520 if ($changesincoursecat) {
2521 cache_helper::purge_by_event('changesincoursecat');
2524 // Test for and remove blocks which aren't appropriate anymore
2525 blocks_remove_inappropriate($course);
2527 // Save any custom role names.
2528 save_local_role_names($course->id, $data);
2530 // update enrol settings
2531 enrol_course_updated(false, $course, $data);
2533 // Update course tags.
2534 if (isset($data->tags)) {
2535 core_tag_tag::set_item_tags('core', 'course', $course->id, context_course::instance($course->id), $data->tags);
2538 // Trigger a course updated event.
2539 $event = \core\event\course_updated::create(array(
2540 'objectid' => $course->id,
2541 'context' => context_course::instance($course->id),
2542 'other' => array('shortname' => $course->shortname,
2543 'fullname' => $course->fullname)
2546 $event->set_legacy_logdata(array($course->id, 'course', 'update', 'edit.php?id=' . $course->id, $course->id));
2547 $event->trigger();
2549 if ($oldcourse->format !== $course->format) {
2550 // Remove all options stored for the previous format
2551 // We assume that new course format migrated everything it needed watching trigger
2552 // 'course_updated' and in method format_XXX::update_course_format_options()
2553 $DB->delete_records('course_format_options',
2554 array('courseid' => $course->id, 'format' => $oldcourse->format));
2559 * Average number of participants
2560 * @return integer
2562 function average_number_of_participants() {
2563 global $DB, $SITE;
2565 //count total of enrolments for visible course (except front page)
2566 $sql = 'SELECT COUNT(*) FROM (
2567 SELECT DISTINCT ue.userid, e.courseid
2568 FROM {user_enrolments} ue, {enrol} e, {course} c
2569 WHERE ue.enrolid = e.id
2570 AND e.courseid <> :siteid
2571 AND c.id = e.courseid
2572 AND c.visible = 1) total';
2573 $params = array('siteid' => $SITE->id);
2574 $enrolmenttotal = $DB->count_records_sql($sql, $params);
2577 //count total of visible courses (minus front page)
2578 $coursetotal = $DB->count_records('course', array('visible' => 1));
2579 $coursetotal = $coursetotal - 1 ;
2581 //average of enrolment
2582 if (empty($coursetotal)) {
2583 $participantaverage = 0;
2584 } else {
2585 $participantaverage = $enrolmenttotal / $coursetotal;
2588 return $participantaverage;
2592 * Average number of course modules
2593 * @return integer
2595 function average_number_of_courses_modules() {
2596 global $DB, $SITE;
2598 //count total of visible course module (except front page)
2599 $sql = 'SELECT COUNT(*) FROM (
2600 SELECT cm.course, cm.module
2601 FROM {course} c, {course_modules} cm
2602 WHERE c.id = cm.course
2603 AND c.id <> :siteid
2604 AND cm.visible = 1
2605 AND c.visible = 1) total';
2606 $params = array('siteid' => $SITE->id);
2607 $moduletotal = $DB->count_records_sql($sql, $params);
2610 //count total of visible courses (minus front page)
2611 $coursetotal = $DB->count_records('course', array('visible' => 1));
2612 $coursetotal = $coursetotal - 1 ;
2614 //average of course module
2615 if (empty($coursetotal)) {
2616 $coursemoduleaverage = 0;
2617 } else {
2618 $coursemoduleaverage = $moduletotal / $coursetotal;
2621 return $coursemoduleaverage;
2625 * This class pertains to course requests and contains methods associated with
2626 * create, approving, and removing course requests.
2628 * Please note we do not allow embedded images here because there is no context
2629 * to store them with proper access control.
2631 * @copyright 2009 Sam Hemelryk
2632 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2633 * @since Moodle 2.0
2635 * @property-read int $id
2636 * @property-read string $fullname
2637 * @property-read string $shortname
2638 * @property-read string $summary
2639 * @property-read int $summaryformat
2640 * @property-read int $summarytrust
2641 * @property-read string $reason
2642 * @property-read int $requester
2644 class course_request {
2647 * This is the stdClass that stores the properties for the course request
2648 * and is externally accessed through the __get magic method
2649 * @var stdClass
2651 protected $properties;
2654 * An array of options for the summary editor used by course request forms.
2655 * This is initially set by {@link summary_editor_options()}
2656 * @var array
2657 * @static
2659 protected static $summaryeditoroptions;
2662 * Static function to prepare the summary editor for working with a course
2663 * request.
2665 * @static
2666 * @param null|stdClass $data Optional, an object containing the default values
2667 * for the form, these may be modified when preparing the
2668 * editor so this should be called before creating the form
2669 * @return stdClass An object that can be used to set the default values for
2670 * an mforms form
2672 public static function prepare($data=null) {
2673 if ($data === null) {
2674 $data = new stdClass;
2676 $data = file_prepare_standard_editor($data, 'summary', self::summary_editor_options());
2677 return $data;
2681 * Static function to create a new course request when passed an array of properties
2682 * for it.
2684 * This function also handles saving any files that may have been used in the editor
2686 * @static
2687 * @param stdClass $data
2688 * @return course_request The newly created course request
2690 public static function create($data) {
2691 global $USER, $DB, $CFG;
2692 $data->requester = $USER->id;
2694 // Setting the default category if none set.
2695 if (empty($data->category) || empty($CFG->requestcategoryselection)) {
2696 $data->category = $CFG->defaultrequestcategory;
2699 // Summary is a required field so copy the text over
2700 $data->summary = $data->summary_editor['text'];
2701 $data->summaryformat = $data->summary_editor['format'];
2703 $data->id = $DB->insert_record('course_request', $data);
2705 // Create a new course_request object and return it
2706 $request = new course_request($data);
2708 // Notify the admin if required.
2709 if ($users = get_users_from_config($CFG->courserequestnotify, 'moodle/site:approvecourse')) {
2711 $a = new stdClass;
2712 $a->link = "$CFG->wwwroot/course/pending.php";
2713 $a->user = fullname($USER);
2714 $subject = get_string('courserequest');
2715 $message = get_string('courserequestnotifyemail', 'admin', $a);
2716 foreach ($users as $user) {
2717 $request->notify($user, $USER, 'courserequested', $subject, $message);
2721 return $request;
2725 * Returns an array of options to use with a summary editor
2727 * @uses course_request::$summaryeditoroptions
2728 * @return array An array of options to use with the editor
2730 public static function summary_editor_options() {
2731 global $CFG;
2732 if (self::$summaryeditoroptions === null) {
2733 self::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
2735 return self::$summaryeditoroptions;
2739 * Loads the properties for this course request object. Id is required and if
2740 * only id is provided then we load the rest of the properties from the database
2742 * @param stdClass|int $properties Either an object containing properties
2743 * or the course_request id to load
2745 public function __construct($properties) {
2746 global $DB;
2747 if (empty($properties->id)) {
2748 if (empty($properties)) {
2749 throw new coding_exception('You must provide a course request id when creating a course_request object');
2751 $id = $properties;
2752 $properties = new stdClass;
2753 $properties->id = (int)$id;
2754 unset($id);
2756 if (empty($properties->requester)) {
2757 if (!($this->properties = $DB->get_record('course_request', array('id' => $properties->id)))) {
2758 print_error('unknowncourserequest');
2760 } else {
2761 $this->properties = $properties;
2763 $this->properties->collision = null;
2767 * Returns the requested property
2769 * @param string $key
2770 * @return mixed
2772 public function __get($key) {
2773 return $this->properties->$key;
2777 * Override this to ensure empty($request->blah) calls return a reliable answer...
2779 * This is required because we define the __get method
2781 * @param mixed $key
2782 * @return bool True is it not empty, false otherwise
2784 public function __isset($key) {
2785 return (!empty($this->properties->$key));
2789 * Returns the user who requested this course
2791 * Uses a static var to cache the results and cut down the number of db queries
2793 * @staticvar array $requesters An array of cached users
2794 * @return stdClass The user who requested the course
2796 public function get_requester() {
2797 global $DB;
2798 static $requesters= array();
2799 if (!array_key_exists($this->properties->requester, $requesters)) {
2800 $requesters[$this->properties->requester] = $DB->get_record('user', array('id'=>$this->properties->requester));
2802 return $requesters[$this->properties->requester];
2806 * Checks that the shortname used by the course does not conflict with any other
2807 * courses that exist
2809 * @param string|null $shortnamemark The string to append to the requests shortname
2810 * should a conflict be found
2811 * @return bool true is there is a conflict, false otherwise
2813 public function check_shortname_collision($shortnamemark = '[*]') {
2814 global $DB;
2816 if ($this->properties->collision !== null) {
2817 return $this->properties->collision;
2820 if (empty($this->properties->shortname)) {
2821 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER);
2822 $this->properties->collision = false;
2823 } else if ($DB->record_exists('course', array('shortname' => $this->properties->shortname))) {
2824 if (!empty($shortnamemark)) {
2825 $this->properties->shortname .= ' '.$shortnamemark;
2827 $this->properties->collision = true;
2828 } else {
2829 $this->properties->collision = false;
2831 return $this->properties->collision;
2835 * Returns the category where this course request should be created
2837 * Note that we don't check here that user has a capability to view
2838 * hidden categories if he has capabilities 'moodle/site:approvecourse' and
2839 * 'moodle/course:changecategory'
2841 * @return coursecat
2843 public function get_category() {
2844 global $CFG;
2845 require_once($CFG->libdir.'/coursecatlib.php');
2846 // If the category is not set, if the current user does not have the rights to change the category, or if the
2847 // category does not exist, we set the default category to the course to be approved.
2848 // The system level is used because the capability moodle/site:approvecourse is based on a system level.
2849 if (empty($this->properties->category) || !has_capability('moodle/course:changecategory', context_system::instance()) ||
2850 (!$category = coursecat::get($this->properties->category, IGNORE_MISSING, true))) {
2851 $category = coursecat::get($CFG->defaultrequestcategory, IGNORE_MISSING, true);
2853 if (!$category) {
2854 $category = coursecat::get_default();
2856 return $category;
2860 * This function approves the request turning it into a course
2862 * This function converts the course request into a course, at the same time
2863 * transferring any files used in the summary to the new course and then removing
2864 * the course request and the files associated with it.
2866 * @return int The id of the course that was created from this request
2868 public function approve() {
2869 global $CFG, $DB, $USER;
2871 $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted'=>0), '*', MUST_EXIST);
2873 $courseconfig = get_config('moodlecourse');
2875 // Transfer appropriate settings
2876 $data = clone($this->properties);
2877 unset($data->id);
2878 unset($data->reason);
2879 unset($data->requester);
2881 // Set category
2882 $category = $this->get_category();
2883 $data->category = $category->id;
2884 // Set misc settings
2885 $data->requested = 1;
2887 // Apply course default settings
2888 $data->format = $courseconfig->format;
2889 $data->newsitems = $courseconfig->newsitems;
2890 $data->showgrades = $courseconfig->showgrades;
2891 $data->showreports = $courseconfig->showreports;
2892 $data->maxbytes = $courseconfig->maxbytes;
2893 $data->groupmode = $courseconfig->groupmode;
2894 $data->groupmodeforce = $courseconfig->groupmodeforce;
2895 $data->visible = $courseconfig->visible;
2896 $data->visibleold = $data->visible;
2897 $data->lang = $courseconfig->lang;
2898 $data->enablecompletion = $courseconfig->enablecompletion;
2900 $course = create_course($data);
2901 $context = context_course::instance($course->id, MUST_EXIST);
2903 // add enrol instances
2904 if (!$DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
2905 if ($manual = enrol_get_plugin('manual')) {
2906 $manual->add_default_instance($course);
2910 // enrol the requester as teacher if necessary
2911 if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
2912 enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid);
2915 $this->delete();
2917 $a = new stdClass();
2918 $a->name = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
2919 $a->url = $CFG->wwwroot.'/course/view.php?id=' . $course->id;
2920 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a), $course->id);
2922 return $course->id;
2926 * Reject a course request
2928 * This function rejects a course request, emailing the requesting user the
2929 * provided notice and then removing the request from the database
2931 * @param string $notice The message to display to the user
2933 public function reject($notice) {
2934 global $USER, $DB;
2935 $user = $DB->get_record('user', array('id' => $this->properties->requester), '*', MUST_EXIST);
2936 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
2937 $this->delete();
2941 * Deletes the course request and any associated files
2943 public function delete() {
2944 global $DB;
2945 $DB->delete_records('course_request', array('id' => $this->properties->id));
2949 * Send a message from one user to another using events_trigger
2951 * @param object $touser
2952 * @param object $fromuser
2953 * @param string $name
2954 * @param string $subject
2955 * @param string $message
2956 * @param int|null $courseid
2958 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message, $courseid = null) {
2959 $eventdata = new \core\message\message();
2960 $eventdata->courseid = empty($courseid) ? SITEID : $courseid;
2961 $eventdata->component = 'moodle';
2962 $eventdata->name = $name;
2963 $eventdata->userfrom = $fromuser;
2964 $eventdata->userto = $touser;
2965 $eventdata->subject = $subject;
2966 $eventdata->fullmessage = $message;
2967 $eventdata->fullmessageformat = FORMAT_PLAIN;
2968 $eventdata->fullmessagehtml = '';
2969 $eventdata->smallmessage = '';
2970 $eventdata->notification = 1;
2971 message_send($eventdata);
2976 * Return a list of page types
2977 * @param string $pagetype current page type
2978 * @param context $parentcontext Block's parent context
2979 * @param context $currentcontext Current context of block
2980 * @return array array of page types
2982 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
2983 if ($pagetype === 'course-index' || $pagetype === 'course-index-category') {
2984 // For courses and categories browsing pages (/course/index.php) add option to show on ANY category page
2985 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
2986 'course-index-*' => get_string('page-course-index-x', 'pagetype'),
2988 } else if ($currentcontext && (!($coursecontext = $currentcontext->get_course_context(false)) || $coursecontext->instanceid == SITEID)) {
2989 // We know for sure that despite pagetype starts with 'course-' this is not a page in course context (i.e. /course/search.php, etc.)
2990 $pagetypes = array('*' => get_string('page-x', 'pagetype'));
2991 } else {
2992 // Otherwise consider it a page inside a course even if $currentcontext is null
2993 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
2994 'course-*' => get_string('page-course-x', 'pagetype'),
2995 'course-view-*' => get_string('page-course-view-x', 'pagetype')
2998 return $pagetypes;
3002 * Determine whether course ajax should be enabled for the specified course
3004 * @param stdClass $course The course to test against
3005 * @return boolean Whether course ajax is enabled or note
3007 function course_ajax_enabled($course) {
3008 global $CFG, $PAGE, $SITE;
3010 // The user must be editing for AJAX to be included
3011 if (!$PAGE->user_is_editing()) {
3012 return false;
3015 // Check that the theme suports
3016 if (!$PAGE->theme->enablecourseajax) {
3017 return false;
3020 // Check that the course format supports ajax functionality
3021 // The site 'format' doesn't have information on course format support
3022 if ($SITE->id !== $course->id) {
3023 $courseformatajaxsupport = course_format_ajax_support($course->format);
3024 if (!$courseformatajaxsupport->capable) {
3025 return false;
3029 // All conditions have been met so course ajax should be enabled
3030 return true;
3034 * Include the relevant javascript and language strings for the resource
3035 * toolbox YUI module
3037 * @param integer $id The ID of the course being applied to
3038 * @param array $usedmodules An array containing the names of the modules in use on the page
3039 * @param array $enabledmodules An array containing the names of the enabled (visible) modules on this site
3040 * @param stdClass $config An object containing configuration parameters for ajax modules including:
3041 * * resourceurl The URL to post changes to for resource changes
3042 * * sectionurl The URL to post changes to for section changes
3043 * * pageparams Additional parameters to pass through in the post
3044 * @return bool
3046 function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) {
3047 global $CFG, $PAGE, $SITE;
3049 // Ensure that ajax should be included
3050 if (!course_ajax_enabled($course)) {
3051 return false;
3054 if (!$config) {
3055 $config = new stdClass();
3058 // The URL to use for resource changes
3059 if (!isset($config->resourceurl)) {
3060 $config->resourceurl = '/course/rest.php';
3063 // The URL to use for section changes
3064 if (!isset($config->sectionurl)) {
3065 $config->sectionurl = '/course/rest.php';
3068 // Any additional parameters which need to be included on page submission
3069 if (!isset($config->pageparams)) {
3070 $config->pageparams = array();
3073 // Include course dragdrop
3074 if (course_format_uses_sections($course->format)) {
3075 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_section_dragdrop',
3076 array(array(
3077 'courseid' => $course->id,
3078 'ajaxurl' => $config->sectionurl,
3079 'config' => $config,
3080 )), null, true);
3082 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_resource_dragdrop',
3083 array(array(
3084 'courseid' => $course->id,
3085 'ajaxurl' => $config->resourceurl,
3086 'config' => $config,
3087 )), null, true);
3090 // Require various strings for the command toolbox
3091 $PAGE->requires->strings_for_js(array(
3092 'moveleft',
3093 'deletechecktype',
3094 'deletechecktypename',
3095 'edittitle',
3096 'edittitleinstructions',
3097 'show',
3098 'hide',
3099 'highlight',
3100 'highlightoff',
3101 'groupsnone',
3102 'groupsvisible',
3103 'groupsseparate',
3104 'clicktochangeinbrackets',
3105 'markthistopic',
3106 'markedthistopic',
3107 'movesection',
3108 'movecoursemodule',
3109 'movecoursesection',
3110 'movecontent',
3111 'tocontent',
3112 'emptydragdropregion',
3113 'afterresource',
3114 'aftersection',
3115 'totopofsection',
3116 ), 'moodle');
3118 // Include section-specific strings for formats which support sections.
3119 if (course_format_uses_sections($course->format)) {
3120 $PAGE->requires->strings_for_js(array(
3121 'showfromothers',
3122 'hidefromothers',
3123 ), 'format_' . $course->format);
3126 // For confirming resource deletion we need the name of the module in question
3127 foreach ($usedmodules as $module => $modname) {
3128 $PAGE->requires->string_for_js('pluginname', $module);
3131 // Load drag and drop upload AJAX.
3132 require_once($CFG->dirroot.'/course/dnduploadlib.php');
3133 dndupload_add_to_course($course, $enabledmodules);
3135 $PAGE->requires->js_call_amd('core_course/actions', 'initCoursePage', array($course->format));
3137 return true;
3141 * Returns the sorted list of available course formats, filtered by enabled if necessary
3143 * @param bool $enabledonly return only formats that are enabled
3144 * @return array array of sorted format names
3146 function get_sorted_course_formats($enabledonly = false) {
3147 global $CFG;
3148 $formats = core_component::get_plugin_list('format');
3150 if (!empty($CFG->format_plugins_sortorder)) {
3151 $order = explode(',', $CFG->format_plugins_sortorder);
3152 $order = array_merge(array_intersect($order, array_keys($formats)),
3153 array_diff(array_keys($formats), $order));
3154 } else {
3155 $order = array_keys($formats);
3157 if (!$enabledonly) {
3158 return $order;
3160 $sortedformats = array();
3161 foreach ($order as $formatname) {
3162 if (!get_config('format_'.$formatname, 'disabled')) {
3163 $sortedformats[] = $formatname;
3166 return $sortedformats;
3170 * The URL to use for the specified course (with section)
3172 * @param int|stdClass $courseorid The course to get the section name for (either object or just course id)
3173 * @param int|stdClass $section Section object from database or just field course_sections.section
3174 * if omitted the course view page is returned
3175 * @param array $options options for view URL. At the moment core uses:
3176 * 'navigation' (bool) if true and section has no separate page, the function returns null
3177 * 'sr' (int) used by multipage formats to specify to which section to return
3178 * @return moodle_url The url of course
3180 function course_get_url($courseorid, $section = null, $options = array()) {
3181 return course_get_format($courseorid)->get_view_url($section, $options);
3185 * Create a module.
3187 * It includes:
3188 * - capability checks and other checks
3189 * - create the module from the module info
3191 * @param object $module
3192 * @return object the created module info
3193 * @throws moodle_exception if user is not allowed to perform the action or module is not allowed in this course
3195 function create_module($moduleinfo) {
3196 global $DB, $CFG;
3198 require_once($CFG->dirroot . '/course/modlib.php');
3200 // Check manadatory attributs.
3201 $mandatoryfields = array('modulename', 'course', 'section', 'visible');
3202 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
3203 $mandatoryfields[] = 'introeditor';
3205 foreach($mandatoryfields as $mandatoryfield) {
3206 if (!isset($moduleinfo->{$mandatoryfield})) {
3207 throw new moodle_exception('createmodulemissingattribut', '', '', $mandatoryfield);
3211 // Some additional checks (capability / existing instances).
3212 $course = $DB->get_record('course', array('id'=>$moduleinfo->course), '*', MUST_EXIST);
3213 list($module, $context, $cw) = can_add_moduleinfo($course, $moduleinfo->modulename, $moduleinfo->section);
3215 // Add the module.
3216 $moduleinfo->module = $module->id;
3217 $moduleinfo = add_moduleinfo($moduleinfo, $course, null);
3219 return $moduleinfo;
3223 * Update a module.
3225 * It includes:
3226 * - capability and other checks
3227 * - update the module
3229 * @param object $module
3230 * @return object the updated module info
3231 * @throws moodle_exception if current user is not allowed to update the module
3233 function update_module($moduleinfo) {
3234 global $DB, $CFG;
3236 require_once($CFG->dirroot . '/course/modlib.php');
3238 // Check the course module exists.
3239 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule, 0, false, MUST_EXIST);
3241 // Check the course exists.
3242 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
3244 // Some checks (capaibility / existing instances).
3245 list($cm, $context, $module, $data, $cw) = can_update_moduleinfo($cm);
3247 // Retrieve few information needed by update_moduleinfo.
3248 $moduleinfo->modulename = $cm->modname;
3249 if (!isset($moduleinfo->scale)) {
3250 $moduleinfo->scale = 0;
3252 $moduleinfo->type = 'mod';
3254 // Update the module.
3255 list($cm, $moduleinfo) = update_moduleinfo($cm, $moduleinfo, $course, null);
3257 return $moduleinfo;
3261 * Duplicate a module on the course for ajax.
3263 * @see mod_duplicate_module()
3264 * @param object $course The course
3265 * @param object $cm The course module to duplicate
3266 * @param int $sr The section to link back to (used for creating the links)
3267 * @throws moodle_exception if the plugin doesn't support duplication
3268 * @return Object containing:
3269 * - fullcontent: The HTML markup for the created CM
3270 * - cmid: The CMID of the newly created CM
3271 * - redirect: Whether to trigger a redirect following this change
3273 function mod_duplicate_activity($course, $cm, $sr = null) {
3274 global $PAGE;
3276 $newcm = duplicate_module($course, $cm);
3278 $resp = new stdClass();
3279 if ($newcm) {
3280 $courserenderer = $PAGE->get_renderer('core', 'course');
3281 $completioninfo = new completion_info($course);
3282 $modulehtml = $courserenderer->course_section_cm($course, $completioninfo,
3283 $newcm, null, array());
3285 $resp->fullcontent = $courserenderer->course_section_cm_list_item($course, $completioninfo, $newcm, $sr);
3286 $resp->cmid = $newcm->id;
3287 } else {
3288 // Trigger a redirect.
3289 $resp->redirect = true;
3291 return $resp;
3295 * Api to duplicate a module.
3297 * @param object $course course object.
3298 * @param object $cm course module object to be duplicated.
3299 * @since Moodle 2.8
3301 * @throws Exception
3302 * @throws coding_exception
3303 * @throws moodle_exception
3304 * @throws restore_controller_exception
3306 * @return cm_info|null cminfo object if we sucessfully duplicated the mod and found the new cm.
3308 function duplicate_module($course, $cm) {
3309 global $CFG, $DB, $USER;
3310 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
3311 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
3312 require_once($CFG->libdir . '/filelib.php');
3314 $a = new stdClass();
3315 $a->modtype = get_string('modulename', $cm->modname);
3316 $a->modname = format_string($cm->name);
3318 if (!plugin_supports('mod', $cm->modname, FEATURE_BACKUP_MOODLE2)) {
3319 throw new moodle_exception('duplicatenosupport', 'error', '', $a);
3322 // Backup the activity.
3324 $bc = new backup_controller(backup::TYPE_1ACTIVITY, $cm->id, backup::FORMAT_MOODLE,
3325 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
3327 $backupid = $bc->get_backupid();
3328 $backupbasepath = $bc->get_plan()->get_basepath();
3330 $bc->execute_plan();
3332 $bc->destroy();
3334 // Restore the backup immediately.
3336 $rc = new restore_controller($backupid, $course->id,
3337 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, backup::TARGET_CURRENT_ADDING);
3339 $cmcontext = context_module::instance($cm->id);
3340 if (!$rc->execute_precheck()) {
3341 $precheckresults = $rc->get_precheck_results();
3342 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
3343 if (empty($CFG->keeptempdirectoriesonbackup)) {
3344 fulldelete($backupbasepath);
3349 $rc->execute_plan();
3351 // Now a bit hacky part follows - we try to get the cmid of the newly
3352 // restored copy of the module.
3353 $newcmid = null;
3354 $tasks = $rc->get_plan()->get_tasks();
3355 foreach ($tasks as $task) {
3356 if (is_subclass_of($task, 'restore_activity_task')) {
3357 if ($task->get_old_contextid() == $cmcontext->id) {
3358 $newcmid = $task->get_moduleid();
3359 break;
3364 // If we know the cmid of the new course module, let us move it
3365 // right below the original one. otherwise it will stay at the
3366 // end of the section.
3367 if ($newcmid) {
3368 $info = get_fast_modinfo($course);
3369 $newcm = $info->get_cm($newcmid);
3370 $section = $DB->get_record('course_sections', array('id' => $cm->section, 'course' => $cm->course));
3371 moveto_module($newcm, $section, $cm);
3372 moveto_module($cm, $section, $newcm);
3374 // Update calendar events with the duplicated module.
3375 $refresheventsfunction = $newcm->modname . '_refresh_events';
3376 if (function_exists($refresheventsfunction)) {
3377 call_user_func($refresheventsfunction, $newcm->course);
3380 // Trigger course module created event. We can trigger the event only if we know the newcmid.
3381 $event = \core\event\course_module_created::create_from_cm($newcm);
3382 $event->trigger();
3384 rebuild_course_cache($cm->course);
3386 $rc->destroy();
3388 if (empty($CFG->keeptempdirectoriesonbackup)) {
3389 fulldelete($backupbasepath);
3392 return isset($newcm) ? $newcm : null;
3396 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3397 * Sorts by descending order of time.
3399 * @param stdClass $a First object
3400 * @param stdClass $b Second object
3401 * @return int 0,1,-1 representing the order
3403 function compare_activities_by_time_desc($a, $b) {
3404 // Make sure the activities actually have a timestamp property.
3405 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3406 return 0;
3408 // We treat instances without timestamp as if they have a timestamp of 0.
3409 if ((!property_exists($a, 'timestamp')) && (property_exists($b,'timestamp'))) {
3410 return 1;
3412 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3413 return -1;
3415 if ($a->timestamp == $b->timestamp) {
3416 return 0;
3418 return ($a->timestamp > $b->timestamp) ? -1 : 1;
3422 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3423 * Sorts by ascending order of time.
3425 * @param stdClass $a First object
3426 * @param stdClass $b Second object
3427 * @return int 0,1,-1 representing the order
3429 function compare_activities_by_time_asc($a, $b) {
3430 // Make sure the activities actually have a timestamp property.
3431 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3432 return 0;
3434 // We treat instances without timestamp as if they have a timestamp of 0.
3435 if ((!property_exists($a, 'timestamp')) && (property_exists($b, 'timestamp'))) {
3436 return -1;
3438 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3439 return 1;
3441 if ($a->timestamp == $b->timestamp) {
3442 return 0;
3444 return ($a->timestamp < $b->timestamp) ? -1 : 1;
3448 * Changes the visibility of a course.
3450 * @param int $courseid The course to change.
3451 * @param bool $show True to make it visible, false otherwise.
3452 * @return bool
3454 function course_change_visibility($courseid, $show = true) {
3455 $course = new stdClass;
3456 $course->id = $courseid;
3457 $course->visible = ($show) ? '1' : '0';
3458 $course->visibleold = $course->visible;
3459 update_course($course);
3460 return true;
3464 * Changes the course sortorder by one, moving it up or down one in respect to sort order.
3466 * @param stdClass|course_in_list $course
3467 * @param bool $up If set to true the course will be moved up one. Otherwise down one.
3468 * @return bool
3470 function course_change_sortorder_by_one($course, $up) {
3471 global $DB;
3472 $params = array($course->sortorder, $course->category);
3473 if ($up) {
3474 $select = 'sortorder < ? AND category = ?';
3475 $sort = 'sortorder DESC';
3476 } else {
3477 $select = 'sortorder > ? AND category = ?';
3478 $sort = 'sortorder ASC';
3480 fix_course_sortorder();
3481 $swapcourse = $DB->get_records_select('course', $select, $params, $sort, '*', 0, 1);
3482 if ($swapcourse) {
3483 $swapcourse = reset($swapcourse);
3484 $DB->set_field('course', 'sortorder', $swapcourse->sortorder, array('id' => $course->id));
3485 $DB->set_field('course', 'sortorder', $course->sortorder, array('id' => $swapcourse->id));
3486 // Finally reorder courses.
3487 fix_course_sortorder();
3488 cache_helper::purge_by_event('changesincourse');
3489 return true;
3491 return false;
3495 * Changes the sort order of courses in a category so that the first course appears after the second.
3497 * @param int|stdClass $courseorid The course to focus on.
3498 * @param int $moveaftercourseid The course to shifter after or 0 if you want it to be the first course in the category.
3499 * @return bool
3501 function course_change_sortorder_after_course($courseorid, $moveaftercourseid) {
3502 global $DB;
3504 if (!is_object($courseorid)) {
3505 $course = get_course($courseorid);
3506 } else {
3507 $course = $courseorid;
3510 if ((int)$moveaftercourseid === 0) {
3511 // We've moving the course to the start of the queue.
3512 $sql = 'SELECT sortorder
3513 FROM {course}
3514 WHERE category = :categoryid
3515 ORDER BY sortorder';
3516 $params = array(
3517 'categoryid' => $course->category
3519 $sortorder = $DB->get_field_sql($sql, $params, IGNORE_MULTIPLE);
3521 $sql = 'UPDATE {course}
3522 SET sortorder = sortorder + 1
3523 WHERE category = :categoryid
3524 AND id <> :id';
3525 $params = array(
3526 'categoryid' => $course->category,
3527 'id' => $course->id,
3529 $DB->execute($sql, $params);
3530 $DB->set_field('course', 'sortorder', $sortorder, array('id' => $course->id));
3531 } else if ($course->id === $moveaftercourseid) {
3532 // They're the same - moronic.
3533 debugging("Invalid move after course given.", DEBUG_DEVELOPER);
3534 return false;
3535 } else {
3536 // Moving this course after the given course. It could be before it could be after.
3537 $moveaftercourse = get_course($moveaftercourseid);
3538 if ($course->category !== $moveaftercourse->category) {
3539 debugging("Cannot re-order courses. The given courses do not belong to the same category.", DEBUG_DEVELOPER);
3540 return false;
3542 // Increment all courses in the same category that are ordered after the moveafter course.
3543 // This makes a space for the course we're moving.
3544 $sql = 'UPDATE {course}
3545 SET sortorder = sortorder + 1
3546 WHERE category = :categoryid
3547 AND sortorder > :sortorder';
3548 $params = array(
3549 'categoryid' => $moveaftercourse->category,
3550 'sortorder' => $moveaftercourse->sortorder
3552 $DB->execute($sql, $params);
3553 $DB->set_field('course', 'sortorder', $moveaftercourse->sortorder + 1, array('id' => $course->id));
3555 fix_course_sortorder();
3556 cache_helper::purge_by_event('changesincourse');
3557 return true;
3561 * Trigger course viewed event. This API function is used when course view actions happens,
3562 * usually in course/view.php but also in external functions.
3564 * @param stdClass $context course context object
3565 * @param int $sectionnumber section number
3566 * @since Moodle 2.9
3568 function course_view($context, $sectionnumber = 0) {
3570 $eventdata = array('context' => $context);
3572 if (!empty($sectionnumber)) {
3573 $eventdata['other']['coursesectionnumber'] = $sectionnumber;
3576 $event = \core\event\course_viewed::create($eventdata);
3577 $event->trigger();
3581 * Returns courses tagged with a specified tag.
3583 * @param core_tag_tag $tag
3584 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
3585 * are displayed on the page and the per-page limit may be bigger
3586 * @param int $fromctx context id where the link was displayed, may be used by callbacks
3587 * to display items in the same context first
3588 * @param int $ctx context id where to search for records
3589 * @param bool $rec search in subcontexts as well
3590 * @param int $page 0-based number of page being displayed
3591 * @return \core_tag\output\tagindex
3593 function course_get_tagged_courses($tag, $exclusivemode = false, $fromctx = 0, $ctx = 0, $rec = 1, $page = 0) {
3594 global $CFG, $PAGE;
3595 require_once($CFG->libdir . '/coursecatlib.php');
3597 $perpage = $exclusivemode ? $CFG->coursesperpage : 5;
3598 $displayoptions = array(
3599 'limit' => $perpage,
3600 'offset' => $page * $perpage,
3601 'viewmoreurl' => null,
3604 $courserenderer = $PAGE->get_renderer('core', 'course');
3605 $totalcount = coursecat::search_courses_count(array('tagid' => $tag->id, 'ctx' => $ctx, 'rec' => $rec));
3606 $content = $courserenderer->tagged_courses($tag->id, $exclusivemode, $ctx, $rec, $displayoptions);
3607 $totalpages = ceil($totalcount / $perpage);
3609 return new core_tag\output\tagindex($tag, 'core', 'course', $content,
3610 $exclusivemode, $fromctx, $ctx, $rec, $page, $totalpages);
3614 * Implements callback inplace_editable() allowing to edit values in-place
3616 * @param string $itemtype
3617 * @param int $itemid
3618 * @param mixed $newvalue
3619 * @return \core\output\inplace_editable
3621 function core_course_inplace_editable($itemtype, $itemid, $newvalue) {
3622 if ($itemtype === 'activityname') {
3623 return \core_course\output\course_module_name::update($itemid, $newvalue);
3628 * Returns course modules tagged with a specified tag ready for output on tag/index.php page
3630 * This is a callback used by the tag area core/course_modules to search for course modules
3631 * tagged with a specific tag.
3633 * @param core_tag_tag $tag
3634 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
3635 * are displayed on the page and the per-page limit may be bigger
3636 * @param int $fromcontextid context id where the link was displayed, may be used by callbacks
3637 * to display items in the same context first
3638 * @param int $contextid context id where to search for records
3639 * @param bool $recursivecontext search in subcontexts as well
3640 * @param int $page 0-based number of page being displayed
3641 * @return \core_tag\output\tagindex
3643 function course_get_tagged_course_modules($tag, $exclusivemode = false, $fromcontextid = 0, $contextid = 0,
3644 $recursivecontext = 1, $page = 0) {
3645 global $OUTPUT;
3646 $perpage = $exclusivemode ? 20 : 5;
3648 // Build select query.
3649 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
3650 $query = "SELECT cm.id AS cmid, c.id AS courseid, $ctxselect
3651 FROM {course_modules} cm
3652 JOIN {tag_instance} tt ON cm.id = tt.itemid
3653 JOIN {course} c ON cm.course = c.id
3654 JOIN {context} ctx ON ctx.instanceid = cm.id AND ctx.contextlevel = :coursemodulecontextlevel
3655 WHERE tt.itemtype = :itemtype AND tt.tagid = :tagid AND tt.component = :component
3656 AND cm.deletioninprogress = 0
3657 AND c.id %COURSEFILTER% AND cm.id %ITEMFILTER%";
3659 $params = array('itemtype' => 'course_modules', 'tagid' => $tag->id, 'component' => 'core',
3660 'coursemodulecontextlevel' => CONTEXT_MODULE);
3661 if ($contextid) {
3662 $context = context::instance_by_id($contextid);
3663 $query .= $recursivecontext ? ' AND (ctx.id = :contextid OR ctx.path LIKE :path)' : ' AND ctx.id = :contextid';
3664 $params['contextid'] = $context->id;
3665 $params['path'] = $context->path.'/%';
3668 $query .= ' ORDER BY';
3669 if ($fromcontextid) {
3670 // In order-clause specify that modules from inside "fromctx" context should be returned first.
3671 $fromcontext = context::instance_by_id($fromcontextid);
3672 $query .= ' (CASE WHEN ctx.id = :fromcontextid OR ctx.path LIKE :frompath THEN 0 ELSE 1 END),';
3673 $params['fromcontextid'] = $fromcontext->id;
3674 $params['frompath'] = $fromcontext->path.'/%';
3676 $query .= ' c.sortorder, cm.id';
3677 $totalpages = $page + 1;
3679 // Use core_tag_index_builder to build and filter the list of items.
3680 // Request one item more than we need so we know if next page exists.
3681 $builder = new core_tag_index_builder('core', 'course_modules', $query, $params, $page * $perpage, $perpage + 1);
3682 while ($item = $builder->has_item_that_needs_access_check()) {
3683 context_helper::preload_from_record($item);
3684 $courseid = $item->courseid;
3685 if (!$builder->can_access_course($courseid)) {
3686 $builder->set_accessible($item, false);
3687 continue;
3689 $modinfo = get_fast_modinfo($builder->get_course($courseid));
3690 // Set accessibility of this item and all other items in the same course.
3691 $builder->walk(function ($taggeditem) use ($courseid, $modinfo, $builder) {
3692 if ($taggeditem->courseid == $courseid) {
3693 $cm = $modinfo->get_cm($taggeditem->cmid);
3694 $builder->set_accessible($taggeditem, $cm->uservisible);
3699 $items = $builder->get_items();
3700 if (count($items) > $perpage) {
3701 $totalpages = $page + 2; // We don't need exact page count, just indicate that the next page exists.
3702 array_pop($items);
3705 // Build the display contents.
3706 if ($items) {
3707 $tagfeed = new core_tag\output\tagfeed();
3708 foreach ($items as $item) {
3709 context_helper::preload_from_record($item);
3710 $course = $builder->get_course($item->courseid);
3711 $modinfo = get_fast_modinfo($course);
3712 $cm = $modinfo->get_cm($item->cmid);
3713 $courseurl = course_get_url($item->courseid, $cm->sectionnum);
3714 $cmname = $cm->get_formatted_name();
3715 if (!$exclusivemode) {
3716 $cmname = shorten_text($cmname, 100);
3718 $cmname = html_writer::link($cm->url?:$courseurl, $cmname);
3719 $coursename = format_string($course->fullname, true,
3720 array('context' => context_course::instance($item->courseid)));
3721 $coursename = html_writer::link($courseurl, $coursename);
3722 $icon = html_writer::empty_tag('img', array('src' => $cm->get_icon_url()));
3723 $tagfeed->add($icon, $cmname, $coursename);
3726 $content = $OUTPUT->render_from_template('core_tag/tagfeed',
3727 $tagfeed->export_for_template($OUTPUT));
3729 return new core_tag\output\tagindex($tag, 'core', 'course_modules', $content,
3730 $exclusivemode, $fromcontextid, $contextid, $recursivecontext, $page, $totalpages);
3735 * Return an object with the list of navigation options in a course that are avaialable or not for the current user.
3736 * This function also handles the frontpage course.
3738 * @param stdClass $context context object (it can be a course context or the system context for frontpage settings)
3739 * @param stdClass $course the course where the settings are being rendered
3740 * @return stdClass the navigation options in a course and their availability status
3741 * @since Moodle 3.2
3743 function course_get_user_navigation_options($context, $course = null) {
3744 global $CFG;
3746 $isloggedin = isloggedin();
3747 $isguestuser = isguestuser();
3748 $isfrontpage = $context->contextlevel == CONTEXT_SYSTEM;
3750 if ($isfrontpage) {
3751 $sitecontext = $context;
3752 } else {
3753 $sitecontext = context_system::instance();
3756 // Sets defaults for all options.
3757 $options = (object) [
3758 'badges' => false,
3759 'blogs' => false,
3760 'calendar' => false,
3761 'competencies' => false,
3762 'grades' => false,
3763 'notes' => false,
3764 'participants' => false,
3765 'search' => false,
3766 'tags' => false,
3769 $options->blogs = !empty($CFG->enableblogs) &&
3770 ($CFG->bloglevel == BLOG_GLOBAL_LEVEL ||
3771 ($CFG->bloglevel == BLOG_SITE_LEVEL and ($isloggedin and !$isguestuser)))
3772 && has_capability('moodle/blog:view', $sitecontext);
3774 $options->notes = !empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $context);
3776 // Frontpage settings?
3777 if ($isfrontpage) {
3778 if ($course->id == SITEID) {
3779 $options->participants = has_capability('moodle/site:viewparticipants', $sitecontext);
3780 } else {
3781 $options->participants = has_capability('moodle/course:viewparticipants', context_course::instance($course->id));
3784 $options->badges = !empty($CFG->enablebadges) && has_capability('moodle/badges:viewbadges', $sitecontext);
3785 $options->tags = !empty($CFG->usetags) && $isloggedin;
3786 $options->search = !empty($CFG->enableglobalsearch) && has_capability('moodle/search:query', $sitecontext);
3787 $options->calendar = $isloggedin;
3788 } else {
3789 $options->participants = has_capability('moodle/course:viewparticipants', $context);
3790 $options->badges = !empty($CFG->enablebadges) && !empty($CFG->badges_allowcoursebadges) &&
3791 has_capability('moodle/badges:viewbadges', $context);
3792 // Add view grade report is permitted.
3793 $grades = false;
3795 if (has_capability('moodle/grade:viewall', $context)) {
3796 $grades = true;
3797 } else if (!empty($course->showgrades)) {
3798 $reports = core_component::get_plugin_list('gradereport');
3799 if (is_array($reports) && count($reports) > 0) { // Get all installed reports.
3800 arsort($reports); // User is last, we want to test it first.
3801 foreach ($reports as $plugin => $plugindir) {
3802 if (has_capability('gradereport/'.$plugin.':view', $context)) {
3803 // Stop when the first visible plugin is found.
3804 $grades = true;
3805 break;
3810 $options->grades = $grades;
3813 if (\core_competency\api::is_enabled()) {
3814 $capabilities = array('moodle/competency:coursecompetencyview', 'moodle/competency:coursecompetencymanage');
3815 $options->competencies = has_any_capability($capabilities, $context);
3817 return $options;
3821 * Return an object with the list of administration options in a course that are available or not for the current user.
3822 * This function also handles the frontpage settings.
3824 * @param stdClass $course course object (for frontpage it should be a clone of $SITE)
3825 * @param stdClass $context context object (course context)
3826 * @return stdClass the administration options in a course and their availability status
3827 * @since Moodle 3.2
3829 function course_get_user_administration_options($course, $context) {
3830 global $CFG;
3831 $isfrontpage = $course->id == SITEID;
3833 $options = new stdClass;
3834 $options->update = has_capability('moodle/course:update', $context);
3835 $options->filters = has_capability('moodle/filter:manage', $context) &&
3836 count(filter_get_available_in_context($context)) > 0;
3837 $options->reports = has_capability('moodle/site:viewreports', $context);
3838 $options->backup = has_capability('moodle/backup:backupcourse', $context);
3839 $options->restore = has_capability('moodle/restore:restorecourse', $context);
3840 $options->files = ($course->legacyfiles == 2 && has_capability('moodle/course:managefiles', $context));
3842 if (!$isfrontpage) {
3843 $options->tags = has_capability('moodle/course:tag', $context);
3844 $options->gradebook = has_capability('moodle/grade:manage', $context);
3845 $options->outcomes = !empty($CFG->enableoutcomes) && has_capability('moodle/course:update', $context);
3846 $options->badges = !empty($CFG->enablebadges);
3847 $options->import = has_capability('moodle/restore:restoretargetimport', $context);
3848 $options->publish = has_capability('moodle/course:publish', $context);
3849 $options->reset = has_capability('moodle/course:reset', $context);
3850 $options->roles = has_capability('moodle/role:switchroles', $context);
3851 } else {
3852 // Set default options to false.
3853 $listofoptions = array('tags', 'gradebook', 'outcomes', 'badges', 'import', 'publish', 'reset', 'roles', 'grades');
3855 foreach ($listofoptions as $option) {
3856 $options->$option = false;
3860 return $options;
3864 * Validates course start and end dates.
3866 * Checks that the end course date is not greater than the start course date.
3868 * $coursedata['startdate'] or $coursedata['enddate'] may not be set, it depends on the form and user input.
3870 * @param array $coursedata May contain startdate and enddate timestamps, depends on the user input.
3871 * @return mixed False if everything alright, error codes otherwise.
3873 function course_validate_dates($coursedata) {
3875 // If both start and end dates are set end date should be later than the start date.
3876 if (!empty($coursedata['startdate']) && !empty($coursedata['enddate']) &&
3877 ($coursedata['enddate'] < $coursedata['startdate'])) {
3878 return 'enddatebeforestartdate';
3881 // If start date is not set end date can not be set.
3882 if (empty($coursedata['startdate']) && !empty($coursedata['enddate'])) {
3883 return 'nostartdatenoenddate';
3886 return false;
3890 * Check for course updates in the given context level instances (only modules supported right Now)
3892 * @param stdClass $course course object
3893 * @param array $tocheck instances to check for updates
3894 * @param array $filter check only for updates in these areas
3895 * @return array list of warnings and instances with updates information
3896 * @since Moodle 3.2
3898 function course_check_updates($course, $tocheck, $filter = array()) {
3899 global $CFG, $DB;
3901 $instances = array();
3902 $warnings = array();
3903 $modulescallbacksupport = array();
3904 $modinfo = get_fast_modinfo($course);
3906 $supportedplugins = get_plugin_list_with_function('mod', 'check_updates_since');
3908 // Check instances.
3909 foreach ($tocheck as $instance) {
3910 if ($instance['contextlevel'] == 'module') {
3911 // Check module visibility.
3912 try {
3913 $cm = $modinfo->get_cm($instance['id']);
3914 } catch (Exception $e) {
3915 $warnings[] = array(
3916 'item' => 'module',
3917 'itemid' => $instance['id'],
3918 'warningcode' => 'cmidnotincourse',
3919 'message' => 'This module id does not belong to this course.'
3921 continue;
3924 if (!$cm->uservisible) {
3925 $warnings[] = array(
3926 'item' => 'module',
3927 'itemid' => $instance['id'],
3928 'warningcode' => 'nonuservisible',
3929 'message' => 'You don\'t have access to this module.'
3931 continue;
3933 if (empty($supportedplugins['mod_' . $cm->modname])) {
3934 $warnings[] = array(
3935 'item' => 'module',
3936 'itemid' => $instance['id'],
3937 'warningcode' => 'missingcallback',
3938 'message' => 'This module does not implement the check_updates_since callback: ' . $instance['contextlevel'],
3940 continue;
3942 // Retrieve the module instance.
3943 $instances[] = array(
3944 'contextlevel' => $instance['contextlevel'],
3945 'id' => $instance['id'],
3946 'updates' => call_user_func($cm->modname . '_check_updates_since', $cm, $instance['since'], $filter)
3949 } else {
3950 $warnings[] = array(
3951 'item' => 'contextlevel',
3952 'itemid' => $instance['id'],
3953 'warningcode' => 'contextlevelnotsupported',
3954 'message' => 'Context level not yet supported ' . $instance['contextlevel'],
3958 return array($instances, $warnings);
3962 * Check module updates since a given time.
3963 * This function checks for updates in the module config, file areas, completion, grades, comments and ratings.
3965 * @param cm_info $cm course module data
3966 * @param int $from the time to check
3967 * @param array $fileareas additional file ares to check
3968 * @param array $filter if we need to filter and return only selected updates
3969 * @return stdClass object with the different updates
3970 * @since Moodle 3.2
3972 function course_check_module_updates_since($cm, $from, $fileareas = array(), $filter = array()) {
3973 global $DB, $CFG, $USER;
3975 $context = $cm->context;
3976 $mod = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
3978 $updates = new stdClass();
3979 $course = get_course($cm->course);
3980 $component = 'mod_' . $cm->modname;
3982 // Check changes in the module configuration.
3983 if (isset($mod->timemodified) and (empty($filter) or in_array('configuration', $filter))) {
3984 $updates->configuration = (object) array('updated' => false);
3985 if ($updates->configuration->updated = $mod->timemodified > $from) {
3986 $updates->configuration->timeupdated = $mod->timemodified;
3990 // Check for updates in files.
3991 if (plugin_supports('mod', $cm->modname, FEATURE_MOD_INTRO)) {
3992 $fileareas[] = 'intro';
3994 if (!empty($fileareas) and (empty($filter) or in_array('fileareas', $filter))) {
3995 $fs = get_file_storage();
3996 $files = $fs->get_area_files($context->id, $component, $fileareas, false, "filearea, timemodified DESC", false, $from);
3997 foreach ($fileareas as $filearea) {
3998 $updates->{$filearea . 'files'} = (object) array('updated' => false);
4000 foreach ($files as $file) {
4001 $updates->{$file->get_filearea() . 'files'}->updated = true;
4002 $updates->{$file->get_filearea() . 'files'}->itemids[] = $file->get_id();
4006 // Check completion.
4007 $supportcompletion = plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_HAS_RULES);
4008 $supportcompletion = $supportcompletion or plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_TRACKS_VIEWS);
4009 if ($supportcompletion and (empty($filter) or in_array('completion', $filter))) {
4010 $updates->completion = (object) array('updated' => false);
4011 $completion = new completion_info($course);
4012 // Use wholecourse to cache all the modules the first time.
4013 $completiondata = $completion->get_data($cm, true);
4014 if ($updates->completion->updated = !empty($completiondata->timemodified) && $completiondata->timemodified > $from) {
4015 $updates->completion->timemodified = $completiondata->timemodified;
4019 // Check grades.
4020 $supportgrades = plugin_supports('mod', $cm->modname, FEATURE_GRADE_HAS_GRADE);
4021 $supportgrades = $supportgrades or plugin_supports('mod', $cm->modname, FEATURE_GRADE_OUTCOMES);
4022 if ($supportgrades and (empty($filter) or (in_array('gradeitems', $filter) or in_array('outcomes', $filter)))) {
4023 require_once($CFG->libdir . '/gradelib.php');
4024 $grades = grade_get_grades($course->id, 'mod', $cm->modname, $mod->id, $USER->id);
4026 if (empty($filter) or in_array('gradeitems', $filter)) {
4027 $updates->gradeitems = (object) array('updated' => false);
4028 foreach ($grades->items as $gradeitem) {
4029 foreach ($gradeitem->grades as $grade) {
4030 if ($grade->datesubmitted > $from or $grade->dategraded > $from) {
4031 $updates->gradeitems->updated = true;
4032 $updates->gradeitems->itemids[] = $gradeitem->id;
4038 if (empty($filter) or in_array('outcomes', $filter)) {
4039 $updates->outcomes = (object) array('updated' => false);
4040 foreach ($grades->outcomes as $outcome) {
4041 foreach ($outcome->grades as $grade) {
4042 if ($grade->datesubmitted > $from or $grade->dategraded > $from) {
4043 $updates->outcomes->updated = true;
4044 $updates->outcomes->itemids[] = $outcome->id;
4051 // Check comments.
4052 if (plugin_supports('mod', $cm->modname, FEATURE_COMMENT) and (empty($filter) or in_array('comments', $filter))) {
4053 $updates->comments = (object) array('updated' => false);
4054 require_once($CFG->dirroot . '/comment/lib.php');
4055 require_once($CFG->dirroot . '/comment/locallib.php');
4056 $manager = new comment_manager();
4057 $comments = $manager->get_component_comments_since($course, $context, $component, $from, $cm);
4058 if (!empty($comments)) {
4059 $updates->comments->updated = true;
4060 $updates->comments->itemids = array_keys($comments);
4064 // Check ratings.
4065 if (plugin_supports('mod', $cm->modname, FEATURE_RATE) and (empty($filter) or in_array('ratings', $filter))) {
4066 $updates->ratings = (object) array('updated' => false);
4067 require_once($CFG->dirroot . '/rating/lib.php');
4068 $manager = new rating_manager();
4069 $ratings = $manager->get_component_ratings_since($context, $component, $from);
4070 if (!empty($ratings)) {
4071 $updates->ratings->updated = true;
4072 $updates->ratings->itemids = array_keys($ratings);
4076 return $updates;