2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Library of useful functions
20 * @copyright 1999 Martin Dougiamas http://dougiamas.com
21 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
22 * @package core_course
25 defined('MOODLE_INTERNAL') || die;
27 require_once($CFG->libdir.'/completionlib.php');
28 require_once($CFG->libdir.'/filelib.php');
29 require_once($CFG->dirroot.'/course/format/lib.php');
31 define('COURSE_MAX_LOGS_PER_PAGE', 1000); // Records.
32 define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds.
35 * Number of courses to display when summaries are included.
37 * @deprecated since 2.4, use $CFG->courseswithsummarieslimit instead.
39 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10);
41 // Max courses in log dropdown before switching to optional.
42 define('COURSE_MAX_COURSES_PER_DROPDOWN', 1000);
43 // Max users in log dropdown before switching to optional.
44 define('COURSE_MAX_USERS_PER_DROPDOWN', 1000);
45 define('FRONTPAGENEWS', '0');
46 define('FRONTPAGECATEGORYNAMES', '2');
47 define('FRONTPAGECATEGORYCOMBO', '4');
48 define('FRONTPAGEENROLLEDCOURSELIST', '5');
49 define('FRONTPAGEALLCOURSELIST', '6');
50 define('FRONTPAGECOURSESEARCH', '7');
51 // Important! Replaced with $CFG->frontpagecourselimit - maximum number of courses displayed on the frontpage.
52 define('EXCELROWS', 65535);
53 define('FIRSTUSEDEXCELROW', 3);
55 define('MOD_CLASS_ACTIVITY', 0);
56 define('MOD_CLASS_RESOURCE', 1);
58 function make_log_url($module, $url) {
61 if (strpos($url, 'report/') === 0) {
62 // there is only one report type, course reports are deprecated
72 if (strpos($url, '../') === 0) {
73 $url = ltrim($url, '.');
75 $url = "/course/$url";
79 $url = "/calendar/$url";
83 $url = "/$module/$url";
96 $url = "/message/$url";
108 $url = "/grade/$url";
111 $url = "/mod/$module/$url";
115 //now let's sanitise urls - there might be some ugly nasties:-(
116 $parts = explode('?', $url);
117 $script = array_shift($parts);
118 if (strpos($script, 'http') === 0) {
119 $script = clean_param($script, PARAM_URL);
121 $script = clean_param($script, PARAM_PATH);
126 $query = implode('', $parts);
127 $query = str_replace('&', '&', $query); // both & and & are stored in db :-|
128 $parts = explode('&', $query);
129 $eq = urlencode('=');
130 foreach ($parts as $key=>$part) {
131 $part = urlencode(urldecode($part));
132 $part = str_replace($eq, '=', $part);
133 $parts[$key] = $part;
135 $query = '?'.implode('&', $parts);
138 return $script.$query;
142 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
143 $modname="", $modid=0, $modaction="", $groupid=0) {
146 // It is assumed that $date is the GMT time of midnight for that day,
147 // and so the next 86400 seconds worth of logs are printed.
149 /// Setup for group handling.
151 // TODO: I don't understand group/context/etc. enough to be able to do
152 // something interesting with it here
153 // What is the context of a remote course?
155 /// If the group mode is separate, and this user does not have editing privileges,
156 /// then only the user's group can be viewed.
157 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
158 // $groupid = get_current_group($course->id);
160 /// If this course doesn't have groups, no groupid can be specified.
161 //else if (!$course->groupmode) {
170 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
172 LEFT JOIN {user} u ON l.userid = u.id
176 $where .= "l.hostid = :hostid";
177 $params['hostid'] = $hostid;
179 // TODO: Is 1 really a magic number referring to the sitename?
180 if ($course != SITEID || $modid != 0) {
181 $where .= " AND l.course=:courseid";
182 $params['courseid'] = $course;
186 $where .= " AND l.module = :modname";
187 $params['modname'] = $modname;
190 if ('site_errors' === $modid) {
191 $where .= " AND ( l.action='error' OR l.action='infected' )";
193 //TODO: This assumes that modids are the same across sites... probably
195 $where .= " AND l.cmid = :modid";
196 $params['modid'] = $modid;
200 $firstletter = substr($modaction, 0, 1);
201 if ($firstletter == '-') {
202 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
203 $params['modaction'] = '%'.substr($modaction, 1).'%';
205 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
206 $params['modaction'] = '%'.$modaction.'%';
211 $where .= " AND l.userid = :user";
212 $params['user'] = $user;
216 $enddate = $date + 86400;
217 $where .= " AND l.time > :date AND l.time < :enddate";
218 $params['date'] = $date;
219 $params['enddate'] = $enddate;
223 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
224 if(!empty($result['totalcount'])) {
225 $where .= " ORDER BY $order";
226 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
228 $result['logs'] = array();
233 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
234 $modname="", $modid=0, $modaction="", $groupid=0) {
235 global $DB, $SESSION, $USER;
236 // It is assumed that $date is the GMT time of midnight for that day,
237 // and so the next 86400 seconds worth of logs are printed.
239 /// Setup for group handling.
241 /// If the group mode is separate, and this user does not have editing privileges,
242 /// then only the user's group can be viewed.
243 if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
244 if (isset($SESSION->currentgroup[$course->id])) {
245 $groupid = $SESSION->currentgroup[$course->id];
247 $groupid = groups_get_all_groups($course->id, $USER->id);
248 if (is_array($groupid)) {
249 $groupid = array_shift(array_keys($groupid));
250 $SESSION->currentgroup[$course->id] = $groupid;
256 /// If this course doesn't have groups, no groupid can be specified.
257 else if (!$course->groupmode) {
264 if ($course->id != SITEID || $modid != 0) {
265 $joins[] = "l.course = :courseid";
266 $params['courseid'] = $course->id;
270 $joins[] = "l.module = :modname";
271 $params['modname'] = $modname;
274 if ('site_errors' === $modid) {
275 $joins[] = "( l.action='error' OR l.action='infected' )";
277 $joins[] = "l.cmid = :modid";
278 $params['modid'] = $modid;
282 $firstletter = substr($modaction, 0, 1);
283 if ($firstletter == '-') {
284 $joins[] = $DB->sql_like('l.action', ':modaction', false, true, true);
285 $params['modaction'] = '%'.substr($modaction, 1).'%';
287 $joins[] = $DB->sql_like('l.action', ':modaction', false);
288 $params['modaction'] = '%'.$modaction.'%';
293 /// Getting all members of a group.
294 if ($groupid and !$user) {
295 if ($gusers = groups_get_members($groupid)) {
296 $gusers = array_keys($gusers);
297 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
299 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
303 $joins[] = "l.userid = :userid";
304 $params['userid'] = $user;
308 $enddate = $date + 86400;
309 $joins[] = "l.time > :date AND l.time < :enddate";
310 $params['date'] = $date;
311 $params['enddate'] = $enddate;
314 $selector = implode(' AND ', $joins);
316 $totalcount = 0; // Initialise
318 $result['logs'] = get_logs($selector, $params, $order, $limitfrom, $limitnum, $totalcount);
319 $result['totalcount'] = $totalcount;
324 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
325 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
327 global $CFG, $DB, $OUTPUT;
329 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
330 $modname, $modid, $modaction, $groupid)) {
331 echo $OUTPUT->notification("No logs found!");
332 echo $OUTPUT->footer();
338 if ($course->id == SITEID) {
340 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
341 foreach ($ccc as $cc) {
342 $courses[$cc->id] = $cc->shortname;
346 $courses[$course->id] = $course->shortname;
349 $totalcount = $logs['totalcount'];
352 $tt = getdate(time());
353 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
355 $strftimedatetime = get_string("strftimedatetime");
357 echo "<div class=\"info\">\n";
358 print_string("displayingrecords", "", $totalcount);
361 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
363 $table = new html_table();
364 $table->classes = array('logtable','generaltable');
365 $table->align = array('right', 'left', 'left');
366 $table->head = array(
368 get_string('ip_address'),
369 get_string('fullnameuser'),
370 get_string('action'),
373 $table->data = array();
375 if ($course->id == SITEID) {
376 array_unshift($table->align, 'left');
377 array_unshift($table->head, get_string('course'));
380 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
381 if (empty($logs['logs'])) {
382 $logs['logs'] = array();
385 foreach ($logs['logs'] as $log) {
387 if (isset($ldcache[$log->module][$log->action])) {
388 $ld = $ldcache[$log->module][$log->action];
390 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
391 $ldcache[$log->module][$log->action] = $ld;
393 if ($ld && is_numeric($log->info)) {
394 // ugly hack to make sure fullname is shown correctly
395 if ($ld->mtable == 'user' && $ld->field == $DB->sql_concat('firstname', "' '" , 'lastname')) {
396 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
398 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
403 $log->info = format_string($log->info);
405 // If $log->url has been trimmed short by the db size restriction
406 // code in add_to_log, keep a note so we don't add a link to a broken url
407 $brokenurl=(core_text::strlen($log->url)==100 && core_text::substr($log->url,97)=='...');
410 if ($course->id == SITEID) {
411 if (empty($log->course)) {
412 $row[] = get_string('site');
414 $row[] = "<a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course])."</a>";
418 $row[] = userdate($log->time, '%a').' '.userdate($log->time, $strftimedatetime);
420 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
421 $row[] = $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 440, 'width' => 700)));
423 $row[] = html_writer::link(new moodle_url("/user/view.php?id={$log->userid}&course={$log->course}"), fullname($log, has_capability('moodle/site:viewfullnames', context_course::instance($course->id))));
425 $displayaction="$log->module $log->action";
427 $row[] = $displayaction;
429 $link = make_log_url($log->module,$log->url);
430 $row[] = $OUTPUT->action_link($link, $displayaction, new popup_action('click', $link, 'fromloglive'), array('height' => 440, 'width' => 700));
433 $table->data[] = $row;
436 echo html_writer::table($table);
437 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
441 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
442 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
444 global $CFG, $DB, $OUTPUT;
446 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
447 $modname, $modid, $modaction, $groupid)) {
448 echo $OUTPUT->notification("No logs found!");
449 echo $OUTPUT->footer();
453 if ($course->id == SITEID) {
455 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
456 foreach ($ccc as $cc) {
457 $courses[$cc->id] = $cc->shortname;
462 $totalcount = $logs['totalcount'];
465 $tt = getdate(time());
466 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
468 $strftimedatetime = get_string("strftimedatetime");
470 echo "<div class=\"info\">\n";
471 print_string("displayingrecords", "", $totalcount);
474 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
476 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
478 if ($course->id == SITEID) {
479 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
481 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
482 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
483 echo "<th class=\"c3 header\">".get_string('fullnameuser')."</th>\n";
484 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
485 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
488 if (empty($logs['logs'])) {
494 foreach ($logs['logs'] as $log) {
496 $log->info = $log->coursename;
497 $row = ($row + 1) % 2;
499 if (isset($ldcache[$log->module][$log->action])) {
500 $ld = $ldcache[$log->module][$log->action];
502 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
503 $ldcache[$log->module][$log->action] = $ld;
505 if (0 && $ld && !empty($log->info)) {
506 // ugly hack to make sure fullname is shown correctly
507 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
508 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
510 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
515 $log->info = format_string($log->info);
517 echo '<tr class="r'.$row.'">';
518 if ($course->id == SITEID) {
519 $courseshortname = format_string($courses[$log->course], true, array('context' => context_course::instance(SITEID)));
520 echo "<td class=\"r$row c0\" >\n";
521 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courseshortname."</a>\n";
524 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time, '%a').
525 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
526 echo "<td class=\"r$row c2\" >\n";
527 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
528 echo $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 400, 'width' => 700)));
530 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', context_course::instance($course->id)));
531 echo "<td class=\"r$row c3\" >\n";
532 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
534 echo "<td class=\"r$row c4\">\n";
535 echo $log->action .': '.$log->module;
537 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
542 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
546 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
547 $modid, $modaction, $groupid) {
550 require_once($CFG->libdir . '/csvlib.class.php');
552 $csvexporter = new csv_export_writer('tab');
555 $header[] = get_string('course');
556 $header[] = get_string('time');
557 $header[] = get_string('ip_address');
558 $header[] = get_string('fullnameuser');
559 $header[] = get_string('action');
560 $header[] = get_string('info');
562 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
563 $modname, $modid, $modaction, $groupid)) {
569 if ($course->id == SITEID) {
571 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
572 foreach ($ccc as $cc) {
573 $courses[$cc->id] = $cc->shortname;
577 $courses[$course->id] = $course->shortname;
582 $tt = getdate(time());
583 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
585 $strftimedatetime = get_string("strftimedatetime");
587 $csvexporter->set_filename('logs', '.txt');
588 $title = array(get_string('savedat').userdate(time(), $strftimedatetime));
589 $csvexporter->add_data($title);
590 $csvexporter->add_data($header);
592 if (empty($logs['logs'])) {
596 foreach ($logs['logs'] as $log) {
597 if (isset($ldcache[$log->module][$log->action])) {
598 $ld = $ldcache[$log->module][$log->action];
600 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
601 $ldcache[$log->module][$log->action] = $ld;
603 if ($ld && is_numeric($log->info)) {
604 // ugly hack to make sure fullname is shown correctly
605 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
606 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
608 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
613 $log->info = format_string($log->info);
614 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
616 $coursecontext = context_course::instance($course->id);
617 $firstField = format_string($courses[$log->course], true, array('context' => $coursecontext));
618 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
619 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
620 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action.' ('.$actionurl.')', $log->info);
621 $csvexporter->add_data($row);
623 $csvexporter->download_file();
628 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
629 $modid, $modaction, $groupid) {
633 require_once("$CFG->libdir/excellib.class.php");
635 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
636 $modname, $modid, $modaction, $groupid)) {
642 if ($course->id == SITEID) {
644 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
645 foreach ($ccc as $cc) {
646 $courses[$cc->id] = $cc->shortname;
650 $courses[$course->id] = $course->shortname;
655 $tt = getdate(time());
656 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
658 $strftimedatetime = get_string("strftimedatetime");
660 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
661 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
664 $workbook = new MoodleExcelWorkbook('-');
665 $workbook->send($filename);
667 $worksheet = array();
668 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
669 get_string('fullnameuser'), get_string('action'), get_string('info'));
671 // Creating worksheets
672 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
673 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
674 $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle);
675 $worksheet[$wsnumber]->set_column(1, 1, 30);
676 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
677 userdate(time(), $strftimedatetime));
679 foreach ($headers as $item) {
680 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
685 if (empty($logs['logs'])) {
690 $formatDate =& $workbook->add_format();
691 $formatDate->set_num_format(get_string('log_excel_date_format'));
693 $row = FIRSTUSEDEXCELROW;
695 $myxls =& $worksheet[$wsnumber];
696 foreach ($logs['logs'] as $log) {
697 if (isset($ldcache[$log->module][$log->action])) {
698 $ld = $ldcache[$log->module][$log->action];
700 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
701 $ldcache[$log->module][$log->action] = $ld;
703 if ($ld && is_numeric($log->info)) {
704 // ugly hack to make sure fullname is shown correctly
705 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
706 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
708 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
713 $log->info = format_string($log->info);
714 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
717 if ($row > EXCELROWS) {
719 $myxls =& $worksheet[$wsnumber];
720 $row = FIRSTUSEDEXCELROW;
724 $coursecontext = context_course::instance($course->id);
726 $myxls->write($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)), '');
727 $myxls->write_date($row, 1, $log->time, $formatDate); // write_date() does conversion/timezone support. MDL-14934
728 $myxls->write($row, 2, $log->ip, '');
729 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
730 $myxls->write($row, 3, $fullname, '');
731 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
732 $myxls->write($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')', '');
733 $myxls->write($row, 5, $log->info, '');
742 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
743 $modid, $modaction, $groupid) {
747 require_once("$CFG->libdir/odslib.class.php");
749 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
750 $modname, $modid, $modaction, $groupid)) {
756 if ($course->id == SITEID) {
758 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
759 foreach ($ccc as $cc) {
760 $courses[$cc->id] = $cc->shortname;
764 $courses[$course->id] = $course->shortname;
769 $tt = getdate(time());
770 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
772 $strftimedatetime = get_string("strftimedatetime");
774 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
775 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
778 $workbook = new MoodleODSWorkbook('-');
779 $workbook->send($filename);
781 $worksheet = array();
782 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
783 get_string('fullnameuser'), get_string('action'), get_string('info'));
785 // Creating worksheets
786 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
787 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
788 $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle);
789 $worksheet[$wsnumber]->set_column(1, 1, 30);
790 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
791 userdate(time(), $strftimedatetime));
793 foreach ($headers as $item) {
794 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
799 if (empty($logs['logs'])) {
804 $formatDate =& $workbook->add_format();
805 $formatDate->set_num_format(get_string('log_excel_date_format'));
807 $row = FIRSTUSEDEXCELROW;
809 $myxls =& $worksheet[$wsnumber];
810 foreach ($logs['logs'] as $log) {
811 if (isset($ldcache[$log->module][$log->action])) {
812 $ld = $ldcache[$log->module][$log->action];
814 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
815 $ldcache[$log->module][$log->action] = $ld;
817 if ($ld && is_numeric($log->info)) {
818 // ugly hack to make sure fullname is shown correctly
819 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
820 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
822 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
827 $log->info = format_string($log->info);
828 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
831 if ($row > EXCELROWS) {
833 $myxls =& $worksheet[$wsnumber];
834 $row = FIRSTUSEDEXCELROW;
838 $coursecontext = context_course::instance($course->id);
840 $myxls->write_string($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)));
841 $myxls->write_date($row, 1, $log->time);
842 $myxls->write_string($row, 2, $log->ip);
843 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
844 $myxls->write_string($row, 3, $fullname);
845 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
846 $myxls->write_string($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')');
847 $myxls->write_string($row, 5, $log->info);
857 * Checks the integrity of the course data.
859 * In summary - compares course_sections.sequence and course_modules.section.
861 * More detailed, checks that:
862 * - course_sections.sequence contains each module id not more than once in the course
863 * - for each moduleid from course_sections.sequence the field course_modules.section
864 * refers to the same section id (this means course_sections.sequence is more
865 * important if they are different)
866 * - ($fullcheck only) each module in the course is present in one of
867 * course_sections.sequence
868 * - ($fullcheck only) removes non-existing course modules from section sequences
870 * If there are any mismatches, the changes are made and records are updated in DB.
872 * Course cache is NOT rebuilt if there are any errors!
874 * This function is used each time when course cache is being rebuilt with $fullcheck = false
875 * and in CLI script admin/cli/fix_course_sequence.php with $fullcheck = true
877 * @param int $courseid id of the course
878 * @param array $rawmods result of funciton {@link get_course_mods()} - containst
879 * the list of enabled course modules in the course. Retrieved from DB if not specified.
880 * Argument ignored in cashe of $fullcheck, the list is retrieved form DB anyway.
881 * @param array $sections records from course_sections table for this course.
882 * Retrieved from DB if not specified
883 * @param bool $fullcheck Will add orphaned modules to their sections and remove non-existing
884 * course modules from sequences. Only to be used in site maintenance mode when we are
885 * sure that another user is not in the middle of the process of moving/removing a module.
886 * @param bool $checkonly Only performs the check without updating DB, outputs all errors as debug messages.
887 * @return array array of messages with found problems. Empty output means everything is ok
889 function course_integrity_check($courseid, $rawmods = null, $sections = null, $fullcheck = false, $checkonly = false) {
892 if ($sections === null) {
893 $sections = $DB->get_records('course_sections', array('course' => $courseid), 'section', 'id,section,sequence');
896 // Retrieve all records from course_modules regardless of module type visibility.
897 $rawmods = $DB->get_records('course_modules', array('course' => $courseid), 'id', 'id,section');
899 if ($rawmods === null) {
900 $rawmods = get_course_mods($courseid);
902 if (!$fullcheck && (empty($sections) || empty($rawmods))) {
903 // If either of the arrays is empty, no modules are displayed anyway.
906 $debuggingprefix = 'Failed integrity check for course ['.$courseid.']. ';
908 // First make sure that each module id appears in section sequences only once.
909 // If it appears in several section sequences the last section wins.
910 // If it appears twice in one section sequence, the first occurence wins.
911 $modsection = array();
912 foreach ($sections as $sectionid => $section) {
913 $sections[$sectionid]->newsequence = $section->sequence;
914 if (!empty($section->sequence)) {
915 $sequence = explode(",", $section->sequence);
916 $sequenceunique = array_unique($sequence);
917 if (count($sequenceunique) != count($sequence)) {
918 // Some course module id appears in this section sequence more than once.
919 ksort($sequenceunique); // Preserve initial order of modules.
920 $sequence = array_values($sequenceunique);
921 $sections[$sectionid]->newsequence = join(',', $sequence);
922 $messages[] = $debuggingprefix.'Sequence for course section ['.
923 $sectionid.'] is "'.$sections[$sectionid]->sequence.'", must be "'.$sections[$sectionid]->newsequence.'"';
925 foreach ($sequence as $cmid) {
926 if (array_key_exists($cmid, $modsection) && isset($rawmods[$cmid])) {
927 // Some course module id appears to be in more than one section's sequences.
928 $wrongsectionid = $modsection[$cmid];
929 $sections[$wrongsectionid]->newsequence = trim(preg_replace("/,$cmid,/", ',', ','.$sections[$wrongsectionid]->newsequence. ','), ',');
930 $messages[] = $debuggingprefix.'Course module ['.$cmid.'] must be removed from sequence of section ['.
931 $wrongsectionid.'] because it is also present in sequence of section ['.$sectionid.']';
933 $modsection[$cmid] = $sectionid;
938 // Add orphaned modules to their sections if they exist or to section 0 otherwise.
940 foreach ($rawmods as $cmid => $mod) {
941 if (!isset($modsection[$cmid])) {
942 // This is a module that is not mentioned in course_section.sequence at all.
943 // Add it to the section $mod->section or to the last available section.
944 if ($mod->section && isset($sections[$mod->section])) {
945 $modsection[$cmid] = $mod->section;
947 $firstsection = reset($sections);
948 $modsection[$cmid] = $firstsection->id;
950 $sections[$modsection[$cmid]]->newsequence = trim($sections[$modsection[$cmid]]->newsequence.','.$cmid, ',');
951 $messages[] = $debuggingprefix.'Course module ['.$cmid.'] is missing from sequence of section ['.
952 $modsection[$cmid].']';
955 foreach ($modsection as $cmid => $sectionid) {
956 if (!isset($rawmods[$cmid])) {
957 // Section $sectionid refers to module id that does not exist.
958 $sections[$sectionid]->newsequence = trim(preg_replace("/,$cmid,/", ',', ','.$sections[$sectionid]->newsequence.','), ',');
959 $messages[] = $debuggingprefix.'Course module ['.$cmid.
960 '] does not exist but is present in the sequence of section ['.$sectionid.']';
965 // Update changed sections.
966 if (!$checkonly && !empty($messages)) {
967 foreach ($sections as $sectionid => $section) {
968 if ($section->newsequence !== $section->sequence) {
969 $DB->update_record('course_sections', array('id' => $sectionid, 'sequence' => $section->newsequence));
974 // Now make sure that all modules point to the correct sections.
975 foreach ($rawmods as $cmid => $mod) {
976 if (isset($modsection[$cmid]) && $modsection[$cmid] != $mod->section) {
978 $DB->update_record('course_modules', array('id' => $cmid, 'section' => $modsection[$cmid]));
980 $messages[] = $debuggingprefix.'Course module ['.$cmid.
981 '] points to section ['.$mod->section.'] instead of ['.$modsection[$cmid].']';
989 * For a given course, returns an array of course activity objects
990 * Each item in the array contains he following properties:
992 function get_array_of_activities($courseid) {
993 // cm - course module id
994 // mod - name of the module (eg forum)
995 // section - the number of the section (eg week or topic)
996 // name - the name of the instance
997 // visible - is the instance visible or not
998 // groupingid - grouping id
999 // extra - contains extra string to include in any link
1002 $course = $DB->get_record('course', array('id'=>$courseid));
1004 if (empty($course)) {
1005 throw new moodle_exception('courseidnotfound');
1010 $rawmods = get_course_mods($courseid);
1011 if (empty($rawmods)) {
1012 return $mod; // always return array
1015 if ($sections = $DB->get_records('course_sections', array('course' => $courseid), 'section ASC', 'id,section,sequence')) {
1016 // First check and correct obvious mismatches between course_sections.sequence and course_modules.section.
1017 if ($errormessages = course_integrity_check($courseid, $rawmods, $sections)) {
1018 debugging(join('<br>', $errormessages));
1019 $rawmods = get_course_mods($courseid);
1020 $sections = $DB->get_records('course_sections', array('course' => $courseid), 'section ASC', 'id,section,sequence');
1022 // Build array of activities.
1023 foreach ($sections as $section) {
1024 if (!empty($section->sequence)) {
1025 $sequence = explode(",", $section->sequence);
1026 foreach ($sequence as $seq) {
1027 if (empty($rawmods[$seq])) {
1030 $mod[$seq] = new stdClass();
1031 $mod[$seq]->id = $rawmods[$seq]->instance;
1032 $mod[$seq]->cm = $rawmods[$seq]->id;
1033 $mod[$seq]->mod = $rawmods[$seq]->modname;
1035 // Oh dear. Inconsistent names left here for backward compatibility.
1036 $mod[$seq]->section = $section->section;
1037 $mod[$seq]->sectionid = $rawmods[$seq]->section;
1039 $mod[$seq]->module = $rawmods[$seq]->module;
1040 $mod[$seq]->added = $rawmods[$seq]->added;
1041 $mod[$seq]->score = $rawmods[$seq]->score;
1042 $mod[$seq]->idnumber = $rawmods[$seq]->idnumber;
1043 $mod[$seq]->visible = $rawmods[$seq]->visible;
1044 $mod[$seq]->visibleold = $rawmods[$seq]->visibleold;
1045 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
1046 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
1047 $mod[$seq]->indent = $rawmods[$seq]->indent;
1048 $mod[$seq]->completion = $rawmods[$seq]->completion;
1049 $mod[$seq]->extra = "";
1050 $mod[$seq]->completiongradeitemnumber =
1051 $rawmods[$seq]->completiongradeitemnumber;
1052 $mod[$seq]->completionview = $rawmods[$seq]->completionview;
1053 $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected;
1054 $mod[$seq]->showdescription = $rawmods[$seq]->showdescription;
1055 $mod[$seq]->availability = $rawmods[$seq]->availability;
1057 $modname = $mod[$seq]->mod;
1058 $functionname = $modname."_get_coursemodule_info";
1060 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
1064 include_once("$CFG->dirroot/mod/$modname/lib.php");
1066 if ($hasfunction = function_exists($functionname)) {
1067 if ($info = $functionname($rawmods[$seq])) {
1068 if (!empty($info->icon)) {
1069 $mod[$seq]->icon = $info->icon;
1071 if (!empty($info->iconcomponent)) {
1072 $mod[$seq]->iconcomponent = $info->iconcomponent;
1074 if (!empty($info->name)) {
1075 $mod[$seq]->name = $info->name;
1077 if ($info instanceof cached_cm_info) {
1078 // When using cached_cm_info you can include three new fields
1079 // that aren't available for legacy code
1080 if (!empty($info->content)) {
1081 $mod[$seq]->content = $info->content;
1083 if (!empty($info->extraclasses)) {
1084 $mod[$seq]->extraclasses = $info->extraclasses;
1086 if (!empty($info->iconurl)) {
1087 // Convert URL to string as it's easier to store. Also serialized object contains \0 byte and can not be written to Postgres DB.
1088 $url = new moodle_url($info->iconurl);
1089 $mod[$seq]->iconurl = $url->out(false);
1091 if (!empty($info->onclick)) {
1092 $mod[$seq]->onclick = $info->onclick;
1094 if (!empty($info->customdata)) {
1095 $mod[$seq]->customdata = $info->customdata;
1098 // When using a stdclass, the (horrible) deprecated ->extra field
1099 // is available for BC
1100 if (!empty($info->extra)) {
1101 $mod[$seq]->extra = $info->extra;
1106 // When there is no modname_get_coursemodule_info function,
1107 // but showdescriptions is enabled, then we use the 'intro'
1108 // and 'introformat' fields in the module table
1109 if (!$hasfunction && $rawmods[$seq]->showdescription) {
1110 if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
1111 array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
1112 // Set content from intro and introformat. Filters are disabled
1113 // because we filter it with format_text at display time
1114 $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
1115 $modvalues, $rawmods[$seq]->id, false);
1117 // To save making another query just below, put name in here
1118 $mod[$seq]->name = $modvalues->name;
1121 if (!isset($mod[$seq]->name)) {
1122 $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
1125 // Minimise the database size by unsetting default options when they are
1126 // 'empty'. This list corresponds to code in the cm_info constructor.
1127 foreach (array('idnumber', 'groupmode', 'groupingid',
1128 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
1129 'icon', 'iconcomponent', 'customdata', 'availability', 'completionview',
1130 'completionexpected', 'score', 'showdescription') as $property) {
1131 if (property_exists($mod[$seq], $property) &&
1132 empty($mod[$seq]->{$property})) {
1133 unset($mod[$seq]->{$property});
1136 // Special case: this value is usually set to null, but may be 0
1137 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
1138 is_null($mod[$seq]->completiongradeitemnumber)) {
1139 unset($mod[$seq]->completiongradeitemnumber);
1149 * Returns the localised human-readable names of all used modules
1151 * @param bool $plural if true returns the plural forms of the names
1152 * @return array where key is the module name (component name without 'mod_') and
1153 * the value is the human-readable string. Array sorted alphabetically by value
1155 function get_module_types_names($plural = false) {
1156 static $modnames = null;
1158 if ($modnames === null) {
1159 $modnames = array(0 => array(), 1 => array());
1160 if ($allmods = $DB->get_records("modules")) {
1161 foreach ($allmods as $mod) {
1162 if (file_exists("$CFG->dirroot/mod/$mod->name/lib.php") && $mod->visible) {
1163 $modnames[0][$mod->name] = get_string("modulename", "$mod->name");
1164 $modnames[1][$mod->name] = get_string("modulenameplural", "$mod->name");
1167 core_collator::asort($modnames[0]);
1168 core_collator::asort($modnames[1]);
1171 return $modnames[(int)$plural];
1175 * Set highlighted section. Only one section can be highlighted at the time.
1177 * @param int $courseid course id
1178 * @param int $marker highlight section with this number, 0 means remove higlightin
1181 function course_set_marker($courseid, $marker) {
1183 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
1184 format_base::reset_course_cache($courseid);
1188 * For a given course section, marks it visible or hidden,
1189 * and does the same for every activity in that section
1191 * @param int $courseid course id
1192 * @param int $sectionnumber The section number to adjust
1193 * @param int $visibility The new visibility
1194 * @return array A list of resources which were hidden in the section
1196 function set_section_visible($courseid, $sectionnumber, $visibility) {
1199 $resourcestotoggle = array();
1200 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
1201 $DB->set_field("course_sections", "visible", "$visibility", array("id"=>$section->id));
1203 $event = \core\event\course_section_updated::create(array(
1204 'context' => context_course::instance($courseid),
1205 'objectid' => $section->id,
1207 'sectionnum' => $sectionnumber
1210 $event->add_record_snapshot('course_sections', $section);
1213 if (!empty($section->sequence)) {
1214 $modules = explode(",", $section->sequence);
1215 foreach ($modules as $moduleid) {
1216 if ($cm = get_coursemodule_from_id(null, $moduleid, $courseid)) {
1218 // As we unhide the section, we use the previously saved visibility stored in visibleold.
1219 set_coursemodule_visible($moduleid, $cm->visibleold);
1221 // We hide the section, so we hide the module but we store the original state in visibleold.
1222 set_coursemodule_visible($moduleid, 0);
1223 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id' => $moduleid));
1225 \core\event\course_module_updated::create_from_cm($cm)->trigger();
1229 rebuild_course_cache($courseid, true);
1231 // Determine which modules are visible for AJAX update
1232 if (!empty($modules)) {
1233 list($insql, $params) = $DB->get_in_or_equal($modules);
1234 $select = 'id ' . $insql . ' AND visible = ?';
1235 array_push($params, $visibility);
1237 $select .= ' AND visibleold = 1';
1239 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
1242 return $resourcestotoggle;
1246 * Retrieve all metadata for the requested modules
1248 * @param object $course The Course
1249 * @param array $modnames An array containing the list of modules and their
1251 * @param int $sectionreturn The section to return to
1252 * @return array A list of stdClass objects containing metadata about each
1255 function get_module_metadata($course, $modnames, $sectionreturn = null) {
1256 global $CFG, $OUTPUT;
1258 // get_module_metadata will be called once per section on the page and courses may show
1259 // different modules to one another
1260 static $modlist = array();
1261 if (!isset($modlist[$course->id])) {
1262 $modlist[$course->id] = array();
1266 $urlbase = new moodle_url('/course/mod.php', array('id' => $course->id, 'sesskey' => sesskey()));
1267 if ($sectionreturn !== null) {
1268 $urlbase->param('sr', $sectionreturn);
1270 foreach($modnames as $modname => $modnamestr) {
1271 if (!course_allowed_module($course, $modname)) {
1274 if (isset($modlist[$course->id][$modname])) {
1275 // This module is already cached
1276 $return[$modname] = $modlist[$course->id][$modname];
1280 // Include the module lib
1281 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1282 if (!file_exists($libfile)) {
1285 include_once($libfile);
1287 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1288 $gettypesfunc = $modname.'_get_types';
1289 $types = MOD_SUBTYPE_NO_CHILDREN;
1290 if (function_exists($gettypesfunc)) {
1291 $types = $gettypesfunc();
1293 if ($types !== MOD_SUBTYPE_NO_CHILDREN) {
1294 if (is_array($types) && count($types) > 0) {
1295 $group = new stdClass();
1296 $group->name = $modname;
1297 $group->icon = $OUTPUT->pix_icon('icon', '', $modname, array('class' => 'icon'));
1298 foreach($types as $type) {
1299 if ($type->typestr === '--') {
1302 if (strpos($type->typestr, '--') === 0) {
1303 $group->title = str_replace('--', '', $type->typestr);
1306 // Set the Sub Type metadata
1307 $subtype = new stdClass();
1308 $subtype->title = $type->typestr;
1309 $subtype->type = str_replace('&', '&', $type->type);
1310 $subtype->name = preg_replace('/.*type=/', '', $subtype->type);
1311 $subtype->archetype = $type->modclass;
1313 // The group archetype should match the subtype archetypes and all subtypes
1314 // should have the same archetype
1315 $group->archetype = $subtype->archetype;
1317 if (!empty($type->help)) {
1318 $subtype->help = $type->help;
1319 } else if (get_string_manager()->string_exists('help' . $subtype->name, $modname)) {
1320 $subtype->help = get_string('help' . $subtype->name, $modname);
1322 $subtype->link = new moodle_url($urlbase, array('add' => $modname, 'type' => $subtype->name));
1323 $group->types[] = $subtype;
1325 $modlist[$course->id][$modname] = $group;
1328 $module = new stdClass();
1329 $module->title = $modnamestr;
1330 $module->name = $modname;
1331 $module->link = new moodle_url($urlbase, array('add' => $modname));
1332 $module->icon = $OUTPUT->pix_icon('icon', '', $module->name, array('class' => 'icon'));
1333 $sm = get_string_manager();
1334 if ($sm->string_exists('modulename_help', $modname)) {
1335 $module->help = get_string('modulename_help', $modname);
1336 if ($sm->string_exists('modulename_link', $modname)) { // Link to further info in Moodle docs
1337 $link = get_string('modulename_link', $modname);
1338 $linktext = get_string('morehelp');
1339 $module->help .= html_writer::tag('div', $OUTPUT->doc_link($link, $linktext, true), array('class' => 'helpdoclink'));
1342 $module->archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1343 $modlist[$course->id][$modname] = $module;
1345 if (isset($modlist[$course->id][$modname])) {
1346 $return[$modname] = $modlist[$course->id][$modname];
1348 debugging("Invalid module metadata configuration for {$modname}");
1356 * Return the course category context for the category with id $categoryid, except
1357 * that if $categoryid is 0, return the system context.
1359 * @param integer $categoryid a category id or 0.
1360 * @return context the corresponding context
1362 function get_category_or_system_context($categoryid) {
1364 return context_coursecat::instance($categoryid, IGNORE_MISSING);
1366 return context_system::instance();
1371 * Returns full course categories trees to be used in html_writer::select()
1373 * Calls {@link coursecat::make_categories_list()} to build the tree and
1374 * adds whitespace to denote nesting
1376 * @return array array mapping coursecat id to the display name
1378 function make_categories_options() {
1380 require_once($CFG->libdir. '/coursecatlib.php');
1381 $cats = coursecat::make_categories_list('', 0, ' / ');
1382 foreach ($cats as $key => $value) {
1383 // Prefix the value with the number of spaces equal to category depth (number of separators in the value).
1384 $cats[$key] = str_repeat(' ', substr_count($value, ' / ')). $value;
1390 * Print the buttons relating to course requests.
1392 * @param object $context current page context.
1394 function print_course_request_buttons($context) {
1395 global $CFG, $DB, $OUTPUT;
1396 if (empty($CFG->enablecourserequests)) {
1399 if (!has_capability('moodle/course:create', $context) && has_capability('moodle/course:request', $context)) {
1400 /// Print a button to request a new course
1401 echo $OUTPUT->single_button(new moodle_url('/course/request.php'), get_string('requestcourse'), 'get');
1403 /// Print a button to manage pending requests
1404 if ($context->contextlevel == CONTEXT_SYSTEM && has_capability('moodle/site:approvecourse', $context)) {
1405 $disabled = !$DB->record_exists('course_request', array());
1406 echo $OUTPUT->single_button(new moodle_url('/course/pending.php'), get_string('coursespending'), 'get', array('disabled' => $disabled));
1411 * Does the user have permission to edit things in this category?
1413 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
1414 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
1416 function can_edit_in_category($categoryid = 0) {
1417 $context = get_category_or_system_context($categoryid);
1418 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
1421 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
1423 function add_course_module($mod) {
1426 $mod->added = time();
1429 $cmid = $DB->insert_record("course_modules", $mod);
1430 rebuild_course_cache($mod->course, true);
1435 * Creates missing course section(s) and rebuilds course cache
1437 * @param int|stdClass $courseorid course id or course object
1438 * @param int|array $sections list of relative section numbers to create
1439 * @return bool if there were any sections created
1441 function course_create_sections_if_missing($courseorid, $sections) {
1443 if (!is_array($sections)) {
1444 $sections = array($sections);
1446 $existing = array_keys(get_fast_modinfo($courseorid)->get_section_info_all());
1447 if (is_object($courseorid)) {
1448 $courseorid = $courseorid->id;
1450 $coursechanged = false;
1451 foreach ($sections as $sectionnum) {
1452 if (!in_array($sectionnum, $existing)) {
1453 $cw = new stdClass();
1454 $cw->course = $courseorid;
1455 $cw->section = $sectionnum;
1457 $cw->summaryformat = FORMAT_HTML;
1459 $id = $DB->insert_record("course_sections", $cw);
1460 $coursechanged = true;
1463 if ($coursechanged) {
1464 rebuild_course_cache($courseorid, true);
1466 return $coursechanged;
1470 * Adds an existing module to the section
1472 * Updates both tables {course_sections} and {course_modules}
1474 * Note: This function does not use modinfo PROVIDED that the section you are
1475 * adding the module to already exists. If the section does not exist, it will
1476 * build modinfo if necessary and create the section.
1478 * @param int|stdClass $courseorid course id or course object
1479 * @param int $cmid id of the module already existing in course_modules table
1480 * @param int $sectionnum relative number of the section (field course_sections.section)
1481 * If section does not exist it will be created
1482 * @param int|stdClass $beforemod id or object with field id corresponding to the module
1483 * before which the module needs to be included. Null for inserting in the
1484 * end of the section
1485 * @return int The course_sections ID where the module is inserted
1487 function course_add_cm_to_section($courseorid, $cmid, $sectionnum, $beforemod = null) {
1488 global $DB, $COURSE;
1489 if (is_object($beforemod)) {
1490 $beforemod = $beforemod->id;
1492 if (is_object($courseorid)) {
1493 $courseid = $courseorid->id;
1495 $courseid = $courseorid;
1497 // Do not try to use modinfo here, there is no guarantee it is valid!
1498 $section = $DB->get_record('course_sections',
1499 array('course' => $courseid, 'section' => $sectionnum), '*', IGNORE_MISSING);
1501 // This function call requires modinfo.
1502 course_create_sections_if_missing($courseorid, $sectionnum);
1503 $section = $DB->get_record('course_sections',
1504 array('course' => $courseid, 'section' => $sectionnum), '*', MUST_EXIST);
1507 $modarray = explode(",", trim($section->sequence));
1508 if (empty($section->sequence)) {
1509 $newsequence = "$cmid";
1510 } else if ($beforemod && ($key = array_keys($modarray, $beforemod))) {
1511 $insertarray = array($cmid, $beforemod);
1512 array_splice($modarray, $key[0], 1, $insertarray);
1513 $newsequence = implode(",", $modarray);
1515 $newsequence = "$section->sequence,$cmid";
1517 $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id));
1518 $DB->set_field('course_modules', 'section', $section->id, array('id' => $cmid));
1519 if (is_object($courseorid)) {
1520 rebuild_course_cache($courseorid->id, true);
1522 rebuild_course_cache($courseorid, true);
1524 return $section->id; // Return course_sections ID that was used.
1528 * Change the group mode of a course module.
1530 * Note: Do not forget to trigger the event \core\event\course_module_updated as it needs
1531 * to be triggered manually, refer to {@link \core\event\course_module_updated::create_from_cm()}.
1533 * @param int $id course module ID.
1534 * @param int $groupmode the new groupmode value.
1535 * @return bool True if the $groupmode was updated.
1537 function set_coursemodule_groupmode($id, $groupmode) {
1539 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST);
1540 if ($cm->groupmode != $groupmode) {
1541 $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id));
1542 rebuild_course_cache($cm->course, true);
1544 return ($cm->groupmode != $groupmode);
1547 function set_coursemodule_idnumber($id, $idnumber) {
1549 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST);
1550 if ($cm->idnumber != $idnumber) {
1551 $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id));
1552 rebuild_course_cache($cm->course, true);
1554 return ($cm->idnumber != $idnumber);
1558 * Set the visibility of a module and inherent properties.
1560 * Note: Do not forget to trigger the event \core\event\course_module_updated as it needs
1561 * to be triggered manually, refer to {@link \core\event\course_module_updated::create_from_cm()}.
1563 * From 2.4 the parameter $prevstateoverrides has been removed, the logic it triggered
1564 * has been moved to {@link set_section_visible()} which was the only place from which
1565 * the parameter was used.
1567 * @param int $id of the module
1568 * @param int $visible state of the module
1569 * @return bool false when the module was not found, true otherwise
1571 function set_coursemodule_visible($id, $visible) {
1573 require_once($CFG->libdir.'/gradelib.php');
1574 require_once($CFG->dirroot.'/calendar/lib.php');
1576 // Trigger developer's attention when using the previously removed argument.
1577 if (func_num_args() > 2) {
1578 debugging('Wrong number of arguments passed to set_coursemodule_visible(), $prevstateoverrides
1579 has been removed.', DEBUG_DEVELOPER);
1582 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
1586 // Create events and propagate visibility to associated grade items if the value has changed.
1587 // Only do this if it's changed to avoid accidently overwriting manual showing/hiding of student grades.
1588 if ($cm->visible == $visible) {
1592 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
1595 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
1596 foreach($events as $event) {
1598 $event = new calendar_event($event);
1599 $event->toggle_visibility(true);
1601 $event = new calendar_event($event);
1602 $event->toggle_visibility(false);
1607 // Updating visible and visibleold to keep them in sync. Only changing a section visibility will
1608 // affect visibleold to allow for an original visibility restore. See set_section_visible().
1609 $cminfo = new stdClass();
1611 $cminfo->visible = $visible;
1612 $cminfo->visibleold = $visible;
1613 $DB->update_record('course_modules', $cminfo);
1615 // Hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there.
1616 // Note that this must be done after updating the row in course_modules, in case
1617 // the modules grade_item_update function needs to access $cm->visible.
1618 if (plugin_supports('mod', $modulename, FEATURE_CONTROLS_GRADE_VISIBILITY) &&
1619 component_callback_exists('mod_' . $modulename, 'grade_item_update')) {
1620 $instance = $DB->get_record($modulename, array('id' => $cm->instance), '*', MUST_EXIST);
1621 component_callback('mod_' . $modulename, 'grade_item_update', array($instance));
1623 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
1625 foreach ($grade_items as $grade_item) {
1626 $grade_item->set_hidden(!$visible);
1631 rebuild_course_cache($cm->course, true);
1636 * This function will handle the whole deletion process of a module. This includes calling
1637 * the modules delete_instance function, deleting files, events, grades, conditional data,
1638 * the data in the course_module and course_sections table and adding a module deletion
1641 * @param int $cmid the course module id
1644 function course_delete_module($cmid) {
1647 require_once($CFG->libdir.'/gradelib.php');
1648 require_once($CFG->libdir.'/questionlib.php');
1649 require_once($CFG->dirroot.'/blog/lib.php');
1650 require_once($CFG->dirroot.'/calendar/lib.php');
1652 // Get the course module.
1653 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
1657 // Get the module context.
1658 $modcontext = context_module::instance($cm->id);
1660 // Get the course module name.
1661 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
1663 // Get the file location of the delete_instance function for this module.
1664 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
1666 // Include the file required to call the delete_instance function for this module.
1667 if (file_exists($modlib)) {
1668 require_once($modlib);
1670 throw new moodle_exception('cannotdeletemodulemissinglib', '', '', null,
1671 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
1674 $deleteinstancefunction = $modulename . '_delete_instance';
1676 // Ensure the delete_instance function exists for this module.
1677 if (!function_exists($deleteinstancefunction)) {
1678 throw new moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
1679 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
1682 // Delete activity context questions and question categories.
1683 question_delete_activity($cm);
1685 // Call the delete_instance function, if it returns false throw an exception.
1686 if (!$deleteinstancefunction($cm->instance)) {
1687 throw new moodle_exception('cannotdeletemoduleinstance', '', '', null,
1688 "Cannot delete the module $modulename (instance).");
1691 // Remove all module files in case modules forget to do that.
1692 $fs = get_file_storage();
1693 $fs->delete_area_files($modcontext->id);
1695 // Delete events from calendar.
1696 if ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename))) {
1697 foreach($events as $event) {
1698 $calendarevent = calendar_event::load($event->id);
1699 $calendarevent->delete();
1703 // Delete grade items, outcome items and grades attached to modules.
1704 if ($grade_items = grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $modulename,
1705 'iteminstance' => $cm->instance, 'courseid' => $cm->course))) {
1706 foreach ($grade_items as $grade_item) {
1707 $grade_item->delete('moddelete');
1711 // Delete completion and availability data; it is better to do this even if the
1712 // features are not turned on, in case they were turned on previously (these will be
1713 // very quick on an empty table).
1714 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
1715 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
1716 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
1718 // Delete all tag instances associated with the instance of this module.
1719 core_tag::delete_instances('mod_' . $modulename, null, $modcontext->id);
1721 // Delete the context.
1722 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
1724 // Delete the module from the course_modules table.
1725 $DB->delete_records('course_modules', array('id' => $cm->id));
1727 // Delete module from that section.
1728 if (!delete_mod_from_section($cm->id, $cm->section)) {
1729 throw new moodle_exception('cannotdeletemodulefromsection', '', '', null,
1730 "Cannot delete the module $modulename (instance) from section.");
1733 // Trigger event for course module delete action.
1734 $event = \core\event\course_module_deleted::create(array(
1735 'courseid' => $cm->course,
1736 'context' => $modcontext,
1737 'objectid' => $cm->id,
1739 'modulename' => $modulename,
1740 'instanceid' => $cm->instance,
1743 $event->add_record_snapshot('course_modules', $cm);
1745 rebuild_course_cache($cm->course, true);
1748 function delete_mod_from_section($modid, $sectionid) {
1751 if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
1753 $modarray = explode(",", $section->sequence);
1755 if ($key = array_keys ($modarray, $modid)) {
1756 array_splice($modarray, $key[0], 1);
1757 $newsequence = implode(",", $modarray);
1758 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
1759 rebuild_course_cache($section->course, true);
1770 * Moves a section within a course, from a position to another.
1771 * Be very careful: $section and $destination refer to section number,
1774 * @param object $course
1775 * @param int $section Section number (not id!!!)
1776 * @param int $destination
1777 * @param bool $ignorenumsections
1778 * @return boolean Result
1780 function move_section_to($course, $section, $destination, $ignorenumsections = false) {
1781 /// Moves a whole course section up and down within the course
1784 if (!$destination && $destination != 0) {
1788 // compartibility with course formats using field 'numsections'
1789 $courseformatoptions = course_get_format($course)->get_format_options();
1790 if ((!$ignorenumsections && array_key_exists('numsections', $courseformatoptions) &&
1791 ($destination > $courseformatoptions['numsections'])) || ($destination < 1)) {
1795 // Get all sections for this course and re-order them (2 of them should now share the same section number)
1796 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
1797 'section ASC, id ASC', 'id, section')) {
1801 $movedsections = reorder_sections($sections, $section, $destination);
1803 // Update all sections. Do this in 2 steps to avoid breaking database
1804 // uniqueness constraint
1805 $transaction = $DB->start_delegated_transaction();
1806 foreach ($movedsections as $id => $position) {
1807 if ($sections[$id] !== $position) {
1808 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
1811 foreach ($movedsections as $id => $position) {
1812 if ($sections[$id] !== $position) {
1813 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
1817 // If we move the highlighted section itself, then just highlight the destination.
1818 // Adjust the higlighted section location if we move something over it either direction.
1819 if ($section == $course->marker) {
1820 course_set_marker($course->id, $destination);
1821 } elseif ($section > $course->marker && $course->marker >= $destination) {
1822 course_set_marker($course->id, $course->marker+1);
1823 } elseif ($section < $course->marker && $course->marker <= $destination) {
1824 course_set_marker($course->id, $course->marker-1);
1827 $transaction->allow_commit();
1828 rebuild_course_cache($course->id, true);
1833 * This method will delete a course section and may delete all modules inside it.
1835 * No permissions are checked here, use {@link course_can_delete_section()} to
1836 * check if section can actually be deleted.
1838 * @param int|stdClass $course
1839 * @param int|stdClass|section_info $section
1840 * @param bool $forcedeleteifnotempty if set to false section will not be deleted if it has modules in it.
1841 * @return bool whether section was deleted
1843 function course_delete_section($course, $section, $forcedeleteifnotempty = true) {
1846 // Prepare variables.
1847 $courseid = (is_object($course)) ? $course->id : (int)$course;
1848 $sectionnum = (is_object($section)) ? $section->section : (int)$section;
1849 $section = $DB->get_record('course_sections', array('course' => $courseid, 'section' => $sectionnum));
1851 // No section exists, can't proceed.
1854 $format = course_get_format($course);
1855 $sectionname = $format->get_section_name($section);
1858 $result = $format->delete_section($section, $forcedeleteifnotempty);
1860 // Trigger an event for course section deletion.
1862 $context = context_course::instance($courseid);
1863 $event = \core\event\course_section_deleted::create(
1865 'objectid' => $section->id,
1866 'courseid' => $courseid,
1867 'context' => $context,
1869 'sectionnum' => $section->section,
1870 'sectionname' => $sectionname,
1874 $event->add_record_snapshot('course_sections', $section);
1881 * Checks if the current user can delete a section (if course format allows it and user has proper permissions).
1883 * @param int|stdClass $course
1884 * @param int|stdClass|section_info $section
1887 function course_can_delete_section($course, $section) {
1888 if (is_object($section)) {
1889 $section = $section->section;
1892 // Not possible to delete 0-section.
1895 // Course format should allow to delete sections.
1896 if (!course_get_format($course)->can_delete_section($section)) {
1899 // Make sure user has capability to update course and move sections.
1900 $context = context_course::instance(is_object($course) ? $course->id : $course);
1901 if (!has_all_capabilities(array('moodle/course:movesections', 'moodle/course:update'), $context)) {
1904 // Make sure user has capability to delete each activity in this section.
1905 $modinfo = get_fast_modinfo($course);
1906 if (!empty($modinfo->sections[$section])) {
1907 foreach ($modinfo->sections[$section] as $cmid) {
1908 if (!has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
1917 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
1918 * an original position number and a target position number, rebuilds the array so that the
1919 * move is made without any duplication of section positions.
1920 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
1921 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
1923 * @param array $sections
1924 * @param int $origin_position
1925 * @param int $target_position
1928 function reorder_sections($sections, $origin_position, $target_position) {
1929 if (!is_array($sections)) {
1933 // We can't move section position 0
1934 if ($origin_position < 1) {
1935 echo "We can't move section position 0";
1939 // Locate origin section in sections array
1940 if (!$origin_key = array_search($origin_position, $sections)) {
1941 echo "searched position not in sections array";
1942 return false; // searched position not in sections array
1945 // Extract origin section
1946 $origin_section = $sections[$origin_key];
1947 unset($sections[$origin_key]);
1949 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
1951 $append_array = array();
1952 foreach ($sections as $id => $position) {
1954 $append_array[$id] = $position;
1955 unset($sections[$id]);
1957 if ($position == $target_position) {
1958 if ($target_position < $origin_position) {
1959 $append_array[$id] = $position;
1960 unset($sections[$id]);
1966 // Append moved section
1967 $sections[$origin_key] = $origin_section;
1969 // Append rest of array (if applicable)
1970 if (!empty($append_array)) {
1971 foreach ($append_array as $id => $position) {
1972 $sections[$id] = $position;
1976 // Renumber positions
1978 foreach ($sections as $id => $p) {
1979 $sections[$id] = $position;
1988 * Move the module object $mod to the specified $section
1989 * If $beforemod exists then that is the module
1990 * before which $modid should be inserted
1992 * @param stdClass|cm_info $mod
1993 * @param stdClass|section_info $section
1994 * @param int|stdClass $beforemod id or object with field id corresponding to the module
1995 * before which the module needs to be included. Null for inserting in the
1996 * end of the section
1997 * @return int new value for module visibility (0 or 1)
1999 function moveto_module($mod, $section, $beforemod=NULL) {
2000 global $OUTPUT, $DB;
2002 // Current module visibility state - return value of this function.
2003 $modvisible = $mod->visible;
2005 // Remove original module from original section.
2006 if (! delete_mod_from_section($mod->id, $mod->section)) {
2007 echo $OUTPUT->notification("Could not delete module from existing section");
2010 // If moving to a hidden section then hide module.
2011 if ($mod->section != $section->id) {
2012 if (!$section->visible && $mod->visible) {
2013 // Module was visible but must become hidden after moving to hidden section.
2015 set_coursemodule_visible($mod->id, 0);
2016 // Set visibleold to 1 so module will be visible when section is made visible.
2017 $DB->set_field('course_modules', 'visibleold', 1, array('id' => $mod->id));
2019 if ($section->visible && !$mod->visible) {
2020 // Hidden module was moved to the visible section, restore the module visibility from visibleold.
2021 set_coursemodule_visible($mod->id, $mod->visibleold);
2022 $modvisible = $mod->visibleold;
2026 // Add the module into the new section.
2027 course_add_cm_to_section($section->course, $mod->id, $section->section, $beforemod);
2032 * Returns the list of all editing actions that current user can perform on the module
2034 * @param cm_info $mod The module to produce editing buttons for
2035 * @param int $indent The current indenting (default -1 means no move left-right actions)
2036 * @param int $sr The section to link back to (used for creating the links)
2037 * @return array array of action_link or pix_icon objects
2039 function course_get_cm_edit_actions(cm_info $mod, $indent = -1, $sr = null) {
2040 global $COURSE, $SITE;
2044 $coursecontext = context_course::instance($mod->course);
2045 $modcontext = context_module::instance($mod->id);
2047 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
2048 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
2050 // No permission to edit anything.
2051 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
2055 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
2058 $str = get_strings(array('delete', 'move', 'moveright', 'moveleft',
2059 'editsettings', 'duplicate', 'hide', 'show'), 'moodle');
2060 $str->assign = get_string('assignroles', 'role');
2061 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
2062 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
2063 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
2066 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
2069 $baseurl->param('sr', $sr);
2074 if ($hasmanageactivities) {
2075 $actions['update'] = new action_menu_link_secondary(
2076 new moodle_url($baseurl, array('update' => $mod->id)),
2077 new pix_icon('t/edit', $str->editsettings, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2079 array('class' => 'editing_update', 'data-action' => 'update')
2084 if ($hasmanageactivities && $indent >= 0) {
2085 $indentlimits = new stdClass();
2086 $indentlimits->min = 0;
2087 $indentlimits->max = 16;
2088 if (right_to_left()) { // Exchange arrows on RTL
2089 $rightarrow = 't/left';
2090 $leftarrow = 't/right';
2092 $rightarrow = 't/right';
2093 $leftarrow = 't/left';
2096 if ($indent >= $indentlimits->max) {
2097 $enabledclass = 'hidden';
2101 $actions['moveright'] = new action_menu_link_secondary(
2102 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
2103 new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2105 array('class' => 'editing_moveright ' . $enabledclass, 'data-action' => 'moveright', 'data-keepopen' => true)
2108 if ($indent <= $indentlimits->min) {
2109 $enabledclass = 'hidden';
2113 $actions['moveleft'] = new action_menu_link_secondary(
2114 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
2115 new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2117 array('class' => 'editing_moveleft ' . $enabledclass, 'data-action' => 'moveleft', 'data-keepopen' => true)
2123 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
2124 if ($mod->visible) {
2125 $actions['hide'] = new action_menu_link_secondary(
2126 new moodle_url($baseurl, array('hide' => $mod->id)),
2127 new pix_icon('t/hide', $str->hide, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2129 array('class' => 'editing_hide', 'data-action' => 'hide')
2132 $actions['show'] = new action_menu_link_secondary(
2133 new moodle_url($baseurl, array('show' => $mod->id)),
2134 new pix_icon('t/show', $str->show, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2136 array('class' => 'editing_show', 'data-action' => 'show')
2141 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
2142 if (has_all_capabilities($dupecaps, $coursecontext) &&
2143 plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2)) {
2144 $actions['duplicate'] = new action_menu_link_secondary(
2145 new moodle_url($baseurl, array('duplicate' => $mod->id)),
2146 new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2148 array('class' => 'editing_duplicate', 'data-action' => 'duplicate', 'data-sr' => $sr)
2153 if ($hasmanageactivities && !$mod->coursegroupmodeforce) {
2154 if (plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
2155 if ($mod->effectivegroupmode == SEPARATEGROUPS) {
2156 $nextgroupmode = VISIBLEGROUPS;
2157 $grouptitle = $str->groupsseparate;
2158 $actionname = 'groupsseparate';
2159 $groupimage = 'i/groups';
2160 } else if ($mod->effectivegroupmode == VISIBLEGROUPS) {
2161 $nextgroupmode = NOGROUPS;
2162 $grouptitle = $str->groupsvisible;
2163 $actionname = 'groupsvisible';
2164 $groupimage = 'i/groupv';
2166 $nextgroupmode = SEPARATEGROUPS;
2167 $grouptitle = $str->groupsnone;
2168 $actionname = 'groupsnone';
2169 $groupimage = 'i/groupn';
2172 $actions[$actionname] = new action_menu_link_primary(
2173 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $nextgroupmode)),
2174 new pix_icon($groupimage, null, 'moodle', array('class' => 'iconsmall')),
2176 array('class' => 'editing_'. $actionname, 'data-action' => $actionname, 'data-nextgroupmode' => $nextgroupmode, 'aria-live' => 'assertive')
2179 $actions['nogroupsupport'] = new action_menu_filler();
2184 if (has_capability('moodle/role:assign', $modcontext)){
2185 $actions['assign'] = new action_menu_link_secondary(
2186 new moodle_url('/admin/roles/assign.php', array('contextid' => $modcontext->id)),
2187 new pix_icon('t/assignroles', $str->assign, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2189 array('class' => 'editing_assign', 'data-action' => 'assignroles')
2194 if ($hasmanageactivities) {
2195 $actions['delete'] = new action_menu_link_secondary(
2196 new moodle_url($baseurl, array('delete' => $mod->id)),
2197 new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2199 array('class' => 'editing_delete', 'data-action' => 'delete')
2207 * Returns the rename action.
2209 * @param cm_info $mod The module to produce editing buttons for
2210 * @param int $sr The section to link back to (used for creating the links)
2211 * @return The markup for the rename action, or an empty string if not available.
2213 function course_get_cm_rename_action(cm_info $mod, $sr = null) {
2214 global $COURSE, $OUTPUT;
2219 $modcontext = context_module::instance($mod->id);
2220 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
2223 $str = get_strings(array('edittitle'));
2226 if (!isset($baseurl)) {
2227 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
2231 $baseurl->param('sr', $sr);
2235 if ($mod->has_view() && $hasmanageactivities && course_ajax_enabled($COURSE) &&
2236 (($mod->course == $COURSE->id) || ($mod->course == SITEID))) {
2237 // we will not display link if we are on some other-course page (where we should not see this module anyway)
2238 return html_writer::span(
2240 new moodle_url($baseurl, array('update' => $mod->id)),
2241 $OUTPUT->pix_icon('t/editstring', '', 'moodle', array('class' => 'iconsmall visibleifjs', 'title' => '')),
2243 'class' => 'editing_title',
2244 'data-action' => 'edittitle',
2245 'title' => $str->edittitle,
2254 * Returns the move action.
2256 * @param cm_info $mod The module to produce a move button for
2257 * @param int $sr The section to link back to (used for creating the links)
2258 * @return The markup for the move action, or an empty string if not available.
2260 function course_get_cm_move(cm_info $mod, $sr = null) {
2266 $modcontext = context_module::instance($mod->id);
2267 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
2270 $str = get_strings(array('move'));
2273 if (!isset($baseurl)) {
2274 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
2277 $baseurl->param('sr', $sr);
2281 if ($hasmanageactivities) {
2282 $pixicon = 'i/dragdrop';
2284 if (!course_ajax_enabled($mod->get_course())) {
2285 // Override for course frontpage until we get drag/drop working there.
2286 $pixicon = 't/move';
2289 return html_writer::link(
2290 new moodle_url($baseurl, array('copy' => $mod->id)),
2291 $OUTPUT->pix_icon($pixicon, $str->move, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2292 array('class' => 'editing_move', 'data-action' => 'move')
2299 * given a course object with shortname & fullname, this function will
2300 * truncate the the number of chars allowed and add ... if it was too long
2302 function course_format_name ($course,$max=100) {
2304 $context = context_course::instance($course->id);
2305 $shortname = format_string($course->shortname, true, array('context' => $context));
2306 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
2307 $str = $shortname.': '. $fullname;
2308 if (core_text::strlen($str) <= $max) {
2312 return core_text::substr($str,0,$max-3).'...';
2317 * Is the user allowed to add this type of module to this course?
2318 * @param object $course the course settings. Only $course->id is used.
2319 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
2320 * @return bool whether the current user is allowed to add this type of module to this course.
2322 function course_allowed_module($course, $modname) {
2323 if (is_numeric($modname)) {
2324 throw new coding_exception('Function course_allowed_module no longer
2325 supports numeric module ids. Please update your code to pass the module name.');
2328 $capability = 'mod/' . $modname . ':addinstance';
2329 if (!get_capability_info($capability)) {
2330 // Debug warning that the capability does not exist, but no more than once per page.
2331 static $warned = array();
2332 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
2333 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
2334 debugging('The module ' . $modname . ' does not define the standard capability ' .
2335 $capability , DEBUG_DEVELOPER);
2336 $warned[$modname] = 1;
2339 // If the capability does not exist, the module can always be added.
2343 $coursecontext = context_course::instance($course->id);
2344 return has_capability($capability, $coursecontext);
2348 * Efficiently moves many courses around while maintaining
2349 * sortorder in order.
2351 * @param array $courseids is an array of course ids
2352 * @param int $categoryid
2353 * @return bool success
2355 function move_courses($courseids, $categoryid) {
2358 if (empty($courseids)) {
2363 if (!$category = $DB->get_record('course_categories', array('id' => $categoryid))) {
2367 $courseids = array_reverse($courseids);
2368 $newparent = context_coursecat::instance($category->id);
2371 list($where, $params) = $DB->get_in_or_equal($courseids);
2372 $dbcourses = $DB->get_records_select('course', 'id ' . $where, $params, '', 'id, category, shortname, fullname');
2373 foreach ($dbcourses as $dbcourse) {
2374 $course = new stdClass();
2375 $course->id = $dbcourse->id;
2376 $course->category = $category->id;
2377 $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
2378 if ($category->visible == 0) {
2379 // Hide the course when moving into hidden category, do not update the visibleold flag - we want to get
2380 // to previous state if somebody unhides the category.
2381 $course->visible = 0;
2384 $DB->update_record('course', $course);
2386 // Update context, so it can be passed to event.
2387 $context = context_course::instance($course->id);
2388 $context->update_moved($newparent);
2390 // Trigger a course updated event.
2391 $event = \core\event\course_updated::create(array(
2392 'objectid' => $course->id,
2393 'context' => context_course::instance($course->id),
2394 'other' => array('shortname' => $dbcourse->shortname,
2395 'fullname' => $dbcourse->fullname)
2397 $event->set_legacy_logdata(array($course->id, 'course', 'move', 'edit.php?id=' . $course->id, $course->id));
2400 fix_course_sortorder();
2401 cache_helper::purge_by_event('changesincourse');
2407 * Returns the display name of the given section that the course prefers
2409 * Implementation of this function is provided by course format
2410 * @see format_base::get_section_name()
2412 * @param int|stdClass $courseorid The course to get the section name for (object or just course id)
2413 * @param int|stdClass $section Section object from database or just field course_sections.section
2414 * @return string Display name that the course format prefers, e.g. "Week 2"
2416 function get_section_name($courseorid, $section) {
2417 return course_get_format($courseorid)->get_section_name($section);
2421 * Tells if current course format uses sections
2423 * @param string $format Course format ID e.g. 'weeks' $course->format
2426 function course_format_uses_sections($format) {
2427 $course = new stdClass();
2428 $course->format = $format;
2429 return course_get_format($course)->uses_sections();
2433 * Returns the information about the ajax support in the given source format
2435 * The returned object's property (boolean)capable indicates that
2436 * the course format supports Moodle course ajax features.
2438 * @param string $format
2441 function course_format_ajax_support($format) {
2442 $course = new stdClass();
2443 $course->format = $format;
2444 return course_get_format($course)->supports_ajax();
2448 * Can the current user delete this course?
2449 * Course creators have exception,
2450 * 1 day after the creation they can sill delete the course.
2451 * @param int $courseid
2454 function can_delete_course($courseid) {
2457 $context = context_course::instance($courseid);
2459 if (has_capability('moodle/course:delete', $context)) {
2463 // hack: now try to find out if creator created this course recently (1 day)
2464 if (!has_capability('moodle/course:create', $context)) {
2468 $since = time() - 60*60*24;
2469 $course = get_course($courseid);
2471 if ($course->timecreated < $since) {
2472 return false; // Return if the course was not created in last 24 hours.
2475 $logmanger = get_log_manager();
2476 $readers = $logmanger->get_readers('\core\log\sql_reader');
2477 $reader = reset($readers);
2479 if (empty($reader)) {
2480 return false; // No log reader found.
2484 $select = "userid = :userid AND courseid = :courseid AND eventname = :eventname AND timecreated > :since";
2485 $params = array('userid' => $USER->id, 'since' => $since, 'courseid' => $course->id, 'eventname' => '\core\event\course_created');
2487 return (bool)$reader->get_events_select_count($select, $params);
2491 * Save the Your name for 'Some role' strings.
2493 * @param integer $courseid the id of this course.
2494 * @param array $data the data that came from the course settings form.
2496 function save_local_role_names($courseid, $data) {
2498 $context = context_course::instance($courseid);
2500 foreach ($data as $fieldname => $value) {
2501 if (strpos($fieldname, 'role_') !== 0) {
2504 list($ignored, $roleid) = explode('_', $fieldname);
2506 // make up our mind whether we want to delete, update or insert
2508 $DB->delete_records('role_names', array('contextid' => $context->id, 'roleid' => $roleid));
2510 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id, 'roleid' => $roleid))) {
2511 $rolename->name = $value;
2512 $DB->update_record('role_names', $rolename);
2515 $rolename = new stdClass;
2516 $rolename->contextid = $context->id;
2517 $rolename->roleid = $roleid;
2518 $rolename->name = $value;
2519 $DB->insert_record('role_names', $rolename);
2521 // This will ensure the course contacts cache is purged..
2522 coursecat::role_assignment_changed($roleid, $context);
2527 * Returns options to use in course overviewfiles filemanager
2529 * @param null|stdClass|course_in_list|int $course either object that has 'id' property or just the course id;
2530 * may be empty if course does not exist yet (course create form)
2531 * @return array|null array of options such as maxfiles, maxbytes, accepted_types, etc.
2532 * or null if overviewfiles are disabled
2534 function course_overviewfiles_options($course) {
2536 if (empty($CFG->courseoverviewfileslimit)) {
2539 $accepted_types = preg_split('/\s*,\s*/', trim($CFG->courseoverviewfilesext), -1, PREG_SPLIT_NO_EMPTY);
2540 if (in_array('*', $accepted_types) || empty($accepted_types)) {
2541 $accepted_types = '*';
2543 // Since config for $CFG->courseoverviewfilesext is a text box, human factor must be considered.
2544 // Make sure extensions are prefixed with dot unless they are valid typegroups
2545 foreach ($accepted_types as $i => $type) {
2546 if (substr($type, 0, 1) !== '.') {
2547 require_once($CFG->libdir. '/filelib.php');
2548 if (!count(file_get_typegroup('extension', $type))) {
2549 // It does not start with dot and is not a valid typegroup, this is most likely extension.
2550 $accepted_types[$i] = '.'. $type;
2555 if (!empty($corrected)) {
2556 set_config('courseoverviewfilesext', join(',', $accepted_types));
2560 'maxfiles' => $CFG->courseoverviewfileslimit,
2561 'maxbytes' => $CFG->maxbytes,
2563 'accepted_types' => $accepted_types
2565 if (!empty($course->id)) {
2566 $options['context'] = context_course::instance($course->id);
2567 } else if (is_int($course) && $course > 0) {
2568 $options['context'] = context_course::instance($course);
2574 * Create a course and either return a $course object
2576 * Please note this functions does not verify any access control,
2577 * the calling code is responsible for all validation (usually it is the form definition).
2579 * @param array $editoroptions course description editor options
2580 * @param object $data - all the data needed for an entry in the 'course' table
2581 * @return object new course instance
2583 function create_course($data, $editoroptions = NULL) {
2585 require_once($CFG->dirroot.'/tag/lib.php');
2587 //check the categoryid - must be given for all new courses
2588 $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
2590 // Check if the shortname already exists.
2591 if (!empty($data->shortname)) {
2592 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
2593 throw new moodle_exception('shortnametaken', '', '', $data->shortname);
2597 // Check if the idnumber already exists.
2598 if (!empty($data->idnumber)) {
2599 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
2600 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber);
2604 // Check if timecreated is given.
2605 $data->timecreated = !empty($data->timecreated) ? $data->timecreated : time();
2606 $data->timemodified = $data->timecreated;
2608 // place at beginning of any category
2609 $data->sortorder = 0;
2611 if ($editoroptions) {
2612 // summary text is updated later, we need context to store the files first
2613 $data->summary = '';
2614 $data->summary_format = FORMAT_HTML;
2617 if (!isset($data->visible)) {
2618 // data not from form, add missing visibility info
2619 $data->visible = $category->visible;
2621 $data->visibleold = $data->visible;
2623 $newcourseid = $DB->insert_record('course', $data);
2624 $context = context_course::instance($newcourseid, MUST_EXIST);
2626 if ($editoroptions) {
2627 // Save the files used in the summary editor and store
2628 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2629 $DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid));
2630 $DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid));
2632 if ($overviewfilesoptions = course_overviewfiles_options($newcourseid)) {
2633 // Save the course overviewfiles
2634 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2637 // update course format options
2638 course_get_format($newcourseid)->update_course_format_options($data);
2640 $course = course_get_format($newcourseid)->get_course();
2642 fix_course_sortorder();
2643 // purge appropriate caches in case fix_course_sortorder() did not change anything
2644 cache_helper::purge_by_event('changesincourse');
2646 // new context created - better mark it as dirty
2647 $context->mark_dirty();
2649 // Trigger a course created event.
2650 $event = \core\event\course_created::create(array(
2651 'objectid' => $course->id,
2652 'context' => context_course::instance($course->id),
2653 'other' => array('shortname' => $course->shortname,
2654 'fullname' => $course->fullname)
2659 blocks_add_default_course_blocks($course);
2661 // Create a default section.
2662 course_create_sections_if_missing($course, 0);
2664 // Save any custom role names.
2665 save_local_role_names($course->id, (array)$data);
2667 // set up enrolments
2668 enrol_course_updated(true, $course, $data);
2670 // Update course tags.
2671 if ($CFG->usetags && isset($data->tags)) {
2672 tag_set('course', $course->id, $data->tags, 'core', context_course::instance($course->id)->id);
2681 * Please note this functions does not verify any access control,
2682 * the calling code is responsible for all validation (usually it is the form definition).
2684 * @param object $data - all the data needed for an entry in the 'course' table
2685 * @param array $editoroptions course description editor options
2688 function update_course($data, $editoroptions = NULL) {
2690 require_once($CFG->dirroot.'/tag/lib.php');
2692 $data->timemodified = time();
2694 $oldcourse = course_get_format($data->id)->get_course();
2695 $context = context_course::instance($oldcourse->id);
2697 if ($editoroptions) {
2698 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2700 if ($overviewfilesoptions = course_overviewfiles_options($data->id)) {
2701 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2704 // Check we don't have a duplicate shortname.
2705 if (!empty($data->shortname) && $oldcourse->shortname != $data->shortname) {
2706 if ($DB->record_exists_sql('SELECT id from {course} WHERE shortname = ? AND id <> ?', array($data->shortname, $data->id))) {
2707 throw new moodle_exception('shortnametaken', '', '', $data->shortname);
2711 // Check we don't have a duplicate idnumber.
2712 if (!empty($data->idnumber) && $oldcourse->idnumber != $data->idnumber) {
2713 if ($DB->record_exists_sql('SELECT id from {course} WHERE idnumber = ? AND id <> ?', array($data->idnumber, $data->id))) {
2714 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber);
2718 if (!isset($data->category) or empty($data->category)) {
2719 // prevent nulls and 0 in category field
2720 unset($data->category);
2722 $changesincoursecat = $movecat = (isset($data->category) and $oldcourse->category != $data->category);
2724 if (!isset($data->visible)) {
2725 // data not from form, add missing visibility info
2726 $data->visible = $oldcourse->visible;
2729 if ($data->visible != $oldcourse->visible) {
2730 // reset the visibleold flag when manually hiding/unhiding course
2731 $data->visibleold = $data->visible;
2732 $changesincoursecat = true;
2735 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category));
2736 if (empty($newcategory->visible)) {
2737 // make sure when moving into hidden category the course is hidden automatically
2743 // Update with the new data
2744 $DB->update_record('course', $data);
2745 // make sure the modinfo cache is reset
2746 rebuild_course_cache($data->id);
2748 // update course format options with full course data
2749 course_get_format($data->id)->update_course_format_options($data, $oldcourse);
2751 $course = $DB->get_record('course', array('id'=>$data->id));
2754 $newparent = context_coursecat::instance($course->category);
2755 $context->update_moved($newparent);
2757 $fixcoursesortorder = $movecat || (isset($data->sortorder) && ($oldcourse->sortorder != $data->sortorder));
2758 if ($fixcoursesortorder) {
2759 fix_course_sortorder();
2762 // purge appropriate caches in case fix_course_sortorder() did not change anything
2763 cache_helper::purge_by_event('changesincourse');
2764 if ($changesincoursecat) {
2765 cache_helper::purge_by_event('changesincoursecat');
2768 // Test for and remove blocks which aren't appropriate anymore
2769 blocks_remove_inappropriate($course);
2771 // Save any custom role names.
2772 save_local_role_names($course->id, $data);
2774 // update enrol settings
2775 enrol_course_updated(false, $course, $data);
2777 // Update course tags.
2778 if ($CFG->usetags && isset($data->tags)) {
2779 tag_set('course', $course->id, $data->tags, 'core', context_course::instance($course->id)->id);
2782 // Trigger a course updated event.
2783 $event = \core\event\course_updated::create(array(
2784 'objectid' => $course->id,
2785 'context' => context_course::instance($course->id),
2786 'other' => array('shortname' => $course->shortname,
2787 'fullname' => $course->fullname)
2790 $event->set_legacy_logdata(array($course->id, 'course', 'update', 'edit.php?id=' . $course->id, $course->id));
2793 if ($oldcourse->format !== $course->format) {
2794 // Remove all options stored for the previous format
2795 // We assume that new course format migrated everything it needed watching trigger
2796 // 'course_updated' and in method format_XXX::update_course_format_options()
2797 $DB->delete_records('course_format_options',
2798 array('courseid' => $course->id, 'format' => $oldcourse->format));
2803 * Average number of participants
2806 function average_number_of_participants() {
2809 //count total of enrolments for visible course (except front page)
2810 $sql = 'SELECT COUNT(*) FROM (
2811 SELECT DISTINCT ue.userid, e.courseid
2812 FROM {user_enrolments} ue, {enrol} e, {course} c
2813 WHERE ue.enrolid = e.id
2814 AND e.courseid <> :siteid
2815 AND c.id = e.courseid
2816 AND c.visible = 1) total';
2817 $params = array('siteid' => $SITE->id);
2818 $enrolmenttotal = $DB->count_records_sql($sql, $params);
2821 //count total of visible courses (minus front page)
2822 $coursetotal = $DB->count_records('course', array('visible' => 1));
2823 $coursetotal = $coursetotal - 1 ;
2825 //average of enrolment
2826 if (empty($coursetotal)) {
2827 $participantaverage = 0;
2829 $participantaverage = $enrolmenttotal / $coursetotal;
2832 return $participantaverage;
2836 * Average number of course modules
2839 function average_number_of_courses_modules() {
2842 //count total of visible course module (except front page)
2843 $sql = 'SELECT COUNT(*) FROM (
2844 SELECT cm.course, cm.module
2845 FROM {course} c, {course_modules} cm
2846 WHERE c.id = cm.course
2849 AND c.visible = 1) total';
2850 $params = array('siteid' => $SITE->id);
2851 $moduletotal = $DB->count_records_sql($sql, $params);
2854 //count total of visible courses (minus front page)
2855 $coursetotal = $DB->count_records('course', array('visible' => 1));
2856 $coursetotal = $coursetotal - 1 ;
2858 //average of course module
2859 if (empty($coursetotal)) {
2860 $coursemoduleaverage = 0;
2862 $coursemoduleaverage = $moduletotal / $coursetotal;
2865 return $coursemoduleaverage;
2869 * This class pertains to course requests and contains methods associated with
2870 * create, approving, and removing course requests.
2872 * Please note we do not allow embedded images here because there is no context
2873 * to store them with proper access control.
2875 * @copyright 2009 Sam Hemelryk
2876 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2879 * @property-read int $id
2880 * @property-read string $fullname
2881 * @property-read string $shortname
2882 * @property-read string $summary
2883 * @property-read int $summaryformat
2884 * @property-read int $summarytrust
2885 * @property-read string $reason
2886 * @property-read int $requester
2888 class course_request {
2891 * This is the stdClass that stores the properties for the course request
2892 * and is externally accessed through the __get magic method
2895 protected $properties;
2898 * An array of options for the summary editor used by course request forms.
2899 * This is initially set by {@link summary_editor_options()}
2903 protected static $summaryeditoroptions;
2906 * Static function to prepare the summary editor for working with a course
2910 * @param null|stdClass $data Optional, an object containing the default values
2911 * for the form, these may be modified when preparing the
2912 * editor so this should be called before creating the form
2913 * @return stdClass An object that can be used to set the default values for
2916 public static function prepare($data=null) {
2917 if ($data === null) {
2918 $data = new stdClass;
2920 $data = file_prepare_standard_editor($data, 'summary', self::summary_editor_options());
2925 * Static function to create a new course request when passed an array of properties
2928 * This function also handles saving any files that may have been used in the editor
2931 * @param stdClass $data
2932 * @return course_request The newly created course request
2934 public static function create($data) {
2935 global $USER, $DB, $CFG;
2936 $data->requester = $USER->id;
2938 // Setting the default category if none set.
2939 if (empty($data->category) || empty($CFG->requestcategoryselection)) {
2940 $data->category = $CFG->defaultrequestcategory;
2943 // Summary is a required field so copy the text over
2944 $data->summary = $data->summary_editor['text'];
2945 $data->summaryformat = $data->summary_editor['format'];
2947 $data->id = $DB->insert_record('course_request', $data);
2949 // Create a new course_request object and return it
2950 $request = new course_request($data);
2952 // Notify the admin if required.
2953 if ($users = get_users_from_config($CFG->courserequestnotify, 'moodle/site:approvecourse')) {
2956 $a->link = "$CFG->wwwroot/course/pending.php";
2957 $a->user = fullname($USER);
2958 $subject = get_string('courserequest');
2959 $message = get_string('courserequestnotifyemail', 'admin', $a);
2960 foreach ($users as $user) {
2961 $request->notify($user, $USER, 'courserequested', $subject, $message);
2969 * Returns an array of options to use with a summary editor
2971 * @uses course_request::$summaryeditoroptions
2972 * @return array An array of options to use with the editor
2974 public static function summary_editor_options() {
2976 if (self::$summaryeditoroptions === null) {
2977 self::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
2979 return self::$summaryeditoroptions;
2983 * Loads the properties for this course request object. Id is required and if
2984 * only id is provided then we load the rest of the properties from the database
2986 * @param stdClass|int $properties Either an object containing properties
2987 * or the course_request id to load
2989 public function __construct($properties) {
2991 if (empty($properties->id)) {
2992 if (empty($properties)) {
2993 throw new coding_exception('You must provide a course request id when creating a course_request object');
2996 $properties = new stdClass;
2997 $properties->id = (int)$id;
3000 if (empty($properties->requester)) {
3001 if (!($this->properties = $DB->get_record('course_request', array('id' => $properties->id)))) {
3002 print_error('unknowncourserequest');
3005 $this->properties = $properties;
3007 $this->properties->collision = null;
3011 * Returns the requested property
3013 * @param string $key
3016 public function __get($key) {
3017 return $this->properties->$key;
3021 * Override this to ensure empty($request->blah) calls return a reliable answer...
3023 * This is required because we define the __get method
3026 * @return bool True is it not empty, false otherwise
3028 public function __isset($key) {
3029 return (!empty($this->properties->$key));
3033 * Returns the user who requested this course
3035 * Uses a static var to cache the results and cut down the number of db queries
3037 * @staticvar array $requesters An array of cached users
3038 * @return stdClass The user who requested the course
3040 public function get_requester() {
3042 static $requesters= array();
3043 if (!array_key_exists($this->properties->requester, $requesters)) {
3044 $requesters[$this->properties->requester] = $DB->get_record('user', array('id'=>$this->properties->requester));
3046 return $requesters[$this->properties->requester];
3050 * Checks that the shortname used by the course does not conflict with any other
3051 * courses that exist
3053 * @param string|null $shortnamemark The string to append to the requests shortname
3054 * should a conflict be found
3055 * @return bool true is there is a conflict, false otherwise
3057 public function check_shortname_collision($shortnamemark = '[*]') {
3060 if ($this->properties->collision !== null) {
3061 return $this->properties->collision;
3064 if (empty($this->properties->shortname)) {
3065 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER);
3066 $this->properties->collision = false;
3067 } else if ($DB->record_exists('course', array('shortname' => $this->properties->shortname))) {
3068 if (!empty($shortnamemark)) {
3069 $this->properties->shortname .= ' '.$shortnamemark;
3071 $this->properties->collision = true;
3073 $this->properties->collision = false;
3075 return $this->properties->collision;
3079 * Returns the category where this course request should be created
3081 * Note that we don't check here that user has a capability to view
3082 * hidden categories if he has capabilities 'moodle/site:approvecourse' and
3083 * 'moodle/course:changecategory'
3087 public function get_category() {
3089 require_once($CFG->libdir.'/coursecatlib.php');
3090 // If the category is not set, if the current user does not have the rights to change the category, or if the
3091 // category does not exist, we set the default category to the course to be approved.
3092 // The system level is used because the capability moodle/site:approvecourse is based on a system level.
3093 if (empty($this->properties->category) || !has_capability('moodle/course:changecategory', context_system::instance()) ||
3094 (!$category = coursecat::get($this->properties->category, IGNORE_MISSING, true))) {
3095 $category = coursecat::get($CFG->defaultrequestcategory, IGNORE_MISSING, true);
3098 $category = coursecat::get_default();
3104 * This function approves the request turning it into a course
3106 * This function converts the course request into a course, at the same time
3107 * transferring any files used in the summary to the new course and then removing
3108 * the course request and the files associated with it.
3110 * @return int The id of the course that was created from this request
3112 public function approve() {
3113 global $CFG, $DB, $USER;
3115 $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted'=>0), '*', MUST_EXIST);
3117 $courseconfig = get_config('moodlecourse');
3119 // Transfer appropriate settings
3120 $data = clone($this->properties);
3122 unset($data->reason);
3123 unset($data->requester);
3126 $category = $this->get_category();
3127 $data->category = $category->id;
3128 // Set misc settings
3129 $data->requested = 1;
3131 // Apply course default settings
3132 $data->format = $courseconfig->format;
3133 $data->newsitems = $courseconfig->newsitems;
3134 $data->showgrades = $courseconfig->showgrades;
3135 $data->showreports = $courseconfig->showreports;
3136 $data->maxbytes = $courseconfig->maxbytes;
3137 $data->groupmode = $courseconfig->groupmode;
3138 $data->groupmodeforce = $courseconfig->groupmodeforce;
3139 $data->visible = $courseconfig->visible;
3140 $data->visibleold = $data->visible;
3141 $data->lang = $courseconfig->lang;
3143 $course = create_course($data);
3144 $context = context_course::instance($course->id, MUST_EXIST);
3146 // add enrol instances
3147 if (!$DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
3148 if ($manual = enrol_get_plugin('manual')) {
3149 $manual->add_default_instance($course);
3153 // enrol the requester as teacher if necessary
3154 if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
3155 enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid);
3160 $a = new stdClass();
3161 $a->name = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
3162 $a->url = $CFG->wwwroot.'/course/view.php?id=' . $course->id;
3163 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a));
3169 * Reject a course request
3171 * This function rejects a course request, emailing the requesting user the
3172 * provided notice and then removing the request from the database
3174 * @param string $notice The message to display to the user
3176 public function reject($notice) {
3178 $user = $DB->get_record('user', array('id' => $this->properties->requester), '*', MUST_EXIST);
3179 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
3184 * Deletes the course request and any associated files
3186 public function delete() {
3188 $DB->delete_records('course_request', array('id' => $this->properties->id));
3192 * Send a message from one user to another using events_trigger
3194 * @param object $touser
3195 * @param object $fromuser
3196 * @param string $name
3197 * @param string $subject
3198 * @param string $message
3200 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message) {
3201 $eventdata = new stdClass();
3202 $eventdata->component = 'moodle';
3203 $eventdata->name = $name;
3204 $eventdata->userfrom = $fromuser;
3205 $eventdata->userto = $touser;
3206 $eventdata->subject = $subject;
3207 $eventdata->fullmessage = $message;
3208 $eventdata->fullmessageformat = FORMAT_PLAIN;
3209 $eventdata->fullmessagehtml = '';
3210 $eventdata->smallmessage = '';
3211 $eventdata->notification = 1;
3212 message_send($eventdata);
3217 * Return a list of page types
3218 * @param string $pagetype current page type
3219 * @param context $parentcontext Block's parent context
3220 * @param context $currentcontext Current context of block
3221 * @return array array of page types
3223 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
3224 if ($pagetype === 'course-index' || $pagetype === 'course-index-category') {
3225 // For courses and categories browsing pages (/course/index.php) add option to show on ANY category page
3226 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
3227 'course-index-*' => get_string('page-course-index-x', 'pagetype'),
3229 } else if ($currentcontext && (!($coursecontext = $currentcontext->get_course_context(false)) || $coursecontext->instanceid == SITEID)) {
3230 // We know for sure that despite pagetype starts with 'course-' this is not a page in course context (i.e. /course/search.php, etc.)
3231 $pagetypes = array('*' => get_string('page-x', 'pagetype'));
3233 // Otherwise consider it a page inside a course even if $currentcontext is null
3234 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
3235 'course-*' => get_string('page-course-x', 'pagetype'),
3236 'course-view-*' => get_string('page-course-view-x', 'pagetype')
3243 * Determine whether course ajax should be enabled for the specified course
3245 * @param stdClass $course The course to test against
3246 * @return boolean Whether course ajax is enabled or note
3248 function course_ajax_enabled($course) {
3249 global $CFG, $PAGE, $SITE;
3251 // The user must be editing for AJAX to be included
3252 if (!$PAGE->user_is_editing()) {
3256 // Check that the theme suports
3257 if (!$PAGE->theme->enablecourseajax) {
3261 // Check that the course format supports ajax functionality
3262 // The site 'format' doesn't have information on course format support
3263 if ($SITE->id !== $course->id) {
3264 $courseformatajaxsupport = course_format_ajax_support($course->format);
3265 if (!$courseformatajaxsupport->capable) {
3270 // All conditions have been met so course ajax should be enabled
3275 * Include the relevant javascript and language strings for the resource
3276 * toolbox YUI module
3278 * @param integer $id The ID of the course being applied to
3279 * @param array $usedmodules An array containing the names of the modules in use on the page
3280 * @param array $enabledmodules An array containing the names of the enabled (visible) modules on this site
3281 * @param stdClass $config An object containing configuration parameters for ajax modules including:
3282 * * resourceurl The URL to post changes to for resource changes
3283 * * sectionurl The URL to post changes to for section changes
3284 * * pageparams Additional parameters to pass through in the post
3287 function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) {
3288 global $CFG, $PAGE, $SITE;
3290 // Ensure that ajax should be included
3291 if (!course_ajax_enabled($course)) {
3296 $config = new stdClass();
3299 // The URL to use for resource changes
3300 if (!isset($config->resourceurl)) {
3301 $config->resourceurl = '/course/rest.php';
3304 // The URL to use for section changes
3305 if (!isset($config->sectionurl)) {
3306 $config->sectionurl = '/course/rest.php';
3309 // Any additional parameters which need to be included on page submission
3310 if (!isset($config->pageparams)) {
3311 $config->pageparams = array();
3314 // Include toolboxes
3315 $PAGE->requires->yui_module('moodle-course-toolboxes',
3316 'M.course.init_resource_toolbox',
3318 'courseid' => $course->id,
3319 'ajaxurl' => $config->resourceurl,
3320 'config' => $config,
3323 $PAGE->requires->yui_module('moodle-course-toolboxes',
3324 'M.course.init_section_toolbox',
3326 'courseid' => $course->id,
3327 'format' => $course->format,
3328 'ajaxurl' => $config->sectionurl,
3329 'config' => $config,
3333 // Include course dragdrop
3334 if (course_format_uses_sections($course->format)) {
3335 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_section_dragdrop',
3337 'courseid' => $course->id,
3338 'ajaxurl' => $config->sectionurl,
3339 'config' => $config,
3342 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_resource_dragdrop',
3344 'courseid' => $course->id,
3345 'ajaxurl' => $config->resourceurl,
3346 'config' => $config,
3350 // Require various strings for the command toolbox
3351 $PAGE->requires->strings_for_js(array(
3354 'deletechecktypename',
3356 'edittitleinstructions',
3364 'clicktochangeinbrackets',
3369 'movecoursesection',
3372 'emptydragdropregion',
3378 // Include section-specific strings for formats which support sections.
3379 if (course_format_uses_sections($course->format)) {
3380 $PAGE->requires->strings_for_js(array(
3383 ), 'format_' . $course->format);
3386 // For confirming resource deletion we need the name of the module in question
3387 foreach ($usedmodules as $module => $modname) {
3388 $PAGE->requires->string_for_js('pluginname', $module);
3391 // Load drag and drop upload AJAX.
3392 require_once($CFG->dirroot.'/course/dnduploadlib.php');
3393 dndupload_add_to_course($course, $enabledmodules);
3399 * Returns the sorted list of available course formats, filtered by enabled if necessary
3401 * @param bool $enabledonly return only formats that are enabled
3402 * @return array array of sorted format names
3404 function get_sorted_course_formats($enabledonly = false) {
3406 $formats = core_component::get_plugin_list('format');
3408 if (!empty($CFG->format_plugins_sortorder)) {
3409 $order = explode(',', $CFG->format_plugins_sortorder);
3410 $order = array_merge(array_intersect($order, array_keys($formats)),
3411 array_diff(array_keys($formats), $order));
3413 $order = array_keys($formats);
3415 if (!$enabledonly) {
3418 $sortedformats = array();
3419 foreach ($order as $formatname) {
3420 if (!get_config('format_'.$formatname, 'disabled')) {
3421 $sortedformats[] = $formatname;
3424 return $sortedformats;
3428 * The URL to use for the specified course (with section)
3430 * @param int|stdClass $courseorid The course to get the section name for (either object or just course id)
3431 * @param int|stdClass $section Section object from database or just field course_sections.section
3432 * if omitted the course view page is returned
3433 * @param array $options options for view URL. At the moment core uses:
3434 * 'navigation' (bool) if true and section has no separate page, the function returns null
3435 * 'sr' (int) used by multipage formats to specify to which section to return
3436 * @return moodle_url The url of course
3438 function course_get_url($courseorid, $section = null, $options = array()) {
3439 return course_get_format($courseorid)->get_view_url($section, $options);
3446 * - capability checks and other checks
3447 * - create the module from the module info
3449 * @param object $module
3450 * @return object the created module info
3451 * @throws moodle_exception if user is not allowed to perform the action or module is not allowed in this course
3453 function create_module($moduleinfo) {
3456 require_once($CFG->dirroot . '/course/modlib.php');
3458 // Check manadatory attributs.
3459 $mandatoryfields = array('modulename', 'course', 'section', 'visible');
3460 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
3461 $mandatoryfields[] = 'introeditor';
3463 foreach($mandatoryfields as $mandatoryfield) {
3464 if (!isset($moduleinfo->{$mandatoryfield})) {
3465 throw new moodle_exception('createmodulemissingattribut', '', '', $mandatoryfield);
3469 // Some additional checks (capability / existing instances).
3470 $course = $DB->get_record('course', array('id'=>$moduleinfo->course), '*', MUST_EXIST);
3471 list($module, $context, $cw) = can_add_moduleinfo($course, $moduleinfo->modulename, $moduleinfo->section);
3474 $moduleinfo->module = $module->id;
3475 $moduleinfo = add_moduleinfo($moduleinfo, $course, null);
3484 * - capability and other checks
3485 * - update the module
3487 * @param object $module
3488 * @return object the updated module info
3489 * @throws moodle_exception if current user is not allowed to update the module
3491 function update_module($moduleinfo) {
3494 require_once($CFG->dirroot . '/course/modlib.php');
3496 // Check the course module exists.
3497 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule, 0, false, MUST_EXIST);
3499 // Check the course exists.
3500 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
3502 // Some checks (capaibility / existing instances).
3503 list($cm, $context, $module, $data, $cw) = can_update_moduleinfo($cm);
3505 // Retrieve few information needed by update_moduleinfo.
3506 $moduleinfo->modulename = $cm->modname;
3507 if (!isset($moduleinfo->scale)) {
3508 $moduleinfo->scale = 0;
3510 $moduleinfo->type = 'mod';
3512 // Update the module.
3513 list($cm, $moduleinfo) = update_moduleinfo($cm, $moduleinfo, $course, null);
3519 * Duplicate a module on the course for ajax.
3521 * @see mod_duplicate_module()
3522 * @param object $course The course
3523 * @param object $cm The course module to duplicate
3524 * @param int $sr The section to link back to (used for creating the links)
3525 * @throws moodle_exception if the plugin doesn't support duplication
3526 * @return Object containing:
3527 * - fullcontent: The HTML markup for the created CM
3528 * - cmid: The CMID of the newly created CM
3529 * - redirect: Whether to trigger a redirect following this change
3531 function mod_duplicate_activity($course, $cm, $sr = null) {
3534 $newcm = duplicate_module($course, $cm);
3536 $resp = new stdClass();
3538 $courserenderer = $PAGE->get_renderer('core', 'course');
3539 $completioninfo = new completion_info($course);
3540 $modulehtml = $courserenderer->course_section_cm($course, $completioninfo,
3541 $newcm, null, array());
3543 $resp->fullcontent = $courserenderer->course_section_cm_list_item($course, $completioninfo, $newcm, $sr);
3544 $resp->cmid = $newcm->id;
3546 // Trigger a redirect.
3547 $resp->redirect = true;
3553 * Api to duplicate a module.
3555 * @param object $course course object.
3556 * @param object $cm course module object to be duplicated.
3560 * @throws coding_exception
3561 * @throws moodle_exception
3562 * @throws restore_controller_exception
3564 * @return cm_info|null cminfo object if we sucessfully duplicated the mod and found the new cm.
3566 function duplicate_module($course, $cm) {
3567 global $CFG, $DB, $USER;
3568 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
3569 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
3570 require_once($CFG->libdir . '/filelib.php');
3572 $a = new stdClass();
3573 $a->modtype = get_string('modulename', $cm->modname);
3574 $a->modname = format_string($cm->name);
3576 if (!plugin_supports('mod', $cm->modname, FEATURE_BACKUP_MOODLE2)) {
3577 throw new moodle_exception('duplicatenosupport', 'error', '', $a);
3580 // Backup the activity.
3582 $bc = new backup_controller(backup::TYPE_1ACTIVITY, $cm->id, backup::FORMAT_MOODLE,
3583 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
3585 $backupid = $bc->get_backupid();
3586 $backupbasepath = $bc->get_plan()->get_basepath();
3588 $bc->execute_plan();
3592 // Restore the backup immediately.
3594 $rc = new restore_controller($backupid, $course->id,
3595 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, backup::TARGET_CURRENT_ADDING);
3597 $cmcontext = context_module::instance($cm->id);
3598 if (!$rc->execute_precheck()) {
3599 $precheckresults = $rc->get_precheck_results();
3600 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
3601 if (empty($CFG->keeptempdirectoriesonbackup)) {
3602 fulldelete($backupbasepath);
3607 $rc->execute_plan();
3609 // Now a bit hacky part follows - we try to get the cmid of the newly
3610 // restored copy of the module.
3612 $tasks = $rc->get_plan()->get_tasks();
3613 foreach ($tasks as $task) {
3614 if (is_subclass_of($task, 'restore_activity_task')) {
3615 if ($task->get_old_contextid() == $cmcontext->id) {
3616 $newcmid = $task->get_moduleid();
3622 // If we know the cmid of the new course module, let us move it
3623 // right below the original one. otherwise it will stay at the
3624 // end of the section.
3626 $info = get_fast_modinfo($course);
3627 $newcm = $info->get_cm($newcmid);
3628 $section = $DB->get_record('course_sections', array('id' => $cm->section, 'course' => $cm->course));
3629 moveto_module($newcm, $section, $cm);
3630 moveto_module($cm, $section, $newcm);
3632 // Trigger course module created event. We can trigger the event only if we know the newcmid.
3633 $event = \core\event\course_module_created::create_from_cm($newcm);
3636 rebuild_course_cache($cm->course);
3640 if (empty($CFG->keeptempdirectoriesonbackup)) {
3641 fulldelete($backupbasepath);
3644 return isset($newcm) ? $newcm : null;
3648 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3649 * Sorts by descending order of time.
3651 * @param stdClass $a First object
3652 * @param stdClass $b Second object
3653 * @return int 0,1,-1 representing the order
3655 function compare_activities_by_time_desc($a, $b) {
3656 // Make sure the activities actually have a timestamp property.
3657 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3660 // We treat instances without timestamp as if they have a timestamp of 0.
3661 if ((!property_exists($a, 'timestamp')) && (property_exists($b,'timestamp'))) {
3664 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3667 if ($a->timestamp == $b->timestamp) {
3670 return ($a->timestamp > $b->timestamp) ? -1 : 1;
3674 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3675 * Sorts by ascending order of time.
3677 * @param stdClass $a First object
3678 * @param stdClass $b Second object
3679 * @return int 0,1,-1 representing the order
3681 function compare_activities_by_time_asc($a, $b) {
3682 // Make sure the activities actually have a timestamp property.
3683 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3686 // We treat instances without timestamp as if they have a timestamp of 0.
3687 if ((!property_exists($a, 'timestamp')) && (property_exists($b, 'timestamp'))) {
3690 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3693 if ($a->timestamp == $b->timestamp) {
3696 return ($a->timestamp < $b->timestamp) ? -1 : 1;
3700 * Changes the visibility of a course.
3702 * @param int $courseid The course to change.
3703 * @param bool $show True to make it visible, false otherwise.
3706 function course_change_visibility($courseid, $show = true) {
3707 $course = new stdClass;
3708 $course->id = $courseid;
3709 $course->visible = ($show) ? '1' : '0';
3710 $course->visibleold = $course->visible;
3711 update_course($course);
3716 * Changes the course sortorder by one, moving it up or down one in respect to sort order.
3718 * @param stdClass|course_in_list $course
3719 * @param bool $up If set to true the course will be moved up one. Otherwise down one.
3722 function course_change_sortorder_by_one($course, $up) {
3724 $params = array($course->sortorder, $course->category);
3726 $select = 'sortorder < ? AND category = ?';
3727 $sort = 'sortorder DESC';
3729 $select = 'sortorder > ? AND category = ?';
3730 $sort = 'sortorder ASC';
3732 fix_course_sortorder();
3733 $swapcourse = $DB->get_records_select('course', $select, $params, $sort, '*', 0, 1);
3735 $swapcourse = reset($swapcourse);
3736 $DB->set_field('course', 'sortorder', $swapcourse->sortorder, array('id' => $course->id));
3737 $DB->set_field('course', 'sortorder', $course->sortorder, array('id' => $swapcourse->id));
3738 // Finally reorder courses.
3739 fix_course_sortorder();
3740 cache_helper::purge_by_event('changesincourse');
3747 * Changes the sort order of courses in a category so that the first course appears after the second.
3749 * @param int|stdClass $courseorid The course to focus on.
3750 * @param int $moveaftercourseid The course to shifter after or 0 if you want it to be the first course in the category.
3753 function course_change_sortorder_after_course($courseorid, $moveaftercourseid) {
3756 if (!is_object($courseorid)) {
3757 $course = get_course($courseorid);
3759 $course = $courseorid;
3762 if ((int)$moveaftercourseid === 0) {
3763 // We've moving the course to the start of the queue.
3764 $sql = 'SELECT sortorder
3766 WHERE category = :categoryid
3767 ORDER BY sortorder';
3769 'categoryid' => $course->category
3771 $sortorder = $DB->get_field_sql($sql, $params, IGNORE_MULTIPLE);
3773 $sql = 'UPDATE {course}
3774 SET sortorder = sortorder + 1
3775 WHERE category = :categoryid
3778 'categoryid' => $course->category,
3779 'id' => $course->id,
3781 $DB->execute($sql, $params);
3782 $DB->set_field('course', 'sortorder', $sortorder, array('id' => $course->id));
3783 } else if ($course->id === $moveaftercourseid) {
3784 // They're the same - moronic.
3785 debugging("Invalid move after course given.", DEBUG_DEVELOPER);
3788 // Moving this course after the given course. It could be before it could be after.
3789 $moveaftercourse = get_course($moveaftercourseid);
3790 if ($course->category !== $moveaftercourse->category) {
3791 debugging("Cannot re-order courses. The given courses do not belong to the same category.", DEBUG_DEVELOPER);
3794 // Increment all courses in the same category that are ordered after the moveafter course.
3795 // This makes a space for the course we're moving.
3796 $sql = 'UPDATE {course}
3797 SET sortorder = sortorder + 1
3798 WHERE category = :categoryid
3799 AND sortorder > :sortorder';
3801 'categoryid' => $moveaftercourse->category,
3802 'sortorder' => $moveaftercourse->sortorder
3804 $DB->execute($sql, $params);
3805 $DB->set_field('course', 'sortorder', $moveaftercourse->sortorder + 1, array('id' => $course->id));
3807 fix_course_sortorder();
3808 cache_helper::purge_by_event('changesincourse');
3813 * Trigger course viewed event. This API function is used when course view actions happens,
3814 * usually in course/view.php but also in external functions.
3816 * @param stdClass $context course context object
3817 * @param int $sectionnumber section number
3820 function course_view($context, $sectionnumber = 0) {
3822 $eventdata = array('context' => $context);
3824 if (!empty($sectionnumber)) {
3825 $eventdata['other']['coursesectionnumber'] = $sectionnumber;
3828 $event = \core\event\course_viewed::create($eventdata);