2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Library of useful functions
20 * @copyright 1999 Martin Dougiamas http://dougiamas.com
21 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
22 * @package core_course
25 defined('MOODLE_INTERNAL') ||
die;
27 require_once($CFG->libdir
.'/completionlib.php');
28 require_once($CFG->libdir
.'/filelib.php');
29 require_once($CFG->dirroot
.'/course/format/lib.php');
31 define('COURSE_MAX_LOGS_PER_PAGE', 1000); // Records.
32 define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds.
35 * Number of courses to display when summaries are included.
37 * @deprecated since 2.4, use $CFG->courseswithsummarieslimit instead.
39 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10);
41 // Max courses in log dropdown before switching to optional.
42 define('COURSE_MAX_COURSES_PER_DROPDOWN', 1000);
43 // Max users in log dropdown before switching to optional.
44 define('COURSE_MAX_USERS_PER_DROPDOWN', 1000);
45 define('FRONTPAGENEWS', '0');
46 define('FRONTPAGECATEGORYNAMES', '2');
47 define('FRONTPAGECATEGORYCOMBO', '4');
48 define('FRONTPAGEENROLLEDCOURSELIST', '5');
49 define('FRONTPAGEALLCOURSELIST', '6');
50 define('FRONTPAGECOURSESEARCH', '7');
51 // Important! Replaced with $CFG->frontpagecourselimit - maximum number of courses displayed on the frontpage.
52 define('EXCELROWS', 65535);
53 define('FIRSTUSEDEXCELROW', 3);
55 define('MOD_CLASS_ACTIVITY', 0);
56 define('MOD_CLASS_RESOURCE', 1);
58 define('COURSE_TIMELINE_ALL', 'all');
59 define('COURSE_TIMELINE_PAST', 'past');
60 define('COURSE_TIMELINE_INPROGRESS', 'inprogress');
61 define('COURSE_TIMELINE_FUTURE', 'future');
62 define('COURSE_DB_QUERY_LIMIT', 1000);
64 function make_log_url($module, $url) {
67 if (strpos($url, 'report/') === 0) {
68 // there is only one report type, course reports are deprecated
78 if (strpos($url, '../') === 0) {
79 $url = ltrim($url, '.');
81 $url = "/course/$url";
85 $url = "/calendar/$url";
89 $url = "/$module/$url";
102 $url = "/message/$url";
105 $url = "/notes/$url";
114 $url = "/grade/$url";
117 $url = "/mod/$module/$url";
121 //now let's sanitise urls - there might be some ugly nasties:-(
122 $parts = explode('?', $url);
123 $script = array_shift($parts);
124 if (strpos($script, 'http') === 0) {
125 $script = clean_param($script, PARAM_URL
);
127 $script = clean_param($script, PARAM_PATH
);
132 $query = implode('', $parts);
133 $query = str_replace('&', '&', $query); // both & and & are stored in db :-|
134 $parts = explode('&', $query);
135 $eq = urlencode('=');
136 foreach ($parts as $key=>$part) {
137 $part = urlencode(urldecode($part));
138 $part = str_replace($eq, '=', $part);
139 $parts[$key] = $part;
141 $query = '?'.implode('&', $parts);
144 return $script.$query;
148 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
149 $modname="", $modid=0, $modaction="", $groupid=0) {
152 // It is assumed that $date is the GMT time of midnight for that day,
153 // and so the next 86400 seconds worth of logs are printed.
155 /// Setup for group handling.
157 // TODO: I don't understand group/context/etc. enough to be able to do
158 // something interesting with it here
159 // What is the context of a remote course?
161 /// If the group mode is separate, and this user does not have editing privileges,
162 /// then only the user's group can be viewed.
163 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
164 // $groupid = get_current_group($course->id);
166 /// If this course doesn't have groups, no groupid can be specified.
167 //else if (!$course->groupmode) {
176 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
178 LEFT JOIN {user} u ON l.userid = u.id
182 $where .= "l.hostid = :hostid";
183 $params['hostid'] = $hostid;
185 // TODO: Is 1 really a magic number referring to the sitename?
186 if ($course != SITEID ||
$modid != 0) {
187 $where .= " AND l.course=:courseid";
188 $params['courseid'] = $course;
192 $where .= " AND l.module = :modname";
193 $params['modname'] = $modname;
196 if ('site_errors' === $modid) {
197 $where .= " AND ( l.action='error' OR l.action='infected' )";
199 //TODO: This assumes that modids are the same across sites... probably
201 $where .= " AND l.cmid = :modid";
202 $params['modid'] = $modid;
206 $firstletter = substr($modaction, 0, 1);
207 if ($firstletter == '-') {
208 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
209 $params['modaction'] = '%'.substr($modaction, 1).'%';
211 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
212 $params['modaction'] = '%'.$modaction.'%';
217 $where .= " AND l.userid = :user";
218 $params['user'] = $user;
222 $enddate = $date +
86400;
223 $where .= " AND l.time > :date AND l.time < :enddate";
224 $params['date'] = $date;
225 $params['enddate'] = $enddate;
229 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
230 if(!empty($result['totalcount'])) {
231 $where .= " ORDER BY $order";
232 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
234 $result['logs'] = array();
240 * Checks the integrity of the course data.
242 * In summary - compares course_sections.sequence and course_modules.section.
244 * More detailed, checks that:
245 * - course_sections.sequence contains each module id not more than once in the course
246 * - for each moduleid from course_sections.sequence the field course_modules.section
247 * refers to the same section id (this means course_sections.sequence is more
248 * important if they are different)
249 * - ($fullcheck only) each module in the course is present in one of
250 * course_sections.sequence
251 * - ($fullcheck only) removes non-existing course modules from section sequences
253 * If there are any mismatches, the changes are made and records are updated in DB.
255 * Course cache is NOT rebuilt if there are any errors!
257 * This function is used each time when course cache is being rebuilt with $fullcheck = false
258 * and in CLI script admin/cli/fix_course_sequence.php with $fullcheck = true
260 * @param int $courseid id of the course
261 * @param array $rawmods result of funciton {@link get_course_mods()} - containst
262 * the list of enabled course modules in the course. Retrieved from DB if not specified.
263 * Argument ignored in cashe of $fullcheck, the list is retrieved form DB anyway.
264 * @param array $sections records from course_sections table for this course.
265 * Retrieved from DB if not specified
266 * @param bool $fullcheck Will add orphaned modules to their sections and remove non-existing
267 * course modules from sequences. Only to be used in site maintenance mode when we are
268 * sure that another user is not in the middle of the process of moving/removing a module.
269 * @param bool $checkonly Only performs the check without updating DB, outputs all errors as debug messages.
270 * @return array array of messages with found problems. Empty output means everything is ok
272 function course_integrity_check($courseid, $rawmods = null, $sections = null, $fullcheck = false, $checkonly = false) {
275 if ($sections === null) {
276 $sections = $DB->get_records('course_sections', array('course' => $courseid), 'section', 'id,section,sequence');
279 // Retrieve all records from course_modules regardless of module type visibility.
280 $rawmods = $DB->get_records('course_modules', array('course' => $courseid), 'id', 'id,section');
282 if ($rawmods === null) {
283 $rawmods = get_course_mods($courseid);
285 if (!$fullcheck && (empty($sections) ||
empty($rawmods))) {
286 // If either of the arrays is empty, no modules are displayed anyway.
289 $debuggingprefix = 'Failed integrity check for course ['.$courseid.']. ';
291 // First make sure that each module id appears in section sequences only once.
292 // If it appears in several section sequences the last section wins.
293 // If it appears twice in one section sequence, the first occurence wins.
294 $modsection = array();
295 foreach ($sections as $sectionid => $section) {
296 $sections[$sectionid]->newsequence
= $section->sequence
;
297 if (!empty($section->sequence
)) {
298 $sequence = explode(",", $section->sequence
);
299 $sequenceunique = array_unique($sequence);
300 if (count($sequenceunique) != count($sequence)) {
301 // Some course module id appears in this section sequence more than once.
302 ksort($sequenceunique); // Preserve initial order of modules.
303 $sequence = array_values($sequenceunique);
304 $sections[$sectionid]->newsequence
= join(',', $sequence);
305 $messages[] = $debuggingprefix.'Sequence for course section ['.
306 $sectionid.'] is "'.$sections[$sectionid]->sequence
.'", must be "'.$sections[$sectionid]->newsequence
.'"';
308 foreach ($sequence as $cmid) {
309 if (array_key_exists($cmid, $modsection) && isset($rawmods[$cmid])) {
310 // Some course module id appears to be in more than one section's sequences.
311 $wrongsectionid = $modsection[$cmid];
312 $sections[$wrongsectionid]->newsequence
= trim(preg_replace("/,$cmid,/", ',', ','.$sections[$wrongsectionid]->newsequence
. ','), ',');
313 $messages[] = $debuggingprefix.'Course module ['.$cmid.'] must be removed from sequence of section ['.
314 $wrongsectionid.'] because it is also present in sequence of section ['.$sectionid.']';
316 $modsection[$cmid] = $sectionid;
321 // Add orphaned modules to their sections if they exist or to section 0 otherwise.
323 foreach ($rawmods as $cmid => $mod) {
324 if (!isset($modsection[$cmid])) {
325 // This is a module that is not mentioned in course_section.sequence at all.
326 // Add it to the section $mod->section or to the last available section.
327 if ($mod->section
&& isset($sections[$mod->section
])) {
328 $modsection[$cmid] = $mod->section
;
330 $firstsection = reset($sections);
331 $modsection[$cmid] = $firstsection->id
;
333 $sections[$modsection[$cmid]]->newsequence
= trim($sections[$modsection[$cmid]]->newsequence
.','.$cmid, ',');
334 $messages[] = $debuggingprefix.'Course module ['.$cmid.'] is missing from sequence of section ['.
335 $modsection[$cmid].']';
338 foreach ($modsection as $cmid => $sectionid) {
339 if (!isset($rawmods[$cmid])) {
340 // Section $sectionid refers to module id that does not exist.
341 $sections[$sectionid]->newsequence
= trim(preg_replace("/,$cmid,/", ',', ','.$sections[$sectionid]->newsequence
.','), ',');
342 $messages[] = $debuggingprefix.'Course module ['.$cmid.
343 '] does not exist but is present in the sequence of section ['.$sectionid.']';
348 // Update changed sections.
349 if (!$checkonly && !empty($messages)) {
350 foreach ($sections as $sectionid => $section) {
351 if ($section->newsequence
!== $section->sequence
) {
352 $DB->update_record('course_sections', array('id' => $sectionid, 'sequence' => $section->newsequence
));
357 // Now make sure that all modules point to the correct sections.
358 foreach ($rawmods as $cmid => $mod) {
359 if (isset($modsection[$cmid]) && $modsection[$cmid] != $mod->section
) {
361 $DB->update_record('course_modules', array('id' => $cmid, 'section' => $modsection[$cmid]));
363 $messages[] = $debuggingprefix.'Course module ['.$cmid.
364 '] points to section ['.$mod->section
.'] instead of ['.$modsection[$cmid].']';
372 * For a given course, returns an array of course activity objects
373 * Each item in the array contains he following properties:
375 function get_array_of_activities($courseid) {
376 // cm - course module id
377 // mod - name of the module (eg forum)
378 // section - the number of the section (eg week or topic)
379 // name - the name of the instance
380 // visible - is the instance visible or not
381 // groupingid - grouping id
382 // extra - contains extra string to include in any link
385 $course = $DB->get_record('course', array('id'=>$courseid));
387 if (empty($course)) {
388 throw new moodle_exception('courseidnotfound');
393 $rawmods = get_course_mods($courseid);
394 if (empty($rawmods)) {
395 return $mod; // always return array
397 $courseformat = course_get_format($course);
399 if ($sections = $DB->get_records('course_sections', array('course' => $courseid),
400 'section ASC', 'id,section,sequence,visible')) {
401 // First check and correct obvious mismatches between course_sections.sequence and course_modules.section.
402 if ($errormessages = course_integrity_check($courseid, $rawmods, $sections)) {
403 debugging(join('<br>', $errormessages));
404 $rawmods = get_course_mods($courseid);
405 $sections = $DB->get_records('course_sections', array('course' => $courseid),
406 'section ASC', 'id,section,sequence,visible');
408 // Build array of activities.
409 foreach ($sections as $section) {
410 if (!empty($section->sequence
)) {
411 $sequence = explode(",", $section->sequence
);
412 foreach ($sequence as $seq) {
413 if (empty($rawmods[$seq])) {
416 // Adjust visibleoncoursepage, value in DB may not respect format availability.
417 $rawmods[$seq]->visibleoncoursepage
= (!$rawmods[$seq]->visible
418 ||
$rawmods[$seq]->visibleoncoursepage
419 ||
empty($CFG->allowstealth
)
420 ||
!$courseformat->allow_stealth_module_visibility($rawmods[$seq], $section)) ?
1 : 0;
422 // Create an object that will be cached.
423 $mod[$seq] = new stdClass();
424 $mod[$seq]->id
= $rawmods[$seq]->instance
;
425 $mod[$seq]->cm
= $rawmods[$seq]->id
;
426 $mod[$seq]->mod
= $rawmods[$seq]->modname
;
428 // Oh dear. Inconsistent names left here for backward compatibility.
429 $mod[$seq]->section
= $section->section
;
430 $mod[$seq]->sectionid
= $rawmods[$seq]->section
;
432 $mod[$seq]->module
= $rawmods[$seq]->module
;
433 $mod[$seq]->added
= $rawmods[$seq]->added
;
434 $mod[$seq]->score
= $rawmods[$seq]->score
;
435 $mod[$seq]->idnumber
= $rawmods[$seq]->idnumber
;
436 $mod[$seq]->visible
= $rawmods[$seq]->visible
;
437 $mod[$seq]->visibleoncoursepage
= $rawmods[$seq]->visibleoncoursepage
;
438 $mod[$seq]->visibleold
= $rawmods[$seq]->visibleold
;
439 $mod[$seq]->groupmode
= $rawmods[$seq]->groupmode
;
440 $mod[$seq]->groupingid
= $rawmods[$seq]->groupingid
;
441 $mod[$seq]->indent
= $rawmods[$seq]->indent
;
442 $mod[$seq]->completion
= $rawmods[$seq]->completion
;
443 $mod[$seq]->extra
= "";
444 $mod[$seq]->completiongradeitemnumber
=
445 $rawmods[$seq]->completiongradeitemnumber
;
446 $mod[$seq]->completionview
= $rawmods[$seq]->completionview
;
447 $mod[$seq]->completionexpected
= $rawmods[$seq]->completionexpected
;
448 $mod[$seq]->showdescription
= $rawmods[$seq]->showdescription
;
449 $mod[$seq]->availability
= $rawmods[$seq]->availability
;
450 $mod[$seq]->deletioninprogress
= $rawmods[$seq]->deletioninprogress
;
452 $modname = $mod[$seq]->mod
;
453 $functionname = $modname."_get_coursemodule_info";
455 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
459 include_once("$CFG->dirroot/mod/$modname/lib.php");
461 if ($hasfunction = function_exists($functionname)) {
462 if ($info = $functionname($rawmods[$seq])) {
463 if (!empty($info->icon
)) {
464 $mod[$seq]->icon
= $info->icon
;
466 if (!empty($info->iconcomponent
)) {
467 $mod[$seq]->iconcomponent
= $info->iconcomponent
;
469 if (!empty($info->name
)) {
470 $mod[$seq]->name
= $info->name
;
472 if ($info instanceof cached_cm_info
) {
473 // When using cached_cm_info you can include three new fields
474 // that aren't available for legacy code
475 if (!empty($info->content
)) {
476 $mod[$seq]->content
= $info->content
;
478 if (!empty($info->extraclasses
)) {
479 $mod[$seq]->extraclasses
= $info->extraclasses
;
481 if (!empty($info->iconurl
)) {
482 // Convert URL to string as it's easier to store. Also serialized object contains \0 byte and can not be written to Postgres DB.
483 $url = new moodle_url($info->iconurl
);
484 $mod[$seq]->iconurl
= $url->out(false);
486 if (!empty($info->onclick
)) {
487 $mod[$seq]->onclick
= $info->onclick
;
489 if (!empty($info->customdata
)) {
490 $mod[$seq]->customdata
= $info->customdata
;
493 // When using a stdclass, the (horrible) deprecated ->extra field
494 // is available for BC
495 if (!empty($info->extra
)) {
496 $mod[$seq]->extra
= $info->extra
;
501 // When there is no modname_get_coursemodule_info function,
502 // but showdescriptions is enabled, then we use the 'intro'
503 // and 'introformat' fields in the module table
504 if (!$hasfunction && $rawmods[$seq]->showdescription
) {
505 if ($modvalues = $DB->get_record($rawmods[$seq]->modname
,
506 array('id' => $rawmods[$seq]->instance
), 'name, intro, introformat')) {
507 // Set content from intro and introformat. Filters are disabled
508 // because we filter it with format_text at display time
509 $mod[$seq]->content
= format_module_intro($rawmods[$seq]->modname
,
510 $modvalues, $rawmods[$seq]->id
, false);
512 // To save making another query just below, put name in here
513 $mod[$seq]->name
= $modvalues->name
;
516 if (!isset($mod[$seq]->name
)) {
517 $mod[$seq]->name
= $DB->get_field($rawmods[$seq]->modname
, "name", array("id"=>$rawmods[$seq]->instance
));
520 // Minimise the database size by unsetting default options when they are
521 // 'empty'. This list corresponds to code in the cm_info constructor.
522 foreach (array('idnumber', 'groupmode', 'groupingid',
523 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
524 'icon', 'iconcomponent', 'customdata', 'availability', 'completionview',
525 'completionexpected', 'score', 'showdescription', 'deletioninprogress') as $property) {
526 if (property_exists($mod[$seq], $property) &&
527 empty($mod[$seq]->{$property})) {
528 unset($mod[$seq]->{$property});
531 // Special case: this value is usually set to null, but may be 0
532 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
533 is_null($mod[$seq]->completiongradeitemnumber
)) {
534 unset($mod[$seq]->completiongradeitemnumber
);
544 * Returns the localised human-readable names of all used modules
546 * @param bool $plural if true returns the plural forms of the names
547 * @return array where key is the module name (component name without 'mod_') and
548 * the value is the human-readable string. Array sorted alphabetically by value
550 function get_module_types_names($plural = false) {
551 static $modnames = null;
553 if ($modnames === null) {
554 $modnames = array(0 => array(), 1 => array());
555 if ($allmods = $DB->get_records("modules")) {
556 foreach ($allmods as $mod) {
557 if (file_exists("$CFG->dirroot/mod/$mod->name/lib.php") && $mod->visible
) {
558 $modnames[0][$mod->name
] = get_string("modulename", "$mod->name");
559 $modnames[1][$mod->name
] = get_string("modulenameplural", "$mod->name");
562 core_collator
::asort($modnames[0]);
563 core_collator
::asort($modnames[1]);
566 return $modnames[(int)$plural];
570 * Set highlighted section. Only one section can be highlighted at the time.
572 * @param int $courseid course id
573 * @param int $marker highlight section with this number, 0 means remove higlightin
576 function course_set_marker($courseid, $marker) {
578 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
579 if ($COURSE && $COURSE->id
== $courseid) {
580 $COURSE->marker
= $marker;
582 if (class_exists('format_base')) {
583 format_base
::reset_course_cache($courseid);
585 course_modinfo
::clear_instance_cache($courseid);
589 * For a given course section, marks it visible or hidden,
590 * and does the same for every activity in that section
592 * @param int $courseid course id
593 * @param int $sectionnumber The section number to adjust
594 * @param int $visibility The new visibility
595 * @return array A list of resources which were hidden in the section
597 function set_section_visible($courseid, $sectionnumber, $visibility) {
600 $resourcestotoggle = array();
601 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
602 course_update_section($courseid, $section, array('visible' => $visibility));
604 // Determine which modules are visible for AJAX update
605 $modules = !empty($section->sequence
) ?
explode(',', $section->sequence
) : array();
606 if (!empty($modules)) {
607 list($insql, $params) = $DB->get_in_or_equal($modules);
608 $select = 'id ' . $insql . ' AND visible = ?';
609 array_push($params, $visibility);
611 $select .= ' AND visibleold = 1';
613 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
616 return $resourcestotoggle;
620 * Retrieve all metadata for the requested modules
622 * @param object $course The Course
623 * @param array $modnames An array containing the list of modules and their
625 * @param int $sectionreturn The section to return to
626 * @return array A list of stdClass objects containing metadata about each
629 function get_module_metadata($course, $modnames, $sectionreturn = null) {
632 // get_module_metadata will be called once per section on the page and courses may show
633 // different modules to one another
634 static $modlist = array();
635 if (!isset($modlist[$course->id
])) {
636 $modlist[$course->id
] = array();
640 $urlbase = new moodle_url('/course/mod.php', array('id' => $course->id
, 'sesskey' => sesskey()));
641 if ($sectionreturn !== null) {
642 $urlbase->param('sr', $sectionreturn);
644 foreach($modnames as $modname => $modnamestr) {
645 if (!course_allowed_module($course, $modname)) {
648 if (isset($modlist[$course->id
][$modname])) {
649 // This module is already cached
650 $return +
= $modlist[$course->id
][$modname];
653 $modlist[$course->id
][$modname] = array();
655 // Create an object for a default representation of this module type in the activity chooser. It will be used
656 // if module does not implement callback get_shortcuts() and it will also be passed to the callback if it exists.
657 $defaultmodule = new stdClass();
658 $defaultmodule->title
= $modnamestr;
659 $defaultmodule->name
= $modname;
660 $defaultmodule->link
= new moodle_url($urlbase, array('add' => $modname));
661 $defaultmodule->icon
= $OUTPUT->pix_icon('icon', '', $defaultmodule->name
, array('class' => 'icon'));
662 $sm = get_string_manager();
663 if ($sm->string_exists('modulename_help', $modname)) {
664 $defaultmodule->help
= get_string('modulename_help', $modname);
665 if ($sm->string_exists('modulename_link', $modname)) { // Link to further info in Moodle docs.
666 $link = get_string('modulename_link', $modname);
667 $linktext = get_string('morehelp');
668 $defaultmodule->help
.= html_writer
::tag('div',
669 $OUTPUT->doc_link($link, $linktext, true), array('class' => 'helpdoclink'));
672 $defaultmodule->archetype
= plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE
, MOD_ARCHETYPE_OTHER
);
674 // Each module can implement callback modulename_get_shortcuts() in its lib.php and return the list
675 // of elements to be added to activity chooser.
676 $items = component_callback($modname, 'get_shortcuts', array($defaultmodule), null);
677 if ($items !== null) {
678 foreach ($items as $item) {
679 // Add all items to the return array. All items must have different links, use them as a key in the return array.
680 if (!isset($item->archetype
)) {
681 $item->archetype
= $defaultmodule->archetype
;
683 if (!isset($item->icon
)) {
684 $item->icon
= $defaultmodule->icon
;
686 // If plugin returned the only one item with the same link as default item - cache it as $modname,
687 // otherwise append the link url to the module name.
688 $item->name
= (count($items) == 1 &&
689 $item->link
->out() === $defaultmodule->link
->out()) ?
$modname : $modname . ':' . $item->link
;
691 // If the module provides the helptext property, append it to the help text to match the look and feel
692 // of the default course modules.
693 if (isset($item->help
) && isset($item->helplink
)) {
694 $linktext = get_string('morehelp');
695 $item->help
.= html_writer
::tag('div',
696 $OUTPUT->doc_link($item->helplink
, $linktext, true), array('class' => 'helpdoclink'));
698 $modlist[$course->id
][$modname][$item->name
] = $item;
700 $return +
= $modlist[$course->id
][$modname];
701 // If get_shortcuts() callback is defined, the default module action is not added.
702 // It is a responsibility of the callback to add it to the return value unless it is not needed.
706 // The callback get_shortcuts() was not found, use the default item for the activity chooser.
707 $modlist[$course->id
][$modname][$modname] = $defaultmodule;
708 $return[$modname] = $defaultmodule;
711 core_collator
::asort_objects_by_property($return, 'title');
716 * Return the course category context for the category with id $categoryid, except
717 * that if $categoryid is 0, return the system context.
719 * @param integer $categoryid a category id or 0.
720 * @return context the corresponding context
722 function get_category_or_system_context($categoryid) {
724 return context_coursecat
::instance($categoryid, IGNORE_MISSING
);
726 return context_system
::instance();
731 * Returns full course categories trees to be used in html_writer::select()
733 * Calls {@link core_course_category::make_categories_list()} to build the tree and
734 * adds whitespace to denote nesting
736 * @return array array mapping course category id to the display name
738 function make_categories_options() {
739 $cats = core_course_category
::make_categories_list('', 0, ' / ');
740 foreach ($cats as $key => $value) {
741 // Prefix the value with the number of spaces equal to category depth (number of separators in the value).
742 $cats[$key] = str_repeat(' ', substr_count($value, ' / ')). $value;
748 * Print the buttons relating to course requests.
750 * @param object $context current page context.
752 function print_course_request_buttons($context) {
753 global $CFG, $DB, $OUTPUT;
754 if (empty($CFG->enablecourserequests
)) {
757 if (!has_capability('moodle/course:create', $context) && has_capability('moodle/course:request', $context)) {
758 /// Print a button to request a new course
759 echo $OUTPUT->single_button(new moodle_url('/course/request.php'), get_string('requestcourse'), 'get');
761 /// Print a button to manage pending requests
762 if ($context->contextlevel
== CONTEXT_SYSTEM
&& has_capability('moodle/site:approvecourse', $context)) {
763 $disabled = !$DB->record_exists('course_request', array());
764 echo $OUTPUT->single_button(new moodle_url('/course/pending.php'), get_string('coursespending'), 'get', array('disabled' => $disabled));
769 * Does the user have permission to edit things in this category?
771 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
772 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
774 function can_edit_in_category($categoryid = 0) {
775 $context = get_category_or_system_context($categoryid);
776 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
779 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
781 function add_course_module($mod) {
784 $mod->added
= time();
787 $cmid = $DB->insert_record("course_modules", $mod);
788 rebuild_course_cache($mod->course
, true);
793 * Creates a course section and adds it to the specified position
795 * @param int|stdClass $courseorid course id or course object
796 * @param int $position position to add to, 0 means to the end. If position is greater than
797 * number of existing secitons, the section is added to the end. This will become sectionnum of the
798 * new section. All existing sections at this or bigger position will be shifted down.
799 * @param bool $skipcheck the check has already been made and we know that the section with this position does not exist
800 * @return stdClass created section object
802 function course_create_section($courseorid, $position = 0, $skipcheck = false) {
804 $courseid = is_object($courseorid) ?
$courseorid->id
: $courseorid;
806 // Find the last sectionnum among existing sections.
808 $lastsection = $position - 1;
810 $lastsection = (int)$DB->get_field_sql('SELECT max(section) from {course_sections} WHERE course = ?', [$courseid]);
813 // First add section to the end.
814 $cw = new stdClass();
815 $cw->course
= $courseid;
816 $cw->section
= $lastsection +
1;
818 $cw->summaryformat
= FORMAT_HTML
;
822 $cw->availability
= null;
823 $cw->timemodified
= time();
824 $cw->id
= $DB->insert_record("course_sections", $cw);
826 // Now move it to the specified position.
827 if ($position > 0 && $position <= $lastsection) {
828 $course = is_object($courseorid) ?
$courseorid : get_course($courseorid);
829 move_section_to($course, $cw->section
, $position, true);
830 $cw->section
= $position;
833 core\event\course_section_created
::create_from_section($cw)->trigger();
835 rebuild_course_cache($courseid, true);
840 * Creates missing course section(s) and rebuilds course cache
842 * @param int|stdClass $courseorid course id or course object
843 * @param int|array $sections list of relative section numbers to create
844 * @return bool if there were any sections created
846 function course_create_sections_if_missing($courseorid, $sections) {
847 if (!is_array($sections)) {
848 $sections = array($sections);
850 $existing = array_keys(get_fast_modinfo($courseorid)->get_section_info_all());
851 if ($newsections = array_diff($sections, $existing)) {
852 foreach ($newsections as $sectionnum) {
853 course_create_section($courseorid, $sectionnum, true);
861 * Adds an existing module to the section
863 * Updates both tables {course_sections} and {course_modules}
865 * Note: This function does not use modinfo PROVIDED that the section you are
866 * adding the module to already exists. If the section does not exist, it will
867 * build modinfo if necessary and create the section.
869 * @param int|stdClass $courseorid course id or course object
870 * @param int $cmid id of the module already existing in course_modules table
871 * @param int $sectionnum relative number of the section (field course_sections.section)
872 * If section does not exist it will be created
873 * @param int|stdClass $beforemod id or object with field id corresponding to the module
874 * before which the module needs to be included. Null for inserting in the
876 * @return int The course_sections ID where the module is inserted
878 function course_add_cm_to_section($courseorid, $cmid, $sectionnum, $beforemod = null) {
880 if (is_object($beforemod)) {
881 $beforemod = $beforemod->id
;
883 if (is_object($courseorid)) {
884 $courseid = $courseorid->id
;
886 $courseid = $courseorid;
888 // Do not try to use modinfo here, there is no guarantee it is valid!
889 $section = $DB->get_record('course_sections',
890 array('course' => $courseid, 'section' => $sectionnum), '*', IGNORE_MISSING
);
892 // This function call requires modinfo.
893 course_create_sections_if_missing($courseorid, $sectionnum);
894 $section = $DB->get_record('course_sections',
895 array('course' => $courseid, 'section' => $sectionnum), '*', MUST_EXIST
);
898 $modarray = explode(",", trim($section->sequence
));
899 if (empty($section->sequence
)) {
900 $newsequence = "$cmid";
901 } else if ($beforemod && ($key = array_keys($modarray, $beforemod))) {
902 $insertarray = array($cmid, $beforemod);
903 array_splice($modarray, $key[0], 1, $insertarray);
904 $newsequence = implode(",", $modarray);
906 $newsequence = "$section->sequence,$cmid";
908 $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id
));
909 $DB->set_field('course_modules', 'section', $section->id
, array('id' => $cmid));
910 if (is_object($courseorid)) {
911 rebuild_course_cache($courseorid->id
, true);
913 rebuild_course_cache($courseorid, true);
915 return $section->id
; // Return course_sections ID that was used.
919 * Change the group mode of a course module.
921 * Note: Do not forget to trigger the event \core\event\course_module_updated as it needs
922 * to be triggered manually, refer to {@link \core\event\course_module_updated::create_from_cm()}.
924 * @param int $id course module ID.
925 * @param int $groupmode the new groupmode value.
926 * @return bool True if the $groupmode was updated.
928 function set_coursemodule_groupmode($id, $groupmode) {
930 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST
);
931 if ($cm->groupmode
!= $groupmode) {
932 $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id
));
933 rebuild_course_cache($cm->course
, true);
935 return ($cm->groupmode
!= $groupmode);
938 function set_coursemodule_idnumber($id, $idnumber) {
940 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST
);
941 if ($cm->idnumber
!= $idnumber) {
942 $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id
));
943 rebuild_course_cache($cm->course
, true);
945 return ($cm->idnumber
!= $idnumber);
949 * Set the visibility of a module and inherent properties.
951 * Note: Do not forget to trigger the event \core\event\course_module_updated as it needs
952 * to be triggered manually, refer to {@link \core\event\course_module_updated::create_from_cm()}.
954 * From 2.4 the parameter $prevstateoverrides has been removed, the logic it triggered
955 * has been moved to {@link set_section_visible()} which was the only place from which
956 * the parameter was used.
958 * @param int $id of the module
959 * @param int $visible state of the module
960 * @param int $visibleoncoursepage state of the module on the course page
961 * @return bool false when the module was not found, true otherwise
963 function set_coursemodule_visible($id, $visible, $visibleoncoursepage = 1) {
965 require_once($CFG->libdir
.'/gradelib.php');
966 require_once($CFG->dirroot
.'/calendar/lib.php');
968 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
972 // Create events and propagate visibility to associated grade items if the value has changed.
973 // Only do this if it's changed to avoid accidently overwriting manual showing/hiding of student grades.
974 if ($cm->visible
== $visible && $cm->visibleoncoursepage
== $visibleoncoursepage) {
978 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module
))) {
981 if (($cm->visible
!= $visible) &&
982 ($events = $DB->get_records('event', array('instance' => $cm->instance
, 'modulename' => $modulename)))) {
983 foreach($events as $event) {
985 $event = new calendar_event($event);
986 $event->toggle_visibility(true);
988 $event = new calendar_event($event);
989 $event->toggle_visibility(false);
994 // Updating visible and visibleold to keep them in sync. Only changing a section visibility will
995 // affect visibleold to allow for an original visibility restore. See set_section_visible().
996 $cminfo = new stdClass();
998 $cminfo->visible
= $visible;
999 $cminfo->visibleoncoursepage
= $visibleoncoursepage;
1000 $cminfo->visibleold
= $visible;
1001 $DB->update_record('course_modules', $cminfo);
1003 // Hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there.
1004 // Note that this must be done after updating the row in course_modules, in case
1005 // the modules grade_item_update function needs to access $cm->visible.
1006 if ($cm->visible
!= $visible &&
1007 plugin_supports('mod', $modulename, FEATURE_CONTROLS_GRADE_VISIBILITY
) &&
1008 component_callback_exists('mod_' . $modulename, 'grade_item_update')) {
1009 $instance = $DB->get_record($modulename, array('id' => $cm->instance
), '*', MUST_EXIST
);
1010 component_callback('mod_' . $modulename, 'grade_item_update', array($instance));
1011 } else if ($cm->visible
!= $visible) {
1012 $grade_items = grade_item
::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance
, 'courseid'=>$cm->course
));
1014 foreach ($grade_items as $grade_item) {
1015 $grade_item->set_hidden(!$visible);
1020 rebuild_course_cache($cm->course
, true);
1025 * Changes the course module name
1027 * @param int $id course module id
1028 * @param string $name new value for a name
1029 * @return bool whether a change was made
1031 function set_coursemodule_name($id, $name) {
1033 require_once($CFG->libdir
. '/gradelib.php');
1035 $cm = get_coursemodule_from_id('', $id, 0, false, MUST_EXIST
);
1037 $module = new \
stdClass();
1038 $module->id
= $cm->instance
;
1040 // Escape strings as they would be by mform.
1041 if (!empty($CFG->formatstringstriptags
)) {
1042 $module->name
= clean_param($name, PARAM_TEXT
);
1044 $module->name
= clean_param($name, PARAM_CLEANHTML
);
1046 if ($module->name
=== $cm->name ||
strval($module->name
) === '') {
1049 if (\core_text
::strlen($module->name
) > 255) {
1050 throw new \
moodle_exception('maximumchars', 'moodle', '', 255);
1053 $module->timemodified
= time();
1054 $DB->update_record($cm->modname
, $module);
1055 $cm->name
= $module->name
;
1056 \core\event\course_module_updated
::create_from_cm($cm)->trigger();
1057 rebuild_course_cache($cm->course
, true);
1059 // Attempt to update the grade item if relevant.
1060 $grademodule = $DB->get_record($cm->modname
, array('id' => $cm->instance
));
1061 $grademodule->cmidnumber
= $cm->idnumber
;
1062 $grademodule->modname
= $cm->modname
;
1063 grade_update_mod_grades($grademodule);
1065 // Update calendar events with the new name.
1066 course_module_update_calendar_events($cm->modname
, $grademodule, $cm);
1072 * This function will handle the whole deletion process of a module. This includes calling
1073 * the modules delete_instance function, deleting files, events, grades, conditional data,
1074 * the data in the course_module and course_sections table and adding a module deletion
1077 * @param int $cmid the course module id
1078 * @param bool $async whether or not to try to delete the module using an adhoc task. Async also depends on a plugin hook.
1079 * @throws moodle_exception
1082 function course_delete_module($cmid, $async = false) {
1083 // Check the 'course_module_background_deletion_recommended' hook first.
1084 // Only use asynchronous deletion if at least one plugin returns true and if async deletion has been requested.
1085 // Both are checked because plugins should not be allowed to dictate the deletion behaviour, only support/decline it.
1086 // It's up to plugins to handle things like whether or not they are enabled.
1087 if ($async && $pluginsfunction = get_plugins_with_function('course_module_background_deletion_recommended')) {
1088 foreach ($pluginsfunction as $plugintype => $plugins) {
1089 foreach ($plugins as $pluginfunction) {
1090 if ($pluginfunction()) {
1091 return course_module_flag_for_async_deletion($cmid);
1099 require_once($CFG->libdir
.'/gradelib.php');
1100 require_once($CFG->libdir
.'/questionlib.php');
1101 require_once($CFG->dirroot
.'/blog/lib.php');
1102 require_once($CFG->dirroot
.'/calendar/lib.php');
1104 // Get the course module.
1105 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
1109 // Get the module context.
1110 $modcontext = context_module
::instance($cm->id
);
1112 // Get the course module name.
1113 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module
), MUST_EXIST
);
1115 // Get the file location of the delete_instance function for this module.
1116 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
1118 // Include the file required to call the delete_instance function for this module.
1119 if (file_exists($modlib)) {
1120 require_once($modlib);
1122 throw new moodle_exception('cannotdeletemodulemissinglib', '', '', null,
1123 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
1126 $deleteinstancefunction = $modulename . '_delete_instance';
1128 // Ensure the delete_instance function exists for this module.
1129 if (!function_exists($deleteinstancefunction)) {
1130 throw new moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
1131 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
1134 // Allow plugins to use this course module before we completely delete it.
1135 if ($pluginsfunction = get_plugins_with_function('pre_course_module_delete')) {
1136 foreach ($pluginsfunction as $plugintype => $plugins) {
1137 foreach ($plugins as $pluginfunction) {
1138 $pluginfunction($cm);
1143 // Delete activity context questions and question categories.
1144 question_delete_activity($cm);
1146 // Call the delete_instance function, if it returns false throw an exception.
1147 if (!$deleteinstancefunction($cm->instance
)) {
1148 throw new moodle_exception('cannotdeletemoduleinstance', '', '', null,
1149 "Cannot delete the module $modulename (instance).");
1152 // Remove all module files in case modules forget to do that.
1153 $fs = get_file_storage();
1154 $fs->delete_area_files($modcontext->id
);
1156 // Delete events from calendar.
1157 if ($events = $DB->get_records('event', array('instance' => $cm->instance
, 'modulename' => $modulename))) {
1158 $coursecontext = context_course
::instance($cm->course
);
1159 foreach($events as $event) {
1160 $event->context
= $coursecontext;
1161 $calendarevent = calendar_event
::load($event);
1162 $calendarevent->delete();
1166 // Delete grade items, outcome items and grades attached to modules.
1167 if ($grade_items = grade_item
::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $modulename,
1168 'iteminstance' => $cm->instance
, 'courseid' => $cm->course
))) {
1169 foreach ($grade_items as $grade_item) {
1170 $grade_item->delete('moddelete');
1174 // Delete associated blogs and blog tag instances.
1175 blog_remove_associations_for_module($modcontext->id
);
1177 // Delete completion and availability data; it is better to do this even if the
1178 // features are not turned on, in case they were turned on previously (these will be
1179 // very quick on an empty table).
1180 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id
));
1181 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id
,
1182 'course' => $cm->course
,
1183 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY
));
1185 // Delete all tag instances associated with the instance of this module.
1186 core_tag_tag
::delete_instances('mod_' . $modulename, null, $modcontext->id
);
1187 core_tag_tag
::remove_all_item_tags('core', 'course_modules', $cm->id
);
1189 // Notify the competency subsystem.
1190 \core_competency\api
::hook_course_module_deleted($cm);
1192 // Delete the context.
1193 context_helper
::delete_instance(CONTEXT_MODULE
, $cm->id
);
1195 // Delete the module from the course_modules table.
1196 $DB->delete_records('course_modules', array('id' => $cm->id
));
1198 // Delete module from that section.
1199 if (!delete_mod_from_section($cm->id
, $cm->section
)) {
1200 throw new moodle_exception('cannotdeletemodulefromsection', '', '', null,
1201 "Cannot delete the module $modulename (instance) from section.");
1204 // Trigger event for course module delete action.
1205 $event = \core\event\course_module_deleted
::create(array(
1206 'courseid' => $cm->course
,
1207 'context' => $modcontext,
1208 'objectid' => $cm->id
,
1210 'modulename' => $modulename,
1211 'instanceid' => $cm->instance
,
1214 $event->add_record_snapshot('course_modules', $cm);
1216 rebuild_course_cache($cm->course
, true);
1220 * Schedule a course module for deletion in the background using an adhoc task.
1222 * This method should not be called directly. Instead, please use course_delete_module($cmid, true), to denote async deletion.
1223 * The real deletion of the module is handled by the task, which calls 'course_delete_module($cmid)'.
1225 * @param int $cmid the course module id.
1226 * @return bool whether the module was successfully scheduled for deletion.
1227 * @throws \moodle_exception
1229 function course_module_flag_for_async_deletion($cmid) {
1230 global $CFG, $DB, $USER;
1231 require_once($CFG->libdir
.'/gradelib.php');
1232 require_once($CFG->libdir
.'/questionlib.php');
1233 require_once($CFG->dirroot
.'/blog/lib.php');
1234 require_once($CFG->dirroot
.'/calendar/lib.php');
1236 // Get the course module.
1237 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
1241 // We need to be reasonably certain the deletion is going to succeed before we background the process.
1242 // Make the necessary delete_instance checks, etc. before proceeding further. Throw exceptions if required.
1244 // Get the course module name.
1245 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module
), MUST_EXIST
);
1247 // Get the file location of the delete_instance function for this module.
1248 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
1250 // Include the file required to call the delete_instance function for this module.
1251 if (file_exists($modlib)) {
1252 require_once($modlib);
1254 throw new \
moodle_exception('cannotdeletemodulemissinglib', '', '', null,
1255 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
1258 $deleteinstancefunction = $modulename . '_delete_instance';
1260 // Ensure the delete_instance function exists for this module.
1261 if (!function_exists($deleteinstancefunction)) {
1262 throw new \
moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
1263 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
1266 // We are going to defer the deletion as we can't be sure how long the module's pre_delete code will run for.
1267 $cm->deletioninprogress
= '1';
1268 $DB->update_record('course_modules', $cm);
1270 // Create an adhoc task for the deletion of the course module. The task takes an array of course modules for removal.
1271 $removaltask = new \core_course\task\
course_delete_modules();
1272 $removaltask->set_custom_data(array(
1273 'cms' => array($cm),
1274 'userid' => $USER->id
,
1275 'realuserid' => \core\session\manager
::get_realuser()->id
1278 // Queue the task for the next run.
1279 \core\task\manager
::queue_adhoc_task($removaltask);
1281 // Reset the course cache to hide the module.
1282 rebuild_course_cache($cm->course
, true);
1286 * Checks whether the given course has any course modules scheduled for adhoc deletion.
1288 * @param int $courseid the id of the course.
1289 * @return bool true if the course contains any modules pending deletion, false otherwise.
1291 function course_modules_pending_deletion($courseid) {
1292 if (empty($courseid)) {
1295 $modinfo = get_fast_modinfo($courseid);
1296 foreach ($modinfo->get_cms() as $module) {
1297 if ($module->deletioninprogress
== '1') {
1305 * Checks whether the course module, as defined by modulename and instanceid, is scheduled for deletion within the given course.
1307 * @param int $courseid the course id.
1308 * @param string $modulename the module name. E.g. 'assign', 'book', etc.
1309 * @param int $instanceid the module instance id.
1310 * @return bool true if the course module is pending deletion, false otherwise.
1312 function course_module_instance_pending_deletion($courseid, $modulename, $instanceid) {
1313 if (empty($courseid) ||
empty($modulename) ||
empty($instanceid)) {
1316 $modinfo = get_fast_modinfo($courseid);
1317 $instances = $modinfo->get_instances_of($modulename);
1318 return isset($instances[$instanceid]) && $instances[$instanceid]->deletioninprogress
;
1321 function delete_mod_from_section($modid, $sectionid) {
1324 if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
1326 $modarray = explode(",", $section->sequence
);
1328 if ($key = array_keys ($modarray, $modid)) {
1329 array_splice($modarray, $key[0], 1);
1330 $newsequence = implode(",", $modarray);
1331 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id
));
1332 rebuild_course_cache($section->course
, true);
1343 * This function updates the calendar events from the information stored in the module table and the course
1346 * @param string $modulename Module name
1347 * @param stdClass $instance Module object. Either the $instance or the $cm must be supplied.
1348 * @param stdClass $cm Course module object. Either the $instance or the $cm must be supplied.
1349 * @return bool Returns true if calendar events are updated.
1350 * @since Moodle 3.3.4
1352 function course_module_update_calendar_events($modulename, $instance = null, $cm = null) {
1355 if (isset($instance) ||
isset($cm)) {
1357 if (!isset($instance)) {
1358 $instance = $DB->get_record($modulename, array('id' => $cm->instance
), '*', MUST_EXIST
);
1361 $cm = get_coursemodule_from_instance($modulename, $instance->id
, $instance->course
);
1364 course_module_calendar_event_update_process($instance, $cm);
1372 * Update all instances through out the site or in a course.
1374 * @param string $modulename Module type to update.
1375 * @param integer $courseid Course id to update events. 0 for the whole site.
1376 * @return bool Returns True if the update was successful.
1377 * @since Moodle 3.3.4
1379 function course_module_bulk_update_calendar_events($modulename, $courseid = 0) {
1384 if (!$instances = $DB->get_records($modulename, array('course' => $courseid))) {
1388 if (!$instances = $DB->get_records($modulename)) {
1393 foreach ($instances as $instance) {
1394 if ($cm = get_coursemodule_from_instance($modulename, $instance->id
, $instance->course
)) {
1395 course_module_calendar_event_update_process($instance, $cm);
1402 * Calendar events for a module instance are updated.
1404 * @param stdClass $instance Module instance object.
1405 * @param stdClass $cm Course Module object.
1406 * @since Moodle 3.3.4
1408 function course_module_calendar_event_update_process($instance, $cm) {
1409 // We need to call *_refresh_events() first because some modules delete 'old' events at the end of the code which
1410 // will remove the completion events.
1411 $refresheventsfunction = $cm->modname
. '_refresh_events';
1412 if (function_exists($refresheventsfunction)) {
1413 call_user_func($refresheventsfunction, $cm->course
, $instance, $cm);
1415 $completionexpected = (!empty($cm->completionexpected
)) ?
$cm->completionexpected
: null;
1416 \core_completion\api
::update_completion_date_event($cm->id
, $cm->modname
, $instance, $completionexpected);
1420 * Moves a section within a course, from a position to another.
1421 * Be very careful: $section and $destination refer to section number,
1424 * @param object $course
1425 * @param int $section Section number (not id!!!)
1426 * @param int $destination
1427 * @param bool $ignorenumsections
1428 * @return boolean Result
1430 function move_section_to($course, $section, $destination, $ignorenumsections = false) {
1431 /// Moves a whole course section up and down within the course
1434 if (!$destination && $destination != 0) {
1438 // compartibility with course formats using field 'numsections'
1439 $courseformatoptions = course_get_format($course)->get_format_options();
1440 if ((!$ignorenumsections && array_key_exists('numsections', $courseformatoptions) &&
1441 ($destination > $courseformatoptions['numsections'])) ||
($destination < 1)) {
1445 // Get all sections for this course and re-order them (2 of them should now share the same section number)
1446 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id
),
1447 'section ASC, id ASC', 'id, section')) {
1451 $movedsections = reorder_sections($sections, $section, $destination);
1453 // Update all sections. Do this in 2 steps to avoid breaking database
1454 // uniqueness constraint
1455 $transaction = $DB->start_delegated_transaction();
1456 foreach ($movedsections as $id => $position) {
1457 if ($sections[$id] !== $position) {
1458 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
1461 foreach ($movedsections as $id => $position) {
1462 if ($sections[$id] !== $position) {
1463 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
1467 // If we move the highlighted section itself, then just highlight the destination.
1468 // Adjust the higlighted section location if we move something over it either direction.
1469 if ($section == $course->marker
) {
1470 course_set_marker($course->id
, $destination);
1471 } elseif ($section > $course->marker
&& $course->marker
>= $destination) {
1472 course_set_marker($course->id
, $course->marker+
1);
1473 } elseif ($section < $course->marker
&& $course->marker
<= $destination) {
1474 course_set_marker($course->id
, $course->marker
-1);
1477 $transaction->allow_commit();
1478 rebuild_course_cache($course->id
, true);
1483 * This method will delete a course section and may delete all modules inside it.
1485 * No permissions are checked here, use {@link course_can_delete_section()} to
1486 * check if section can actually be deleted.
1488 * @param int|stdClass $course
1489 * @param int|stdClass|section_info $section
1490 * @param bool $forcedeleteifnotempty if set to false section will not be deleted if it has modules in it.
1491 * @param bool $async whether or not to try to delete the section using an adhoc task. Async also depends on a plugin hook.
1492 * @return bool whether section was deleted
1494 function course_delete_section($course, $section, $forcedeleteifnotempty = true, $async = false) {
1497 // Prepare variables.
1498 $courseid = (is_object($course)) ?
$course->id
: (int)$course;
1499 $sectionnum = (is_object($section)) ?
$section->section
: (int)$section;
1500 $section = $DB->get_record('course_sections', array('course' => $courseid, 'section' => $sectionnum));
1502 // No section exists, can't proceed.
1506 // Check the 'course_module_background_deletion_recommended' hook first.
1507 // Only use asynchronous deletion if at least one plugin returns true and if async deletion has been requested.
1508 // Both are checked because plugins should not be allowed to dictate the deletion behaviour, only support/decline it.
1509 // It's up to plugins to handle things like whether or not they are enabled.
1510 if ($async && $pluginsfunction = get_plugins_with_function('course_module_background_deletion_recommended')) {
1511 foreach ($pluginsfunction as $plugintype => $plugins) {
1512 foreach ($plugins as $pluginfunction) {
1513 if ($pluginfunction()) {
1514 return course_delete_section_async($section, $forcedeleteifnotempty);
1520 $format = course_get_format($course);
1521 $sectionname = $format->get_section_name($section);
1524 $result = $format->delete_section($section, $forcedeleteifnotempty);
1526 // Trigger an event for course section deletion.
1528 $context = context_course
::instance($courseid);
1529 $event = \core\event\course_section_deleted
::create(
1531 'objectid' => $section->id
,
1532 'courseid' => $courseid,
1533 'context' => $context,
1535 'sectionnum' => $section->section
,
1536 'sectionname' => $sectionname,
1540 $event->add_record_snapshot('course_sections', $section);
1547 * Course section deletion, using an adhoc task for deletion of the modules it contains.
1548 * 1. Schedule all modules within the section for adhoc removal.
1549 * 2. Move all modules to course section 0.
1550 * 3. Delete the resulting empty section.
1552 * @param \stdClass $section the section to schedule for deletion.
1553 * @param bool $forcedeleteifnotempty whether to force section deletion if it contains modules.
1554 * @return bool true if the section was scheduled for deletion, false otherwise.
1556 function course_delete_section_async($section, $forcedeleteifnotempty = true) {
1559 // Objects only, and only valid ones.
1560 if (!is_object($section) ||
empty($section->id
)) {
1564 // Does the object currently exist in the DB for removal (check for stale objects).
1565 $section = $DB->get_record('course_sections', array('id' => $section->id
));
1566 if (!$section ||
!$section->section
) {
1567 // No section exists, or the section is 0. Can't proceed.
1571 // Check whether the section can be removed.
1572 if (!$forcedeleteifnotempty && (!empty($section->sequence
) ||
!empty($section->summary
))) {
1576 $format = course_get_format($section->course
);
1577 $sectionname = $format->get_section_name($section);
1579 // Flag those modules having no existing deletion flag. Some modules may have been scheduled for deletion manually, and we don't
1580 // want to create additional adhoc deletion tasks for these. Moving them to section 0 will suffice.
1581 $affectedmods = $DB->get_records_select('course_modules', 'course = ? AND section = ? AND deletioninprogress <> ?',
1582 [$section->course
, $section->id
, 1], '', 'id');
1583 $DB->set_field('course_modules', 'deletioninprogress', '1', ['course' => $section->course
, 'section' => $section->id
]);
1585 // Move all modules to section 0.
1586 $modules = $DB->get_records('course_modules', ['section' => $section->id
], '');
1587 $sectionzero = $DB->get_record('course_sections', ['course' => $section->course
, 'section' => '0']);
1588 foreach ($modules as $mod) {
1589 moveto_module($mod, $sectionzero);
1592 // Create and queue an adhoc task for the deletion of the modules.
1593 $removaltask = new \core_course\task\
course_delete_modules();
1595 'cms' => $affectedmods,
1596 'userid' => $USER->id
,
1597 'realuserid' => \core\session\manager
::get_realuser()->id
1599 $removaltask->set_custom_data($data);
1600 \core\task\manager
::queue_adhoc_task($removaltask);
1602 // Delete the now empty section, passing in only the section number, which forces the function to fetch a new object.
1603 // The refresh is needed because the section->sequence is now stale.
1604 $result = $format->delete_section($section->section
, $forcedeleteifnotempty);
1606 // Trigger an event for course section deletion.
1608 $context = \context_course
::instance($section->course
);
1609 $event = \core\event\course_section_deleted
::create(
1611 'objectid' => $section->id
,
1612 'courseid' => $section->course
,
1613 'context' => $context,
1615 'sectionnum' => $section->section
,
1616 'sectionname' => $sectionname,
1620 $event->add_record_snapshot('course_sections', $section);
1623 rebuild_course_cache($section->course
, true);
1629 * Updates the course section
1631 * This function does not check permissions or clean values - this has to be done prior to calling it.
1633 * @param int|stdClass $course
1634 * @param stdClass $section record from course_sections table - it will be updated with the new values
1635 * @param array|stdClass $data
1637 function course_update_section($course, $section, $data) {
1640 $courseid = (is_object($course)) ?
$course->id
: (int)$course;
1642 // Some fields can not be updated using this method.
1643 $data = array_diff_key((array)$data, array('id', 'course', 'section', 'sequence'));
1644 $changevisibility = (array_key_exists('visible', $data) && (bool)$data['visible'] != (bool)$section->visible
);
1645 if (array_key_exists('name', $data) && \core_text
::strlen($data['name']) > 255) {
1646 throw new moodle_exception('maximumchars', 'moodle', '', 255);
1649 // Update record in the DB and course format options.
1650 $data['id'] = $section->id
;
1651 $data['timemodified'] = time();
1652 $DB->update_record('course_sections', $data);
1653 rebuild_course_cache($courseid, true);
1654 course_get_format($courseid)->update_section_format_options($data);
1656 // Update fields of the $section object.
1657 foreach ($data as $key => $value) {
1658 if (property_exists($section, $key)) {
1659 $section->$key = $value;
1663 // Trigger an event for course section update.
1664 $event = \core\event\course_section_updated
::create(
1666 'objectid' => $section->id
,
1667 'courseid' => $courseid,
1668 'context' => context_course
::instance($courseid),
1669 'other' => array('sectionnum' => $section->section
)
1674 // If section visibility was changed, hide the modules in this section too.
1675 if ($changevisibility && !empty($section->sequence
)) {
1676 $modules = explode(',', $section->sequence
);
1677 foreach ($modules as $moduleid) {
1678 if ($cm = get_coursemodule_from_id(null, $moduleid, $courseid)) {
1679 if ($data['visible']) {
1680 // As we unhide the section, we use the previously saved visibility stored in visibleold.
1681 set_coursemodule_visible($moduleid, $cm->visibleold
, $cm->visibleoncoursepage
);
1683 // We hide the section, so we hide the module but we store the original state in visibleold.
1684 set_coursemodule_visible($moduleid, 0, $cm->visibleoncoursepage
);
1685 $DB->set_field('course_modules', 'visibleold', $cm->visible
, array('id' => $moduleid));
1687 \core\event\course_module_updated
::create_from_cm($cm)->trigger();
1694 * Checks if the current user can delete a section (if course format allows it and user has proper permissions).
1696 * @param int|stdClass $course
1697 * @param int|stdClass|section_info $section
1700 function course_can_delete_section($course, $section) {
1701 if (is_object($section)) {
1702 $section = $section->section
;
1705 // Not possible to delete 0-section.
1708 // Course format should allow to delete sections.
1709 if (!course_get_format($course)->can_delete_section($section)) {
1712 // Make sure user has capability to update course and move sections.
1713 $context = context_course
::instance(is_object($course) ?
$course->id
: $course);
1714 if (!has_all_capabilities(array('moodle/course:movesections', 'moodle/course:update'), $context)) {
1717 // Make sure user has capability to delete each activity in this section.
1718 $modinfo = get_fast_modinfo($course);
1719 if (!empty($modinfo->sections
[$section])) {
1720 foreach ($modinfo->sections
[$section] as $cmid) {
1721 if (!has_capability('moodle/course:manageactivities', context_module
::instance($cmid))) {
1730 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
1731 * an original position number and a target position number, rebuilds the array so that the
1732 * move is made without any duplication of section positions.
1733 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
1734 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
1736 * @param array $sections
1737 * @param int $origin_position
1738 * @param int $target_position
1741 function reorder_sections($sections, $origin_position, $target_position) {
1742 if (!is_array($sections)) {
1746 // We can't move section position 0
1747 if ($origin_position < 1) {
1748 echo "We can't move section position 0";
1752 // Locate origin section in sections array
1753 if (!$origin_key = array_search($origin_position, $sections)) {
1754 echo "searched position not in sections array";
1755 return false; // searched position not in sections array
1758 // Extract origin section
1759 $origin_section = $sections[$origin_key];
1760 unset($sections[$origin_key]);
1762 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
1764 $append_array = array();
1765 foreach ($sections as $id => $position) {
1767 $append_array[$id] = $position;
1768 unset($sections[$id]);
1770 if ($position == $target_position) {
1771 if ($target_position < $origin_position) {
1772 $append_array[$id] = $position;
1773 unset($sections[$id]);
1779 // Append moved section
1780 $sections[$origin_key] = $origin_section;
1782 // Append rest of array (if applicable)
1783 if (!empty($append_array)) {
1784 foreach ($append_array as $id => $position) {
1785 $sections[$id] = $position;
1789 // Renumber positions
1791 foreach ($sections as $id => $p) {
1792 $sections[$id] = $position;
1801 * Move the module object $mod to the specified $section
1802 * If $beforemod exists then that is the module
1803 * before which $modid should be inserted
1805 * @param stdClass|cm_info $mod
1806 * @param stdClass|section_info $section
1807 * @param int|stdClass $beforemod id or object with field id corresponding to the module
1808 * before which the module needs to be included. Null for inserting in the
1809 * end of the section
1810 * @return int new value for module visibility (0 or 1)
1812 function moveto_module($mod, $section, $beforemod=NULL) {
1813 global $OUTPUT, $DB;
1815 // Current module visibility state - return value of this function.
1816 $modvisible = $mod->visible
;
1818 // Remove original module from original section.
1819 if (! delete_mod_from_section($mod->id
, $mod->section
)) {
1820 echo $OUTPUT->notification("Could not delete module from existing section");
1823 // If moving to a hidden section then hide module.
1824 if ($mod->section
!= $section->id
) {
1825 if (!$section->visible
&& $mod->visible
) {
1826 // Module was visible but must become hidden after moving to hidden section.
1828 set_coursemodule_visible($mod->id
, 0);
1829 // Set visibleold to 1 so module will be visible when section is made visible.
1830 $DB->set_field('course_modules', 'visibleold', 1, array('id' => $mod->id
));
1832 if ($section->visible
&& !$mod->visible
) {
1833 // Hidden module was moved to the visible section, restore the module visibility from visibleold.
1834 set_coursemodule_visible($mod->id
, $mod->visibleold
);
1835 $modvisible = $mod->visibleold
;
1839 // Add the module into the new section.
1840 course_add_cm_to_section($section->course
, $mod->id
, $section->section
, $beforemod);
1845 * Returns the list of all editing actions that current user can perform on the module
1847 * @param cm_info $mod The module to produce editing buttons for
1848 * @param int $indent The current indenting (default -1 means no move left-right actions)
1849 * @param int $sr The section to link back to (used for creating the links)
1850 * @return array array of action_link or pix_icon objects
1852 function course_get_cm_edit_actions(cm_info
$mod, $indent = -1, $sr = null) {
1853 global $COURSE, $SITE, $CFG;
1857 $coursecontext = context_course
::instance($mod->course
);
1858 $modcontext = context_module
::instance($mod->id
);
1859 $courseformat = course_get_format($mod->get_course());
1861 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
1862 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
1864 // No permission to edit anything.
1865 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
1869 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
1872 $str = get_strings(array('delete', 'move', 'moveright', 'moveleft',
1873 'editsettings', 'duplicate', 'modhide', 'makeavailable', 'makeunavailable', 'modshow'), 'moodle');
1874 $str->assign
= get_string('assignroles', 'role');
1875 $str->groupsnone
= get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
1876 $str->groupsseparate
= get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
1877 $str->groupsvisible
= get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
1880 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
1883 $baseurl->param('sr', $sr);
1888 if ($hasmanageactivities) {
1889 $actions['update'] = new action_menu_link_secondary(
1890 new moodle_url($baseurl, array('update' => $mod->id
)),
1891 new pix_icon('t/edit', $str->editsettings
, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1893 array('class' => 'editing_update', 'data-action' => 'update')
1898 if ($hasmanageactivities && $indent >= 0) {
1899 $indentlimits = new stdClass();
1900 $indentlimits->min
= 0;
1901 $indentlimits->max
= 16;
1902 if (right_to_left()) { // Exchange arrows on RTL
1903 $rightarrow = 't/left';
1904 $leftarrow = 't/right';
1906 $rightarrow = 't/right';
1907 $leftarrow = 't/left';
1910 if ($indent >= $indentlimits->max
) {
1911 $enabledclass = 'hidden';
1915 $actions['moveright'] = new action_menu_link_secondary(
1916 new moodle_url($baseurl, array('id' => $mod->id
, 'indent' => '1')),
1917 new pix_icon($rightarrow, $str->moveright
, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1919 array('class' => 'editing_moveright ' . $enabledclass, 'data-action' => 'moveright',
1920 'data-keepopen' => true, 'data-sectionreturn' => $sr)
1923 if ($indent <= $indentlimits->min
) {
1924 $enabledclass = 'hidden';
1928 $actions['moveleft'] = new action_menu_link_secondary(
1929 new moodle_url($baseurl, array('id' => $mod->id
, 'indent' => '-1')),
1930 new pix_icon($leftarrow, $str->moveleft
, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1932 array('class' => 'editing_moveleft ' . $enabledclass, 'data-action' => 'moveleft',
1933 'data-keepopen' => true, 'data-sectionreturn' => $sr)
1938 // Hide/Show/Available/Unavailable.
1939 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
1940 $allowstealth = !empty($CFG->allowstealth
) && $courseformat->allow_stealth_module_visibility($mod, $mod->get_section_info());
1942 $sectionvisible = $mod->get_section_info()->visible
;
1943 // The module on the course page may be in one of the following states:
1944 // - Available and displayed on the course page ($displayedoncoursepage);
1945 // - Not available and not displayed on the course page ($unavailable);
1946 // - Available but not displayed on the course page ($stealth) - this can also be a visible activity in a hidden section.
1947 $displayedoncoursepage = $mod->visible
&& $mod->visibleoncoursepage
&& $sectionvisible;
1948 $unavailable = !$mod->visible
;
1949 $stealth = $mod->visible
&& (!$mod->visibleoncoursepage ||
!$sectionvisible);
1950 if ($displayedoncoursepage) {
1951 $actions['hide'] = new action_menu_link_secondary(
1952 new moodle_url($baseurl, array('hide' => $mod->id
)),
1953 new pix_icon('t/hide', $str->modhide
, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1955 array('class' => 'editing_hide', 'data-action' => 'hide')
1957 } else if (!$displayedoncoursepage && $sectionvisible) {
1958 // Offer to "show" only if the section is visible.
1959 $actions['show'] = new action_menu_link_secondary(
1960 new moodle_url($baseurl, array('show' => $mod->id
)),
1961 new pix_icon('t/show', $str->modshow
, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1963 array('class' => 'editing_show', 'data-action' => 'show')
1968 // When making the "stealth" module unavailable we perform the same action as hiding the visible module.
1969 $actions['hide'] = new action_menu_link_secondary(
1970 new moodle_url($baseurl, array('hide' => $mod->id
)),
1971 new pix_icon('t/unblock', $str->makeunavailable
, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1972 $str->makeunavailable
,
1973 array('class' => 'editing_makeunavailable', 'data-action' => 'hide', 'data-sectionreturn' => $sr)
1975 } else if ($unavailable && (!$sectionvisible ||
$allowstealth) && $mod->has_view()) {
1976 // Allow to make visually hidden module available in gradebook and other reports by making it a "stealth" module.
1977 // When the section is hidden it is an equivalent of "showing" the module.
1978 // Activities without the link (i.e. labels) can not be made available but hidden on course page.
1979 $action = $sectionvisible ?
'stealth' : 'show';
1980 $actions[$action] = new action_menu_link_secondary(
1981 new moodle_url($baseurl, array($action => $mod->id
)),
1982 new pix_icon('t/block', $str->makeavailable
, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1983 $str->makeavailable
,
1984 array('class' => 'editing_makeavailable', 'data-action' => $action, 'data-sectionreturn' => $sr)
1989 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
1990 if (has_all_capabilities($dupecaps, $coursecontext) &&
1991 plugin_supports('mod', $mod->modname
, FEATURE_BACKUP_MOODLE2
) &&
1992 course_allowed_module($mod->get_course(), $mod->modname
)) {
1993 $actions['duplicate'] = new action_menu_link_secondary(
1994 new moodle_url($baseurl, array('duplicate' => $mod->id
)),
1995 new pix_icon('t/copy', $str->duplicate
, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1997 array('class' => 'editing_duplicate', 'data-action' => 'duplicate', 'data-sectionreturn' => $sr)
2002 if ($hasmanageactivities && !$mod->coursegroupmodeforce
) {
2003 if (plugin_supports('mod', $mod->modname
, FEATURE_GROUPS
, 0)) {
2004 if ($mod->effectivegroupmode
== SEPARATEGROUPS
) {
2005 $nextgroupmode = VISIBLEGROUPS
;
2006 $grouptitle = $str->groupsseparate
;
2007 $actionname = 'groupsseparate';
2008 $nextactionname = 'groupsvisible';
2009 $groupimage = 'i/groups';
2010 } else if ($mod->effectivegroupmode
== VISIBLEGROUPS
) {
2011 $nextgroupmode = NOGROUPS
;
2012 $grouptitle = $str->groupsvisible
;
2013 $actionname = 'groupsvisible';
2014 $nextactionname = 'groupsnone';
2015 $groupimage = 'i/groupv';
2017 $nextgroupmode = SEPARATEGROUPS
;
2018 $grouptitle = $str->groupsnone
;
2019 $actionname = 'groupsnone';
2020 $nextactionname = 'groupsseparate';
2021 $groupimage = 'i/groupn';
2024 $actions[$actionname] = new action_menu_link_primary(
2025 new moodle_url($baseurl, array('id' => $mod->id
, 'groupmode' => $nextgroupmode)),
2026 new pix_icon($groupimage, $grouptitle, 'moodle', array('class' => 'iconsmall')),
2028 array('class' => 'editing_'. $actionname, 'data-action' => $nextactionname,
2029 'aria-live' => 'assertive', 'data-sectionreturn' => $sr)
2032 $actions['nogroupsupport'] = new action_menu_filler();
2037 if (has_capability('moodle/role:assign', $modcontext)){
2038 $actions['assign'] = new action_menu_link_secondary(
2039 new moodle_url('/admin/roles/assign.php', array('contextid' => $modcontext->id
)),
2040 new pix_icon('t/assignroles', $str->assign
, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2042 array('class' => 'editing_assign', 'data-action' => 'assignroles', 'data-sectionreturn' => $sr)
2047 if ($hasmanageactivities) {
2048 $actions['delete'] = new action_menu_link_secondary(
2049 new moodle_url($baseurl, array('delete' => $mod->id
)),
2050 new pix_icon('t/delete', $str->delete
, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2052 array('class' => 'editing_delete', 'data-action' => 'delete', 'data-sectionreturn' => $sr)
2060 * Returns the move action.
2062 * @param cm_info $mod The module to produce a move button for
2063 * @param int $sr The section to link back to (used for creating the links)
2064 * @return The markup for the move action, or an empty string if not available.
2066 function course_get_cm_move(cm_info
$mod, $sr = null) {
2072 $modcontext = context_module
::instance($mod->id
);
2073 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
2076 $str = get_strings(array('move'));
2079 if (!isset($baseurl)) {
2080 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
2083 $baseurl->param('sr', $sr);
2087 if ($hasmanageactivities) {
2088 $pixicon = 'i/dragdrop';
2090 if (!course_ajax_enabled($mod->get_course())) {
2091 // Override for course frontpage until we get drag/drop working there.
2092 $pixicon = 't/move';
2095 return html_writer
::link(
2096 new moodle_url($baseurl, array('copy' => $mod->id
)),
2097 $OUTPUT->pix_icon($pixicon, $str->move
, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2098 array('class' => 'editing_move', 'data-action' => 'move', 'data-sectionreturn' => $sr)
2105 * given a course object with shortname & fullname, this function will
2106 * truncate the the number of chars allowed and add ... if it was too long
2108 function course_format_name ($course,$max=100) {
2110 $context = context_course
::instance($course->id
);
2111 $shortname = format_string($course->shortname
, true, array('context' => $context));
2112 $fullname = format_string($course->fullname
, true, array('context' => context_course
::instance($course->id
)));
2113 $str = $shortname.': '. $fullname;
2114 if (core_text
::strlen($str) <= $max) {
2118 return core_text
::substr($str,0,$max-3).'...';
2123 * Is the user allowed to add this type of module to this course?
2124 * @param object $course the course settings. Only $course->id is used.
2125 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
2126 * @return bool whether the current user is allowed to add this type of module to this course.
2128 function course_allowed_module($course, $modname) {
2129 if (is_numeric($modname)) {
2130 throw new coding_exception('Function course_allowed_module no longer
2131 supports numeric module ids. Please update your code to pass the module name.');
2134 $capability = 'mod/' . $modname . ':addinstance';
2135 if (!get_capability_info($capability)) {
2136 // Debug warning that the capability does not exist, but no more than once per page.
2137 static $warned = array();
2138 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE
, MOD_ARCHETYPE_OTHER
);
2139 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM
) {
2140 debugging('The module ' . $modname . ' does not define the standard capability ' .
2141 $capability , DEBUG_DEVELOPER
);
2142 $warned[$modname] = 1;
2145 // If the capability does not exist, the module can always be added.
2149 $coursecontext = context_course
::instance($course->id
);
2150 return has_capability($capability, $coursecontext);
2154 * Efficiently moves many courses around while maintaining
2155 * sortorder in order.
2157 * @param array $courseids is an array of course ids
2158 * @param int $categoryid
2159 * @return bool success
2161 function move_courses($courseids, $categoryid) {
2164 if (empty($courseids)) {
2169 if (!$category = $DB->get_record('course_categories', array('id' => $categoryid))) {
2173 $courseids = array_reverse($courseids);
2174 $newparent = context_coursecat
::instance($category->id
);
2177 list($where, $params) = $DB->get_in_or_equal($courseids);
2178 $dbcourses = $DB->get_records_select('course', 'id ' . $where, $params, '', 'id, category, shortname, fullname');
2179 foreach ($dbcourses as $dbcourse) {
2180 $course = new stdClass();
2181 $course->id
= $dbcourse->id
;
2182 $course->category
= $category->id
;
2183 $course->sortorder
= $category->sortorder + MAX_COURSES_IN_CATEGORY
- $i++
;
2184 if ($category->visible
== 0) {
2185 // Hide the course when moving into hidden category, do not update the visibleold flag - we want to get
2186 // to previous state if somebody unhides the category.
2187 $course->visible
= 0;
2190 $DB->update_record('course', $course);
2192 // Update context, so it can be passed to event.
2193 $context = context_course
::instance($course->id
);
2194 $context->update_moved($newparent);
2196 // Trigger a course updated event.
2197 $event = \core\event\course_updated
::create(array(
2198 'objectid' => $course->id
,
2199 'context' => context_course
::instance($course->id
),
2200 'other' => array('shortname' => $dbcourse->shortname
,
2201 'fullname' => $dbcourse->fullname
)
2203 $event->set_legacy_logdata(array($course->id
, 'course', 'move', 'edit.php?id=' . $course->id
, $course->id
));
2206 fix_course_sortorder();
2207 cache_helper
::purge_by_event('changesincourse');
2213 * Returns the display name of the given section that the course prefers
2215 * Implementation of this function is provided by course format
2216 * @see format_base::get_section_name()
2218 * @param int|stdClass $courseorid The course to get the section name for (object or just course id)
2219 * @param int|stdClass $section Section object from database or just field course_sections.section
2220 * @return string Display name that the course format prefers, e.g. "Week 2"
2222 function get_section_name($courseorid, $section) {
2223 return course_get_format($courseorid)->get_section_name($section);
2227 * Tells if current course format uses sections
2229 * @param string $format Course format ID e.g. 'weeks' $course->format
2232 function course_format_uses_sections($format) {
2233 $course = new stdClass();
2234 $course->format
= $format;
2235 return course_get_format($course)->uses_sections();
2239 * Returns the information about the ajax support in the given source format
2241 * The returned object's property (boolean)capable indicates that
2242 * the course format supports Moodle course ajax features.
2244 * @param string $format
2247 function course_format_ajax_support($format) {
2248 $course = new stdClass();
2249 $course->format
= $format;
2250 return course_get_format($course)->supports_ajax();
2254 * Can the current user delete this course?
2255 * Course creators have exception,
2256 * 1 day after the creation they can sill delete the course.
2257 * @param int $courseid
2260 function can_delete_course($courseid) {
2263 $context = context_course
::instance($courseid);
2265 if (has_capability('moodle/course:delete', $context)) {
2269 // hack: now try to find out if creator created this course recently (1 day)
2270 if (!has_capability('moodle/course:create', $context)) {
2274 $since = time() - 60*60*24;
2275 $course = get_course($courseid);
2277 if ($course->timecreated
< $since) {
2278 return false; // Return if the course was not created in last 24 hours.
2281 $logmanger = get_log_manager();
2282 $readers = $logmanger->get_readers('\core\log\sql_reader');
2283 $reader = reset($readers);
2285 if (empty($reader)) {
2286 return false; // No log reader found.
2290 $select = "userid = :userid AND courseid = :courseid AND eventname = :eventname AND timecreated > :since";
2291 $params = array('userid' => $USER->id
, 'since' => $since, 'courseid' => $course->id
, 'eventname' => '\core\event\course_created');
2293 return (bool)$reader->get_events_select_count($select, $params);
2297 * Save the Your name for 'Some role' strings.
2299 * @param integer $courseid the id of this course.
2300 * @param array $data the data that came from the course settings form.
2302 function save_local_role_names($courseid, $data) {
2304 $context = context_course
::instance($courseid);
2306 foreach ($data as $fieldname => $value) {
2307 if (strpos($fieldname, 'role_') !== 0) {
2310 list($ignored, $roleid) = explode('_', $fieldname);
2312 // make up our mind whether we want to delete, update or insert
2314 $DB->delete_records('role_names', array('contextid' => $context->id
, 'roleid' => $roleid));
2316 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id
, 'roleid' => $roleid))) {
2317 $rolename->name
= $value;
2318 $DB->update_record('role_names', $rolename);
2321 $rolename = new stdClass
;
2322 $rolename->contextid
= $context->id
;
2323 $rolename->roleid
= $roleid;
2324 $rolename->name
= $value;
2325 $DB->insert_record('role_names', $rolename);
2327 // This will ensure the course contacts cache is purged..
2328 core_course_category
::role_assignment_changed($roleid, $context);
2333 * Returns options to use in course overviewfiles filemanager
2335 * @param null|stdClass|core_course_list_element|int $course either object that has 'id' property or just the course id;
2336 * may be empty if course does not exist yet (course create form)
2337 * @return array|null array of options such as maxfiles, maxbytes, accepted_types, etc.
2338 * or null if overviewfiles are disabled
2340 function course_overviewfiles_options($course) {
2342 if (empty($CFG->courseoverviewfileslimit
)) {
2345 $accepted_types = preg_split('/\s*,\s*/', trim($CFG->courseoverviewfilesext
), -1, PREG_SPLIT_NO_EMPTY
);
2346 if (in_array('*', $accepted_types) ||
empty($accepted_types)) {
2347 $accepted_types = '*';
2349 // Since config for $CFG->courseoverviewfilesext is a text box, human factor must be considered.
2350 // Make sure extensions are prefixed with dot unless they are valid typegroups
2351 foreach ($accepted_types as $i => $type) {
2352 if (substr($type, 0, 1) !== '.') {
2353 require_once($CFG->libdir
. '/filelib.php');
2354 if (!count(file_get_typegroup('extension', $type))) {
2355 // It does not start with dot and is not a valid typegroup, this is most likely extension.
2356 $accepted_types[$i] = '.'. $type;
2361 if (!empty($corrected)) {
2362 set_config('courseoverviewfilesext', join(',', $accepted_types));
2366 'maxfiles' => $CFG->courseoverviewfileslimit
,
2367 'maxbytes' => $CFG->maxbytes
,
2369 'accepted_types' => $accepted_types
2371 if (!empty($course->id
)) {
2372 $options['context'] = context_course
::instance($course->id
);
2373 } else if (is_int($course) && $course > 0) {
2374 $options['context'] = context_course
::instance($course);
2380 * Create a course and either return a $course object
2382 * Please note this functions does not verify any access control,
2383 * the calling code is responsible for all validation (usually it is the form definition).
2385 * @param array $editoroptions course description editor options
2386 * @param object $data - all the data needed for an entry in the 'course' table
2387 * @return object new course instance
2389 function create_course($data, $editoroptions = NULL) {
2392 //check the categoryid - must be given for all new courses
2393 $category = $DB->get_record('course_categories', array('id'=>$data->category
), '*', MUST_EXIST
);
2395 // Check if the shortname already exists.
2396 if (!empty($data->shortname
)) {
2397 if ($DB->record_exists('course', array('shortname' => $data->shortname
))) {
2398 throw new moodle_exception('shortnametaken', '', '', $data->shortname
);
2402 // Check if the idnumber already exists.
2403 if (!empty($data->idnumber
)) {
2404 if ($DB->record_exists('course', array('idnumber' => $data->idnumber
))) {
2405 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber
);
2409 if ($errorcode = course_validate_dates((array)$data)) {
2410 throw new moodle_exception($errorcode);
2413 // Check if timecreated is given.
2414 $data->timecreated
= !empty($data->timecreated
) ?
$data->timecreated
: time();
2415 $data->timemodified
= $data->timecreated
;
2417 // place at beginning of any category
2418 $data->sortorder
= 0;
2420 if ($editoroptions) {
2421 // summary text is updated later, we need context to store the files first
2422 $data->summary
= '';
2423 $data->summary_format
= FORMAT_HTML
;
2426 if (!isset($data->visible
)) {
2427 // data not from form, add missing visibility info
2428 $data->visible
= $category->visible
;
2430 $data->visibleold
= $data->visible
;
2432 $newcourseid = $DB->insert_record('course', $data);
2433 $context = context_course
::instance($newcourseid, MUST_EXIST
);
2435 if ($editoroptions) {
2436 // Save the files used in the summary editor and store
2437 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2438 $DB->set_field('course', 'summary', $data->summary
, array('id'=>$newcourseid));
2439 $DB->set_field('course', 'summaryformat', $data->summary_format
, array('id'=>$newcourseid));
2441 if ($overviewfilesoptions = course_overviewfiles_options($newcourseid)) {
2442 // Save the course overviewfiles
2443 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2446 // update course format options
2447 course_get_format($newcourseid)->update_course_format_options($data);
2449 $course = course_get_format($newcourseid)->get_course();
2451 fix_course_sortorder();
2452 // purge appropriate caches in case fix_course_sortorder() did not change anything
2453 cache_helper
::purge_by_event('changesincourse');
2455 // Trigger a course created event.
2456 $event = \core\event\course_created
::create(array(
2457 'objectid' => $course->id
,
2458 'context' => context_course
::instance($course->id
),
2459 'other' => array('shortname' => $course->shortname
,
2460 'fullname' => $course->fullname
)
2466 blocks_add_default_course_blocks($course);
2468 // Create default section and initial sections if specified (unless they've already been created earlier).
2469 // We do not want to call course_create_sections_if_missing() because to avoid creating course cache.
2470 $numsections = isset($data->numsections
) ?
$data->numsections
: 0;
2471 $existingsections = $DB->get_fieldset_sql('SELECT section from {course_sections} WHERE course = ?', [$newcourseid]);
2472 $newsections = array_diff(range(0, $numsections), $existingsections);
2473 foreach ($newsections as $sectionnum) {
2474 course_create_section($newcourseid, $sectionnum, true);
2477 // Save any custom role names.
2478 save_local_role_names($course->id
, (array)$data);
2480 // set up enrolments
2481 enrol_course_updated(true, $course, $data);
2483 // Update course tags.
2484 if (isset($data->tags
)) {
2485 core_tag_tag
::set_item_tags('core', 'course', $course->id
, context_course
::instance($course->id
), $data->tags
);
2494 * Please note this functions does not verify any access control,
2495 * the calling code is responsible for all validation (usually it is the form definition).
2497 * @param object $data - all the data needed for an entry in the 'course' table
2498 * @param array $editoroptions course description editor options
2501 function update_course($data, $editoroptions = NULL) {
2504 $data->timemodified
= time();
2506 // Prevent changes on front page course.
2507 if ($data->id
== SITEID
) {
2508 throw new moodle_exception('invalidcourse', 'error');
2511 $oldcourse = course_get_format($data->id
)->get_course();
2512 $context = context_course
::instance($oldcourse->id
);
2514 if ($editoroptions) {
2515 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2517 if ($overviewfilesoptions = course_overviewfiles_options($data->id
)) {
2518 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2521 // Check we don't have a duplicate shortname.
2522 if (!empty($data->shortname
) && $oldcourse->shortname
!= $data->shortname
) {
2523 if ($DB->record_exists_sql('SELECT id from {course} WHERE shortname = ? AND id <> ?', array($data->shortname
, $data->id
))) {
2524 throw new moodle_exception('shortnametaken', '', '', $data->shortname
);
2528 // Check we don't have a duplicate idnumber.
2529 if (!empty($data->idnumber
) && $oldcourse->idnumber
!= $data->idnumber
) {
2530 if ($DB->record_exists_sql('SELECT id from {course} WHERE idnumber = ? AND id <> ?', array($data->idnumber
, $data->id
))) {
2531 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber
);
2535 if ($errorcode = course_validate_dates((array)$data)) {
2536 throw new moodle_exception($errorcode);
2539 if (!isset($data->category
) or empty($data->category
)) {
2540 // prevent nulls and 0 in category field
2541 unset($data->category
);
2543 $changesincoursecat = $movecat = (isset($data->category
) and $oldcourse->category
!= $data->category
);
2545 if (!isset($data->visible
)) {
2546 // data not from form, add missing visibility info
2547 $data->visible
= $oldcourse->visible
;
2550 if ($data->visible
!= $oldcourse->visible
) {
2551 // reset the visibleold flag when manually hiding/unhiding course
2552 $data->visibleold
= $data->visible
;
2553 $changesincoursecat = true;
2556 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category
));
2557 if (empty($newcategory->visible
)) {
2558 // make sure when moving into hidden category the course is hidden automatically
2564 // Set newsitems to 0 if format does not support announcements.
2565 if (isset($data->format
)) {
2566 $newcourseformat = course_get_format((object)['format' => $data->format
]);
2567 if (!$newcourseformat->supports_news()) {
2568 $data->newsitems
= 0;
2572 // Update with the new data
2573 $DB->update_record('course', $data);
2574 // make sure the modinfo cache is reset
2575 rebuild_course_cache($data->id
);
2577 // update course format options with full course data
2578 course_get_format($data->id
)->update_course_format_options($data, $oldcourse);
2580 $course = $DB->get_record('course', array('id'=>$data->id
));
2583 $newparent = context_coursecat
::instance($course->category
);
2584 $context->update_moved($newparent);
2586 $fixcoursesortorder = $movecat ||
(isset($data->sortorder
) && ($oldcourse->sortorder
!= $data->sortorder
));
2587 if ($fixcoursesortorder) {
2588 fix_course_sortorder();
2591 // purge appropriate caches in case fix_course_sortorder() did not change anything
2592 cache_helper
::purge_by_event('changesincourse');
2593 if ($changesincoursecat) {
2594 cache_helper
::purge_by_event('changesincoursecat');
2597 // Test for and remove blocks which aren't appropriate anymore
2598 blocks_remove_inappropriate($course);
2600 // Save any custom role names.
2601 save_local_role_names($course->id
, $data);
2603 // update enrol settings
2604 enrol_course_updated(false, $course, $data);
2606 // Update course tags.
2607 if (isset($data->tags
)) {
2608 core_tag_tag
::set_item_tags('core', 'course', $course->id
, context_course
::instance($course->id
), $data->tags
);
2611 // Trigger a course updated event.
2612 $event = \core\event\course_updated
::create(array(
2613 'objectid' => $course->id
,
2614 'context' => context_course
::instance($course->id
),
2615 'other' => array('shortname' => $course->shortname
,
2616 'fullname' => $course->fullname
)
2619 $event->set_legacy_logdata(array($course->id
, 'course', 'update', 'edit.php?id=' . $course->id
, $course->id
));
2622 if ($oldcourse->format
!== $course->format
) {
2623 // Remove all options stored for the previous format
2624 // We assume that new course format migrated everything it needed watching trigger
2625 // 'course_updated' and in method format_XXX::update_course_format_options()
2626 $DB->delete_records('course_format_options',
2627 array('courseid' => $course->id
, 'format' => $oldcourse->format
));
2632 * Average number of participants
2635 function average_number_of_participants() {
2638 //count total of enrolments for visible course (except front page)
2639 $sql = 'SELECT COUNT(*) FROM (
2640 SELECT DISTINCT ue.userid, e.courseid
2641 FROM {user_enrolments} ue, {enrol} e, {course} c
2642 WHERE ue.enrolid = e.id
2643 AND e.courseid <> :siteid
2644 AND c.id = e.courseid
2645 AND c.visible = 1) total';
2646 $params = array('siteid' => $SITE->id
);
2647 $enrolmenttotal = $DB->count_records_sql($sql, $params);
2650 //count total of visible courses (minus front page)
2651 $coursetotal = $DB->count_records('course', array('visible' => 1));
2652 $coursetotal = $coursetotal - 1 ;
2654 //average of enrolment
2655 if (empty($coursetotal)) {
2656 $participantaverage = 0;
2658 $participantaverage = $enrolmenttotal / $coursetotal;
2661 return $participantaverage;
2665 * Average number of course modules
2668 function average_number_of_courses_modules() {
2671 //count total of visible course module (except front page)
2672 $sql = 'SELECT COUNT(*) FROM (
2673 SELECT cm.course, cm.module
2674 FROM {course} c, {course_modules} cm
2675 WHERE c.id = cm.course
2678 AND c.visible = 1) total';
2679 $params = array('siteid' => $SITE->id
);
2680 $moduletotal = $DB->count_records_sql($sql, $params);
2683 //count total of visible courses (minus front page)
2684 $coursetotal = $DB->count_records('course', array('visible' => 1));
2685 $coursetotal = $coursetotal - 1 ;
2687 //average of course module
2688 if (empty($coursetotal)) {
2689 $coursemoduleaverage = 0;
2691 $coursemoduleaverage = $moduletotal / $coursetotal;
2694 return $coursemoduleaverage;
2698 * This class pertains to course requests and contains methods associated with
2699 * create, approving, and removing course requests.
2701 * Please note we do not allow embedded images here because there is no context
2702 * to store them with proper access control.
2704 * @copyright 2009 Sam Hemelryk
2705 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2708 * @property-read int $id
2709 * @property-read string $fullname
2710 * @property-read string $shortname
2711 * @property-read string $summary
2712 * @property-read int $summaryformat
2713 * @property-read int $summarytrust
2714 * @property-read string $reason
2715 * @property-read int $requester
2717 class course_request
{
2720 * This is the stdClass that stores the properties for the course request
2721 * and is externally accessed through the __get magic method
2724 protected $properties;
2727 * An array of options for the summary editor used by course request forms.
2728 * This is initially set by {@link summary_editor_options()}
2732 protected static $summaryeditoroptions;
2735 * Static function to prepare the summary editor for working with a course
2739 * @param null|stdClass $data Optional, an object containing the default values
2740 * for the form, these may be modified when preparing the
2741 * editor so this should be called before creating the form
2742 * @return stdClass An object that can be used to set the default values for
2745 public static function prepare($data=null) {
2746 if ($data === null) {
2747 $data = new stdClass
;
2749 $data = file_prepare_standard_editor($data, 'summary', self
::summary_editor_options());
2754 * Static function to create a new course request when passed an array of properties
2757 * This function also handles saving any files that may have been used in the editor
2760 * @param stdClass $data
2761 * @return course_request The newly created course request
2763 public static function create($data) {
2764 global $USER, $DB, $CFG;
2765 $data->requester
= $USER->id
;
2767 // Setting the default category if none set.
2768 if (empty($data->category
) ||
empty($CFG->requestcategoryselection
)) {
2769 $data->category
= $CFG->defaultrequestcategory
;
2772 // Summary is a required field so copy the text over
2773 $data->summary
= $data->summary_editor
['text'];
2774 $data->summaryformat
= $data->summary_editor
['format'];
2776 $data->id
= $DB->insert_record('course_request', $data);
2778 // Create a new course_request object and return it
2779 $request = new course_request($data);
2781 // Notify the admin if required.
2782 if ($users = get_users_from_config($CFG->courserequestnotify
, 'moodle/site:approvecourse')) {
2785 $a->link
= "$CFG->wwwroot/course/pending.php";
2786 $a->user
= fullname($USER);
2787 $subject = get_string('courserequest');
2788 $message = get_string('courserequestnotifyemail', 'admin', $a);
2789 foreach ($users as $user) {
2790 $request->notify($user, $USER, 'courserequested', $subject, $message);
2798 * Returns an array of options to use with a summary editor
2800 * @uses course_request::$summaryeditoroptions
2801 * @return array An array of options to use with the editor
2803 public static function summary_editor_options() {
2805 if (self
::$summaryeditoroptions === null) {
2806 self
::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
2808 return self
::$summaryeditoroptions;
2812 * Loads the properties for this course request object. Id is required and if
2813 * only id is provided then we load the rest of the properties from the database
2815 * @param stdClass|int $properties Either an object containing properties
2816 * or the course_request id to load
2818 public function __construct($properties) {
2820 if (empty($properties->id
)) {
2821 if (empty($properties)) {
2822 throw new coding_exception('You must provide a course request id when creating a course_request object');
2825 $properties = new stdClass
;
2826 $properties->id
= (int)$id;
2829 if (empty($properties->requester
)) {
2830 if (!($this->properties
= $DB->get_record('course_request', array('id' => $properties->id
)))) {
2831 print_error('unknowncourserequest');
2834 $this->properties
= $properties;
2836 $this->properties
->collision
= null;
2840 * Returns the requested property
2842 * @param string $key
2845 public function __get($key) {
2846 return $this->properties
->$key;
2850 * Override this to ensure empty($request->blah) calls return a reliable answer...
2852 * This is required because we define the __get method
2855 * @return bool True is it not empty, false otherwise
2857 public function __isset($key) {
2858 return (!empty($this->properties
->$key));
2862 * Returns the user who requested this course
2864 * Uses a static var to cache the results and cut down the number of db queries
2866 * @staticvar array $requesters An array of cached users
2867 * @return stdClass The user who requested the course
2869 public function get_requester() {
2871 static $requesters= array();
2872 if (!array_key_exists($this->properties
->requester
, $requesters)) {
2873 $requesters[$this->properties
->requester
] = $DB->get_record('user', array('id'=>$this->properties
->requester
));
2875 return $requesters[$this->properties
->requester
];
2879 * Checks that the shortname used by the course does not conflict with any other
2880 * courses that exist
2882 * @param string|null $shortnamemark The string to append to the requests shortname
2883 * should a conflict be found
2884 * @return bool true is there is a conflict, false otherwise
2886 public function check_shortname_collision($shortnamemark = '[*]') {
2889 if ($this->properties
->collision
!== null) {
2890 return $this->properties
->collision
;
2893 if (empty($this->properties
->shortname
)) {
2894 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER
);
2895 $this->properties
->collision
= false;
2896 } else if ($DB->record_exists('course', array('shortname' => $this->properties
->shortname
))) {
2897 if (!empty($shortnamemark)) {
2898 $this->properties
->shortname
.= ' '.$shortnamemark;
2900 $this->properties
->collision
= true;
2902 $this->properties
->collision
= false;
2904 return $this->properties
->collision
;
2908 * Returns the category where this course request should be created
2910 * Note that we don't check here that user has a capability to view
2911 * hidden categories if he has capabilities 'moodle/site:approvecourse' and
2912 * 'moodle/course:changecategory'
2914 * @return core_course_category
2916 public function get_category() {
2918 // If the category is not set, if the current user does not have the rights to change the category, or if the
2919 // category does not exist, we set the default category to the course to be approved.
2920 // The system level is used because the capability moodle/site:approvecourse is based on a system level.
2921 if (empty($this->properties
->category
) ||
!has_capability('moodle/course:changecategory', context_system
::instance()) ||
2922 (!$category = core_course_category
::get($this->properties
->category
, IGNORE_MISSING
, true))) {
2923 $category = core_course_category
::get($CFG->defaultrequestcategory
, IGNORE_MISSING
, true);
2926 $category = core_course_category
::get_default();
2932 * This function approves the request turning it into a course
2934 * This function converts the course request into a course, at the same time
2935 * transferring any files used in the summary to the new course and then removing
2936 * the course request and the files associated with it.
2938 * @return int The id of the course that was created from this request
2940 public function approve() {
2941 global $CFG, $DB, $USER;
2943 require_once($CFG->dirroot
. '/backup/util/includes/restore_includes.php');
2945 $user = $DB->get_record('user', array('id' => $this->properties
->requester
, 'deleted'=>0), '*', MUST_EXIST
);
2947 $courseconfig = get_config('moodlecourse');
2949 // Transfer appropriate settings
2950 $data = clone($this->properties
);
2952 unset($data->reason
);
2953 unset($data->requester
);
2956 $category = $this->get_category();
2957 $data->category
= $category->id
;
2958 // Set misc settings
2959 $data->requested
= 1;
2961 // Apply course default settings
2962 $data->format
= $courseconfig->format
;
2963 $data->newsitems
= $courseconfig->newsitems
;
2964 $data->showgrades
= $courseconfig->showgrades
;
2965 $data->showreports
= $courseconfig->showreports
;
2966 $data->maxbytes
= $courseconfig->maxbytes
;
2967 $data->groupmode
= $courseconfig->groupmode
;
2968 $data->groupmodeforce
= $courseconfig->groupmodeforce
;
2969 $data->visible
= $courseconfig->visible
;
2970 $data->visibleold
= $data->visible
;
2971 $data->lang
= $courseconfig->lang
;
2972 $data->enablecompletion
= $courseconfig->enablecompletion
;
2973 $data->numsections
= $courseconfig->numsections
;
2974 $data->startdate
= usergetmidnight(time());
2975 if ($courseconfig->courseenddateenabled
) {
2976 $data->enddate
= usergetmidnight(time()) +
$courseconfig->courseduration
;
2979 list($data->fullname
, $data->shortname
) = restore_dbops
::calculate_course_names(0, $data->fullname
, $data->shortname
);
2981 $course = create_course($data);
2982 $context = context_course
::instance($course->id
, MUST_EXIST
);
2984 // add enrol instances
2985 if (!$DB->record_exists('enrol', array('courseid'=>$course->id
, 'enrol'=>'manual'))) {
2986 if ($manual = enrol_get_plugin('manual')) {
2987 $manual->add_default_instance($course);
2991 // enrol the requester as teacher if necessary
2992 if (!empty($CFG->creatornewroleid
) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
2993 enrol_try_internal_enrol($course->id
, $user->id
, $CFG->creatornewroleid
);
2998 $a = new stdClass();
2999 $a->name
= format_string($course->fullname
, true, array('context' => context_course
::instance($course->id
)));
3000 $a->url
= $CFG->wwwroot
.'/course/view.php?id=' . $course->id
;
3001 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a), $course->id
);
3007 * Reject a course request
3009 * This function rejects a course request, emailing the requesting user the
3010 * provided notice and then removing the request from the database
3012 * @param string $notice The message to display to the user
3014 public function reject($notice) {
3016 $user = $DB->get_record('user', array('id' => $this->properties
->requester
), '*', MUST_EXIST
);
3017 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
3022 * Deletes the course request and any associated files
3024 public function delete() {
3026 $DB->delete_records('course_request', array('id' => $this->properties
->id
));
3030 * Send a message from one user to another using events_trigger
3032 * @param object $touser
3033 * @param object $fromuser
3034 * @param string $name
3035 * @param string $subject
3036 * @param string $message
3037 * @param int|null $courseid
3039 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message, $courseid = null) {
3040 $eventdata = new \core\message\
message();
3041 $eventdata->courseid
= empty($courseid) ? SITEID
: $courseid;
3042 $eventdata->component
= 'moodle';
3043 $eventdata->name
= $name;
3044 $eventdata->userfrom
= $fromuser;
3045 $eventdata->userto
= $touser;
3046 $eventdata->subject
= $subject;
3047 $eventdata->fullmessage
= $message;
3048 $eventdata->fullmessageformat
= FORMAT_PLAIN
;
3049 $eventdata->fullmessagehtml
= '';
3050 $eventdata->smallmessage
= '';
3051 $eventdata->notification
= 1;
3052 message_send($eventdata);
3057 * Return a list of page types
3058 * @param string $pagetype current page type
3059 * @param context $parentcontext Block's parent context
3060 * @param context $currentcontext Current context of block
3061 * @return array array of page types
3063 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
3064 if ($pagetype === 'course-index' ||
$pagetype === 'course-index-category') {
3065 // For courses and categories browsing pages (/course/index.php) add option to show on ANY category page
3066 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
3067 'course-index-*' => get_string('page-course-index-x', 'pagetype'),
3069 } else if ($currentcontext && (!($coursecontext = $currentcontext->get_course_context(false)) ||
$coursecontext->instanceid
== SITEID
)) {
3070 // We know for sure that despite pagetype starts with 'course-' this is not a page in course context (i.e. /course/search.php, etc.)
3071 $pagetypes = array('*' => get_string('page-x', 'pagetype'));
3073 // Otherwise consider it a page inside a course even if $currentcontext is null
3074 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
3075 'course-*' => get_string('page-course-x', 'pagetype'),
3076 'course-view-*' => get_string('page-course-view-x', 'pagetype')
3083 * Determine whether course ajax should be enabled for the specified course
3085 * @param stdClass $course The course to test against
3086 * @return boolean Whether course ajax is enabled or note
3088 function course_ajax_enabled($course) {
3089 global $CFG, $PAGE, $SITE;
3091 // The user must be editing for AJAX to be included
3092 if (!$PAGE->user_is_editing()) {
3096 // Check that the theme suports
3097 if (!$PAGE->theme
->enablecourseajax
) {
3101 // Check that the course format supports ajax functionality
3102 // The site 'format' doesn't have information on course format support
3103 if ($SITE->id
!== $course->id
) {
3104 $courseformatajaxsupport = course_format_ajax_support($course->format
);
3105 if (!$courseformatajaxsupport->capable
) {
3110 // All conditions have been met so course ajax should be enabled
3115 * Include the relevant javascript and language strings for the resource
3116 * toolbox YUI module
3118 * @param integer $id The ID of the course being applied to
3119 * @param array $usedmodules An array containing the names of the modules in use on the page
3120 * @param array $enabledmodules An array containing the names of the enabled (visible) modules on this site
3121 * @param stdClass $config An object containing configuration parameters for ajax modules including:
3122 * * resourceurl The URL to post changes to for resource changes
3123 * * sectionurl The URL to post changes to for section changes
3124 * * pageparams Additional parameters to pass through in the post
3127 function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) {
3128 global $CFG, $PAGE, $SITE;
3130 // Ensure that ajax should be included
3131 if (!course_ajax_enabled($course)) {
3136 $config = new stdClass();
3139 // The URL to use for resource changes
3140 if (!isset($config->resourceurl
)) {
3141 $config->resourceurl
= '/course/rest.php';
3144 // The URL to use for section changes
3145 if (!isset($config->sectionurl
)) {
3146 $config->sectionurl
= '/course/rest.php';
3149 // Any additional parameters which need to be included on page submission
3150 if (!isset($config->pageparams
)) {
3151 $config->pageparams
= array();
3154 // Include course dragdrop
3155 if (course_format_uses_sections($course->format
)) {
3156 $PAGE->requires
->yui_module('moodle-course-dragdrop', 'M.course.init_section_dragdrop',
3158 'courseid' => $course->id
,
3159 'ajaxurl' => $config->sectionurl
,
3160 'config' => $config,
3163 $PAGE->requires
->yui_module('moodle-course-dragdrop', 'M.course.init_resource_dragdrop',
3165 'courseid' => $course->id
,
3166 'ajaxurl' => $config->resourceurl
,
3167 'config' => $config,
3171 // Require various strings for the command toolbox
3172 $PAGE->requires
->strings_for_js(array(
3175 'deletechecktypename',
3177 'edittitleinstructions',
3185 'clicktochangeinbrackets',
3190 'movecoursesection',
3193 'emptydragdropregion',
3199 // Include section-specific strings for formats which support sections.
3200 if (course_format_uses_sections($course->format
)) {
3201 $PAGE->requires
->strings_for_js(array(
3204 ), 'format_' . $course->format
);
3207 // For confirming resource deletion we need the name of the module in question
3208 foreach ($usedmodules as $module => $modname) {
3209 $PAGE->requires
->string_for_js('pluginname', $module);
3212 // Load drag and drop upload AJAX.
3213 require_once($CFG->dirroot
.'/course/dnduploadlib.php');
3214 dndupload_add_to_course($course, $enabledmodules);
3216 $PAGE->requires
->js_call_amd('core_course/actions', 'initCoursePage', array($course->format
));
3222 * Returns the sorted list of available course formats, filtered by enabled if necessary
3224 * @param bool $enabledonly return only formats that are enabled
3225 * @return array array of sorted format names
3227 function get_sorted_course_formats($enabledonly = false) {
3229 $formats = core_component
::get_plugin_list('format');
3231 if (!empty($CFG->format_plugins_sortorder
)) {
3232 $order = explode(',', $CFG->format_plugins_sortorder
);
3233 $order = array_merge(array_intersect($order, array_keys($formats)),
3234 array_diff(array_keys($formats), $order));
3236 $order = array_keys($formats);
3238 if (!$enabledonly) {
3241 $sortedformats = array();
3242 foreach ($order as $formatname) {
3243 if (!get_config('format_'.$formatname, 'disabled')) {
3244 $sortedformats[] = $formatname;
3247 return $sortedformats;
3251 * The URL to use for the specified course (with section)
3253 * @param int|stdClass $courseorid The course to get the section name for (either object or just course id)
3254 * @param int|stdClass $section Section object from database or just field course_sections.section
3255 * if omitted the course view page is returned
3256 * @param array $options options for view URL. At the moment core uses:
3257 * 'navigation' (bool) if true and section has no separate page, the function returns null
3258 * 'sr' (int) used by multipage formats to specify to which section to return
3259 * @return moodle_url The url of course
3261 function course_get_url($courseorid, $section = null, $options = array()) {
3262 return course_get_format($courseorid)->get_view_url($section, $options);
3269 * - capability checks and other checks
3270 * - create the module from the module info
3272 * @param object $module
3273 * @return object the created module info
3274 * @throws moodle_exception if user is not allowed to perform the action or module is not allowed in this course
3276 function create_module($moduleinfo) {
3279 require_once($CFG->dirroot
. '/course/modlib.php');
3281 // Check manadatory attributs.
3282 $mandatoryfields = array('modulename', 'course', 'section', 'visible');
3283 if (plugin_supports('mod', $moduleinfo->modulename
, FEATURE_MOD_INTRO
, true)) {
3284 $mandatoryfields[] = 'introeditor';
3286 foreach($mandatoryfields as $mandatoryfield) {
3287 if (!isset($moduleinfo->{$mandatoryfield})) {
3288 throw new moodle_exception('createmodulemissingattribut', '', '', $mandatoryfield);
3292 // Some additional checks (capability / existing instances).
3293 $course = $DB->get_record('course', array('id'=>$moduleinfo->course
), '*', MUST_EXIST
);
3294 list($module, $context, $cw) = can_add_moduleinfo($course, $moduleinfo->modulename
, $moduleinfo->section
);
3297 $moduleinfo->module
= $module->id
;
3298 $moduleinfo = add_moduleinfo($moduleinfo, $course, null);
3307 * - capability and other checks
3308 * - update the module
3310 * @param object $module
3311 * @return object the updated module info
3312 * @throws moodle_exception if current user is not allowed to update the module
3314 function update_module($moduleinfo) {
3317 require_once($CFG->dirroot
. '/course/modlib.php');
3319 // Check the course module exists.
3320 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule
, 0, false, MUST_EXIST
);
3322 // Check the course exists.
3323 $course = $DB->get_record('course', array('id'=>$cm->course
), '*', MUST_EXIST
);
3325 // Some checks (capaibility / existing instances).
3326 list($cm, $context, $module, $data, $cw) = can_update_moduleinfo($cm);
3328 // Retrieve few information needed by update_moduleinfo.
3329 $moduleinfo->modulename
= $cm->modname
;
3330 if (!isset($moduleinfo->scale
)) {
3331 $moduleinfo->scale
= 0;
3333 $moduleinfo->type
= 'mod';
3335 // Update the module.
3336 list($cm, $moduleinfo) = update_moduleinfo($cm, $moduleinfo, $course, null);
3342 * Duplicate a module on the course for ajax.
3344 * @see mod_duplicate_module()
3345 * @param object $course The course
3346 * @param object $cm The course module to duplicate
3347 * @param int $sr The section to link back to (used for creating the links)
3348 * @throws moodle_exception if the plugin doesn't support duplication
3349 * @return Object containing:
3350 * - fullcontent: The HTML markup for the created CM
3351 * - cmid: The CMID of the newly created CM
3352 * - redirect: Whether to trigger a redirect following this change
3354 function mod_duplicate_activity($course, $cm, $sr = null) {
3357 $newcm = duplicate_module($course, $cm);
3359 $resp = new stdClass();
3361 $courserenderer = $PAGE->get_renderer('core', 'course');
3362 $completioninfo = new completion_info($course);
3363 $modulehtml = $courserenderer->course_section_cm($course, $completioninfo,
3364 $newcm, null, array());
3366 $resp->fullcontent
= $courserenderer->course_section_cm_list_item($course, $completioninfo, $newcm, $sr);
3367 $resp->cmid
= $newcm->id
;
3369 // Trigger a redirect.
3370 $resp->redirect
= true;
3376 * Api to duplicate a module.
3378 * @param object $course course object.
3379 * @param object $cm course module object to be duplicated.
3383 * @throws coding_exception
3384 * @throws moodle_exception
3385 * @throws restore_controller_exception
3387 * @return cm_info|null cminfo object if we sucessfully duplicated the mod and found the new cm.
3389 function duplicate_module($course, $cm) {
3390 global $CFG, $DB, $USER;
3391 require_once($CFG->dirroot
. '/backup/util/includes/backup_includes.php');
3392 require_once($CFG->dirroot
. '/backup/util/includes/restore_includes.php');
3393 require_once($CFG->libdir
. '/filelib.php');
3395 $a = new stdClass();
3396 $a->modtype
= get_string('modulename', $cm->modname
);
3397 $a->modname
= format_string($cm->name
);
3399 if (!plugin_supports('mod', $cm->modname
, FEATURE_BACKUP_MOODLE2
)) {
3400 throw new moodle_exception('duplicatenosupport', 'error', '', $a);
3403 // Backup the activity.
3405 $bc = new backup_controller(backup
::TYPE_1ACTIVITY
, $cm->id
, backup
::FORMAT_MOODLE
,
3406 backup
::INTERACTIVE_NO
, backup
::MODE_IMPORT
, $USER->id
);
3408 $backupid = $bc->get_backupid();
3409 $backupbasepath = $bc->get_plan()->get_basepath();
3411 $bc->execute_plan();
3415 // Restore the backup immediately.
3417 $rc = new restore_controller($backupid, $course->id
,
3418 backup
::INTERACTIVE_NO
, backup
::MODE_IMPORT
, $USER->id
, backup
::TARGET_CURRENT_ADDING
);
3420 $cmcontext = context_module
::instance($cm->id
);
3421 if (!$rc->execute_precheck()) {
3422 $precheckresults = $rc->get_precheck_results();
3423 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
3424 if (empty($CFG->keeptempdirectoriesonbackup
)) {
3425 fulldelete($backupbasepath);
3430 $rc->execute_plan();
3432 // Now a bit hacky part follows - we try to get the cmid of the newly
3433 // restored copy of the module.
3435 $tasks = $rc->get_plan()->get_tasks();
3436 foreach ($tasks as $task) {
3437 if (is_subclass_of($task, 'restore_activity_task')) {
3438 if ($task->get_old_contextid() == $cmcontext->id
) {
3439 $newcmid = $task->get_moduleid();
3447 if (empty($CFG->keeptempdirectoriesonbackup
)) {
3448 fulldelete($backupbasepath);
3451 // If we know the cmid of the new course module, let us move it
3452 // right below the original one. otherwise it will stay at the
3453 // end of the section.
3455 // Proceed with activity renaming before everything else. We don't use APIs here to avoid
3456 // triggering a lot of create/update duplicated events.
3457 $newcm = get_coursemodule_from_id($cm->modname
, $newcmid, $cm->course
);
3458 // Add ' (copy)' to duplicates. Note we don't cleanup or validate lengths here. It comes
3459 // from original name that was valid, so the copy should be too.
3460 $newname = get_string('duplicatedmodule', 'moodle', $newcm->name
);
3461 $DB->set_field($cm->modname
, 'name', $newname, ['id' => $newcm->instance
]);
3463 $section = $DB->get_record('course_sections', array('id' => $cm->section
, 'course' => $cm->course
));
3464 $modarray = explode(",", trim($section->sequence
));
3465 $cmindex = array_search($cm->id
, $modarray);
3466 if ($cmindex !== false && $cmindex < count($modarray) - 1) {
3467 moveto_module($newcm, $section, $modarray[$cmindex +
1]);
3470 // Update calendar events with the duplicated module.
3471 // The following line is to be removed in MDL-58906.
3472 course_module_update_calendar_events($newcm->modname
, null, $newcm);
3474 // Trigger course module created event. We can trigger the event only if we know the newcmid.
3475 $newcm = get_fast_modinfo($cm->course
)->get_cm($newcmid);
3476 $event = \core\event\course_module_created
::create_from_cm($newcm);
3480 return isset($newcm) ?
$newcm : null;
3484 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3485 * Sorts by descending order of time.
3487 * @param stdClass $a First object
3488 * @param stdClass $b Second object
3489 * @return int 0,1,-1 representing the order
3491 function compare_activities_by_time_desc($a, $b) {
3492 // Make sure the activities actually have a timestamp property.
3493 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3496 // We treat instances without timestamp as if they have a timestamp of 0.
3497 if ((!property_exists($a, 'timestamp')) && (property_exists($b,'timestamp'))) {
3500 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3503 if ($a->timestamp
== $b->timestamp
) {
3506 return ($a->timestamp
> $b->timestamp
) ?
-1 : 1;
3510 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3511 * Sorts by ascending order of time.
3513 * @param stdClass $a First object
3514 * @param stdClass $b Second object
3515 * @return int 0,1,-1 representing the order
3517 function compare_activities_by_time_asc($a, $b) {
3518 // Make sure the activities actually have a timestamp property.
3519 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3522 // We treat instances without timestamp as if they have a timestamp of 0.
3523 if ((!property_exists($a, 'timestamp')) && (property_exists($b, 'timestamp'))) {
3526 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3529 if ($a->timestamp
== $b->timestamp
) {
3532 return ($a->timestamp
< $b->timestamp
) ?
-1 : 1;
3536 * Changes the visibility of a course.
3538 * @param int $courseid The course to change.
3539 * @param bool $show True to make it visible, false otherwise.
3542 function course_change_visibility($courseid, $show = true) {
3543 $course = new stdClass
;
3544 $course->id
= $courseid;
3545 $course->visible
= ($show) ?
'1' : '0';
3546 $course->visibleold
= $course->visible
;
3547 update_course($course);
3552 * Changes the course sortorder by one, moving it up or down one in respect to sort order.
3554 * @param stdClass|core_course_list_element $course
3555 * @param bool $up If set to true the course will be moved up one. Otherwise down one.
3558 function course_change_sortorder_by_one($course, $up) {
3560 $params = array($course->sortorder
, $course->category
);
3562 $select = 'sortorder < ? AND category = ?';
3563 $sort = 'sortorder DESC';
3565 $select = 'sortorder > ? AND category = ?';
3566 $sort = 'sortorder ASC';
3568 fix_course_sortorder();
3569 $swapcourse = $DB->get_records_select('course', $select, $params, $sort, '*', 0, 1);
3571 $swapcourse = reset($swapcourse);
3572 $DB->set_field('course', 'sortorder', $swapcourse->sortorder
, array('id' => $course->id
));
3573 $DB->set_field('course', 'sortorder', $course->sortorder
, array('id' => $swapcourse->id
));
3574 // Finally reorder courses.
3575 fix_course_sortorder();
3576 cache_helper
::purge_by_event('changesincourse');
3583 * Changes the sort order of courses in a category so that the first course appears after the second.
3585 * @param int|stdClass $courseorid The course to focus on.
3586 * @param int $moveaftercourseid The course to shifter after or 0 if you want it to be the first course in the category.
3589 function course_change_sortorder_after_course($courseorid, $moveaftercourseid) {
3592 if (!is_object($courseorid)) {
3593 $course = get_course($courseorid);
3595 $course = $courseorid;
3598 if ((int)$moveaftercourseid === 0) {
3599 // We've moving the course to the start of the queue.
3600 $sql = 'SELECT sortorder
3602 WHERE category = :categoryid
3603 ORDER BY sortorder';
3605 'categoryid' => $course->category
3607 $sortorder = $DB->get_field_sql($sql, $params, IGNORE_MULTIPLE
);
3609 $sql = 'UPDATE {course}
3610 SET sortorder = sortorder + 1
3611 WHERE category = :categoryid
3614 'categoryid' => $course->category
,
3615 'id' => $course->id
,
3617 $DB->execute($sql, $params);
3618 $DB->set_field('course', 'sortorder', $sortorder, array('id' => $course->id
));
3619 } else if ($course->id
=== $moveaftercourseid) {
3620 // They're the same - moronic.
3621 debugging("Invalid move after course given.", DEBUG_DEVELOPER
);
3624 // Moving this course after the given course. It could be before it could be after.
3625 $moveaftercourse = get_course($moveaftercourseid);
3626 if ($course->category
!== $moveaftercourse->category
) {
3627 debugging("Cannot re-order courses. The given courses do not belong to the same category.", DEBUG_DEVELOPER
);
3630 // Increment all courses in the same category that are ordered after the moveafter course.
3631 // This makes a space for the course we're moving.
3632 $sql = 'UPDATE {course}
3633 SET sortorder = sortorder + 1
3634 WHERE category = :categoryid
3635 AND sortorder > :sortorder';
3637 'categoryid' => $moveaftercourse->category
,
3638 'sortorder' => $moveaftercourse->sortorder
3640 $DB->execute($sql, $params);
3641 $DB->set_field('course', 'sortorder', $moveaftercourse->sortorder +
1, array('id' => $course->id
));
3643 fix_course_sortorder();
3644 cache_helper
::purge_by_event('changesincourse');
3649 * Trigger course viewed event. This API function is used when course view actions happens,
3650 * usually in course/view.php but also in external functions.
3652 * @param stdClass $context course context object
3653 * @param int $sectionnumber section number
3656 function course_view($context, $sectionnumber = 0) {
3658 $eventdata = array('context' => $context);
3660 if (!empty($sectionnumber)) {
3661 $eventdata['other']['coursesectionnumber'] = $sectionnumber;
3664 $event = \core\event\course_viewed
::create($eventdata);
3669 * Returns courses tagged with a specified tag.
3671 * @param core_tag_tag $tag
3672 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
3673 * are displayed on the page and the per-page limit may be bigger
3674 * @param int $fromctx context id where the link was displayed, may be used by callbacks
3675 * to display items in the same context first
3676 * @param int $ctx context id where to search for records
3677 * @param bool $rec search in subcontexts as well
3678 * @param int $page 0-based number of page being displayed
3679 * @return \core_tag\output\tagindex
3681 function course_get_tagged_courses($tag, $exclusivemode = false, $fromctx = 0, $ctx = 0, $rec = 1, $page = 0) {
3684 $perpage = $exclusivemode ?
$CFG->coursesperpage
: 5;
3685 $displayoptions = array(
3686 'limit' => $perpage,
3687 'offset' => $page * $perpage,
3688 'viewmoreurl' => null,
3691 $courserenderer = $PAGE->get_renderer('core', 'course');
3692 $totalcount = core_course_category
::search_courses_count(array('tagid' => $tag->id
, 'ctx' => $ctx, 'rec' => $rec));
3693 $content = $courserenderer->tagged_courses($tag->id
, $exclusivemode, $ctx, $rec, $displayoptions);
3694 $totalpages = ceil($totalcount / $perpage);
3696 return new core_tag\output\tagindex
($tag, 'core', 'course', $content,
3697 $exclusivemode, $fromctx, $ctx, $rec, $page, $totalpages);
3701 * Implements callback inplace_editable() allowing to edit values in-place
3703 * @param string $itemtype
3704 * @param int $itemid
3705 * @param mixed $newvalue
3706 * @return \core\output\inplace_editable
3708 function core_course_inplace_editable($itemtype, $itemid, $newvalue) {
3709 if ($itemtype === 'activityname') {
3710 return \core_course\output\course_module_name
::update($itemid, $newvalue);
3715 * This function calculates the minimum and maximum cutoff values for the timestart of
3718 * It will return an array with two values, the first being the minimum cutoff value and
3719 * the second being the maximum cutoff value. Either or both values can be null, which
3720 * indicates there is no minimum or maximum, respectively.
3722 * If a cutoff is required then the function must return an array containing the cutoff
3723 * timestamp and error string to display to the user if the cutoff value is violated.
3725 * A minimum and maximum cutoff return value will look like:
3727 * [1505704373, 'The date must be after this date'],
3728 * [1506741172, 'The date must be before this date']
3731 * @param calendar_event $event The calendar event to get the time range for
3732 * @param stdClass $course The course object to get the range from
3733 * @return array Returns an array with min and max date.
3735 function core_course_core_calendar_get_valid_event_timestart_range(\calendar_event
$event, $course) {
3739 if ($course->startdate
) {
3742 get_string('errorbeforecoursestart', 'calendar')
3746 return [$mindate, $maxdate];
3750 * Returns course modules tagged with a specified tag ready for output on tag/index.php page
3752 * This is a callback used by the tag area core/course_modules to search for course modules
3753 * tagged with a specific tag.
3755 * @param core_tag_tag $tag
3756 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
3757 * are displayed on the page and the per-page limit may be bigger
3758 * @param int $fromcontextid context id where the link was displayed, may be used by callbacks
3759 * to display items in the same context first
3760 * @param int $contextid context id where to search for records
3761 * @param bool $recursivecontext search in subcontexts as well
3762 * @param int $page 0-based number of page being displayed
3763 * @return \core_tag\output\tagindex
3765 function course_get_tagged_course_modules($tag, $exclusivemode = false, $fromcontextid = 0, $contextid = 0,
3766 $recursivecontext = 1, $page = 0) {
3768 $perpage = $exclusivemode ?
20 : 5;
3770 // Build select query.
3771 $ctxselect = context_helper
::get_preload_record_columns_sql('ctx');
3772 $query = "SELECT cm.id AS cmid, c.id AS courseid, $ctxselect
3773 FROM {course_modules} cm
3774 JOIN {tag_instance} tt ON cm.id = tt.itemid
3775 JOIN {course} c ON cm.course = c.id
3776 JOIN {context} ctx ON ctx.instanceid = cm.id AND ctx.contextlevel = :coursemodulecontextlevel
3777 WHERE tt.itemtype = :itemtype AND tt.tagid = :tagid AND tt.component = :component
3778 AND cm.deletioninprogress = 0
3779 AND c.id %COURSEFILTER% AND cm.id %ITEMFILTER%";
3781 $params = array('itemtype' => 'course_modules', 'tagid' => $tag->id
, 'component' => 'core',
3782 'coursemodulecontextlevel' => CONTEXT_MODULE
);
3784 $context = context
::instance_by_id($contextid);
3785 $query .= $recursivecontext ?
' AND (ctx.id = :contextid OR ctx.path LIKE :path)' : ' AND ctx.id = :contextid';
3786 $params['contextid'] = $context->id
;
3787 $params['path'] = $context->path
.'/%';
3790 $query .= ' ORDER BY';
3791 if ($fromcontextid) {
3792 // In order-clause specify that modules from inside "fromctx" context should be returned first.
3793 $fromcontext = context
::instance_by_id($fromcontextid);
3794 $query .= ' (CASE WHEN ctx.id = :fromcontextid OR ctx.path LIKE :frompath THEN 0 ELSE 1 END),';
3795 $params['fromcontextid'] = $fromcontext->id
;
3796 $params['frompath'] = $fromcontext->path
.'/%';
3798 $query .= ' c.sortorder, cm.id';
3799 $totalpages = $page +
1;
3801 // Use core_tag_index_builder to build and filter the list of items.
3802 // Request one item more than we need so we know if next page exists.
3803 $builder = new core_tag_index_builder('core', 'course_modules', $query, $params, $page * $perpage, $perpage +
1);
3804 while ($item = $builder->has_item_that_needs_access_check()) {
3805 context_helper
::preload_from_record($item);
3806 $courseid = $item->courseid
;
3807 if (!$builder->can_access_course($courseid)) {
3808 $builder->set_accessible($item, false);
3811 $modinfo = get_fast_modinfo($builder->get_course($courseid));
3812 // Set accessibility of this item and all other items in the same course.
3813 $builder->walk(function ($taggeditem) use ($courseid, $modinfo, $builder) {
3814 if ($taggeditem->courseid
== $courseid) {
3815 $cm = $modinfo->get_cm($taggeditem->cmid
);
3816 $builder->set_accessible($taggeditem, $cm->uservisible
);
3821 $items = $builder->get_items();
3822 if (count($items) > $perpage) {
3823 $totalpages = $page +
2; // We don't need exact page count, just indicate that the next page exists.
3827 // Build the display contents.
3829 $tagfeed = new core_tag\output\tagfeed
();
3830 foreach ($items as $item) {
3831 context_helper
::preload_from_record($item);
3832 $course = $builder->get_course($item->courseid
);
3833 $modinfo = get_fast_modinfo($course);
3834 $cm = $modinfo->get_cm($item->cmid
);
3835 $courseurl = course_get_url($item->courseid
, $cm->sectionnum
);
3836 $cmname = $cm->get_formatted_name();
3837 if (!$exclusivemode) {
3838 $cmname = shorten_text($cmname, 100);
3840 $cmname = html_writer
::link($cm->url?
:$courseurl, $cmname);
3841 $coursename = format_string($course->fullname
, true,
3842 array('context' => context_course
::instance($item->courseid
)));
3843 $coursename = html_writer
::link($courseurl, $coursename);
3844 $icon = html_writer
::empty_tag('img', array('src' => $cm->get_icon_url()));
3845 $tagfeed->add($icon, $cmname, $coursename);
3848 $content = $OUTPUT->render_from_template('core_tag/tagfeed',
3849 $tagfeed->export_for_template($OUTPUT));
3851 return new core_tag\output\tagindex
($tag, 'core', 'course_modules', $content,
3852 $exclusivemode, $fromcontextid, $contextid, $recursivecontext, $page, $totalpages);
3857 * Return an object with the list of navigation options in a course that are avaialable or not for the current user.
3858 * This function also handles the frontpage course.
3860 * @param stdClass $context context object (it can be a course context or the system context for frontpage settings)
3861 * @param stdClass $course the course where the settings are being rendered
3862 * @return stdClass the navigation options in a course and their availability status
3865 function course_get_user_navigation_options($context, $course = null) {
3868 $isloggedin = isloggedin();
3869 $isguestuser = isguestuser();
3870 $isfrontpage = $context->contextlevel
== CONTEXT_SYSTEM
;
3873 $sitecontext = $context;
3875 $sitecontext = context_system
::instance();
3878 // Sets defaults for all options.
3879 $options = (object) [
3882 'calendar' => false,
3883 'competencies' => false,
3886 'participants' => false,
3891 $options->blogs
= !empty($CFG->enableblogs
) &&
3892 ($CFG->bloglevel
== BLOG_GLOBAL_LEVEL ||
3893 ($CFG->bloglevel
== BLOG_SITE_LEVEL
and ($isloggedin and !$isguestuser)))
3894 && has_capability('moodle/blog:view', $sitecontext);
3896 $options->notes
= !empty($CFG->enablenotes
) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $context);
3898 // Frontpage settings?
3900 // We are on the front page, so make sure we use the proper capability (site:viewparticipants).
3901 $options->participants
= course_can_view_participants($sitecontext);
3902 $options->badges
= !empty($CFG->enablebadges
) && has_capability('moodle/badges:viewbadges', $sitecontext);
3903 $options->tags
= !empty($CFG->usetags
) && $isloggedin;
3904 $options->search
= !empty($CFG->enableglobalsearch
) && has_capability('moodle/search:query', $sitecontext);
3905 $options->calendar
= $isloggedin;
3907 // We are in a course, so make sure we use the proper capability (course:viewparticipants).
3908 $options->participants
= course_can_view_participants($context);
3909 $options->badges
= !empty($CFG->enablebadges
) && !empty($CFG->badges_allowcoursebadges
) &&
3910 has_capability('moodle/badges:viewbadges', $context);
3911 // Add view grade report is permitted.
3914 if (has_capability('moodle/grade:viewall', $context)) {
3916 } else if (!empty($course->showgrades
)) {
3917 $reports = core_component
::get_plugin_list('gradereport');
3918 if (is_array($reports) && count($reports) > 0) { // Get all installed reports.
3919 arsort($reports); // User is last, we want to test it first.
3920 foreach ($reports as $plugin => $plugindir) {
3921 if (has_capability('gradereport/'.$plugin.':view', $context)) {
3922 // Stop when the first visible plugin is found.
3929 $options->grades
= $grades;
3932 if (\core_competency\api
::is_enabled()) {
3933 $capabilities = array('moodle/competency:coursecompetencyview', 'moodle/competency:coursecompetencymanage');
3934 $options->competencies
= has_any_capability($capabilities, $context);
3940 * Return an object with the list of administration options in a course that are available or not for the current user.
3941 * This function also handles the frontpage settings.
3943 * @param stdClass $course course object (for frontpage it should be a clone of $SITE)
3944 * @param stdClass $context context object (course context)
3945 * @return stdClass the administration options in a course and their availability status
3948 function course_get_user_administration_options($course, $context) {
3950 $isfrontpage = $course->id
== SITEID
;
3951 $completionenabled = $CFG->enablecompletion
&& $course->enablecompletion
;
3952 $hascompletiontabs = count(core_completion\manager
::get_available_completion_tabs($course, $context)) > 0;
3954 $options = new stdClass
;
3955 $options->update
= has_capability('moodle/course:update', $context);
3956 $options->editcompletion
= $CFG->enablecompletion
&&
3957 $course->enablecompletion
&&
3958 ($options->update ||
$hascompletiontabs);
3959 $options->filters
= has_capability('moodle/filter:manage', $context) &&
3960 count(filter_get_available_in_context($context)) > 0;
3961 $options->reports
= has_capability('moodle/site:viewreports', $context);
3962 $options->backup
= has_capability('moodle/backup:backupcourse', $context);
3963 $options->restore
= has_capability('moodle/restore:restorecourse', $context);
3964 $options->files
= ($course->legacyfiles
== 2 && has_capability('moodle/course:managefiles', $context));
3966 if (!$isfrontpage) {
3967 $options->tags
= has_capability('moodle/course:tag', $context);
3968 $options->gradebook
= has_capability('moodle/grade:manage', $context);
3969 $options->outcomes
= !empty($CFG->enableoutcomes
) && has_capability('moodle/course:update', $context);
3970 $options->badges
= !empty($CFG->enablebadges
);
3971 $options->import
= has_capability('moodle/restore:restoretargetimport', $context);
3972 $options->publish
= has_capability('moodle/course:publish', $context);
3973 $options->reset
= has_capability('moodle/course:reset', $context);
3974 $options->roles
= has_capability('moodle/role:switchroles', $context);
3976 // Set default options to false.
3977 $listofoptions = array('tags', 'gradebook', 'outcomes', 'badges', 'import', 'publish', 'reset', 'roles', 'grades');
3979 foreach ($listofoptions as $option) {
3980 $options->$option = false;
3988 * Validates course start and end dates.
3990 * Checks that the end course date is not greater than the start course date.
3992 * $coursedata['startdate'] or $coursedata['enddate'] may not be set, it depends on the form and user input.
3994 * @param array $coursedata May contain startdate and enddate timestamps, depends on the user input.
3995 * @return mixed False if everything alright, error codes otherwise.
3997 function course_validate_dates($coursedata) {
3999 // If both start and end dates are set end date should be later than the start date.
4000 if (!empty($coursedata['startdate']) && !empty($coursedata['enddate']) &&
4001 ($coursedata['enddate'] < $coursedata['startdate'])) {
4002 return 'enddatebeforestartdate';
4005 // If start date is not set end date can not be set.
4006 if (empty($coursedata['startdate']) && !empty($coursedata['enddate'])) {
4007 return 'nostartdatenoenddate';
4014 * Check for course updates in the given context level instances (only modules supported right Now)
4016 * @param stdClass $course course object
4017 * @param array $tocheck instances to check for updates
4018 * @param array $filter check only for updates in these areas
4019 * @return array list of warnings and instances with updates information
4022 function course_check_updates($course, $tocheck, $filter = array()) {
4025 $instances = array();
4026 $warnings = array();
4027 $modulescallbacksupport = array();
4028 $modinfo = get_fast_modinfo($course);
4030 $supportedplugins = get_plugin_list_with_function('mod', 'check_updates_since');
4033 foreach ($tocheck as $instance) {
4034 if ($instance['contextlevel'] == 'module') {
4035 // Check module visibility.
4037 $cm = $modinfo->get_cm($instance['id']);
4038 } catch (Exception
$e) {
4039 $warnings[] = array(
4041 'itemid' => $instance['id'],
4042 'warningcode' => 'cmidnotincourse',
4043 'message' => 'This module id does not belong to this course.'
4048 if (!$cm->uservisible
) {
4049 $warnings[] = array(
4051 'itemid' => $instance['id'],
4052 'warningcode' => 'nonuservisible',
4053 'message' => 'You don\'t have access to this module.'
4057 if (empty($supportedplugins['mod_' . $cm->modname
])) {
4058 $warnings[] = array(
4060 'itemid' => $instance['id'],
4061 'warningcode' => 'missingcallback',
4062 'message' => 'This module does not implement the check_updates_since callback: ' . $instance['contextlevel'],
4066 // Retrieve the module instance.
4067 $instances[] = array(
4068 'contextlevel' => $instance['contextlevel'],
4069 'id' => $instance['id'],
4070 'updates' => call_user_func($cm->modname
. '_check_updates_since', $cm, $instance['since'], $filter)
4074 $warnings[] = array(
4075 'item' => 'contextlevel',
4076 'itemid' => $instance['id'],
4077 'warningcode' => 'contextlevelnotsupported',
4078 'message' => 'Context level not yet supported ' . $instance['contextlevel'],
4082 return array($instances, $warnings);
4086 * This function classifies a course as past, in progress or future.
4088 * This function may incur a DB hit to calculate course completion.
4089 * @param stdClass $course Course record
4090 * @param stdClass $user User record (optional - defaults to $USER).
4091 * @param completion_info $completioninfo Completion record for the user (optional - will be fetched if required).
4092 * @return string (one of COURSE_TIMELINE_FUTURE, COURSE_TIMELINE_INPROGRESS or COURSE_TIMELINE_PAST)
4094 function course_classify_for_timeline($course, $user = null, $completioninfo = null) {
4097 if ($user == null) {
4103 if (!empty($course->enddate
) && (course_classify_end_date($course) < $today)) {
4104 return COURSE_TIMELINE_PAST
;
4107 if ($completioninfo == null) {
4108 $completioninfo = new completion_info($course);
4111 // Course was completed.
4112 if ($completioninfo->is_enabled() && $completioninfo->is_course_complete($user->id
)) {
4113 return COURSE_TIMELINE_PAST
;
4116 // Start date not reached.
4117 if (!empty($course->startdate
) && (course_classify_start_date($course) > $today)) {
4118 return COURSE_TIMELINE_FUTURE
;
4121 // Everything else is in progress.
4122 return COURSE_TIMELINE_INPROGRESS
;
4126 * This function calculates the end date to use for display classification purposes,
4127 * incorporating the grace period, if any.
4129 * @param stdClass $course The course record.
4130 * @return int The new enddate.
4132 function course_classify_end_date($course) {
4134 $coursegraceperiodafter = (empty($CFG->coursegraceperiodafter
)) ?
0 : $CFG->coursegraceperiodafter
;
4135 $enddate = (new \
DateTimeImmutable())->setTimestamp($course->enddate
)->modify("+{$coursegraceperiodafter} days");
4136 return $enddate->getTimestamp();
4140 * This function calculates the start date to use for display classification purposes,
4141 * incorporating the grace period, if any.
4143 * @param stdClass $course The course record.
4144 * @return int The new startdate.
4146 function course_classify_start_date($course) {
4148 $coursegraceperiodbefore = (empty($CFG->coursegraceperiodbefore
)) ?
0 : $CFG->coursegraceperiodbefore
;
4149 $startdate = (new \
DateTimeImmutable())->setTimestamp($course->startdate
)->modify("-{$coursegraceperiodbefore} days");
4150 return $startdate->getTimestamp();
4154 * Group a list of courses into either past, future, or in progress.
4156 * The return value will be an array indexed by the COURSE_TIMELINE_* constants
4157 * with each value being an array of courses in that group.
4160 * COURSE_TIMELINE_PAST => [... list of past courses ...],
4161 * COURSE_TIMELINE_FUTURE => [],
4162 * COURSE_TIMELINE_INPROGRESS => []
4165 * @param array $courses List of courses to be grouped.
4168 function course_classify_courses_for_timeline(array $courses) {
4169 return array_reduce($courses, function($carry, $course) {
4170 $classification = course_classify_for_timeline($course);
4171 array_push($carry[$classification], $course);
4175 COURSE_TIMELINE_PAST
=> [],
4176 COURSE_TIMELINE_FUTURE
=> [],
4177 COURSE_TIMELINE_INPROGRESS
=> []
4182 * Get the list of enrolled courses for the current user.
4184 * This function returns a Generator. The courses will be loaded from the database
4185 * in chunks rather than a single query.
4187 * @param int $limit Restrict result set to this amount
4188 * @param int $offset Skip this number of records from the start of the result set
4189 * @param string|null $sort SQL string for sorting
4190 * @param string|null $fields SQL string for fields to be returned
4191 * @param int $dbquerylimit The number of records to load per DB request
4194 function course_get_enrolled_courses_for_logged_in_user(
4197 string $sort = null,
4198 string $fields = null,
4199 int $dbquerylimit = COURSE_DB_QUERY_LIMIT
4202 $haslimit = !empty($limit);
4204 $querylimit = (!$haslimit ||
$limit > $dbquerylimit) ?
$dbquerylimit : $limit;
4206 while ($courses = enrol_get_my_courses($fields, $sort, $querylimit, [], false, $offset)) {
4207 yield from
$courses;
4209 $recordsloaded +
= $querylimit;
4211 if (count($courses) < $querylimit) {
4214 if ($haslimit && $recordsloaded >= $limit) {
4218 $offset +
= $querylimit;
4223 * Search the given $courses for any that match the given $classification up to the specified
4226 * This function will return the subset of courses that match the classification as well as the
4227 * number of courses it had to process to build that subset.
4229 * It is recommended that for larger sets of courses this function is given a Generator that loads
4230 * the courses from the database in chunks.
4232 * @param array|Traversable $courses List of courses to process
4233 * @param string $classification One of the COURSE_TIMELINE_* constants
4234 * @param int $limit Limit the number of results to this amount
4235 * @return array First value is the filtered courses, second value is the number of courses processed
4237 function course_filter_courses_by_timeline_classification(
4239 string $classification,
4243 if (!in_array($classification,
4244 [COURSE_TIMELINE_ALL
, COURSE_TIMELINE_PAST
, COURSE_TIMELINE_INPROGRESS
, COURSE_TIMELINE_FUTURE
])) {
4245 $message = 'Classification must be one of COURSE_TIMELINE_ALL, COURSE_TIMELINE_PAST, '
4246 . 'COURSE_TIMELINE_INPROGRESS or COURSE_TIMELINE_FUTURE';
4247 throw new moodle_exception($message);
4250 $filteredcourses = [];
4251 $numberofcoursesprocessed = 0;
4254 foreach ($courses as $course) {
4255 $numberofcoursesprocessed++
;
4257 if ($classification == COURSE_TIMELINE_ALL ||
$classification == course_classify_for_timeline($course)) {
4258 $filteredcourses[] = $course;
4262 if ($limit && $filtermatches >= $limit) {
4263 // We've found the number of requested courses. No need to continue searching.
4268 // Return the number of filtered courses as well as the number of courses that were searched
4269 // in order to find the matching courses. This allows the calling code to do some kind of
4271 return [$filteredcourses, $numberofcoursesprocessed];
4275 * Check module updates since a given time.
4276 * This function checks for updates in the module config, file areas, completion, grades, comments and ratings.
4278 * @param cm_info $cm course module data
4279 * @param int $from the time to check
4280 * @param array $fileareas additional file ares to check
4281 * @param array $filter if we need to filter and return only selected updates
4282 * @return stdClass object with the different updates
4285 function course_check_module_updates_since($cm, $from, $fileareas = array(), $filter = array()) {
4286 global $DB, $CFG, $USER;
4288 $context = $cm->context
;
4289 $mod = $DB->get_record($cm->modname
, array('id' => $cm->instance
), '*', MUST_EXIST
);
4291 $updates = new stdClass();
4292 $course = get_course($cm->course
);
4293 $component = 'mod_' . $cm->modname
;
4295 // Check changes in the module configuration.
4296 if (isset($mod->timemodified
) and (empty($filter) or in_array('configuration', $filter))) {
4297 $updates->configuration
= (object) array('updated' => false);
4298 if ($updates->configuration
->updated
= $mod->timemodified
> $from) {
4299 $updates->configuration
->timeupdated
= $mod->timemodified
;
4303 // Check for updates in files.
4304 if (plugin_supports('mod', $cm->modname
, FEATURE_MOD_INTRO
)) {
4305 $fileareas[] = 'intro';
4307 if (!empty($fileareas) and (empty($filter) or in_array('fileareas', $filter))) {
4308 $fs = get_file_storage();
4309 $files = $fs->get_area_files($context->id
, $component, $fileareas, false, "filearea, timemodified DESC", false, $from);
4310 foreach ($fileareas as $filearea) {
4311 $updates->{$filearea . 'files'} = (object) array('updated' => false);
4313 foreach ($files as $file) {
4314 $updates->{$file->get_filearea() . 'files'}->updated
= true;
4315 $updates->{$file->get_filearea() . 'files'}->itemids
[] = $file->get_id();
4319 // Check completion.
4320 $supportcompletion = plugin_supports('mod', $cm->modname
, FEATURE_COMPLETION_HAS_RULES
);
4321 $supportcompletion = $supportcompletion or plugin_supports('mod', $cm->modname
, FEATURE_COMPLETION_TRACKS_VIEWS
);
4322 if ($supportcompletion and (empty($filter) or in_array('completion', $filter))) {
4323 $updates->completion
= (object) array('updated' => false);
4324 $completion = new completion_info($course);
4325 // Use wholecourse to cache all the modules the first time.
4326 $completiondata = $completion->get_data($cm, true);
4327 if ($updates->completion
->updated
= !empty($completiondata->timemodified
) && $completiondata->timemodified
> $from) {
4328 $updates->completion
->timemodified
= $completiondata->timemodified
;
4333 $supportgrades = plugin_supports('mod', $cm->modname
, FEATURE_GRADE_HAS_GRADE
);
4334 $supportgrades = $supportgrades or plugin_supports('mod', $cm->modname
, FEATURE_GRADE_OUTCOMES
);
4335 if ($supportgrades and (empty($filter) or (in_array('gradeitems', $filter) or in_array('outcomes', $filter)))) {
4336 require_once($CFG->libdir
. '/gradelib.php');
4337 $grades = grade_get_grades($course->id
, 'mod', $cm->modname
, $mod->id
, $USER->id
);
4339 if (empty($filter) or in_array('gradeitems', $filter)) {
4340 $updates->gradeitems
= (object) array('updated' => false);
4341 foreach ($grades->items
as $gradeitem) {
4342 foreach ($gradeitem->grades
as $grade) {
4343 if ($grade->datesubmitted
> $from or $grade->dategraded
> $from) {
4344 $updates->gradeitems
->updated
= true;
4345 $updates->gradeitems
->itemids
[] = $gradeitem->id
;
4351 if (empty($filter) or in_array('outcomes', $filter)) {
4352 $updates->outcomes
= (object) array('updated' => false);
4353 foreach ($grades->outcomes
as $outcome) {
4354 foreach ($outcome->grades
as $grade) {
4355 if ($grade->datesubmitted
> $from or $grade->dategraded
> $from) {
4356 $updates->outcomes
->updated
= true;
4357 $updates->outcomes
->itemids
[] = $outcome->id
;
4365 if (plugin_supports('mod', $cm->modname
, FEATURE_COMMENT
) and (empty($filter) or in_array('comments', $filter))) {
4366 $updates->comments
= (object) array('updated' => false);
4367 require_once($CFG->dirroot
. '/comment/lib.php');
4368 require_once($CFG->dirroot
. '/comment/locallib.php');
4369 $manager = new comment_manager();
4370 $comments = $manager->get_component_comments_since($course, $context, $component, $from, $cm);
4371 if (!empty($comments)) {
4372 $updates->comments
->updated
= true;
4373 $updates->comments
->itemids
= array_keys($comments);
4378 if (plugin_supports('mod', $cm->modname
, FEATURE_RATE
) and (empty($filter) or in_array('ratings', $filter))) {
4379 $updates->ratings
= (object) array('updated' => false);
4380 require_once($CFG->dirroot
. '/rating/lib.php');
4381 $manager = new rating_manager();
4382 $ratings = $manager->get_component_ratings_since($context, $component, $from);
4383 if (!empty($ratings)) {
4384 $updates->ratings
->updated
= true;
4385 $updates->ratings
->itemids
= array_keys($ratings);
4393 * Returns true if the user can view the participant page, false otherwise,
4395 * @param context $context The context we are checking.
4398 function course_can_view_participants($context) {
4399 $viewparticipantscap = 'moodle/course:viewparticipants';
4400 if ($context->contextlevel
== CONTEXT_SYSTEM
) {
4401 $viewparticipantscap = 'moodle/site:viewparticipants';
4404 return has_any_capability([$viewparticipantscap, 'moodle/course:enrolreview'], $context);
4408 * Checks if a user can view the participant page, if not throws an exception.
4410 * @param context $context The context we are checking.
4411 * @throws required_capability_exception
4413 function course_require_view_participants($context) {
4414 if (!course_can_view_participants($context)) {
4415 $viewparticipantscap = 'moodle/course:viewparticipants';
4416 if ($context->contextlevel
== CONTEXT_SYSTEM
) {
4417 $viewparticipantscap = 'moodle/site:viewparticipants';
4419 throw new required_capability_exception($context, $viewparticipantscap, 'nopermissions', '');
4424 * Return whether the user can download from the specified backup file area in the given context.
4426 * @param string $filearea the backup file area. E.g. 'course', 'backup' or 'automated'.
4427 * @param \context $context
4428 * @param stdClass $user the user object. If not provided, the current user will be checked.
4429 * @return bool true if the user is allowed to download in the context, false otherwise.
4431 function can_download_from_backup_filearea($filearea, \context
$context, stdClass
$user = null) {
4432 $candownload = false;
4433 switch ($filearea) {
4436 $candownload = has_capability('moodle/backup:downloadfile', $context, $user);
4439 // Given the automated backups may contain userinfo, we restrict access such that only users who are able to
4440 // restore with userinfo are able to download the file. Users can't create these backups, so checking 'backup:userinfo'
4441 // doesn't make sense here.
4442 $candownload = has_capability('moodle/backup:downloadfile', $context, $user) &&
4443 has_capability('moodle/restore:userinfo', $context, $user);
4449 return $candownload;