3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * Library of useful functions
21 * @copyright 1999 Martin Dougiamas http://dougiamas.com
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') || die;
29 require_once($CFG->libdir.'/completionlib.php');
30 require_once($CFG->libdir.'/filelib.php');
32 define('COURSE_MAX_LOG_DISPLAY', 150); // days
33 define('COURSE_MAX_LOGS_PER_PAGE', 1000); // records
34 define('COURSE_LIVELOG_REFRESH', 60); // Seconds
35 define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds
36 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10); // courses
37 define('COURSE_MAX_COURSES_PER_DROPDOWN',1000); // max courses in log dropdown before switching to optional
38 define('COURSE_MAX_USERS_PER_DROPDOWN',1000); // max users in log dropdown before switching to optional
39 define('FRONTPAGENEWS', '0');
40 define('FRONTPAGECOURSELIST', '1');
41 define('FRONTPAGECATEGORYNAMES', '2');
42 define('FRONTPAGETOPICONLY', '3');
43 define('FRONTPAGECATEGORYCOMBO', '4');
44 define('FRONTPAGECOURSELIMIT', 200); // maximum number of courses displayed on the frontpage
45 define('EXCELROWS', 65535);
46 define('FIRSTUSEDEXCELROW', 3);
48 define('MOD_CLASS_ACTIVITY', 0);
49 define('MOD_CLASS_RESOURCE', 1);
51 function make_log_url($module, $url) {
60 if (strpos($url, '../') === 0) {
61 $url = ltrim($url, '.');
63 $url = "/course/$url";
68 $url = "/$module/$url";
81 $url = "/message/$url";
93 $url = "/mod/$module/$url";
97 //now let's sanitise urls - there might be some ugly nasties:-(
98 $parts = explode('?', $url);
99 $script = array_shift($parts);
100 if (strpos($script, 'http') === 0) {
101 $script = clean_param($script, PARAM_URL);
103 $script = clean_param($script, PARAM_PATH);
108 $query = implode('', $parts);
109 $query = str_replace('&', '&', $query); // both & and & are stored in db :-|
110 $parts = explode('&', $query);
111 $eq = urlencode('=');
112 foreach ($parts as $key=>$part) {
113 $part = urlencode(urldecode($part));
114 $part = str_replace($eq, '=', $part);
115 $parts[$key] = $part;
117 $query = '?'.implode('&', $parts);
120 return $script.$query;
124 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
125 $modname="", $modid=0, $modaction="", $groupid=0) {
128 // It is assumed that $date is the GMT time of midnight for that day,
129 // and so the next 86400 seconds worth of logs are printed.
131 /// Setup for group handling.
133 // TODO: I don't understand group/context/etc. enough to be able to do
134 // something interesting with it here
135 // What is the context of a remote course?
137 /// If the group mode is separate, and this user does not have editing privileges,
138 /// then only the user's group can be viewed.
139 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
140 // $groupid = get_current_group($course->id);
142 /// If this course doesn't have groups, no groupid can be specified.
143 //else if (!$course->groupmode) {
151 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
153 LEFT JOIN {user} u ON l.userid = u.id
157 $where .= "l.hostid = :hostid";
158 $params['hostid'] = $hostid;
160 // TODO: Is 1 really a magic number referring to the sitename?
161 if ($course != SITEID || $modid != 0) {
162 $where .= " AND l.course=:courseid";
163 $params['courseid'] = $course;
167 $where .= " AND l.module = :modname";
168 $params['modname'] = $modname;
171 if ('site_errors' === $modid) {
172 $where .= " AND ( l.action='error' OR l.action='infected' )";
174 //TODO: This assumes that modids are the same across sites... probably
176 $where .= " AND l.cmid = :modid";
177 $params['modid'] = $modid;
181 $firstletter = substr($modaction, 0, 1);
182 if ($firstletter == '-') {
183 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
184 $params['modaction'] = '%'.substr($modaction, 1).'%';
186 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
187 $params['modaction'] = '%'.$modaction.'%';
192 $where .= " AND l.userid = :user";
193 $params['user'] = $user;
197 $enddate = $date + 86400;
198 $where .= " AND l.time > :date AND l.time < :enddate";
199 $params['date'] = $date;
200 $params['enddate'] = $enddate;
204 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
205 if(!empty($result['totalcount'])) {
206 $where .= " ORDER BY $order";
207 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
209 $result['logs'] = array();
214 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
215 $modname="", $modid=0, $modaction="", $groupid=0) {
216 global $DB, $SESSION, $USER;
217 // It is assumed that $date is the GMT time of midnight for that day,
218 // and so the next 86400 seconds worth of logs are printed.
220 /// Setup for group handling.
222 /// If the group mode is separate, and this user does not have editing privileges,
223 /// then only the user's group can be viewed.
224 if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
225 if (isset($SESSION->currentgroup[$course->id])) {
226 $groupid = $SESSION->currentgroup[$course->id];
228 $groupid = groups_get_all_groups($course->id, $USER->id);
229 if (is_array($groupid)) {
230 $groupid = array_shift(array_keys($groupid));
231 $SESSION->currentgroup[$course->id] = $groupid;
237 /// If this course doesn't have groups, no groupid can be specified.
238 else if (!$course->groupmode) {
245 if ($course->id != SITEID || $modid != 0) {
246 $joins[] = "l.course = :courseid";
247 $params['courseid'] = $course->id;
251 $joins[] = "l.module = :modname";
252 $params['modname'] = $modname;
255 if ('site_errors' === $modid) {
256 $joins[] = "( l.action='error' OR l.action='infected' )";
258 $joins[] = "l.cmid = :modid";
259 $params['modid'] = $modid;
263 $firstletter = substr($modaction, 0, 1);
264 if ($firstletter == '-') {
265 $joins[] = $DB->sql_like('l.action', ':modaction', false, true, true);
266 $params['modaction'] = '%'.substr($modaction, 1).'%';
268 $joins[] = $DB->sql_like('l.action', ':modaction', false);
269 $params['modaction'] = '%'.$modaction.'%';
274 /// Getting all members of a group.
275 if ($groupid and !$user) {
276 if ($gusers = groups_get_members($groupid)) {
277 $gusers = array_keys($gusers);
278 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
280 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
284 $joins[] = "l.userid = :userid";
285 $params['userid'] = $user;
289 $enddate = $date + 86400;
290 $joins[] = "l.time > :date AND l.time < :enddate";
291 $params['date'] = $date;
292 $params['enddate'] = $enddate;
295 $selector = implode(' AND ', $joins);
297 $totalcount = 0; // Initialise
299 $result['logs'] = get_logs($selector, $params, $order, $limitfrom, $limitnum, $totalcount);
300 $result['totalcount'] = $totalcount;
305 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
306 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
308 global $CFG, $DB, $OUTPUT;
310 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
311 $modname, $modid, $modaction, $groupid)) {
312 echo $OUTPUT->notification("No logs found!");
313 echo $OUTPUT->footer();
319 if ($course->id == SITEID) {
321 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
322 foreach ($ccc as $cc) {
323 $courses[$cc->id] = $cc->shortname;
327 $courses[$course->id] = $course->shortname;
330 $totalcount = $logs['totalcount'];
333 $tt = getdate(time());
334 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
336 $strftimedatetime = get_string("strftimedatetime");
338 echo "<div class=\"info\">\n";
339 print_string("displayingrecords", "", $totalcount);
342 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
344 $table = new html_table();
345 $table->classes = array('logtable','generalbox');
346 $table->align = array('right', 'left', 'left');
347 $table->head = array(
349 get_string('ip_address'),
350 get_string('fullnameuser'),
351 get_string('action'),
354 $table->data = array();
356 if ($course->id == SITEID) {
357 array_unshift($table->align, 'left');
358 array_unshift($table->head, get_string('course'));
361 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
362 if (empty($logs['logs'])) {
363 $logs['logs'] = array();
366 foreach ($logs['logs'] as $log) {
368 if (isset($ldcache[$log->module][$log->action])) {
369 $ld = $ldcache[$log->module][$log->action];
371 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
372 $ldcache[$log->module][$log->action] = $ld;
374 if ($ld && is_numeric($log->info)) {
375 // ugly hack to make sure fullname is shown correctly
376 if ($ld->mtable == 'user' && $ld->field == $DB->sql_concat('firstname', "' '" , 'lastname')) {
377 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
379 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
384 $log->info = format_string($log->info);
386 // If $log->url has been trimmed short by the db size restriction
387 // code in add_to_log, keep a note so we don't add a link to a broken url
388 $tl=textlib_get_instance();
389 $brokenurl=($tl->strlen($log->url)==100 && $tl->substr($log->url,97)=='...');
392 if ($course->id == SITEID) {
393 if (empty($log->course)) {
394 $row[] = get_string('site');
396 $row[] = "<a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course])."</a>";
400 $row[] = userdate($log->time, '%a').' '.userdate($log->time, $strftimedatetime);
402 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
403 $row[] = $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 440, 'width' => 700)));
405 $row[] = html_writer::link(new moodle_url("/user/view.php?id={$log->userid}&course={$log->course}"), fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id))));
407 $displayaction="$log->module $log->action";
409 $row[] = $displayaction;
411 $link = make_log_url($log->module,$log->url);
412 $row[] = $OUTPUT->action_link($link, $displayaction, new popup_action('click', $link, 'fromloglive'), array('height' => 440, 'width' => 700));
415 $table->data[] = $row;
418 echo html_writer::table($table);
419 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
423 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
424 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
426 global $CFG, $DB, $OUTPUT;
428 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
429 $modname, $modid, $modaction, $groupid)) {
430 echo $OUTPUT->notification("No logs found!");
431 echo $OUTPUT->footer();
435 if ($course->id == SITEID) {
437 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
438 foreach ($ccc as $cc) {
439 $courses[$cc->id] = $cc->shortname;
444 $totalcount = $logs['totalcount'];
447 $tt = getdate(time());
448 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
450 $strftimedatetime = get_string("strftimedatetime");
452 echo "<div class=\"info\">\n";
453 print_string("displayingrecords", "", $totalcount);
456 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
458 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
460 if ($course->id == SITEID) {
461 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
463 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
464 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
465 echo "<th class=\"c3 header\">".get_string('fullnameuser')."</th>\n";
466 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
467 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
470 if (empty($logs['logs'])) {
476 foreach ($logs['logs'] as $log) {
478 $log->info = $log->coursename;
479 $row = ($row + 1) % 2;
481 if (isset($ldcache[$log->module][$log->action])) {
482 $ld = $ldcache[$log->module][$log->action];
484 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
485 $ldcache[$log->module][$log->action] = $ld;
487 if (0 && $ld && !empty($log->info)) {
488 // ugly hack to make sure fullname is shown correctly
489 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
490 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
492 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
497 $log->info = format_string($log->info);
499 echo '<tr class="r'.$row.'">';
500 if ($course->id == SITEID) {
501 echo "<td class=\"r$row c0\" >\n";
502 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courses[$log->course]."</a>\n";
505 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time, '%a').
506 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
507 echo "<td class=\"r$row c2\" >\n";
508 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
509 echo $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 400, 'width' => 700)));
511 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
512 echo "<td class=\"r$row c3\" >\n";
513 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
515 echo "<td class=\"r$row c4\">\n";
516 echo $log->action .': '.$log->module;
518 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
523 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
527 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
528 $modid, $modaction, $groupid) {
531 $text = get_string('course')."\t".get_string('time')."\t".get_string('ip_address')."\t".
532 get_string('fullnameuser')."\t".get_string('action')."\t".get_string('info');
534 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
535 $modname, $modid, $modaction, $groupid)) {
541 if ($course->id == SITEID) {
543 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
544 foreach ($ccc as $cc) {
545 $courses[$cc->id] = $cc->shortname;
549 $courses[$course->id] = $course->shortname;
554 $tt = getdate(time());
555 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
557 $strftimedatetime = get_string("strftimedatetime");
559 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
561 header("Content-Type: application/download\n");
562 header("Content-Disposition: attachment; filename=$filename");
563 header("Expires: 0");
564 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
565 header("Pragma: public");
567 echo get_string('savedat').userdate(time(), $strftimedatetime)."\n";
570 if (empty($logs['logs'])) {
574 foreach ($logs['logs'] as $log) {
575 if (isset($ldcache[$log->module][$log->action])) {
576 $ld = $ldcache[$log->module][$log->action];
578 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
579 $ldcache[$log->module][$log->action] = $ld;
581 if ($ld && !empty($log->info)) {
582 // ugly hack to make sure fullname is shown correctly
583 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
584 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
586 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
591 $log->info = format_string($log->info);
592 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
594 $firstField = $courses[$log->course];
595 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
596 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action, $log->info);
597 $text = implode("\t", $row);
604 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
605 $modid, $modaction, $groupid) {
609 require_once("$CFG->libdir/excellib.class.php");
611 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
612 $modname, $modid, $modaction, $groupid)) {
618 if ($course->id == SITEID) {
620 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
621 foreach ($ccc as $cc) {
622 $courses[$cc->id] = $cc->shortname;
626 $courses[$course->id] = $course->shortname;
631 $tt = getdate(time());
632 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
634 $strftimedatetime = get_string("strftimedatetime");
636 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
637 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
640 $workbook = new MoodleExcelWorkbook('-');
641 $workbook->send($filename);
643 $worksheet = array();
644 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
645 get_string('fullnameuser'), get_string('action'), get_string('info'));
647 // Creating worksheets
648 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
649 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
650 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
651 $worksheet[$wsnumber]->set_column(1, 1, 30);
652 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
653 userdate(time(), $strftimedatetime));
655 foreach ($headers as $item) {
656 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
661 if (empty($logs['logs'])) {
666 $formatDate =& $workbook->add_format();
667 $formatDate->set_num_format(get_string('log_excel_date_format'));
669 $row = FIRSTUSEDEXCELROW;
671 $myxls =& $worksheet[$wsnumber];
672 foreach ($logs['logs'] as $log) {
673 if (isset($ldcache[$log->module][$log->action])) {
674 $ld = $ldcache[$log->module][$log->action];
676 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
677 $ldcache[$log->module][$log->action] = $ld;
679 if ($ld && !empty($log->info)) {
680 // ugly hack to make sure fullname is shown correctly
681 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
682 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
684 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
689 $log->info = format_string($log->info);
690 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
693 if ($row > EXCELROWS) {
695 $myxls =& $worksheet[$wsnumber];
696 $row = FIRSTUSEDEXCELROW;
700 $myxls->write($row, 0, $courses[$log->course], '');
701 $myxls->write_date($row, 1, $log->time, $formatDate); // write_date() does conversion/timezone support. MDL-14934
702 $myxls->write($row, 2, $log->ip, '');
703 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
704 $myxls->write($row, 3, $fullname, '');
705 $myxls->write($row, 4, $log->module.' '.$log->action, '');
706 $myxls->write($row, 5, $log->info, '');
715 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
716 $modid, $modaction, $groupid) {
720 require_once("$CFG->libdir/odslib.class.php");
722 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
723 $modname, $modid, $modaction, $groupid)) {
729 if ($course->id == SITEID) {
731 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
732 foreach ($ccc as $cc) {
733 $courses[$cc->id] = $cc->shortname;
737 $courses[$course->id] = $course->shortname;
742 $tt = getdate(time());
743 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
745 $strftimedatetime = get_string("strftimedatetime");
747 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
748 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
751 $workbook = new MoodleODSWorkbook('-');
752 $workbook->send($filename);
754 $worksheet = array();
755 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
756 get_string('fullnameuser'), get_string('action'), get_string('info'));
758 // Creating worksheets
759 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
760 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
761 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
762 $worksheet[$wsnumber]->set_column(1, 1, 30);
763 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
764 userdate(time(), $strftimedatetime));
766 foreach ($headers as $item) {
767 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
772 if (empty($logs['logs'])) {
777 $formatDate =& $workbook->add_format();
778 $formatDate->set_num_format(get_string('log_excel_date_format'));
780 $row = FIRSTUSEDEXCELROW;
782 $myxls =& $worksheet[$wsnumber];
783 foreach ($logs['logs'] as $log) {
784 if (isset($ldcache[$log->module][$log->action])) {
785 $ld = $ldcache[$log->module][$log->action];
787 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
788 $ldcache[$log->module][$log->action] = $ld;
790 if ($ld && !empty($log->info)) {
791 // ugly hack to make sure fullname is shown correctly
792 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
793 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
795 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
800 $log->info = format_string($log->info);
801 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
804 if ($row > EXCELROWS) {
806 $myxls =& $worksheet[$wsnumber];
807 $row = FIRSTUSEDEXCELROW;
811 $myxls->write_string($row, 0, $courses[$log->course]);
812 $myxls->write_date($row, 1, $log->time);
813 $myxls->write_string($row, 2, $log->ip);
814 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
815 $myxls->write_string($row, 3, $fullname);
816 $myxls->write_string($row, 4, $log->module.' '.$log->action);
817 $myxls->write_string($row, 5, $log->info);
827 function print_log_graph($course, $userid=0, $type="course.png", $date=0) {
829 if (empty($CFG->gdversion)) {
830 echo "(".get_string("gdneed").")";
832 // MDL-10818, do not display broken graph when user has no permission to view graph
833 if (has_capability('coursereport/log:view', get_context_instance(CONTEXT_COURSE, $course->id)) ||
834 ($course->showreports and $USER->id == $userid)) {
835 echo '<img src="'.$CFG->wwwroot.'/course/report/log/graph.php?id='.$course->id.
836 '&user='.$userid.'&type='.$type.'&date='.$date.'" alt="" />';
842 function print_overview($courses, array $remote_courses=array()) {
843 global $CFG, $USER, $DB, $OUTPUT;
845 $htmlarray = array();
846 if ($modules = $DB->get_records('modules')) {
847 foreach ($modules as $mod) {
848 if (file_exists(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php')) {
849 include_once(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php');
850 $fname = $mod->name.'_print_overview';
851 if (function_exists($fname)) {
852 $fname($courses,$htmlarray);
857 foreach ($courses as $course) {
858 echo $OUTPUT->box_start('coursebox');
859 $attributes = array('title' => s($course->fullname));
860 if (empty($course->visible)) {
861 $attributes['class'] = 'dimmed';
863 echo $OUTPUT->heading(html_writer::link(
864 new moodle_url('/course/view.php', array('id' => $course->id)), format_string($course->fullname), $attributes), 3);
865 if (array_key_exists($course->id,$htmlarray)) {
866 foreach ($htmlarray[$course->id] as $modname => $html) {
870 echo $OUTPUT->box_end();
873 if (!empty($remote_courses)) {
874 echo $OUTPUT->heading(get_string('remotecourses', 'mnet'));
876 foreach ($remote_courses as $course) {
877 echo $OUTPUT->box_start('coursebox');
878 $attributes = array('title' => s($course->fullname));
879 echo $OUTPUT->heading(html_writer::link(
880 new moodle_url('/auth/mnet/jump.php', array('hostid' => $course->hostid, 'wantsurl' => '/course/view.php?id='.$course->remoteid)),
881 format_string($course->shortname),
882 $attributes) . ' (' . format_string($course->hostname) . ')', 3);
883 echo $OUTPUT->box_end();
889 * This function trawls through the logs looking for
890 * anything new since the user's last login
892 function print_recent_activity($course) {
893 // $course is an object
894 global $CFG, $USER, $SESSION, $DB, $OUTPUT;
896 $context = get_context_instance(CONTEXT_COURSE, $course->id);
898 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
900 $timestart = round(time() - COURSE_MAX_RECENT_PERIOD, -2); // better db caching for guests - 100 seconds
902 if (!isguestuser()) {
903 if (!empty($USER->lastcourseaccess[$course->id])) {
904 if ($USER->lastcourseaccess[$course->id] > $timestart) {
905 $timestart = $USER->lastcourseaccess[$course->id];
910 echo '<div class="activitydate">';
911 echo get_string('activitysince', '', userdate($timestart));
913 echo '<div class="activityhead">';
915 echo '<a href="'.$CFG->wwwroot.'/course/recent.php?id='.$course->id.'">'.get_string('recentactivityreport').'</a>';
921 /// Firstly, have there been any new enrolments?
923 $users = get_recent_enrolments($course->id, $timestart);
925 //Accessibility: new users now appear in an <OL> list.
927 echo '<div class="newusers">';
928 echo $OUTPUT->heading(get_string("newusers").':', 3);
930 echo "<ol class=\"list\">\n";
931 foreach ($users as $user) {
932 $fullname = fullname($user, $viewfullnames);
933 echo '<li class="name"><a href="'."$CFG->wwwroot/user/view.php?id=$user->id&course=$course->id\">$fullname</a></li>\n";
935 echo "</ol>\n</div>\n";
938 /// Next, have there been any modifications to the course structure?
940 $modinfo =& get_fast_modinfo($course);
942 $changelist = array();
944 $logs = $DB->get_records_select('log', "time > ? AND course = ? AND
945 module = 'course' AND
946 (action = 'add mod' OR action = 'update mod' OR action = 'delete mod')",
947 array($timestart, $course->id), "id ASC");
950 $actions = array('add mod', 'update mod', 'delete mod');
951 $newgones = array(); // added and later deleted items
952 foreach ($logs as $key => $log) {
953 if (!in_array($log->action, $actions)) {
956 $info = explode(' ', $log->info);
958 // note: in most cases I replaced hardcoding of label with use of
959 // $cm->has_view() but it was not possible to do this here because
960 // we don't necessarily have the $cm for it
961 if ($info[0] == 'label') { // Labels are ignored in recent activity
965 if (count($info) != 2) {
966 debugging("Incorrect log entry info: id = ".$log->id, DEBUG_DEVELOPER);
971 $instanceid = $info[1];
973 if ($log->action == 'delete mod') {
974 // unfortunately we do not know if the mod was visible
975 if (!array_key_exists($log->info, $newgones)) {
976 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $modname));
977 $changelist[$log->info] = array ('operation' => 'delete', 'text' => $strdeleted);
980 if (!isset($modinfo->instances[$modname][$instanceid])) {
981 if ($log->action == 'add mod') {
982 // do not display added and later deleted activities
983 $newgones[$log->info] = true;
987 $cm = $modinfo->instances[$modname][$instanceid];
988 if (!$cm->uservisible) {
992 if ($log->action == 'add mod') {
993 $stradded = get_string('added', 'moodle', get_string('modulename', $modname));
994 $changelist[$log->info] = array('operation' => 'add', 'text' => "$stradded:<br /><a href=\"$CFG->wwwroot/mod/$cm->modname/view.php?id={$cm->id}\">".format_string($cm->name, true)."</a>");
996 } else if ($log->action == 'update mod' and empty($changelist[$log->info])) {
997 $strupdated = get_string('updated', 'moodle', get_string('modulename', $modname));
998 $changelist[$log->info] = array('operation' => 'update', 'text' => "$strupdated:<br /><a href=\"$CFG->wwwroot/mod/$cm->modname/view.php?id={$cm->id}\">".format_string($cm->name, true)."</a>");
1004 if (!empty($changelist)) {
1005 echo $OUTPUT->heading(get_string("courseupdates").':', 3);
1007 foreach ($changelist as $changeinfo => $change) {
1008 echo '<p class="activity">'.$change['text'].'</p>';
1012 /// Now display new things from each module
1014 $usedmodules = array();
1015 foreach($modinfo->cms as $cm) {
1016 if (isset($usedmodules[$cm->modname])) {
1019 if (!$cm->uservisible) {
1022 $usedmodules[$cm->modname] = $cm->modname;
1025 foreach ($usedmodules as $modname) { // Each module gets it's own logs and prints them
1026 if (file_exists($CFG->dirroot.'/mod/'.$modname.'/lib.php')) {
1027 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
1028 $print_recent_activity = $modname.'_print_recent_activity';
1029 if (function_exists($print_recent_activity)) {
1030 // NOTE: original $isteacher (second parameter below) was replaced with $viewfullnames!
1031 $content = $print_recent_activity($course, $viewfullnames, $timestart) || $content;
1034 debugging("Missing lib.php in lib/{$modname} - please reinstall files or uninstall the module");
1039 echo '<p class="message">'.get_string('nothingnew').'</p>';
1044 * For a given course, returns an array of course activity objects
1045 * Each item in the array contains he following properties:
1047 function get_array_of_activities($courseid) {
1048 // cm - course module id
1049 // mod - name of the module (eg forum)
1050 // section - the number of the section (eg week or topic)
1051 // name - the name of the instance
1052 // visible - is the instance visible or not
1053 // groupingid - grouping id
1054 // groupmembersonly - is this instance visible to group members only
1055 // extra - contains extra string to include in any link
1057 if(!empty($CFG->enableavailability)) {
1058 require_once($CFG->libdir.'/conditionlib.php');
1061 $course = $DB->get_record('course', array('id'=>$courseid));
1063 if (empty($course)) {
1064 throw new moodle_exception('courseidnotfound');
1069 $rawmods = get_course_mods($courseid);
1070 if (empty($rawmods)) {
1071 return $mod; // always return array
1074 if ($sections = $DB->get_records("course_sections", array("course"=>$courseid), "section ASC")) {
1075 foreach ($sections as $section) {
1076 if (!empty($section->sequence)) {
1077 $sequence = explode(",", $section->sequence);
1078 foreach ($sequence as $seq) {
1079 if (empty($rawmods[$seq])) {
1082 $mod[$seq]->id = $rawmods[$seq]->instance;
1083 $mod[$seq]->cm = $rawmods[$seq]->id;
1084 $mod[$seq]->mod = $rawmods[$seq]->modname;
1086 // Oh dear. Inconsistent names left here for backward compatibility.
1087 $mod[$seq]->section = $section->section;
1088 $mod[$seq]->sectionid = $rawmods[$seq]->section;
1090 $mod[$seq]->module = $rawmods[$seq]->module;
1091 $mod[$seq]->added = $rawmods[$seq]->added;
1092 $mod[$seq]->score = $rawmods[$seq]->score;
1093 $mod[$seq]->idnumber = $rawmods[$seq]->idnumber;
1094 $mod[$seq]->visible = $rawmods[$seq]->visible;
1095 $mod[$seq]->visibleold = $rawmods[$seq]->visibleold;
1096 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
1097 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
1098 $mod[$seq]->groupmembersonly = $rawmods[$seq]->groupmembersonly;
1099 $mod[$seq]->indent = $rawmods[$seq]->indent;
1100 $mod[$seq]->completion = $rawmods[$seq]->completion;
1101 $mod[$seq]->extra = "";
1102 $mod[$seq]->completiongradeitemnumber =
1103 $rawmods[$seq]->completiongradeitemnumber;
1104 $mod[$seq]->completionview = $rawmods[$seq]->completionview;
1105 $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected;
1106 $mod[$seq]->availablefrom = $rawmods[$seq]->availablefrom;
1107 $mod[$seq]->availableuntil = $rawmods[$seq]->availableuntil;
1108 $mod[$seq]->showavailability = $rawmods[$seq]->showavailability;
1109 $mod[$seq]->showdescription = $rawmods[$seq]->showdescription;
1110 if (!empty($CFG->enableavailability)) {
1111 condition_info::fill_availability_conditions($rawmods[$seq]);
1112 $mod[$seq]->conditionscompletion = $rawmods[$seq]->conditionscompletion;
1113 $mod[$seq]->conditionsgrade = $rawmods[$seq]->conditionsgrade;
1116 $modname = $mod[$seq]->mod;
1117 $functionname = $modname."_get_coursemodule_info";
1119 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
1123 include_once("$CFG->dirroot/mod/$modname/lib.php");
1125 if ($hasfunction = function_exists($functionname)) {
1126 if ($info = $functionname($rawmods[$seq])) {
1127 if (!empty($info->icon)) {
1128 $mod[$seq]->icon = $info->icon;
1130 if (!empty($info->iconcomponent)) {
1131 $mod[$seq]->iconcomponent = $info->iconcomponent;
1133 if (!empty($info->name)) {
1134 $mod[$seq]->name = $info->name;
1136 if ($info instanceof cached_cm_info) {
1137 // When using cached_cm_info you can include three new fields
1138 // that aren't available for legacy code
1139 if (!empty($info->content)) {
1140 $mod[$seq]->content = $info->content;
1142 if (!empty($info->extraclasses)) {
1143 $mod[$seq]->extraclasses = $info->extraclasses;
1145 if (!empty($info->onclick)) {
1146 $mod[$seq]->onclick = $info->onclick;
1148 if (!empty($info->customdata)) {
1149 $mod[$seq]->customdata = $info->customdata;
1152 // When using a stdclass, the (horrible) deprecated ->extra field
1153 // is available for BC
1154 if (!empty($info->extra)) {
1155 $mod[$seq]->extra = $info->extra;
1160 // When there is no modname_get_coursemodule_info function,
1161 // but showdescriptions is enabled, then we use the 'intro'
1162 // and 'introformat' fields in the module table
1163 if (!$hasfunction && $rawmods[$seq]->showdescription) {
1164 if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
1165 array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
1166 // Set content from intro and introformat. Filters are disabled
1167 // because we filter it with format_text at display time
1168 $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
1169 $modvalues, $rawmods[$seq]->id, false);
1171 // To save making another query just below, put name in here
1172 $mod[$seq]->name = $modvalues->name;
1175 if (!isset($mod[$seq]->name)) {
1176 $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
1179 // Minimise the database size by unsetting default options when they are
1180 // 'empty'. This list corresponds to code in the cm_info constructor.
1181 foreach (array('idnumber', 'groupmode', 'groupingid', 'groupmembersonly',
1182 'indent', 'completion', 'extra', 'extraclasses', 'onclick', 'content',
1183 'icon', 'iconcomponent', 'customdata', 'showavailability', 'availablefrom',
1184 'availableuntil', 'conditionscompletion', 'conditionsgrade',
1185 'completionview', 'completionexpected', 'score', 'showdescription')
1187 if (property_exists($mod[$seq], $property) &&
1188 empty($mod[$seq]->{$property})) {
1189 unset($mod[$seq]->{$property});
1192 // Special case: this value is usually set to null, but may be 0
1193 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
1194 is_null($mod[$seq]->completiongradeitemnumber)) {
1195 unset($mod[$seq]->completiongradeitemnumber);
1206 * Returns a number of useful structures for course displays
1208 function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
1209 global $CFG, $DB, $COURSE;
1211 $mods = array(); // course modules indexed by id
1212 $modnames = array(); // all course module names (except resource!)
1213 $modnamesplural= array(); // all course module names (plural form)
1214 $modnamesused = array(); // course module names used
1216 if ($allmods = $DB->get_records("modules")) {
1217 foreach ($allmods as $mod) {
1218 if (!file_exists("$CFG->dirroot/mod/$mod->name/lib.php")) {
1221 if ($mod->visible) {
1222 $modnames[$mod->name] = get_string("modulename", "$mod->name");
1223 $modnamesplural[$mod->name] = get_string("modulenameplural", "$mod->name");
1226 collatorlib::asort($modnames);
1228 print_error("nomodules", 'debug');
1231 $course = ($courseid==$COURSE->id) ? $COURSE : $DB->get_record('course',array('id'=>$courseid));
1232 $modinfo = get_fast_modinfo($course);
1234 if ($rawmods=$modinfo->cms) {
1235 foreach($rawmods as $mod) { // Index the mods
1236 if (empty($modnames[$mod->modname])) {
1239 $mods[$mod->id] = $mod;
1240 $mods[$mod->id]->modfullname = $modnames[$mod->modname];
1241 if (!$mod->visible and !has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_COURSE, $courseid))) {
1245 if (!groups_course_module_visible($mod)) {
1248 $modnamesused[$mod->modname] = $modnames[$mod->modname];
1250 if ($modnamesused) {
1251 collatorlib::asort($modnamesused);
1257 * Returns an array of sections for the requested course id
1259 * This function stores the sections against the course id within a staticvar encase
1260 * of subsequent requests. This is used all over + in some standard libs and course
1261 * format callbacks so subsequent requests are a reality.
1263 * @staticvar array $coursesections
1264 * @param int $courseid
1265 * @return array Array of sections
1267 function get_all_sections($courseid) {
1269 static $coursesections = array();
1270 if (!array_key_exists($courseid, $coursesections)) {
1271 $coursesections[$courseid] = $DB->get_records("course_sections", array("course"=>"$courseid"), "section",
1272 "section, id, course, name, summary, summaryformat, sequence, visible");
1274 return $coursesections[$courseid];
1278 * Returns the course section to display or 0 meaning show all sections. Returns 0 for guests.
1279 * It also sets the $USER->display cache to array($courseid=>return value)
1281 * @param int $courseid The course id
1282 * @return int Course section to display, 0 means all
1284 function course_get_display($courseid) {
1287 if (!isloggedin() or isguestuser()) {
1288 //do not get settings in db for guests
1289 return 0; //return the implicit setting
1292 if (!isset($USER->display[$courseid])) {
1293 if (!$display = $DB->get_field('course_display', 'display', array('userid' => $USER->id, 'course'=>$courseid))) {
1294 $display = 0; // all sections option is not stored in DB, this makes the table much smaller
1296 //use display cache for one course only - we need to keep session small
1297 $USER->display = array($courseid => $display);
1300 return $USER->display[$courseid];
1304 * Show one section only or all sections.
1306 * @param int $courseid The course id
1307 * @param mixed $display show only this section, 0 or 'all' means show all sections
1308 * @return int Course section to display, 0 means all
1310 function course_set_display($courseid, $display) {
1313 if ($display === 'all' or empty($display)) {
1317 if (!isloggedin() or isguestuser()) {
1318 //do not store settings in db for guests
1322 if ($display == 0) {
1323 //show all, do not store anything in database
1324 $DB->delete_records('course_display', array('userid' => $USER->id, 'course' => $courseid));
1327 if ($DB->record_exists('course_display', array('userid' => $USER->id, 'course' => $courseid))) {
1328 $DB->set_field('course_display', 'display', $display, array('userid' => $USER->id, 'course' => $courseid));
1330 $record = new stdClass();
1331 $record->userid = $USER->id;
1332 $record->course = $courseid;
1333 $record->display = $display;
1334 $DB->insert_record('course_display', $record);
1338 //use display cache for one course only - we need to keep session small
1339 $USER->display = array($courseid => $display);
1345 * For a given course section, marks it visible or hidden,
1346 * and does the same for every activity in that section
1348 function set_section_visible($courseid, $sectionnumber, $visibility) {
1351 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
1352 $DB->set_field("course_sections", "visible", "$visibility", array("id"=>$section->id));
1353 if (!empty($section->sequence)) {
1354 $modules = explode(",", $section->sequence);
1355 foreach ($modules as $moduleid) {
1356 set_coursemodule_visible($moduleid, $visibility, true);
1359 rebuild_course_cache($courseid);
1364 * Obtains shared data that is used in print_section when displaying a
1365 * course-module entry.
1367 * Calls format_text or format_string as appropriate, and obtains the correct icon.
1369 * This data is also used in other areas of the code.
1370 * @param cm_info $cm Course-module data (must come from get_fast_modinfo)
1371 * @param object $course Moodle course object
1372 * @return array An array with the following values in this order:
1373 * $content (optional extra content for after link),
1374 * $instancename (text of link)
1376 function get_print_section_cm_text(cm_info $cm, $course) {
1379 // Get content from modinfo if specified. Content displays either
1380 // in addition to the standard link (below), or replaces it if
1381 // the link is turned off by setting ->url to null.
1382 if (($content = $cm->get_content()) !== '') {
1383 // Improve filter performance by preloading filter setttings for all
1384 // activities on the course (this does nothing if called multiple
1386 filter_preload_activities($cm->get_modinfo());
1388 // Get module context
1389 $modulecontext = get_context_instance(CONTEXT_MODULE, $cm->id);
1390 $labelformatoptions = new stdClass();
1391 $labelformatoptions->noclean = true;
1392 $labelformatoptions->overflowdiv = true;
1393 $labelformatoptions->context = $modulecontext;
1394 $content = format_text($content, FORMAT_HTML, $labelformatoptions);
1399 // Get course context
1400 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
1401 $stringoptions = new stdClass;
1402 $stringoptions->context = $coursecontext;
1403 $instancename = format_string($cm->name, true, $stringoptions);
1404 return array($content, $instancename);
1408 * Prints a section full of activity modules
1410 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%", $hidecompletion=false) {
1411 global $CFG, $USER, $DB, $PAGE, $OUTPUT;
1413 static $initialised;
1415 static $groupbuttons;
1416 static $groupbuttonslink;
1419 static $strmovehere;
1420 static $strmovefull;
1421 static $strunreadpostsone;
1423 static $modulenames;
1425 if (!isset($initialised)) {
1426 $groupbuttons = ($course->groupmode or (!$course->groupmodeforce));
1427 $groupbuttonslink = (!$course->groupmodeforce);
1428 $isediting = $PAGE->user_is_editing();
1429 $ismoving = $isediting && ismoving($course->id);
1431 $strmovehere = get_string("movehere");
1432 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1434 $modulenames = array();
1435 $initialised = true;
1438 $tl = textlib_get_instance();
1440 $modinfo = get_fast_modinfo($course);
1441 $completioninfo = new completion_info($course);
1443 //Accessibility: replace table with list <ul>, but don't output empty list.
1444 if (!empty($section->sequence)) {
1446 // Fix bug #5027, don't want style=\"width:$width\".
1447 echo "<ul class=\"section img-text\">\n";
1448 $sectionmods = explode(",", $section->sequence);
1450 foreach ($sectionmods as $modnumber) {
1451 if (empty($mods[$modnumber])) {
1458 $mod = $mods[$modnumber];
1460 if ($ismoving and $mod->id == $USER->activitycopy) {
1461 // do not display moving mod
1465 if (isset($modinfo->cms[$modnumber])) {
1466 // We can continue (because it will not be displayed at all)
1468 // 1) The activity is not visible to users
1470 // 2a) The 'showavailability' option is not set (if that is set,
1471 // we need to display the activity so we can show
1472 // availability info)
1474 // 2b) The 'availableinfo' is empty, i.e. the activity was
1475 // hidden in a way that leaves no info, such as using the
1477 if (!$modinfo->cms[$modnumber]->uservisible &&
1478 (empty($modinfo->cms[$modnumber]->showavailability) ||
1479 empty($modinfo->cms[$modnumber]->availableinfo))) {
1480 // visibility shortcut
1484 if (!file_exists("$CFG->dirroot/mod/$mod->modname/lib.php")) {
1485 // module not installed
1488 if (!coursemodule_visible_for_user($mod) &&
1489 empty($mod->showavailability)) {
1490 // full visibility check
1495 if (!isset($modulenames[$mod->modname])) {
1496 $modulenames[$mod->modname] = get_string('modulename', $mod->modname);
1498 $modulename = $modulenames[$mod->modname];
1500 // In some cases the activity is visible to user, but it is
1501 // dimmed. This is done if viewhiddenactivities is true and if:
1502 // 1. the activity is not visible, or
1503 // 2. the activity has dates set which do not include current, or
1504 // 3. the activity has any other conditions set (regardless of whether
1505 // current user meets them)
1506 $canviewhidden = has_capability(
1507 'moodle/course:viewhiddenactivities',
1508 get_context_instance(CONTEXT_MODULE, $mod->id));
1509 $accessiblebutdim = false;
1510 if ($canviewhidden) {
1511 $accessiblebutdim = !$mod->visible;
1512 if (!empty($CFG->enableavailability)) {
1513 $accessiblebutdim = $accessiblebutdim ||
1514 $mod->availablefrom > time() ||
1515 ($mod->availableuntil && $mod->availableuntil < time()) ||
1516 count($mod->conditionsgrade) > 0 ||
1517 count($mod->conditionscompletion) > 0;
1521 $liclasses = array();
1522 $liclasses[] = 'activity';
1523 $liclasses[] = $mod->modname;
1524 $liclasses[] = 'modtype_'.$mod->modname;
1525 $extraclasses = $mod->get_extra_classes();
1526 if ($extraclasses) {
1527 $liclasses = array_merge($liclasses, explode(' ', $extraclasses));
1529 echo html_writer::start_tag('li', array('class'=>join(' ', $liclasses), 'id'=>'module-'.$modnumber));
1531 echo '<a title="'.$strmovefull.'"'.
1532 ' href="'.$CFG->wwwroot.'/course/mod.php?moveto='.$mod->id.'&sesskey='.sesskey().'">'.
1533 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1534 ' alt="'.$strmovehere.'" /></a><br />
1538 $classes = array('mod-indent');
1539 if (!empty($mod->indent)) {
1540 $classes[] = 'mod-indent-'.$mod->indent;
1541 if ($mod->indent > 15) {
1542 $classes[] = 'mod-indent-huge';
1545 echo html_writer::start_tag('div', array('class'=>join(' ', $classes)));
1547 // Get data about this course-module
1548 list($content, $instancename) =
1549 get_print_section_cm_text($modinfo->cms[$modnumber], $course);
1551 //Accessibility: for files get description via icon, this is very ugly hack!
1553 $altname = $mod->modfullname;
1554 if (!empty($customicon)) {
1555 $archetype = plugin_supports('mod', $mod->modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1556 if ($archetype == MOD_ARCHETYPE_RESOURCE) {
1557 $mimetype = mimeinfo_from_icon('type', $customicon);
1558 $altname = get_mimetype_description($mimetype);
1561 // Avoid unnecessary duplication: if e.g. a forum name already
1562 // includes the word forum (or Forum, etc) then it is unhelpful
1563 // to include that in the accessible description that is added.
1564 if (false !== strpos($tl->strtolower($instancename),
1565 $tl->strtolower($altname))) {
1568 // File type after name, for alphabetic lists (screen reader).
1570 $altname = get_accesshide(' '.$altname);
1573 // We may be displaying this just in order to show information
1574 // about visibility, without the actual link
1576 if ($mod->uservisible) {
1577 // Nope - in this case the link is fully working for user
1580 if ($accessiblebutdim) {
1581 $linkclasses .= ' dimmed';
1582 $textclasses .= ' dimmed_text';
1583 $accesstext = '<span class="accesshide">'.
1584 get_string('hiddenfromstudents').': </span>';
1589 $linkcss = 'class="' . trim($linkclasses) . '" ';
1594 $textcss = 'class="' . trim($textclasses) . '" ';
1599 // Get on-click attribute value if specified
1600 $onclick = $mod->get_on_click();
1602 $onclick = ' onclick="' . $onclick . '"';
1605 if ($url = $mod->get_url()) {
1606 // Display link itself
1607 echo '<a ' . $linkcss . $mod->extra . $onclick .
1608 ' href="' . $url . '"><img src="' . $mod->get_icon_url() .
1609 '" class="activityicon" alt="' .
1610 $modulename . '" /> ' .
1611 $accesstext . '<span class="instancename">' .
1612 $instancename . $altname . '</span></a>';
1614 // If specified, display extra content after link
1616 $contentpart = '<div class="contentafterlink' .
1617 trim($textclasses) . '">' . $content . '</div>';
1620 // No link, so display only content
1621 $contentpart = '<div ' . $textcss . $mod->extra . '>' .
1622 $accesstext . $content . '</div>';
1625 if (!empty($mod->groupingid) && has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
1626 if (!isset($groupings)) {
1627 $groupings = groups_get_all_groupings($course->id);
1629 echo " <span class=\"groupinglabel\">(".format_string($groupings[$mod->groupingid]->name).')</span>';
1632 $textclasses = $extraclasses;
1633 $textclasses .= ' dimmed_text';
1635 $textcss = 'class="' . trim($textclasses) . '" ';
1639 $accesstext = '<span class="accesshide">' .
1640 get_string('notavailableyet', 'condition') .
1643 if ($url = $mod->get_url()) {
1644 // Display greyed-out text of link
1645 echo '<div ' . $textcss . $mod->extra .
1646 ' >' . '<img src="' . $mod->get_icon_url() .
1647 '" class="activityicon" alt="' .
1649 '" /> <span>'. $instancename . $altname .
1652 // Do not display content after link when it is greyed out like this.
1654 // No link, so display only content (also greyed)
1655 $contentpart = '<div ' . $textcss . $mod->extra . '>' .
1656 $accesstext . $content . '</div>';
1660 // Module can put text after the link (e.g. forum unread)
1661 echo $mod->get_after_link();
1663 // If there is content but NO link (eg label), then display the
1664 // content here (BEFORE any icons). In this case cons must be
1665 // displayed after the content so that it makes more sense visually
1666 // and for accessibility reasons, e.g. if you have a one-line label
1667 // it should work similarly (at least in terms of ordering) to an
1674 if ($groupbuttons and plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
1675 if (! $mod->groupmodelink = $groupbuttonslink) {
1676 $mod->groupmode = $course->groupmode;
1680 $mod->groupmode = false;
1682 echo ' ';
1683 echo make_editing_buttons($mod, $absolute, true, $mod->indent, $section->section);
1684 echo $mod->get_after_edit_icons();
1688 $completion = $hidecompletion
1689 ? COMPLETION_TRACKING_NONE
1690 : $completioninfo->is_enabled($mod);
1691 if ($completion!=COMPLETION_TRACKING_NONE && isloggedin() &&
1692 !isguestuser() && $mod->uservisible) {
1693 $completiondata = $completioninfo->get_data($mod,true);
1694 $completionicon = '';
1696 switch ($completion) {
1697 case COMPLETION_TRACKING_MANUAL :
1698 $completionicon = 'manual-enabled'; break;
1699 case COMPLETION_TRACKING_AUTOMATIC :
1700 $completionicon = 'auto-enabled'; break;
1703 } else if ($completion==COMPLETION_TRACKING_MANUAL) {
1704 switch($completiondata->completionstate) {
1705 case COMPLETION_INCOMPLETE:
1706 $completionicon = 'manual-n'; break;
1707 case COMPLETION_COMPLETE:
1708 $completionicon = 'manual-y'; break;
1710 } else { // Automatic
1711 switch($completiondata->completionstate) {
1712 case COMPLETION_INCOMPLETE:
1713 $completionicon = 'auto-n'; break;
1714 case COMPLETION_COMPLETE:
1715 $completionicon = 'auto-y'; break;
1716 case COMPLETION_COMPLETE_PASS:
1717 $completionicon = 'auto-pass'; break;
1718 case COMPLETION_COMPLETE_FAIL:
1719 $completionicon = 'auto-fail'; break;
1722 if ($completionicon) {
1723 $imgsrc = $OUTPUT->pix_url('i/completion-'.$completionicon);
1724 $imgalt = s(get_string('completion-alt-'.$completionicon, 'completion'));
1725 if ($completion == COMPLETION_TRACKING_MANUAL && !$isediting) {
1726 $imgtitle = s(get_string('completion-title-'.$completionicon, 'completion'));
1728 $completiondata->completionstate==COMPLETION_COMPLETE
1729 ? COMPLETION_INCOMPLETE
1730 : COMPLETION_COMPLETE;
1731 // In manual mode the icon is a toggle form...
1733 // If this completion state is used by the
1734 // conditional activities system, we need to turn
1736 if (!empty($CFG->enableavailability) &&
1737 condition_info::completion_value_used_as_condition($course, $mod)) {
1738 $extraclass = ' preventjs';
1743 <form class='togglecompletion$extraclass' method='post' action='".$CFG->wwwroot."/course/togglecompletion.php'><div>
1744 <input type='hidden' name='id' value='{$mod->id}' />
1745 <input type='hidden' name='sesskey' value='".sesskey()."' />
1746 <input type='hidden' name='completionstate' value='$newstate' />
1747 <input type='image' src='$imgsrc' alt='$imgalt' title='$imgtitle' />
1750 // In auto mode, or when editing, the icon is just an image
1751 echo "<span class='autocompletion'>";
1752 echo "<img src='$imgsrc' alt='$imgalt' title='$imgalt' /></span>";
1757 // If there is content AND a link, then display the content here
1758 // (AFTER any icons). Otherwise it was displayed before
1763 // Show availability information (for someone who isn't allowed to
1764 // see the activity itself, or for staff)
1765 if (!$mod->uservisible) {
1766 echo '<div class="availabilityinfo">'.$mod->availableinfo.'</div>';
1767 } else if ($canviewhidden && !empty($CFG->enableavailability)) {
1768 $ci = new condition_info($mod);
1769 $fullinfo = $ci->get_full_information();
1771 echo '<div class="availabilityinfo">'.get_string($mod->showavailability
1772 ? 'userrestriction_visible'
1773 : 'userrestriction_hidden','condition',
1774 $fullinfo).'</div>';
1778 echo html_writer::end_tag('div');
1779 echo html_writer::end_tag('li')."\n";
1782 } elseif ($ismoving) {
1783 echo "<ul class=\"section\">\n";
1787 echo '<li><a title="'.$strmovefull.'"'.
1788 ' href="'.$CFG->wwwroot.'/course/mod.php?movetosection='.$section->id.'&sesskey='.sesskey().'">'.
1789 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1790 ' alt="'.$strmovehere.'" /></a></li>
1793 if (!empty($section->sequence) || $ismoving) {
1794 echo "</ul><!--class='section'-->\n\n";
1799 * Prints the menus to add activities and resources.
1801 function print_section_add_menus($course, $section, $modnames, $vertical=false, $return=false) {
1802 global $CFG, $OUTPUT;
1804 // check to see if user can add menus
1805 if (!has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $course->id))) {
1809 $urlbase = "/course/mod.php?id=$course->id§ion=$section&sesskey=".sesskey().'&add=';
1811 $resources = array();
1812 $activities = array();
1814 foreach($modnames as $modname=>$modnamestr) {
1815 if (!course_allowed_module($course, $modname)) {
1819 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1820 if (!file_exists($libfile)) {
1823 include_once($libfile);
1824 $gettypesfunc = $modname.'_get_types';
1825 if (function_exists($gettypesfunc)) {
1826 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1827 if ($types = $gettypesfunc()) {
1831 foreach($types as $type) {
1832 if ($type->typestr === '--') {
1835 if (strpos($type->typestr, '--') === 0) {
1836 $groupname = str_replace('--', '', $type->typestr);
1839 $type->type = str_replace('&', '&', $type->type);
1840 if ($type->modclass == MOD_CLASS_RESOURCE) {
1841 $atype = MOD_CLASS_RESOURCE;
1843 $menu[$urlbase.$type->type] = $type->typestr;
1845 if (!is_null($groupname)) {
1846 if ($atype == MOD_CLASS_RESOURCE) {
1847 $resources[] = array($groupname=>$menu);
1849 $activities[] = array($groupname=>$menu);
1852 if ($atype == MOD_CLASS_RESOURCE) {
1853 $resources = array_merge($resources, $menu);
1855 $activities = array_merge($activities, $menu);
1860 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1861 if ($archetype == MOD_ARCHETYPE_RESOURCE) {
1862 $resources[$urlbase.$modname] = $modnamestr;
1864 // all other archetypes are considered activity
1865 $activities[$urlbase.$modname] = $modnamestr;
1870 $straddactivity = get_string('addactivity');
1871 $straddresource = get_string('addresource');
1873 $output = '<div class="section_add_menus">';
1876 $output .= '<div class="horizontal">';
1879 if (!empty($resources)) {
1880 $select = new url_select($resources, '', array(''=>$straddresource), "ressection$section");
1881 $select->set_help_icon('resources');
1882 $output .= $OUTPUT->render($select);
1885 if (!empty($activities)) {
1886 $select = new url_select($activities, '', array(''=>$straddactivity), "section$section");
1887 $select->set_help_icon('activities');
1888 $output .= $OUTPUT->render($select);
1892 $output .= '</div>';
1895 $output .= '</div>';
1905 * Return the course category context for the category with id $categoryid, except
1906 * that if $categoryid is 0, return the system context.
1908 * @param integer $categoryid a category id or 0.
1909 * @return object the corresponding context
1911 function get_category_or_system_context($categoryid) {
1913 return get_context_instance(CONTEXT_COURSECAT, $categoryid);
1915 return get_context_instance(CONTEXT_SYSTEM);
1920 * Gets the child categories of a given courses category. Uses a static cache
1921 * to make repeat calls efficient.
1923 * @param int $parentid the id of a course category.
1924 * @return array all the child course categories.
1926 function get_child_categories($parentid) {
1927 static $allcategories = null;
1929 // only fill in this variable the first time
1930 if (null == $allcategories) {
1931 $allcategories = array();
1933 $categories = get_categories();
1934 foreach ($categories as $category) {
1935 if (empty($allcategories[$category->parent])) {
1936 $allcategories[$category->parent] = array();
1938 $allcategories[$category->parent][] = $category;
1942 if (empty($allcategories[$parentid])) {
1945 return $allcategories[$parentid];
1950 * This function recursively travels the categories, building up a nice list
1951 * for display. It also makes an array that list all the parents for each
1954 * For example, if you have a tree of categories like:
1955 * Miscellaneous (id = 1)
1956 * Subcategory (id = 2)
1957 * Sub-subcategory (id = 4)
1958 * Other category (id = 3)
1959 * Then after calling this function you will have
1960 * $list = array(1 => 'Miscellaneous', 2 => 'Miscellaneous / Subcategory',
1961 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
1962 * 3 => 'Other category');
1963 * $parents = array(2 => array(1), 4 => array(1, 2));
1965 * If you specify $requiredcapability, then only categories where the current
1966 * user has that capability will be added to $list, although all categories
1967 * will still be added to $parents, and if you only have $requiredcapability
1968 * in a child category, not the parent, then the child catgegory will still be
1971 * If you specify the option $excluded, then that category, and all its children,
1972 * are omitted from the tree. This is useful when you are doing something like
1973 * moving categories, where you do not want to allow people to move a category
1974 * to be the child of itself.
1976 * @param array $list For output, accumulates an array categoryid => full category path name
1977 * @param array $parents For output, accumulates an array categoryid => list of parent category ids.
1978 * @param string/array $requiredcapability if given, only categories where the current
1979 * user has this capability will be added to $list. Can also be an array of capabilities,
1980 * in which case they are all required.
1981 * @param integer $excludeid Omit this category and its children from the lists built.
1982 * @param object $category Build the tree starting at this category - otherwise starts at the top level.
1983 * @param string $path For internal use, as part of recursive calls.
1985 function make_categories_list(&$list, &$parents, $requiredcapability = '',
1986 $excludeid = 0, $category = NULL, $path = "") {
1988 // initialize the arrays if needed
1989 if (!is_array($list)) {
1992 if (!is_array($parents)) {
1996 if (empty($category)) {
1997 // Start at the top level.
1998 $category = new stdClass;
2001 // This is the excluded category, don't include it.
2002 if ($excludeid > 0 && $excludeid == $category->id) {
2008 $path = $path.' / '.format_string($category->name);
2010 $path = format_string($category->name);
2013 // Add this category to $list, if the permissions check out.
2014 if (empty($requiredcapability)) {
2015 $list[$category->id] = $path;
2018 ensure_context_subobj_present($category, CONTEXT_COURSECAT);
2019 $requiredcapability = (array)$requiredcapability;
2020 if (has_all_capabilities($requiredcapability, $category->context)) {
2021 $list[$category->id] = $path;
2026 // Add all the children recursively, while updating the parents array.
2027 if ($categories = get_child_categories($category->id)) {
2028 foreach ($categories as $cat) {
2029 if (!empty($category->id)) {
2030 if (isset($parents[$category->id])) {
2031 $parents[$cat->id] = $parents[$category->id];
2033 $parents[$cat->id][] = $category->id;
2035 make_categories_list($list, $parents, $requiredcapability, $excludeid, $cat, $path);
2041 * This function generates a structured array of courses and categories.
2043 * The depth of categories is limited by $CFG->maxcategorydepth however there
2044 * is no limit on the number of courses!
2046 * Suitable for use with the course renderers course_category_tree method:
2047 * $renderer = $PAGE->get_renderer('core','course');
2048 * echo $renderer->course_category_tree(get_course_category_tree());
2050 * @global moodle_database $DB
2054 function get_course_category_tree($id = 0, $depth = 0) {
2056 $viewhiddencats = has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_SYSTEM));
2057 $categories = get_child_categories($id);
2058 $categoryids = array();
2059 foreach ($categories as $key => &$category) {
2060 if (!$category->visible && !$viewhiddencats) {
2061 unset($categories[$key]);
2064 $categoryids[$category->id] = $category;
2065 if (empty($CFG->maxcategorydepth) || $depth <= $CFG->maxcategorydepth) {
2066 list($category->categories, $subcategories) = get_course_category_tree($category->id, $depth+1);
2067 foreach ($subcategories as $subid=>$subcat) {
2068 $categoryids[$subid] = $subcat;
2070 $category->courses = array();
2075 // This is a recursive call so return the required array
2076 return array($categories, $categoryids);
2079 // The depth is 0 this function has just been called so we can finish it off
2081 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
2082 list($catsql, $catparams) = $DB->get_in_or_equal(array_keys($categoryids));
2084 c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary,c.category
2088 WHERE c.category $catsql ORDER BY c.sortorder ASC";
2089 if ($courses = $DB->get_records_sql($sql, $catparams)) {
2090 // loop throught them
2091 foreach ($courses as $course) {
2092 if ($course->id == SITEID) {
2095 context_instance_preload($course);
2096 if (!empty($course->visible) || has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id))) {
2097 $categoryids[$course->category]->courses[$course->id] = $course;
2105 * Recursive function to print out all the categories in a nice format
2106 * with or without courses included
2108 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true) {
2111 // maxcategorydepth == 0 meant no limit
2112 if (!empty($CFG->maxcategorydepth) && $depth >= $CFG->maxcategorydepth) {
2116 if (!$displaylist) {
2117 make_categories_list($displaylist, $parentslist);
2121 if ($category->visible or has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_SYSTEM))) {
2122 print_category_info($category, $depth, $showcourses);
2124 return; // Don't bother printing children of invisible categories
2128 $category->id = "0";
2131 if ($categories = get_child_categories($category->id)) { // Print all the children recursively
2132 $countcats = count($categories);
2136 foreach ($categories as $cat) {
2138 if ($count == $countcats) {
2141 $up = $first ? false : true;
2142 $down = $last ? false : true;
2145 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1, $showcourses);
2151 * This function will return $options array for html_writer::select(), with whitespace to denote nesting.
2153 function make_categories_options() {
2154 make_categories_list($cats,$parents);
2155 foreach ($cats as $key => $value) {
2156 if (array_key_exists($key,$parents)) {
2157 if ($indent = count($parents[$key])) {
2158 for ($i = 0; $i < $indent; $i++) {
2159 $cats[$key] = ' '.$cats[$key];
2168 * Prints the category info in indented fashion
2169 * This function is only used by print_whole_category_list() above
2171 function print_category_info($category, $depth=0, $showcourses = false) {
2172 global $CFG, $DB, $OUTPUT;
2174 $strsummary = get_string('summary');
2177 if (!$category->visible) {
2178 $catlinkcss = array('class'=>'dimmed');
2180 static $coursecount = null;
2181 if (null === $coursecount) {
2182 // only need to check this once
2183 $coursecount = $DB->count_records('course') <= FRONTPAGECOURSELIMIT;
2186 if ($showcourses and $coursecount) {
2187 $catimage = '<img src="'.$OUTPUT->pix_url('i/course') . '" alt="" />';
2189 $catimage = " ";
2192 $courses = get_courses($category->id, 'c.sortorder ASC', 'c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary');
2193 if ($showcourses and $coursecount) {
2194 echo '<div class="categorylist clearfix">';
2196 $cat .= html_writer::tag('div', $catimage, array('class'=>'image'));
2197 $catlink = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), format_string($category->name), $catlinkcss);
2198 $cat .= html_writer::tag('div', $catlink, array('class'=>'name'));
2202 for ($i=0; $i< $depth; $i++) {
2203 $html = html_writer::tag('div', $html . $cat, array('class'=>'indentation'));
2209 echo html_writer::tag('div', $html, array('class'=>'category'));
2210 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
2212 // does the depth exceed maxcategorydepth
2213 // maxcategorydepth == 0 or unset meant no limit
2214 $limit = !(isset($CFG->maxcategorydepth) && ($depth >= $CFG->maxcategorydepth-1));
2215 if ($courses && ($limit || $CFG->maxcategorydepth == 0)) {
2216 foreach ($courses as $course) {
2218 if (!$course->visible) {
2219 $linkcss = array('class'=>'dimmed');
2222 $courselink = html_writer::link(new moodle_url('/course/view.php', array('id'=>$course->id)), format_string($course->fullname), $linkcss);
2226 if ($icons = enrol_get_course_info_icons($course)) {
2227 foreach ($icons as $pix_icon) {
2228 $courseicon = $OUTPUT->render($pix_icon).' ';
2232 $coursecontent = html_writer::tag('div', $courseicon.$courselink, array('class'=>'name'));
2234 if ($course->summary) {
2235 $link = new moodle_url('/course/info.php?id='.$course->id);
2236 $actionlink = $OUTPUT->action_link($link, '<img alt="'.$strsummary.'" src="'.$OUTPUT->pix_url('i/info') . '" />',
2237 new popup_action('click', $link, 'courseinfo', array('height' => 400, 'width' => 500)),
2238 array('title'=>$strsummary));
2240 $coursecontent .= html_writer::tag('div', $actionlink, array('class'=>'info'));
2244 for ($i=0; $i <= $depth; $i++) {
2245 $html = html_writer::tag('div', $html . $coursecontent , array('class'=>'indentation'));
2246 $coursecontent = '';
2248 echo html_writer::tag('div', $html, array('class'=>'course clearfloat'));
2253 echo '<div class="categorylist">';
2255 $cat = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), format_string($category->name), $catlinkcss);
2256 $cat .= html_writer::tag('span', ' ('.count($courses).')', array('title'=>get_string('numberofcourses'), 'class'=>'numberofcourse'));
2259 for ($i=0; $i< $depth; $i++) {
2260 $html = html_writer::tag('div', $html .$cat, array('class'=>'indentation'));
2267 echo html_writer::tag('div', $html, array('class'=>'category'));
2268 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
2274 * Print the buttons relating to course requests.
2276 * @param object $systemcontext the system context.
2278 function print_course_request_buttons($systemcontext) {
2279 global $CFG, $DB, $OUTPUT;
2280 if (empty($CFG->enablecourserequests)) {
2283 if (!has_capability('moodle/course:create', $systemcontext) && has_capability('moodle/course:request', $systemcontext)) {
2284 /// Print a button to request a new course
2285 echo $OUTPUT->single_button('request.php', get_string('requestcourse'), 'get');
2287 /// Print a button to manage pending requests
2288 if (has_capability('moodle/site:approvecourse', $systemcontext)) {
2289 $disabled = !$DB->record_exists('course_request', array());
2290 echo $OUTPUT->single_button('pending.php', get_string('coursespending'), 'get', array('disabled'=>$disabled));
2295 * Does the user have permission to edit things in this category?
2297 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2298 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
2300 function can_edit_in_category($categoryid = 0) {
2301 $context = get_category_or_system_context($categoryid);
2302 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
2306 * Prints the turn editing on/off button on course/index.php or course/category.php.
2308 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2309 * @return string HTML of the editing button, or empty string, if this user is not allowed
2312 function update_category_button($categoryid = 0) {
2313 global $CFG, $PAGE, $OUTPUT;
2315 // Check permissions.
2316 if (!can_edit_in_category($categoryid)) {
2320 // Work out the appropriate action.
2321 if ($PAGE->user_is_editing()) {
2322 $label = get_string('turneditingoff');
2325 $label = get_string('turneditingon');
2329 // Generate the button HTML.
2330 $options = array('categoryedit' => $edit, 'sesskey' => sesskey());
2332 $options['id'] = $categoryid;
2333 $page = 'category.php';
2335 $page = 'index.php';
2337 return $OUTPUT->single_button(new moodle_url('/course/' . $page, $options), $label, 'get');
2341 * Category is 0 (for all courses) or an object
2343 function print_courses($category) {
2344 global $CFG, $OUTPUT;
2346 if (!is_object($category) && $category==0) {
2347 $categories = get_child_categories(0); // Parent = 0 ie top-level categories only
2348 if (is_array($categories) && count($categories) == 1) {
2349 $category = array_shift($categories);
2350 $courses = get_courses_wmanagers($category->id,
2352 array('summary','summaryformat'));
2354 $courses = get_courses_wmanagers('all',
2356 array('summary','summaryformat'));
2360 $courses = get_courses_wmanagers($category->id,
2362 array('summary','summaryformat'));
2366 echo html_writer::start_tag('ul', array('class'=>'unlist'));
2367 foreach ($courses as $course) {
2368 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
2369 if ($course->visible == 1 || has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2370 echo html_writer::start_tag('li');
2371 print_course($course);
2372 echo html_writer::end_tag('li');
2375 echo html_writer::end_tag('ul');
2377 echo $OUTPUT->heading(get_string("nocoursesyet"));
2378 $context = get_context_instance(CONTEXT_SYSTEM);
2379 if (has_capability('moodle/course:create', $context)) {
2381 if (!empty($category->id)) {
2382 $options['category'] = $category->id;
2384 $options['category'] = $CFG->defaultrequestcategory;
2386 echo html_writer::start_tag('div', array('class'=>'addcoursebutton'));
2387 echo $OUTPUT->single_button(new moodle_url('/course/edit.php', $options), get_string("addnewcourse"));
2388 echo html_writer::end_tag('div');
2394 * Print a description of a course, suitable for browsing in a list.
2396 * @param object $course the course object.
2397 * @param string $highlightterms (optional) some search terms that should be highlighted in the display.
2399 function print_course($course, $highlightterms = '') {
2400 global $CFG, $USER, $DB, $OUTPUT;
2402 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2404 // Rewrite file URLs so that they are correct
2405 $course->summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', NULL);
2407 echo html_writer::start_tag('div', array('class'=>'coursebox clearfix'));
2408 echo html_writer::start_tag('div', array('class'=>'info'));
2409 echo html_writer::start_tag('h3', array('class'=>'name'));
2411 $linkhref = new moodle_url('/course/view.php', array('id'=>$course->id));
2412 $linktext = highlight($highlightterms, format_string($course->fullname));
2413 $linkparams = array('title'=>get_string('entercourse'));
2414 if (empty($course->visible)) {
2415 $linkparams['class'] = 'dimmed';
2417 echo html_writer::link($linkhref, $linktext, $linkparams);
2418 echo html_writer::end_tag('h3');
2420 /// first find all roles that are supposed to be displayed
2421 if (!empty($CFG->coursecontact)) {
2422 $managerroles = explode(',', $CFG->coursecontact);
2423 $namesarray = array();
2424 if (isset($course->managers)) {
2425 if (count($course->managers)) {
2426 $rusers = $course->managers;
2427 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2429 /// Rename some of the role names if needed
2430 if (isset($context)) {
2431 $aliasnames = $DB->get_records('role_names', array('contextid'=>$context->id), '', 'roleid,contextid,name');
2434 // keep a note of users displayed to eliminate duplicates
2435 $usersshown = array();
2436 foreach ($rusers as $ra) {
2438 // if we've already displayed user don't again
2439 if (in_array($ra->user->id,$usersshown)) {
2442 $usersshown[] = $ra->user->id;
2444 $fullname = fullname($ra->user, $canviewfullnames);
2446 if (isset($aliasnames[$ra->roleid])) {
2447 $ra->rolename = $aliasnames[$ra->roleid]->name;
2450 $namesarray[] = format_string($ra->rolename).': '.
2451 html_writer::link(new moodle_url('/user/view.php', array('id'=>$ra->user->id, 'course'=>SITEID)), $fullname);
2455 $rusers = get_role_users($managerroles, $context,
2456 true, '', 'r.sortorder ASC, u.lastname ASC');
2457 if (is_array($rusers) && count($rusers)) {
2458 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2460 /// Rename some of the role names if needed
2461 if (isset($context)) {
2462 $aliasnames = $DB->get_records('role_names', array('contextid'=>$context->id), '', 'roleid,contextid,name');
2465 foreach ($rusers as $teacher) {
2466 $fullname = fullname($teacher, $canviewfullnames);
2468 /// Apply role names
2469 if (isset($aliasnames[$teacher->roleid])) {
2470 $teacher->rolename = $aliasnames[$teacher->roleid]->name;
2473 $namesarray[] = format_string($teacher->rolename).': '.
2474 html_writer::link(new moodle_url('/user/view.php', array('id'=>$teacher->id, 'course'=>SITEID)), $fullname);
2479 if (!empty($namesarray)) {
2480 echo html_writer::start_tag('ul', array('class'=>'teachers'));
2481 foreach ($namesarray as $name) {
2482 echo html_writer::tag('li', $name);
2484 echo html_writer::end_tag('ul');
2487 echo html_writer::end_tag('div'); // End of info div
2489 echo html_writer::start_tag('div', array('class'=>'summary'));
2491 $options->noclean = true;
2492 $options->para = false;
2493 $options->overflowdiv = true;
2494 if (!isset($course->summaryformat)) {
2495 $course->summaryformat = FORMAT_MOODLE;
2497 echo highlight($highlightterms, format_text($course->summary, $course->summaryformat, $options, $course->id));
2498 if ($icons = enrol_get_course_info_icons($course)) {
2499 echo html_writer::start_tag('div', array('class'=>'enrolmenticons'));
2500 foreach ($icons as $icon) {
2501 echo $OUTPUT->render($icon);
2503 echo html_writer::end_tag('div'); // End of enrolmenticons div
2505 echo html_writer::end_tag('div'); // End of summary div
2506 echo html_writer::end_tag('div'); // End of coursebox div
2510 * Prints custom user information on the home page.
2511 * Over time this can include all sorts of information
2513 function print_my_moodle() {
2514 global $USER, $CFG, $DB, $OUTPUT;
2516 if (!isloggedin() or isguestuser()) {
2517 print_error('nopermissions', '', '', 'See My Moodle');
2520 $courses = enrol_get_my_courses('summary', 'visible DESC,sortorder ASC');
2522 $rcourses = array();
2523 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
2524 $rcourses = get_my_remotecourses($USER->id);
2525 $rhosts = get_my_remotehosts();
2528 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
2530 if (!empty($courses)) {
2531 echo '<ul class="unlist">';
2532 foreach ($courses as $course) {
2533 if ($course->id == SITEID) {
2537 print_course($course);
2544 if (!empty($rcourses)) {
2545 // at the IDP, we know of all the remote courses
2546 foreach ($rcourses as $course) {
2547 print_remote_course($course, "100%");
2549 } elseif (!empty($rhosts)) {
2550 // non-IDP, we know of all the remote servers, but not courses
2551 foreach ($rhosts as $host) {
2552 print_remote_host($host, "100%");
2558 if ($DB->count_records("course") > (count($courses) + 1) ) { // Some courses not being displayed
2559 echo "<table width=\"100%\"><tr><td align=\"center\">";
2560 print_course_search("", false, "short");
2561 echo "</td><td align=\"center\">";
2562 echo $OUTPUT->single_button("$CFG->wwwroot/course/index.php", get_string("fulllistofcourses"), "get");
2563 echo "</td></tr></table>\n";
2567 if ($DB->count_records("course_categories") > 1) {
2568 echo $OUTPUT->box_start("categorybox");
2569 print_whole_category_list();
2570 echo $OUTPUT->box_end();
2578 function print_course_search($value="", $return=false, $format="plain") {
2584 $id = 'coursesearch';
2590 $strsearchcourses= get_string("searchcourses");
2592 if ($format == 'plain') {
2593 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2594 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2595 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
2596 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" value="'.s($value).'" />';
2597 $output .= '<input type="submit" value="'.get_string('go').'" />';
2598 $output .= '</fieldset></form>';
2599 } else if ($format == 'short') {
2600 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2601 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2602 $output .= '<label for="shortsearchbox">'.$strsearchcourses.': </label>';
2603 $output .= '<input type="text" id="shortsearchbox" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2604 $output .= '<input type="submit" value="'.get_string('go').'" />';
2605 $output .= '</fieldset></form>';
2606 } else if ($format == 'navbar') {
2607 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2608 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2609 $output .= '<label for="navsearchbox">'.$strsearchcourses.': </label>';
2610 $output .= '<input type="text" id="navsearchbox" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2611 $output .= '<input type="submit" value="'.get_string('go').'" />';
2612 $output .= '</fieldset></form>';
2621 function print_remote_course($course, $width="100%") {
2626 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&wantsurl=/course/view.php?id={$course->remoteid}";
2628 echo '<div class="coursebox remotecoursebox clearfix">';
2629 echo '<div class="info">';
2630 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2631 $linkcss.' href="'.$url.'">'
2632 . format_string($course->fullname) .'</a><br />'
2633 . format_string($course->hostname) . ' : '
2634 . format_string($course->cat_name) . ' : '
2635 . format_string($course->shortname). '</div>';
2636 echo '</div><div class="summary">';
2638 $options->noclean = true;
2639 $options->para = false;
2640 $options->overflowdiv = true;
2641 echo format_text($course->summary, $course->summaryformat, $options);
2646 function print_remote_host($host, $width="100%") {
2651 echo '<div class="coursebox clearfix">';
2652 echo '<div class="info">';
2653 echo '<div class="name">';
2654 echo '<img src="'.$OUTPUT->pix_url('i/mnethost') . '" class="icon" alt="'.get_string('course').'" />';
2655 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2656 . s($host['name']).'</a> - ';
2657 echo $host['count'] . ' ' . get_string('courses');
2664 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2666 function add_course_module($mod) {
2669 $mod->added = time();
2672 return $DB->insert_record("course_modules", $mod);
2676 * Returns course section - creates new if does not exist yet.
2677 * @param int $relative section number
2678 * @param int $courseid
2679 * @return object $course_section object
2681 function get_course_section($section, $courseid) {
2684 if ($cw = $DB->get_record("course_sections", array("section"=>$section, "course"=>$courseid))) {
2687 $cw = new stdClass();
2688 $cw->course = $courseid;
2689 $cw->section = $section;
2691 $cw->summaryformat = FORMAT_HTML;
2693 $id = $DB->insert_record("course_sections", $cw);
2694 return $DB->get_record("course_sections", array("id"=>$id));
2697 * Given a full mod object with section and course already defined, adds this module to that section.
2699 * @param object $mod
2700 * @param int $beforemod An existing ID which we will insert the new module before
2701 * @return int The course_sections ID where the mod is inserted
2703 function add_mod_to_section($mod, $beforemod=NULL) {
2706 if ($section = $DB->get_record("course_sections", array("course"=>$mod->course, "section"=>$mod->section))) {
2708 $section->sequence = trim($section->sequence);
2710 if (empty($section->sequence)) {
2711 $newsequence = "$mod->coursemodule";
2713 } else if ($beforemod) {
2714 $modarray = explode(",", $section->sequence);
2716 if ($key = array_keys($modarray, $beforemod->id)) {
2717 $insertarray = array($mod->id, $beforemod->id);
2718 array_splice($modarray, $key[0], 1, $insertarray);
2719 $newsequence = implode(",", $modarray);
2721 } else { // Just tack it on the end anyway
2722 $newsequence = "$section->sequence,$mod->coursemodule";
2726 $newsequence = "$section->sequence,$mod->coursemodule";
2729 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
2730 return $section->id; // Return course_sections ID that was used.
2732 } else { // Insert a new record
2733 $section->course = $mod->course;
2734 $section->section = $mod->section;
2735 $section->summary = "";
2736 $section->summaryformat = FORMAT_HTML;
2737 $section->sequence = $mod->coursemodule;
2738 return $DB->insert_record("course_sections", $section);
2742 function set_coursemodule_groupmode($id, $groupmode) {
2744 return $DB->set_field("course_modules", "groupmode", $groupmode, array("id"=>$id));
2747 function set_coursemodule_idnumber($id, $idnumber) {
2749 return $DB->set_field("course_modules", "idnumber", $idnumber, array("id"=>$id));
2753 * $prevstateoverrides = true will set the visibility of the course module
2754 * to what is defined in visibleold. This enables us to remember the current
2755 * visibility when making a whole section hidden, so that when we toggle
2756 * that section back to visible, we are able to return the visibility of
2757 * the course module back to what it was originally.
2759 function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
2761 require_once($CFG->libdir.'/gradelib.php');
2763 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2766 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
2769 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2770 foreach($events as $event) {
2779 // hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there
2780 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
2782 foreach ($grade_items as $grade_item) {
2783 $grade_item->set_hidden(!$visible);
2787 if ($prevstateoverrides) {
2788 if ($visible == '0') {
2789 // Remember the current visible state so we can toggle this back.
2790 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id'=>$id));
2792 // Get the previous saved visible states.
2793 return $DB->set_field('course_modules', 'visible', $cm->visibleold, array('id'=>$id));
2796 return $DB->set_field("course_modules", "visible", $visible, array("id"=>$id));
2800 * Delete a course module and any associated data at the course level (events)
2801 * Until 1.5 this function simply marked a deleted flag ... now it
2802 * deletes it completely.
2805 function delete_course_module($id) {
2807 require_once($CFG->libdir.'/gradelib.php');
2808 require_once($CFG->dirroot.'/blog/lib.php');
2810 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2813 $modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module));
2814 //delete events from calendar
2815 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2816 foreach($events as $event) {
2817 delete_event($event->id);
2820 //delete grade items, outcome items and grades attached to modules
2821 if ($grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2822 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course))) {
2823 foreach ($grade_items as $grade_item) {
2824 $grade_item->delete('moddelete');
2827 // Delete completion and availability data; it is better to do this even if the
2828 // features are not turned on, in case they were turned on previously (these will be
2829 // very quick on an empty table)
2830 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
2831 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id));
2833 delete_context(CONTEXT_MODULE, $cm->id);
2834 return $DB->delete_records('course_modules', array('id'=>$cm->id));
2837 function delete_mod_from_section($mod, $section) {
2840 if ($section = $DB->get_record("course_sections", array("id"=>$section)) ) {
2842 $modarray = explode(",", $section->sequence);
2844 if ($key = array_keys ($modarray, $mod)) {
2845 array_splice($modarray, $key[0], 1);
2846 $newsequence = implode(",", $modarray);
2847 return $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
2857 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
2859 * @param object $course
2860 * @param int $section
2861 * @param int $move (-1 or 1)
2863 function move_section($course, $section, $move) {
2864 /// Moves a whole course section up and down within the course
2871 $sectiondest = $section + $move;
2873 if ($sectiondest > $course->numsections or $sectiondest < 1) {
2877 if (!$sectionrecord = $DB->get_record("course_sections", array("course"=>$course->id, "section"=>$section))) {
2881 if (!$sectiondestrecord = $DB->get_record("course_sections", array("course"=>$course->id, "section"=>$sectiondest))) {
2885 $DB->set_field("course_sections", "section", $sectiondest, array("id"=>$sectionrecord->id));
2886 $DB->set_field("course_sections", "section", $section, array("id"=>$sectiondestrecord->id));
2888 // if the focus is on the section that is being moved, then move the focus along
2889 if (course_get_display($course->id) == $section) {
2890 course_set_display($course->id, $sectiondest);
2893 // Check for duplicates and fix order if needed.
2894 // There is a very rare case that some sections in the same course have the same section id.
2895 $sections = $DB->get_records('course_sections', array('course'=>$course->id), 'section ASC');
2897 foreach ($sections as $section) {
2898 if ($section->section != $n) {
2899 $DB->set_field('course_sections', 'section', $n, array('id'=>$section->id));
2907 * Moves a section within a course, from a position to another.
2908 * Be very careful: $section and $destination refer to section number,
2911 * @param object $course
2912 * @param int $section Section number (not id!!!)
2913 * @param int $destination
2914 * @return boolean Result
2916 function move_section_to($course, $section, $destination) {
2917 /// Moves a whole course section up and down within the course
2920 if (!$destination && $destination != 0) {
2924 if ($destination > $course->numsections) {
2928 // Get all sections for this course and re-order them (2 of them should now share the same section number)
2929 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
2930 'section ASC, id ASC', 'id, section')) {
2934 $sections = reorder_sections($sections, $section, $destination);
2936 // Update all sections
2937 foreach ($sections as $id => $position) {
2938 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
2941 // if the focus is on the section that is being moved, then move the focus along
2942 if (course_get_display($course->id) == $section) {
2943 course_set_display($course->id, $destination);
2949 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
2950 * an original position number and a target position number, rebuilds the array so that the
2951 * move is made without any duplication of section positions.
2952 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
2953 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
2955 * @param array $sections
2956 * @param int $origin_position
2957 * @param int $target_position
2960 function reorder_sections($sections, $origin_position, $target_position) {
2961 if (!is_array($sections)) {
2965 // We can't move section position 0
2966 if ($origin_position < 1) {
2967 echo "We can't move section position 0";
2971 // Locate origin section in sections array
2972 if (!$origin_key = array_search($origin_position, $sections)) {
2973 echo "searched position not in sections array";
2974 return false; // searched position not in sections array
2977 // Extract origin section
2978 $origin_section = $sections[$origin_key];
2979 unset($sections[$origin_key]);
2981 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
2983 $append_array = array();
2984 foreach ($sections as $id => $position) {
2986 $append_array[$id] = $position;
2987 unset($sections[$id]);
2989 if ($position == $target_position) {
2994 // Append moved section
2995 $sections[$origin_key] = $origin_section;
2997 // Append rest of array (if applicable)
2998 if (!empty($append_array)) {
2999 foreach ($append_array as $id => $position) {
3000 $sections[$id] = $position;
3004 // Renumber positions
3006 foreach ($sections as $id => $p) {
3007 $sections[$id] = $position;
3016 * Move the module object $mod to the specified $section
3017 * If $beforemod exists then that is the module
3018 * before which $modid should be inserted
3019 * All parameters are objects
3021 function moveto_module($mod, $section, $beforemod=NULL) {
3022 global $DB, $OUTPUT;
3024 /// Remove original module from original section
3025 if (! delete_mod_from_section($mod->id, $mod->section)) {
3026 echo $OUTPUT->notification("Could not delete module from existing section");
3029 /// Update module itself if necessary
3031 if ($mod->section != $section->id) {
3032 $mod->section = $section->id;
3033 $DB->update_record("course_modules", $mod);
3034 // if moving to a hidden section then hide module
3035 if (!$section->visible) {
3036 set_coursemodule_visible($mod->id, 0);
3040 /// Add the module into the new section
3042 $mod->course = $section->course;
3043 $mod->section = $section->section; // need relative reference
3044 $mod->coursemodule = $mod->id;
3046 if (! add_mod_to_section($mod, $beforemod)) {
3054 * Produces the editing buttons for a module
3056 * @global core_renderer $OUTPUT
3057 * @staticvar type $str
3058 * @param stdClass $mod The module to produce editing buttons for
3059 * @param bool $absolute If true an absolute link is produced (default true)
3060 * @param bool $moveselect If true a move seleciton process is used (default true)
3061 * @param int $indent The current indenting
3062 * @param int $section The section to link back to
3063 * @return string XHTML for the editing buttons
3065 function make_editing_buttons(stdClass $mod, $absolute = true, $moveselect = true, $indent=-1, $section=-1) {
3066 global $CFG, $OUTPUT;
3070 $coursecontext = get_context_instance(CONTEXT_COURSE, $mod->course);
3071 $modcontext = get_context_instance(CONTEXT_MODULE, $mod->id);
3073 // no permission to edit
3074 if (!has_capability('moodle/course:manageactivities', $modcontext)) {
3079 $str = new stdClass;
3080 $str->assign = get_string("assignroles", 'role');
3081 $str->delete = get_string("delete");
3082 $str->move = get_string("move");
3083 $str->moveup = get_string("moveup");
3084 $str->movedown = get_string("movedown");
3085 $str->moveright = get_string("moveright");
3086 $str->moveleft = get_string("moveleft");
3087 $str->update = get_string("update");
3088 $str->duplicate = get_string("duplicate");
3089 $str->hide = get_string("hide");
3090 $str->show = get_string("show");
3091 $str->clicktochange = get_string("clicktochange");
3092 $str->forcedmode = get_string("forcedmode");
3093 $str->groupsnone = get_string("groupsnone");
3094 $str->groupsseparate = get_string("groupsseparate");
3095 $str->groupsvisible = get_string("groupsvisible");
3099 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
3101 $baseurl = new moodle_url('mod.php', array('sesskey' => sesskey()));
3104 if ($section >= 0) {
3105 $baseurl->param('sr', $section);
3110 if (has_capability('moodle/course:update', $coursecontext)) {
3111 if (right_to_left()) { // Exchange arrows on RTL
3112 $rightarrow = 't/left';
3113 $leftarrow = 't/right';
3115 $rightarrow = 't/right';
3116 $leftarrow = 't/left';
3120 $actions[] = new action_link(
3121 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
3122 new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall')),
3124 array('class' => 'editing_moveleft', 'title' => $str->moveleft)
3128 $actions[] = new action_link(
3129 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
3130 new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall')),
3132 array('class' => 'editing_moveright', 'title' => $str->moveright)
3138 if (has_capability('moodle/course:update', $coursecontext)) {
3140 $actions[] = new action_link(
3141 new moodle_url($baseurl, array('copy' => $mod->id)),
3142 new pix_icon('t/move', $str->move, 'moodle', array('class' => 'iconsmall')),
3144 array('class' => 'editing_move', 'title' => $str->move)
3147 $actions[] = new action_link(
3148 new moodle_url($baseurl, array('id' => $mod->id, 'move' => '-1')),
3149 new pix_icon('t/up', $str->moveup, 'moodle', array('class' => 'iconsmall')),
3151 array('class' => 'editing_moveup', 'title' => $str->moveup)
3153 $actions[] = new action_link(
3154 new moodle_url($baseurl, array('id' => $mod->id, 'move' => '1')),
3155 new pix_icon('t/down', $str->movedown, 'moodle', array('class' => 'iconsmall')),
3157 array('class' => 'editing_movedown', 'title' => $str->movedown)
3163 $actions[] = new action_link(
3164 new moodle_url($baseurl, array('update' => $mod->id)),
3165 new pix_icon('t/edit', $str->update, 'moodle', array('class' => 'iconsmall')),
3167 array('class' => 'editing_update', 'title' => $str->update)
3170 // Duplicate (require both target import caps to be able to duplicate, see modduplicate.php)
3171 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
3172 if (has_all_capabilities($dupecaps, $coursecontext)) {
3173 $actions[] = new action_link(
3174 new moodle_url($baseurl, array('duplicate' => $mod->id)),
3175 new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall')),
3177 array('class' => 'editing_duplicate', 'title' => $str->duplicate)
3182 $actions[] = new action_link(
3183 new moodle_url($baseurl, array('delete' => $mod->id)),
3184 new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall')),
3186 array('class' => 'editing_delete', 'title' => $str->delete)
3190 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
3191 if ($mod->visible) {
3192 $actions[] = new action_link(
3193 new moodle_url($baseurl, array('hide' => $mod->id)),
3194 new pix_icon('t/hide', $str->hide, 'moodle', array('class' => 'iconsmall')),
3196 array('class' => 'editing_hide', 'title' => $str->hide)
3199 $actions[] = new action_link(
3200 new moodle_url($baseurl, array('show' => $mod->id)),
3201 new pix_icon('t/show', $str->show, 'moodle', array('class' => 'iconsmall')),
3203 array('class' => 'editing_show', 'title' => $str->show)
3209 if ($mod->groupmode !== false) {
3210 if ($mod->groupmode == SEPARATEGROUPS) {
3212 $grouptitle = $str->groupsseparate;
3213 $groupclass = 'editing_groupsseparate';
3214 $groupimage = 't/groups';
3215 } else if ($mod->groupmode == VISIBLEGROUPS) {
3217 $grouptitle = $str->groupsvisible;
3218 $groupclass = 'editing_groupsvisible';
3219 $groupimage = 't/groupv';
3222 $grouptitle = $str->groupsnone;
3223 $groupclass = 'editing_groupsnone';
3224 $groupimage = 't/groupn';
3226 if ($mod->groupmodelink) {
3227 $actions[] = new action_link(
3228 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $groupmode)),
3229 new pix_icon($groupimage, $grouptitle, 'moodle', array('class' => 'iconsmall')),
3231 array('class' => $groupclass, 'title' => $grouptitle.' ('.$str->clicktochange.')')
3234 $actions[] = new pix_icon($groupimage, $grouptitle, 'moodle', array('title' => $grouptitle.' ('.$str->forcedmode.')', 'class' => 'iconsmall'));
3239 if (has_capability('moodle/course:managegroups', $modcontext)){
3240 $actions[] = new action_link(
3241 new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $modcontext->id)),
3242 new pix_icon('i/roles', $str->assign, 'moodle', array('class' => 'iconsmall')),
3244 array('class' => 'editing_assign', 'title' => $str->assign)
3248 $output = html_writer::start_tag('span', array('class' => 'commands'));
3249 foreach ($actions as $action) {
3250 if ($action instanceof renderable) {
3251 $output .= $OUTPUT->render($action);
3256 $output .= html_writer::end_tag('span');
3261 * given a course object with shortname & fullname, this function will
3262 * truncate the the number of chars allowed and add ... if it was too long
3264 function course_format_name ($course,$max=100) {
3266 $str = $course->shortname.': '. $course->fullname;
3267 if (textlib::strlen($str) <= $max) {
3271 return textlib::substr($str,0,$max-3).'...';
3275 function update_restricted_mods($course, $mods) {
3278 /// Delete all the current restricted list
3279 $DB->delete_records('course_allowed_modules', array('course'=>$course->id));
3281 if (empty($course->restrictmodules)) {
3282 return; // We're done
3285 /// Insert the new list of restricted mods
3286 foreach ($mods as $mod) {
3288 continue; // this is the 'allow none' option
3290 $am = new stdClass();
3291 $am->course = $course->id;
3293 $DB->insert_record('course_allowed_modules',$am);
3298 * This function will take an int (module id) or a string (module name)
3299 * and return true or false, whether it's allowed in the given course (object)
3300 * $mod is not allowed to be an object, as the field for the module id is inconsistent
3301 * depending on where in the code it's called from (sometimes $mod->id, sometimes $mod->module)
3304 function course_allowed_module($course,$mod) {
3307 if (empty($course->restrictmodules)) {
3311 // Admins and admin-like people who can edit everything can also add anything.
3312 // Originally there was a course:update test only, but it did not match the test in course edit form
3313 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
3317 if (is_numeric($mod)) {
3319 } else if (is_string($mod)) {
3320 $modid = $DB->get_field('modules', 'id', array('name'=>$mod));
3322 if (empty($modid)) {
3326 return $DB->record_exists('course_allowed_modules', array('course'=>$course->id, 'module'=>$modid));
3330 * Recursively delete category including all subcategories and courses.
3331 * @param stdClass $category
3332 * @param boolean $showfeedback display some notices
3333 * @return array return deleted courses
3335 function category_delete_full($category, $showfeedback=true) {
3337 require_once($CFG->libdir.'/gradelib.php');
3338 require_once($CFG->libdir.'/questionlib.php');
3339 require_once($CFG->dirroot.'/cohort/lib.php');
3341 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3342 foreach ($children as $childcat) {
3343 category_delete_full($childcat, $showfeedback);
3347 $deletedcourses = array();
3348 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC')) {
3349 foreach ($courses as $course) {
3350 if (!delete_course($course, false)) {
3351 throw new moodle_exception('cannotdeletecategorycourse','','',$course->shortname);
3353 $deletedcourses[] = $course;
3357 // move or delete cohorts in this context
3358 cohort_delete_category($category);
3360 // now delete anything that may depend on course category context
3361 grade_course_category_delete($category->id, 0, $showfeedback);
3362 if (!question_delete_course_category($category, 0, $showfeedback)) {
3363 throw new moodle_exception('cannotdeletecategoryquestions','','',$category->name);
3366 // finally delete the category and it's context
3367 $DB->delete_records('course_categories', array('id'=>$category->id));
3368 delete_context(CONTEXT_COURSECAT, $category->id);
3370 events_trigger('course_category_deleted', $category);
3372 return $deletedcourses;
3376 * Delete category, but move contents to another category.
3377 * @param object $ccategory
3378 * @param int $newparentid category id
3379 * @return bool status
3381 function category_delete_move($category, $newparentid, $showfeedback=true) {
3382 global $CFG, $DB, $OUTPUT;
3383 require_once($CFG->libdir.'/gradelib.php');
3384 require_once($CFG->libdir.'/questionlib.php');
3385 require_once($CFG->dirroot.'/cohort/lib.php');
3387 if (!$newparentcat = $DB->get_record('course_categories', array('id'=>$newparentid))) {
3391 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3392 foreach ($children as $childcat) {
3393 move_category($childcat, $newparentcat);
3397 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC', 'id')) {
3398 if (!move_courses(array_keys($courses), $newparentid)) {
3399 echo $OUTPUT->notification("Error moving courses");
3402 echo $OUTPUT->notification(get_string('coursesmovedout', '', format_string($category->name)), 'notifysuccess');
3405 // move or delete cohorts in this context
3406 cohort_delete_category($category);
3408 // now delete anything that may depend on course category context
3409 grade_course_category_delete($category->id, $newparentid, $showfeedback);
3410 if (!question_delete_course_category($category, $newparentcat, $showfeedback)) {
3411 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $category), 'notifysuccess');
3415 // finally delete the category and it's context
3416 $DB->delete_records('course_categories', array('id'=>$category->id));
3417 delete_context(CONTEXT_COURSECAT, $category->id);
3419 events_trigger('course_category_deleted', $category);
3421 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', format_string($category->name)), 'notifysuccess');
3427 * Efficiently moves many courses around while maintaining
3428 * sortorder in order.
3430 * @param array $courseids is an array of course ids
3431 * @param int $categoryid
3432 * @return bool success
3434 function move_courses($courseids, $categoryid) {
3435 global $CFG, $DB, $OUTPUT;
3437 if (empty($courseids)) {
3442 if (!$category = $DB->get_record('course_categories', array('id'=>$categoryid))) {
3446 $courseids = array_reverse($courseids);
3447 $newparent = get_context_instance(CONTEXT_COURSECAT, $category->id);
3450 foreach ($courseids as $courseid) {
3451 if ($course = $DB->get_record('course', array('id'=>$courseid), 'id, category')) {
3452 $course = new stdClass();
3453 $course->id = $courseid;
3454 $course->category = $category->id;
3455 $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
3456 if ($category->visible == 0) {
3457 // hide the course when moving into hidden category,
3458 // do not update the visibleold flag - we want to get to previous state if somebody unhides the category
3459 $course->visible = 0;
3462 $DB->update_record('course', $course);
3464 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3465 context_moved($context, $newparent);
3468 fix_course_sortorder();
3474 * Hide course category and child course and subcategories
3475 * @param stdClass $category
3478 function course_category_hide($category) {
3481 $category->visible = 0;
3482 $DB->set_field('course_categories', 'visible', 0, array('id'=>$category->id));
3483 $DB->set_field('course_categories', 'visibleold', 0, array('id'=>$category->id));
3484 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($category->id)); // store visible flag so that we can return to it if we immediately unhide
3485 $DB->set_field('course', 'visible', 0, array('category' => $category->id));
3486 // get all child categories and hide too
3487 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
3488 foreach ($subcats as $cat) {
3489 $DB->set_field('course_categories', 'visibleold', $cat->visible, array('id'=>$cat->id));
3490 $DB->set_field('course_categories', 'visible', 0, array('id'=>$cat->id));
3491 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id));
3492 $DB->set_field('course', 'visible', 0, array('category' => $cat->id));
3498 * Show course category and child course and subcategories
3499 * @param stdClass $category
3502 function course_category_show($category) {
3505 $category->visible = 1;
3506 $DB->set_field('course_categories', 'visible', 1, array('id'=>$category->id));
3507 $DB->set_field('course_categories', 'visibleold', 1, array('id'=>$category->id));