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_LOGS_PER_PAGE', 1000); // records
33 define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds
34 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10); // courses
35 define('COURSE_MAX_COURSES_PER_DROPDOWN',1000); // max courses in log dropdown before switching to optional
36 define('COURSE_MAX_USERS_PER_DROPDOWN',1000); // max users in log dropdown before switching to optional
37 define('FRONTPAGENEWS', '0');
38 define('FRONTPAGECOURSELIST', '1');
39 define('FRONTPAGECATEGORYNAMES', '2');
40 define('FRONTPAGETOPICONLY', '3');
41 define('FRONTPAGECATEGORYCOMBO', '4');
42 define('FRONTPAGECOURSELIMIT', 200); // maximum number of courses displayed on the frontpage
43 define('EXCELROWS', 65535);
44 define('FIRSTUSEDEXCELROW', 3);
46 define('MOD_CLASS_ACTIVITY', 0);
47 define('MOD_CLASS_RESOURCE', 1);
49 function make_log_url($module, $url) {
52 if (strpos($url, 'report/') === 0) {
53 // there is only one report type, course reports are deprecated
63 if (strpos($url, '../') === 0) {
64 $url = ltrim($url, '.');
66 $url = "/course/$url";
71 $url = "/$module/$url";
84 $url = "/message/$url";
96 $url = "/mod/$module/$url";
100 //now let's sanitise urls - there might be some ugly nasties:-(
101 $parts = explode('?', $url);
102 $script = array_shift($parts);
103 if (strpos($script, 'http') === 0) {
104 $script = clean_param($script, PARAM_URL);
106 $script = clean_param($script, PARAM_PATH);
111 $query = implode('', $parts);
112 $query = str_replace('&', '&', $query); // both & and & are stored in db :-|
113 $parts = explode('&', $query);
114 $eq = urlencode('=');
115 foreach ($parts as $key=>$part) {
116 $part = urlencode(urldecode($part));
117 $part = str_replace($eq, '=', $part);
118 $parts[$key] = $part;
120 $query = '?'.implode('&', $parts);
123 return $script.$query;
127 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
128 $modname="", $modid=0, $modaction="", $groupid=0) {
131 // It is assumed that $date is the GMT time of midnight for that day,
132 // and so the next 86400 seconds worth of logs are printed.
134 /// Setup for group handling.
136 // TODO: I don't understand group/context/etc. enough to be able to do
137 // something interesting with it here
138 // What is the context of a remote course?
140 /// If the group mode is separate, and this user does not have editing privileges,
141 /// then only the user's group can be viewed.
142 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
143 // $groupid = get_current_group($course->id);
145 /// If this course doesn't have groups, no groupid can be specified.
146 //else if (!$course->groupmode) {
155 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
157 LEFT JOIN {user} u ON l.userid = u.id
161 $where .= "l.hostid = :hostid";
162 $params['hostid'] = $hostid;
164 // TODO: Is 1 really a magic number referring to the sitename?
165 if ($course != SITEID || $modid != 0) {
166 $where .= " AND l.course=:courseid";
167 $params['courseid'] = $course;
171 $where .= " AND l.module = :modname";
172 $params['modname'] = $modname;
175 if ('site_errors' === $modid) {
176 $where .= " AND ( l.action='error' OR l.action='infected' )";
178 //TODO: This assumes that modids are the same across sites... probably
180 $where .= " AND l.cmid = :modid";
181 $params['modid'] = $modid;
185 $firstletter = substr($modaction, 0, 1);
186 if ($firstletter == '-') {
187 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
188 $params['modaction'] = '%'.substr($modaction, 1).'%';
190 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
191 $params['modaction'] = '%'.$modaction.'%';
196 $where .= " AND l.userid = :user";
197 $params['user'] = $user;
201 $enddate = $date + 86400;
202 $where .= " AND l.time > :date AND l.time < :enddate";
203 $params['date'] = $date;
204 $params['enddate'] = $enddate;
208 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
209 if(!empty($result['totalcount'])) {
210 $where .= " ORDER BY $order";
211 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
213 $result['logs'] = array();
218 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
219 $modname="", $modid=0, $modaction="", $groupid=0) {
220 global $DB, $SESSION, $USER;
221 // It is assumed that $date is the GMT time of midnight for that day,
222 // and so the next 86400 seconds worth of logs are printed.
224 /// Setup for group handling.
226 /// If the group mode is separate, and this user does not have editing privileges,
227 /// then only the user's group can be viewed.
228 if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
229 if (isset($SESSION->currentgroup[$course->id])) {
230 $groupid = $SESSION->currentgroup[$course->id];
232 $groupid = groups_get_all_groups($course->id, $USER->id);
233 if (is_array($groupid)) {
234 $groupid = array_shift(array_keys($groupid));
235 $SESSION->currentgroup[$course->id] = $groupid;
241 /// If this course doesn't have groups, no groupid can be specified.
242 else if (!$course->groupmode) {
249 if ($course->id != SITEID || $modid != 0) {
250 $joins[] = "l.course = :courseid";
251 $params['courseid'] = $course->id;
255 $joins[] = "l.module = :modname";
256 $params['modname'] = $modname;
259 if ('site_errors' === $modid) {
260 $joins[] = "( l.action='error' OR l.action='infected' )";
262 $joins[] = "l.cmid = :modid";
263 $params['modid'] = $modid;
267 $firstletter = substr($modaction, 0, 1);
268 if ($firstletter == '-') {
269 $joins[] = $DB->sql_like('l.action', ':modaction', false, true, true);
270 $params['modaction'] = '%'.substr($modaction, 1).'%';
272 $joins[] = $DB->sql_like('l.action', ':modaction', false);
273 $params['modaction'] = '%'.$modaction.'%';
278 /// Getting all members of a group.
279 if ($groupid and !$user) {
280 if ($gusers = groups_get_members($groupid)) {
281 $gusers = array_keys($gusers);
282 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
284 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
288 $joins[] = "l.userid = :userid";
289 $params['userid'] = $user;
293 $enddate = $date + 86400;
294 $joins[] = "l.time > :date AND l.time < :enddate";
295 $params['date'] = $date;
296 $params['enddate'] = $enddate;
299 $selector = implode(' AND ', $joins);
301 $totalcount = 0; // Initialise
303 $result['logs'] = get_logs($selector, $params, $order, $limitfrom, $limitnum, $totalcount);
304 $result['totalcount'] = $totalcount;
309 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
310 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
312 global $CFG, $DB, $OUTPUT;
314 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
315 $modname, $modid, $modaction, $groupid)) {
316 echo $OUTPUT->notification("No logs found!");
317 echo $OUTPUT->footer();
323 if ($course->id == SITEID) {
325 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
326 foreach ($ccc as $cc) {
327 $courses[$cc->id] = $cc->shortname;
331 $courses[$course->id] = $course->shortname;
334 $totalcount = $logs['totalcount'];
337 $tt = getdate(time());
338 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
340 $strftimedatetime = get_string("strftimedatetime");
342 echo "<div class=\"info\">\n";
343 print_string("displayingrecords", "", $totalcount);
346 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
348 $table = new html_table();
349 $table->classes = array('logtable','generalbox');
350 $table->align = array('right', 'left', 'left');
351 $table->head = array(
353 get_string('ip_address'),
354 get_string('fullnameuser'),
355 get_string('action'),
358 $table->data = array();
360 if ($course->id == SITEID) {
361 array_unshift($table->align, 'left');
362 array_unshift($table->head, get_string('course'));
365 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
366 if (empty($logs['logs'])) {
367 $logs['logs'] = array();
370 foreach ($logs['logs'] as $log) {
372 if (isset($ldcache[$log->module][$log->action])) {
373 $ld = $ldcache[$log->module][$log->action];
375 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
376 $ldcache[$log->module][$log->action] = $ld;
378 if ($ld && is_numeric($log->info)) {
379 // ugly hack to make sure fullname is shown correctly
380 if ($ld->mtable == 'user' && $ld->field == $DB->sql_concat('firstname', "' '" , 'lastname')) {
381 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
383 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
388 $log->info = format_string($log->info);
390 // If $log->url has been trimmed short by the db size restriction
391 // code in add_to_log, keep a note so we don't add a link to a broken url
392 $brokenurl=(textlib::strlen($log->url)==100 && textlib::substr($log->url,97)=='...');
395 if ($course->id == SITEID) {
396 if (empty($log->course)) {
397 $row[] = get_string('site');
399 $row[] = "<a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course])."</a>";
403 $row[] = userdate($log->time, '%a').' '.userdate($log->time, $strftimedatetime);
405 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
406 $row[] = $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 440, 'width' => 700)));
408 $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))));
410 $displayaction="$log->module $log->action";
412 $row[] = $displayaction;
414 $link = make_log_url($log->module,$log->url);
415 $row[] = $OUTPUT->action_link($link, $displayaction, new popup_action('click', $link, 'fromloglive'), array('height' => 440, 'width' => 700));
418 $table->data[] = $row;
421 echo html_writer::table($table);
422 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
426 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
427 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
429 global $CFG, $DB, $OUTPUT;
431 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
432 $modname, $modid, $modaction, $groupid)) {
433 echo $OUTPUT->notification("No logs found!");
434 echo $OUTPUT->footer();
438 if ($course->id == SITEID) {
440 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
441 foreach ($ccc as $cc) {
442 $courses[$cc->id] = $cc->shortname;
447 $totalcount = $logs['totalcount'];
450 $tt = getdate(time());
451 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
453 $strftimedatetime = get_string("strftimedatetime");
455 echo "<div class=\"info\">\n";
456 print_string("displayingrecords", "", $totalcount);
459 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
461 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
463 if ($course->id == SITEID) {
464 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
466 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
467 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
468 echo "<th class=\"c3 header\">".get_string('fullnameuser')."</th>\n";
469 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
470 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
473 if (empty($logs['logs'])) {
479 foreach ($logs['logs'] as $log) {
481 $log->info = $log->coursename;
482 $row = ($row + 1) % 2;
484 if (isset($ldcache[$log->module][$log->action])) {
485 $ld = $ldcache[$log->module][$log->action];
487 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
488 $ldcache[$log->module][$log->action] = $ld;
490 if (0 && $ld && !empty($log->info)) {
491 // ugly hack to make sure fullname is shown correctly
492 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
493 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
495 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
500 $log->info = format_string($log->info);
502 echo '<tr class="r'.$row.'">';
503 if ($course->id == SITEID) {
504 $courseshortname = format_string($courses[$log->course], true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
505 echo "<td class=\"r$row c0\" >\n";
506 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courseshortname."</a>\n";
509 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time, '%a').
510 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
511 echo "<td class=\"r$row c2\" >\n";
512 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
513 echo $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 400, 'width' => 700)));
515 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
516 echo "<td class=\"r$row c3\" >\n";
517 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
519 echo "<td class=\"r$row c4\">\n";
520 echo $log->action .': '.$log->module;
522 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
527 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
531 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
532 $modid, $modaction, $groupid) {
535 $text = get_string('course')."\t".get_string('time')."\t".get_string('ip_address')."\t".
536 get_string('fullnameuser')."\t".get_string('action')."\t".get_string('info');
538 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
539 $modname, $modid, $modaction, $groupid)) {
545 if ($course->id == SITEID) {
547 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
548 foreach ($ccc as $cc) {
549 $courses[$cc->id] = $cc->shortname;
553 $courses[$course->id] = $course->shortname;
558 $tt = getdate(time());
559 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
561 $strftimedatetime = get_string("strftimedatetime");
563 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
565 header("Content-Type: application/download\n");
566 header("Content-Disposition: attachment; filename=$filename");
567 header("Expires: 0");
568 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
569 header("Pragma: public");
571 echo get_string('savedat').userdate(time(), $strftimedatetime)."\n";
574 if (empty($logs['logs'])) {
578 foreach ($logs['logs'] as $log) {
579 if (isset($ldcache[$log->module][$log->action])) {
580 $ld = $ldcache[$log->module][$log->action];
582 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
583 $ldcache[$log->module][$log->action] = $ld;
585 if ($ld && !empty($log->info)) {
586 // ugly hack to make sure fullname is shown correctly
587 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
588 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
590 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
595 $log->info = format_string($log->info);
596 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
598 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
599 $firstField = format_string($courses[$log->course], true, array('context' => $coursecontext));
600 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
601 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action, $log->info);
602 $text = implode("\t", $row);
609 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
610 $modid, $modaction, $groupid) {
614 require_once("$CFG->libdir/excellib.class.php");
616 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
617 $modname, $modid, $modaction, $groupid)) {
623 if ($course->id == SITEID) {
625 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
626 foreach ($ccc as $cc) {
627 $courses[$cc->id] = $cc->shortname;
631 $courses[$course->id] = $course->shortname;
636 $tt = getdate(time());
637 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
639 $strftimedatetime = get_string("strftimedatetime");
641 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
642 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
645 $workbook = new MoodleExcelWorkbook('-');
646 $workbook->send($filename);
648 $worksheet = array();
649 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
650 get_string('fullnameuser'), get_string('action'), get_string('info'));
652 // Creating worksheets
653 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
654 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
655 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
656 $worksheet[$wsnumber]->set_column(1, 1, 30);
657 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
658 userdate(time(), $strftimedatetime));
660 foreach ($headers as $item) {
661 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
666 if (empty($logs['logs'])) {
671 $formatDate =& $workbook->add_format();
672 $formatDate->set_num_format(get_string('log_excel_date_format'));
674 $row = FIRSTUSEDEXCELROW;
676 $myxls =& $worksheet[$wsnumber];
677 foreach ($logs['logs'] as $log) {
678 if (isset($ldcache[$log->module][$log->action])) {
679 $ld = $ldcache[$log->module][$log->action];
681 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
682 $ldcache[$log->module][$log->action] = $ld;
684 if ($ld && !empty($log->info)) {
685 // ugly hack to make sure fullname is shown correctly
686 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
687 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
689 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
694 $log->info = format_string($log->info);
695 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
698 if ($row > EXCELROWS) {
700 $myxls =& $worksheet[$wsnumber];
701 $row = FIRSTUSEDEXCELROW;
705 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
707 $myxls->write($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)), '');
708 $myxls->write_date($row, 1, $log->time, $formatDate); // write_date() does conversion/timezone support. MDL-14934
709 $myxls->write($row, 2, $log->ip, '');
710 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
711 $myxls->write($row, 3, $fullname, '');
712 $myxls->write($row, 4, $log->module.' '.$log->action, '');
713 $myxls->write($row, 5, $log->info, '');
722 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
723 $modid, $modaction, $groupid) {
727 require_once("$CFG->libdir/odslib.class.php");
729 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
730 $modname, $modid, $modaction, $groupid)) {
736 if ($course->id == SITEID) {
738 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
739 foreach ($ccc as $cc) {
740 $courses[$cc->id] = $cc->shortname;
744 $courses[$course->id] = $course->shortname;
749 $tt = getdate(time());
750 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
752 $strftimedatetime = get_string("strftimedatetime");
754 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
755 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
758 $workbook = new MoodleODSWorkbook('-');
759 $workbook->send($filename);
761 $worksheet = array();
762 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
763 get_string('fullnameuser'), get_string('action'), get_string('info'));
765 // Creating worksheets
766 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
767 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
768 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
769 $worksheet[$wsnumber]->set_column(1, 1, 30);
770 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
771 userdate(time(), $strftimedatetime));
773 foreach ($headers as $item) {
774 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
779 if (empty($logs['logs'])) {
784 $formatDate =& $workbook->add_format();
785 $formatDate->set_num_format(get_string('log_excel_date_format'));
787 $row = FIRSTUSEDEXCELROW;
789 $myxls =& $worksheet[$wsnumber];
790 foreach ($logs['logs'] as $log) {
791 if (isset($ldcache[$log->module][$log->action])) {
792 $ld = $ldcache[$log->module][$log->action];
794 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
795 $ldcache[$log->module][$log->action] = $ld;
797 if ($ld && !empty($log->info)) {
798 // ugly hack to make sure fullname is shown correctly
799 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
800 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
802 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
807 $log->info = format_string($log->info);
808 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
811 if ($row > EXCELROWS) {
813 $myxls =& $worksheet[$wsnumber];
814 $row = FIRSTUSEDEXCELROW;
818 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
820 $myxls->write_string($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)));
821 $myxls->write_date($row, 1, $log->time);
822 $myxls->write_string($row, 2, $log->ip);
823 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
824 $myxls->write_string($row, 3, $fullname);
825 $myxls->write_string($row, 4, $log->module.' '.$log->action);
826 $myxls->write_string($row, 5, $log->info);
836 function print_overview($courses, array $remote_courses=array()) {
837 global $CFG, $USER, $DB, $OUTPUT;
839 $htmlarray = array();
840 if ($modules = $DB->get_records('modules')) {
841 foreach ($modules as $mod) {
842 if (file_exists(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php')) {
843 include_once(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php');
844 $fname = $mod->name.'_print_overview';
845 if (function_exists($fname)) {
846 $fname($courses,$htmlarray);
851 foreach ($courses as $course) {
852 $fullname = format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
853 echo $OUTPUT->box_start('coursebox');
854 $attributes = array('title' => s($fullname));
855 if (empty($course->visible)) {
856 $attributes['class'] = 'dimmed';
858 echo $OUTPUT->heading(html_writer::link(
859 new moodle_url('/course/view.php', array('id' => $course->id)), $fullname, $attributes), 3);
860 if (array_key_exists($course->id,$htmlarray)) {
861 foreach ($htmlarray[$course->id] as $modname => $html) {
865 echo $OUTPUT->box_end();
868 if (!empty($remote_courses)) {
869 echo $OUTPUT->heading(get_string('remotecourses', 'mnet'));
871 foreach ($remote_courses as $course) {
872 echo $OUTPUT->box_start('coursebox');
873 $attributes = array('title' => s($course->fullname));
874 echo $OUTPUT->heading(html_writer::link(
875 new moodle_url('/auth/mnet/jump.php', array('hostid' => $course->hostid, 'wantsurl' => '/course/view.php?id='.$course->remoteid)),
876 format_string($course->shortname),
877 $attributes) . ' (' . format_string($course->hostname) . ')', 3);
878 echo $OUTPUT->box_end();
884 * This function trawls through the logs looking for
885 * anything new since the user's last login
887 function print_recent_activity($course) {
888 // $course is an object
889 global $CFG, $USER, $SESSION, $DB, $OUTPUT;
891 $context = get_context_instance(CONTEXT_COURSE, $course->id);
893 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
895 $timestart = round(time() - COURSE_MAX_RECENT_PERIOD, -2); // better db caching for guests - 100 seconds
897 if (!isguestuser()) {
898 if (!empty($USER->lastcourseaccess[$course->id])) {
899 if ($USER->lastcourseaccess[$course->id] > $timestart) {
900 $timestart = $USER->lastcourseaccess[$course->id];
905 echo '<div class="activitydate">';
906 echo get_string('activitysince', '', userdate($timestart));
908 echo '<div class="activityhead">';
910 echo '<a href="'.$CFG->wwwroot.'/course/recent.php?id='.$course->id.'">'.get_string('recentactivityreport').'</a>';
916 /// Firstly, have there been any new enrolments?
918 $users = get_recent_enrolments($course->id, $timestart);
920 //Accessibility: new users now appear in an <OL> list.
922 echo '<div class="newusers">';
923 echo $OUTPUT->heading(get_string("newusers").':', 3);
925 echo "<ol class=\"list\">\n";
926 foreach ($users as $user) {
927 $fullname = fullname($user, $viewfullnames);
928 echo '<li class="name"><a href="'."$CFG->wwwroot/user/view.php?id=$user->id&course=$course->id\">$fullname</a></li>\n";
930 echo "</ol>\n</div>\n";
933 /// Next, have there been any modifications to the course structure?
935 $modinfo = get_fast_modinfo($course);
937 $changelist = array();
939 $logs = $DB->get_records_select('log', "time > ? AND course = ? AND
940 module = 'course' AND
941 (action = 'add mod' OR action = 'update mod' OR action = 'delete mod')",
942 array($timestart, $course->id), "id ASC");
945 $actions = array('add mod', 'update mod', 'delete mod');
946 $newgones = array(); // added and later deleted items
947 foreach ($logs as $key => $log) {
948 if (!in_array($log->action, $actions)) {
951 $info = explode(' ', $log->info);
953 // note: in most cases I replaced hardcoding of label with use of
954 // $cm->has_view() but it was not possible to do this here because
955 // we don't necessarily have the $cm for it
956 if ($info[0] == 'label') { // Labels are ignored in recent activity
960 if (count($info) != 2) {
961 debugging("Incorrect log entry info: id = ".$log->id, DEBUG_DEVELOPER);
966 $instanceid = $info[1];
968 if ($log->action == 'delete mod') {
969 // unfortunately we do not know if the mod was visible
970 if (!array_key_exists($log->info, $newgones)) {
971 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $modname));
972 $changelist[$log->info] = array ('operation' => 'delete', 'text' => $strdeleted);
975 if (!isset($modinfo->instances[$modname][$instanceid])) {
976 if ($log->action == 'add mod') {
977 // do not display added and later deleted activities
978 $newgones[$log->info] = true;
982 $cm = $modinfo->instances[$modname][$instanceid];
983 if (!$cm->uservisible) {
987 if ($log->action == 'add mod') {
988 $stradded = get_string('added', 'moodle', get_string('modulename', $modname));
989 $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>");
991 } else if ($log->action == 'update mod' and empty($changelist[$log->info])) {
992 $strupdated = get_string('updated', 'moodle', get_string('modulename', $modname));
993 $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>");
999 if (!empty($changelist)) {
1000 echo $OUTPUT->heading(get_string("courseupdates").':', 3);
1002 foreach ($changelist as $changeinfo => $change) {
1003 echo '<p class="activity">'.$change['text'].'</p>';
1007 /// Now display new things from each module
1009 $usedmodules = array();
1010 foreach($modinfo->cms as $cm) {
1011 if (isset($usedmodules[$cm->modname])) {
1014 if (!$cm->uservisible) {
1017 $usedmodules[$cm->modname] = $cm->modname;
1020 foreach ($usedmodules as $modname) { // Each module gets it's own logs and prints them
1021 if (file_exists($CFG->dirroot.'/mod/'.$modname.'/lib.php')) {
1022 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
1023 $print_recent_activity = $modname.'_print_recent_activity';
1024 if (function_exists($print_recent_activity)) {
1025 // NOTE: original $isteacher (second parameter below) was replaced with $viewfullnames!
1026 $content = $print_recent_activity($course, $viewfullnames, $timestart) || $content;
1029 debugging("Missing lib.php in lib/{$modname} - please reinstall files or uninstall the module");
1034 echo '<p class="message">'.get_string('nothingnew').'</p>';
1039 * For a given course, returns an array of course activity objects
1040 * Each item in the array contains he following properties:
1042 function get_array_of_activities($courseid) {
1043 // cm - course module id
1044 // mod - name of the module (eg forum)
1045 // section - the number of the section (eg week or topic)
1046 // name - the name of the instance
1047 // visible - is the instance visible or not
1048 // groupingid - grouping id
1049 // groupmembersonly - is this instance visible to group members only
1050 // extra - contains extra string to include in any link
1052 if(!empty($CFG->enableavailability)) {
1053 require_once($CFG->libdir.'/conditionlib.php');
1056 $course = $DB->get_record('course', array('id'=>$courseid));
1058 if (empty($course)) {
1059 throw new moodle_exception('courseidnotfound');
1064 $rawmods = get_course_mods($courseid);
1065 if (empty($rawmods)) {
1066 return $mod; // always return array
1069 if ($sections = $DB->get_records("course_sections", array("course"=>$courseid), "section ASC")) {
1070 foreach ($sections as $section) {
1071 if (!empty($section->sequence)) {
1072 $sequence = explode(",", $section->sequence);
1073 foreach ($sequence as $seq) {
1074 if (empty($rawmods[$seq])) {
1077 $mod[$seq] = new stdClass();
1078 $mod[$seq]->id = $rawmods[$seq]->instance;
1079 $mod[$seq]->cm = $rawmods[$seq]->id;
1080 $mod[$seq]->mod = $rawmods[$seq]->modname;
1082 // Oh dear. Inconsistent names left here for backward compatibility.
1083 $mod[$seq]->section = $section->section;
1084 $mod[$seq]->sectionid = $rawmods[$seq]->section;
1086 $mod[$seq]->module = $rawmods[$seq]->module;
1087 $mod[$seq]->added = $rawmods[$seq]->added;
1088 $mod[$seq]->score = $rawmods[$seq]->score;
1089 $mod[$seq]->idnumber = $rawmods[$seq]->idnumber;
1090 $mod[$seq]->visible = $rawmods[$seq]->visible;
1091 $mod[$seq]->visibleold = $rawmods[$seq]->visibleold;
1092 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
1093 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
1094 $mod[$seq]->groupmembersonly = $rawmods[$seq]->groupmembersonly;
1095 $mod[$seq]->indent = $rawmods[$seq]->indent;
1096 $mod[$seq]->completion = $rawmods[$seq]->completion;
1097 $mod[$seq]->extra = "";
1098 $mod[$seq]->completiongradeitemnumber =
1099 $rawmods[$seq]->completiongradeitemnumber;
1100 $mod[$seq]->completionview = $rawmods[$seq]->completionview;
1101 $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected;
1102 $mod[$seq]->availablefrom = $rawmods[$seq]->availablefrom;
1103 $mod[$seq]->availableuntil = $rawmods[$seq]->availableuntil;
1104 $mod[$seq]->showavailability = $rawmods[$seq]->showavailability;
1105 $mod[$seq]->showdescription = $rawmods[$seq]->showdescription;
1106 if (!empty($CFG->enableavailability)) {
1107 condition_info::fill_availability_conditions($rawmods[$seq]);
1108 $mod[$seq]->conditionscompletion = $rawmods[$seq]->conditionscompletion;
1109 $mod[$seq]->conditionsgrade = $rawmods[$seq]->conditionsgrade;
1112 $modname = $mod[$seq]->mod;
1113 $functionname = $modname."_get_coursemodule_info";
1115 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
1119 include_once("$CFG->dirroot/mod/$modname/lib.php");
1121 if ($hasfunction = function_exists($functionname)) {
1122 if ($info = $functionname($rawmods[$seq])) {
1123 if (!empty($info->icon)) {
1124 $mod[$seq]->icon = $info->icon;
1126 if (!empty($info->iconcomponent)) {
1127 $mod[$seq]->iconcomponent = $info->iconcomponent;
1129 if (!empty($info->name)) {
1130 $mod[$seq]->name = $info->name;
1132 if ($info instanceof cached_cm_info) {
1133 // When using cached_cm_info you can include three new fields
1134 // that aren't available for legacy code
1135 if (!empty($info->content)) {
1136 $mod[$seq]->content = $info->content;
1138 if (!empty($info->extraclasses)) {
1139 $mod[$seq]->extraclasses = $info->extraclasses;
1141 if (!empty($info->iconurl)) {
1142 $mod[$seq]->iconurl = $info->iconurl;
1144 if (!empty($info->onclick)) {
1145 $mod[$seq]->onclick = $info->onclick;
1147 if (!empty($info->customdata)) {
1148 $mod[$seq]->customdata = $info->customdata;
1151 // When using a stdclass, the (horrible) deprecated ->extra field
1152 // is available for BC
1153 if (!empty($info->extra)) {
1154 $mod[$seq]->extra = $info->extra;
1159 // When there is no modname_get_coursemodule_info function,
1160 // but showdescriptions is enabled, then we use the 'intro'
1161 // and 'introformat' fields in the module table
1162 if (!$hasfunction && $rawmods[$seq]->showdescription) {
1163 if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
1164 array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
1165 // Set content from intro and introformat. Filters are disabled
1166 // because we filter it with format_text at display time
1167 $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
1168 $modvalues, $rawmods[$seq]->id, false);
1170 // To save making another query just below, put name in here
1171 $mod[$seq]->name = $modvalues->name;
1174 if (!isset($mod[$seq]->name)) {
1175 $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
1178 // Minimise the database size by unsetting default options when they are
1179 // 'empty'. This list corresponds to code in the cm_info constructor.
1180 foreach (array('idnumber', 'groupmode', 'groupingid', 'groupmembersonly',
1181 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
1182 'icon', 'iconcomponent', 'customdata', 'showavailability', 'availablefrom',
1183 'availableuntil', 'conditionscompletion', 'conditionsgrade',
1184 'completionview', 'completionexpected', 'score', 'showdescription')
1186 if (property_exists($mod[$seq], $property) &&
1187 empty($mod[$seq]->{$property})) {
1188 unset($mod[$seq]->{$property});
1191 // Special case: this value is usually set to null, but may be 0
1192 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
1193 is_null($mod[$seq]->completiongradeitemnumber)) {
1194 unset($mod[$seq]->completiongradeitemnumber);
1205 * Returns a number of useful structures for course displays
1207 function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
1208 global $CFG, $DB, $COURSE;
1210 $mods = array(); // course modules indexed by id
1211 $modnames = array(); // all course module names (except resource!)
1212 $modnamesplural= array(); // all course module names (plural form)
1213 $modnamesused = array(); // course module names used
1215 if ($allmods = $DB->get_records("modules")) {
1216 foreach ($allmods as $mod) {
1217 if (!file_exists("$CFG->dirroot/mod/$mod->name/lib.php")) {
1220 if ($mod->visible) {
1221 $modnames[$mod->name] = get_string("modulename", "$mod->name");
1222 $modnamesplural[$mod->name] = get_string("modulenameplural", "$mod->name");
1225 collatorlib::asort($modnames);
1227 print_error("nomodules", 'debug');
1230 $course = ($courseid==$COURSE->id) ? $COURSE : $DB->get_record('course',array('id'=>$courseid));
1231 $modinfo = get_fast_modinfo($course);
1233 if ($rawmods=$modinfo->cms) {
1234 foreach($rawmods as $mod) { // Index the mods
1235 if (empty($modnames[$mod->modname])) {
1238 $mods[$mod->id] = $mod;
1239 $mods[$mod->id]->modfullname = $modnames[$mod->modname];
1240 if (!$mod->visible and !has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_COURSE, $courseid))) {
1244 if (!groups_course_module_visible($mod)) {
1247 $modnamesused[$mod->modname] = $modnames[$mod->modname];
1249 if ($modnamesused) {
1250 collatorlib::asort($modnamesused);
1256 * Returns an array of sections for the requested course id
1258 * This function stores the sections against the course id within a staticvar encase
1259 * of subsequent requests. This is used all over + in some standard libs and course
1260 * format callbacks so subsequent requests are a reality.
1262 * @staticvar array $coursesections
1263 * @param int $courseid
1264 * @return array Array of sections
1266 function get_all_sections($courseid) {
1268 static $coursesections = array();
1269 if (!array_key_exists($courseid, $coursesections)) {
1270 $coursesections[$courseid] = $DB->get_records("course_sections", array("course"=>"$courseid"), "section",
1271 "section, id, course, name, summary, summaryformat, sequence, visible");
1273 return $coursesections[$courseid];
1277 * Returns the course section to display or 0 meaning show all sections. Returns 0 for guests.
1278 * It also sets the $USER->display cache to array($courseid=>return value)
1280 * @param int $courseid The course id
1281 * @return int Course section to display, 0 means all
1283 function course_get_display($courseid) {
1286 if (!isloggedin() or isguestuser()) {
1287 //do not get settings in db for guests
1288 return 0; //return the implicit setting
1291 if (!isset($USER->display[$courseid])) {
1292 if (!$display = $DB->get_field('course_display', 'display', array('userid' => $USER->id, 'course'=>$courseid))) {
1293 $display = 0; // all sections option is not stored in DB, this makes the table much smaller
1295 //use display cache for one course only - we need to keep session small
1296 $USER->display = array($courseid => $display);
1299 return $USER->display[$courseid];
1303 * Show one section only or all sections.
1305 * @param int $courseid The course id
1306 * @param mixed $display show only this section, 0 or 'all' means show all sections
1307 * @return int Course section to display, 0 means all
1309 function course_set_display($courseid, $display) {
1312 if ($display === 'all' or empty($display)) {
1316 if (!isloggedin() or isguestuser()) {
1317 //do not store settings in db for guests
1321 if ($display == 0) {
1322 //show all, do not store anything in database
1323 $DB->delete_records('course_display', array('userid' => $USER->id, 'course' => $courseid));
1326 if ($DB->record_exists('course_display', array('userid' => $USER->id, 'course' => $courseid))) {
1327 $DB->set_field('course_display', 'display', $display, array('userid' => $USER->id, 'course' => $courseid));
1329 $record = new stdClass();
1330 $record->userid = $USER->id;
1331 $record->course = $courseid;
1332 $record->display = $display;
1333 $DB->insert_record('course_display', $record);
1337 //use display cache for one course only - we need to keep session small
1338 $USER->display = array($courseid => $display);
1344 * Set highlighted section. Only one section can be highlighted at the time.
1346 * @param int $courseid course id
1347 * @param int $marker highlight section with this number, 0 means remove higlightin
1350 function course_set_marker($courseid, $marker) {
1352 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
1356 * For a given course section, marks it visible or hidden,
1357 * and does the same for every activity in that section
1359 function set_section_visible($courseid, $sectionnumber, $visibility) {
1362 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
1363 $DB->set_field("course_sections", "visible", "$visibility", array("id"=>$section->id));
1364 if (!empty($section->sequence)) {
1365 $modules = explode(",", $section->sequence);
1366 foreach ($modules as $moduleid) {
1367 set_coursemodule_visible($moduleid, $visibility, true);
1370 rebuild_course_cache($courseid);
1375 * Obtains shared data that is used in print_section when displaying a
1376 * course-module entry.
1378 * Calls format_text or format_string as appropriate, and obtains the correct icon.
1380 * This data is also used in other areas of the code.
1381 * @param cm_info $cm Course-module data (must come from get_fast_modinfo)
1382 * @param object $course Moodle course object
1383 * @return array An array with the following values in this order:
1384 * $content (optional extra content for after link),
1385 * $instancename (text of link)
1387 function get_print_section_cm_text(cm_info $cm, $course) {
1390 // Get content from modinfo if specified. Content displays either
1391 // in addition to the standard link (below), or replaces it if
1392 // the link is turned off by setting ->url to null.
1393 if (($content = $cm->get_content()) !== '') {
1394 // Improve filter performance by preloading filter setttings for all
1395 // activities on the course (this does nothing if called multiple
1397 filter_preload_activities($cm->get_modinfo());
1399 // Get module context
1400 $modulecontext = get_context_instance(CONTEXT_MODULE, $cm->id);
1401 $labelformatoptions = new stdClass();
1402 $labelformatoptions->noclean = true;
1403 $labelformatoptions->overflowdiv = true;
1404 $labelformatoptions->context = $modulecontext;
1405 $content = format_text($content, FORMAT_HTML, $labelformatoptions);
1410 // Get course context
1411 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
1412 $stringoptions = new stdClass;
1413 $stringoptions->context = $coursecontext;
1414 $instancename = format_string($cm->name, true, $stringoptions);
1415 return array($content, $instancename);
1419 * Prints a section full of activity modules
1421 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%", $hidecompletion=false) {
1422 global $CFG, $USER, $DB, $PAGE, $OUTPUT;
1424 static $initialised;
1426 static $groupbuttons;
1427 static $groupbuttonslink;
1430 static $strmovehere;
1431 static $strmovefull;
1432 static $strunreadpostsone;
1434 static $modulenames;
1436 if (!isset($initialised)) {
1437 $groupbuttons = ($course->groupmode or (!$course->groupmodeforce));
1438 $groupbuttonslink = (!$course->groupmodeforce);
1439 $isediting = $PAGE->user_is_editing();
1440 $ismoving = $isediting && ismoving($course->id);
1442 $strmovehere = get_string("movehere");
1443 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1445 $modulenames = array();
1446 $initialised = true;
1449 $modinfo = get_fast_modinfo($course);
1450 $completioninfo = new completion_info($course);
1452 //Accessibility: replace table with list <ul>, but don't output empty list.
1453 if (!empty($section->sequence)) {
1455 // Fix bug #5027, don't want style=\"width:$width\".
1456 echo "<ul class=\"section img-text\">\n";
1457 $sectionmods = explode(",", $section->sequence);
1459 foreach ($sectionmods as $modnumber) {
1460 if (empty($mods[$modnumber])) {
1467 $mod = $mods[$modnumber];
1469 if ($ismoving and $mod->id == $USER->activitycopy) {
1470 // do not display moving mod
1474 if (isset($modinfo->cms[$modnumber])) {
1475 // We can continue (because it will not be displayed at all)
1477 // 1) The activity is not visible to users
1479 // 2a) The 'showavailability' option is not set (if that is set,
1480 // we need to display the activity so we can show
1481 // availability info)
1483 // 2b) The 'availableinfo' is empty, i.e. the activity was
1484 // hidden in a way that leaves no info, such as using the
1486 if (!$modinfo->cms[$modnumber]->uservisible &&
1487 (empty($modinfo->cms[$modnumber]->showavailability) ||
1488 empty($modinfo->cms[$modnumber]->availableinfo))) {
1489 // visibility shortcut
1493 if (!file_exists("$CFG->dirroot/mod/$mod->modname/lib.php")) {
1494 // module not installed
1497 if (!coursemodule_visible_for_user($mod) &&
1498 empty($mod->showavailability)) {
1499 // full visibility check
1504 if (!isset($modulenames[$mod->modname])) {
1505 $modulenames[$mod->modname] = get_string('modulename', $mod->modname);
1507 $modulename = $modulenames[$mod->modname];
1509 // In some cases the activity is visible to user, but it is
1510 // dimmed. This is done if viewhiddenactivities is true and if:
1511 // 1. the activity is not visible, or
1512 // 2. the activity has dates set which do not include current, or
1513 // 3. the activity has any other conditions set (regardless of whether
1514 // current user meets them)
1515 $canviewhidden = has_capability(
1516 'moodle/course:viewhiddenactivities',
1517 get_context_instance(CONTEXT_MODULE, $mod->id));
1518 $accessiblebutdim = false;
1519 if ($canviewhidden) {
1520 $accessiblebutdim = !$mod->visible;
1521 if (!empty($CFG->enableavailability)) {
1522 $accessiblebutdim = $accessiblebutdim ||
1523 $mod->availablefrom > time() ||
1524 ($mod->availableuntil && $mod->availableuntil < time()) ||
1525 count($mod->conditionsgrade) > 0 ||
1526 count($mod->conditionscompletion) > 0;
1530 $liclasses = array();
1531 $liclasses[] = 'activity';
1532 $liclasses[] = $mod->modname;
1533 $liclasses[] = 'modtype_'.$mod->modname;
1534 $extraclasses = $mod->get_extra_classes();
1535 if ($extraclasses) {
1536 $liclasses = array_merge($liclasses, explode(' ', $extraclasses));
1538 echo html_writer::start_tag('li', array('class'=>join(' ', $liclasses), 'id'=>'module-'.$modnumber));
1540 echo '<a title="'.$strmovefull.'"'.
1541 ' href="'.$CFG->wwwroot.'/course/mod.php?moveto='.$mod->id.'&sesskey='.sesskey().'">'.
1542 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1543 ' alt="'.$strmovehere.'" /></a><br />
1547 $classes = array('mod-indent');
1548 if (!empty($mod->indent)) {
1549 $classes[] = 'mod-indent-'.$mod->indent;
1550 if ($mod->indent > 15) {
1551 $classes[] = 'mod-indent-huge';
1554 echo html_writer::start_tag('div', array('class'=>join(' ', $classes)));
1556 // Get data about this course-module
1557 list($content, $instancename) =
1558 get_print_section_cm_text($modinfo->cms[$modnumber], $course);
1560 //Accessibility: for files get description via icon, this is very ugly hack!
1562 $altname = $mod->modfullname;
1563 if (!empty($customicon)) {
1564 $archetype = plugin_supports('mod', $mod->modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1565 if ($archetype == MOD_ARCHETYPE_RESOURCE) {
1566 $mimetype = mimeinfo_from_icon('type', $customicon);
1567 $altname = get_mimetype_description($mimetype);
1570 // Avoid unnecessary duplication: if e.g. a forum name already
1571 // includes the word forum (or Forum, etc) then it is unhelpful
1572 // to include that in the accessible description that is added.
1573 if (false !== strpos(textlib::strtolower($instancename),
1574 textlib::strtolower($altname))) {
1577 // File type after name, for alphabetic lists (screen reader).
1579 $altname = get_accesshide(' '.$altname);
1582 // We may be displaying this just in order to show information
1583 // about visibility, without the actual link
1585 if ($mod->uservisible) {
1586 // Nope - in this case the link is fully working for user
1589 if ($accessiblebutdim) {
1590 $linkclasses .= ' dimmed';
1591 $textclasses .= ' dimmed_text';
1592 $accesstext = '<span class="accesshide">'.
1593 get_string('hiddenfromstudents').': </span>';
1598 $linkcss = 'class="' . trim($linkclasses) . '" ';
1603 $textcss = 'class="' . trim($textclasses) . '" ';
1608 // Get on-click attribute value if specified
1609 $onclick = $mod->get_on_click();
1611 $onclick = ' onclick="' . $onclick . '"';
1614 if ($url = $mod->get_url()) {
1615 // Display link itself
1616 echo '<a ' . $linkcss . $mod->extra . $onclick .
1617 ' href="' . $url . '"><img src="' . $mod->get_icon_url() .
1618 '" class="activityicon" alt="' .
1619 $modulename . '" /> ' .
1620 $accesstext . '<span class="instancename">' .
1621 $instancename . $altname . '</span></a>';
1623 // If specified, display extra content after link
1625 $contentpart = '<div class="' . trim('contentafterlink' . $textclasses) .
1626 '">' . $content . '</div>';
1629 // No link, so display only content
1630 $contentpart = '<div ' . $textcss . $mod->extra . '>' .
1631 $accesstext . $content . '</div>';
1634 if (!empty($mod->groupingid) && has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
1635 if (!isset($groupings)) {
1636 $groupings = groups_get_all_groupings($course->id);
1638 echo " <span class=\"groupinglabel\">(".format_string($groupings[$mod->groupingid]->name).')</span>';
1641 $textclasses = $extraclasses;
1642 $textclasses .= ' dimmed_text';
1644 $textcss = 'class="' . trim($textclasses) . '" ';
1648 $accesstext = '<span class="accesshide">' .
1649 get_string('notavailableyet', 'condition') .
1652 if ($url = $mod->get_url()) {
1653 // Display greyed-out text of link
1654 echo '<div ' . $textcss . $mod->extra .
1655 ' >' . '<img src="' . $mod->get_icon_url() .
1656 '" class="activityicon" alt="' .
1658 '" /> <span>'. $instancename . $altname .
1661 // Do not display content after link when it is greyed out like this.
1663 // No link, so display only content (also greyed)
1664 $contentpart = '<div ' . $textcss . $mod->extra . '>' .
1665 $accesstext . $content . '</div>';
1669 // Module can put text after the link (e.g. forum unread)
1670 echo $mod->get_after_link();
1672 // If there is content but NO link (eg label), then display the
1673 // content here (BEFORE any icons). In this case cons must be
1674 // displayed after the content so that it makes more sense visually
1675 // and for accessibility reasons, e.g. if you have a one-line label
1676 // it should work similarly (at least in terms of ordering) to an
1683 if ($groupbuttons and plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
1684 if (! $mod->groupmodelink = $groupbuttonslink) {
1685 $mod->groupmode = $course->groupmode;
1689 $mod->groupmode = false;
1691 echo ' ';
1692 echo make_editing_buttons($mod, $absolute, true, $mod->indent, $section->section);
1693 echo $mod->get_after_edit_icons();
1697 $completion = $hidecompletion
1698 ? COMPLETION_TRACKING_NONE
1699 : $completioninfo->is_enabled($mod);
1700 if ($completion!=COMPLETION_TRACKING_NONE && isloggedin() &&
1701 !isguestuser() && $mod->uservisible) {
1702 $completiondata = $completioninfo->get_data($mod,true);
1703 $completionicon = '';
1705 switch ($completion) {
1706 case COMPLETION_TRACKING_MANUAL :
1707 $completionicon = 'manual-enabled'; break;
1708 case COMPLETION_TRACKING_AUTOMATIC :
1709 $completionicon = 'auto-enabled'; break;
1712 } else if ($completion==COMPLETION_TRACKING_MANUAL) {
1713 switch($completiondata->completionstate) {
1714 case COMPLETION_INCOMPLETE:
1715 $completionicon = 'manual-n'; break;
1716 case COMPLETION_COMPLETE:
1717 $completionicon = 'manual-y'; break;
1719 } else { // Automatic
1720 switch($completiondata->completionstate) {
1721 case COMPLETION_INCOMPLETE:
1722 $completionicon = 'auto-n'; break;
1723 case COMPLETION_COMPLETE:
1724 $completionicon = 'auto-y'; break;
1725 case COMPLETION_COMPLETE_PASS:
1726 $completionicon = 'auto-pass'; break;
1727 case COMPLETION_COMPLETE_FAIL:
1728 $completionicon = 'auto-fail'; break;
1731 if ($completionicon) {
1732 $imgsrc = $OUTPUT->pix_url('i/completion-'.$completionicon);
1733 $imgalt = s(get_string('completion-alt-'.$completionicon, 'completion', $mod->name));
1734 if ($completion == COMPLETION_TRACKING_MANUAL && !$isediting) {
1735 $imgtitle = s(get_string('completion-title-'.$completionicon, 'completion', $mod->name));
1737 $completiondata->completionstate==COMPLETION_COMPLETE
1738 ? COMPLETION_INCOMPLETE
1739 : COMPLETION_COMPLETE;
1740 // In manual mode the icon is a toggle form...
1742 // If this completion state is used by the
1743 // conditional activities system, we need to turn
1745 if (!empty($CFG->enableavailability) &&
1746 condition_info::completion_value_used_as_condition($course, $mod)) {
1747 $extraclass = ' preventjs';
1752 <form class='togglecompletion$extraclass' method='post' action='".$CFG->wwwroot."/course/togglecompletion.php'><div>
1753 <input type='hidden' name='id' value='{$mod->id}' />
1754 <input type='hidden' name='modulename' value='".s($mod->name)."' />
1755 <input type='hidden' name='sesskey' value='".sesskey()."' />
1756 <input type='hidden' name='completionstate' value='$newstate' />
1757 <input type='image' src='$imgsrc' alt='$imgalt' title='$imgtitle' />
1760 // In auto mode, or when editing, the icon is just an image
1761 echo "<span class='autocompletion'>";
1762 echo "<img src='$imgsrc' alt='$imgalt' title='$imgalt' /></span>";
1767 // If there is content AND a link, then display the content here
1768 // (AFTER any icons). Otherwise it was displayed before
1773 // Show availability information (for someone who isn't allowed to
1774 // see the activity itself, or for staff)
1775 if (!$mod->uservisible) {
1776 echo '<div class="availabilityinfo">'.$mod->availableinfo.'</div>';
1777 } else if ($canviewhidden && !empty($CFG->enableavailability)) {
1778 $ci = new condition_info($mod);
1779 $fullinfo = $ci->get_full_information();
1781 echo '<div class="availabilityinfo">'.get_string($mod->showavailability
1782 ? 'userrestriction_visible'
1783 : 'userrestriction_hidden','condition',
1784 $fullinfo).'</div>';
1788 echo html_writer::end_tag('div');
1789 echo html_writer::end_tag('li')."\n";
1792 } elseif ($ismoving) {
1793 echo "<ul class=\"section\">\n";
1797 echo '<li><a title="'.$strmovefull.'"'.
1798 ' href="'.$CFG->wwwroot.'/course/mod.php?movetosection='.$section->id.'&sesskey='.sesskey().'">'.
1799 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1800 ' alt="'.$strmovehere.'" /></a></li>
1803 if (!empty($section->sequence) || $ismoving) {
1804 echo "</ul><!--class='section'-->\n\n";
1809 * Prints the menus to add activities and resources.
1811 function print_section_add_menus($course, $section, $modnames, $vertical=false, $return=false) {
1812 global $CFG, $OUTPUT;
1814 // check to see if user can add menus
1815 if (!has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $course->id))) {
1819 // Retrieve all modules with associated metadata
1820 $modules = get_module_metadata($course, $modnames);
1822 // We'll sort resources and activities into two lists
1823 $resources = array();
1824 $activities = array();
1826 // We need to add the section section to the link for each module
1827 $sectionlink = '§ion=' . $section;
1829 foreach ($modules as $module) {
1830 if (isset($module->types)) {
1831 // This module has a subtype
1832 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1833 $subtypes = array();
1834 foreach ($module->types as $subtype) {
1835 $subtypes[$subtype->link . $sectionlink] = $subtype->title;
1838 // Sort module subtypes into the list
1839 if (!empty($module->title)) {
1840 // This grouping has a name
1841 if ($module->archetype == MOD_CLASS_RESOURCE) {
1842 $resources[] = array($module->title=>$subtypes);
1844 $activities[] = array($module->title=>$subtypes);
1847 // This grouping does not have a name
1848 if ($module->archetype == MOD_CLASS_RESOURCE) {
1849 $resources = array_merge($resources, $subtypes);
1851 $activities = array_merge($activities, $subtypes);
1855 // This module has no subtypes
1856 if ($module->archetype == MOD_ARCHETYPE_RESOURCE) {
1857 $resources[$module->link . $sectionlink] = $module->title;
1858 } else if ($module->archetype === MOD_ARCHETYPE_SYSTEM) {
1859 // System modules cannot be added by user, do not add to dropdown
1861 $activities[$module->link . $sectionlink] = $module->title;
1866 $straddactivity = get_string('addactivity');
1867 $straddresource = get_string('addresource');
1869 $output = '<div class="section_add_menus">';
1872 $output .= '<div class="horizontal">';
1875 if (!empty($resources)) {
1876 $select = new url_select($resources, '', array(''=>$straddresource), "ressection$section");
1877 $select->set_help_icon('resources');
1878 $output .= $OUTPUT->render($select);
1881 if (!empty($activities)) {
1882 $select = new url_select($activities, '', array(''=>$straddactivity), "section$section");
1883 $select->set_help_icon('activities');
1884 $output .= $OUTPUT->render($select);
1888 $output .= '</div>';
1891 $output .= '</div>';
1901 * Retrieve all metadata for the requested modules
1903 * @param object $course The Course
1904 * @param array $modnames An array containing the list of modules and their
1906 * @return array A list of stdClass objects containing metadata about each
1909 function get_module_metadata($course, $modnames) {
1910 global $CFG, $OUTPUT;
1912 // get_module_metadata will be called once per section on the page and courses may show
1913 // different modules to one another
1914 static $modlist = array();
1915 if (!isset($modlist[$course->id])) {
1916 $modlist[$course->id] = array();
1920 $urlbase = "/course/mod.php?id=$course->id&sesskey=".sesskey().'&add=';
1921 foreach($modnames as $modname => $modnamestr) {
1922 if (!course_allowed_module($course, $modname)) {
1925 if (isset($modlist[$modname])) {
1926 // This module is already cached
1927 $return[$modname] = $modlist[$course->id][$modname];
1931 // Include the module lib
1932 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1933 if (!file_exists($libfile)) {
1936 include_once($libfile);
1938 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1939 $gettypesfunc = $modname.'_get_types';
1940 if (function_exists($gettypesfunc)) {
1941 if ($types = $gettypesfunc()) {
1942 $group = new stdClass();
1943 $group->name = $modname;
1944 $group->icon = $OUTPUT->pix_icon('icon', '', $modname, array('class' => 'icon'));
1945 foreach($types as $type) {
1946 if ($type->typestr === '--') {
1949 if (strpos($type->typestr, '--') === 0) {
1950 $group->title = str_replace('--', '', $type->typestr);
1953 // Set the Sub Type metadata
1954 $subtype = new stdClass();
1955 $subtype->title = $type->typestr;
1956 $subtype->type = str_replace('&', '&', $type->type);
1957 $subtype->name = preg_replace('/.*type=/', '', $subtype->type);
1958 $subtype->archetype = $type->modclass;
1960 // The group archetype should match the subtype archetypes and all subtypes
1961 // should have the same archetype
1962 $group->archetype = $subtype->archetype;
1964 if (get_string_manager()->string_exists('help' . $subtype->name, $modname)) {
1965 $subtype->help = get_string('help' . $subtype->name, $modname);
1967 $subtype->link = $urlbase . $subtype->type;
1968 $group->types[] = $subtype;
1970 $modlist[$course->id][$modname] = $group;
1973 $module = new stdClass();
1974 $module->title = get_string('modulename', $modname);
1975 $module->name = $modname;
1976 $module->link = $urlbase . $modname;
1977 $module->icon = $OUTPUT->pix_icon('icon', '', $module->name, array('class' => 'icon'));
1978 if (get_string_manager()->string_exists('modulename_help', $modname)) {
1979 $module->help = get_string('modulename_help', $modname);
1981 $module->archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1982 $modlist[$course->id][$modname] = $module;
1984 $return[$modname] = $modlist[$course->id][$modname];
1991 * Return the course category context for the category with id $categoryid, except
1992 * that if $categoryid is 0, return the system context.
1994 * @param integer $categoryid a category id or 0.
1995 * @return object the corresponding context
1997 function get_category_or_system_context($categoryid) {
1999 return get_context_instance(CONTEXT_COURSECAT, $categoryid);
2001 return get_context_instance(CONTEXT_SYSTEM);
2006 * Gets the child categories of a given courses category. Uses a static cache
2007 * to make repeat calls efficient.
2009 * @param int $parentid the id of a course category.
2010 * @return array all the child course categories.
2012 function get_child_categories($parentid) {
2013 static $allcategories = null;
2015 // only fill in this variable the first time
2016 if (null == $allcategories) {
2017 $allcategories = array();
2019 $categories = get_categories();
2020 foreach ($categories as $category) {
2021 if (empty($allcategories[$category->parent])) {
2022 $allcategories[$category->parent] = array();
2024 $allcategories[$category->parent][] = $category;
2028 if (empty($allcategories[$parentid])) {
2031 return $allcategories[$parentid];
2036 * This function recursively travels the categories, building up a nice list
2037 * for display. It also makes an array that list all the parents for each
2040 * For example, if you have a tree of categories like:
2041 * Miscellaneous (id = 1)
2042 * Subcategory (id = 2)
2043 * Sub-subcategory (id = 4)
2044 * Other category (id = 3)
2045 * Then after calling this function you will have
2046 * $list = array(1 => 'Miscellaneous', 2 => 'Miscellaneous / Subcategory',
2047 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
2048 * 3 => 'Other category');
2049 * $parents = array(2 => array(1), 4 => array(1, 2));
2051 * If you specify $requiredcapability, then only categories where the current
2052 * user has that capability will be added to $list, although all categories
2053 * will still be added to $parents, and if you only have $requiredcapability
2054 * in a child category, not the parent, then the child catgegory will still be
2057 * If you specify the option $excluded, then that category, and all its children,
2058 * are omitted from the tree. This is useful when you are doing something like
2059 * moving categories, where you do not want to allow people to move a category
2060 * to be the child of itself.
2062 * @param array $list For output, accumulates an array categoryid => full category path name
2063 * @param array $parents For output, accumulates an array categoryid => list of parent category ids.
2064 * @param string/array $requiredcapability if given, only categories where the current
2065 * user has this capability will be added to $list. Can also be an array of capabilities,
2066 * in which case they are all required.
2067 * @param integer $excludeid Omit this category and its children from the lists built.
2068 * @param object $category Build the tree starting at this category - otherwise starts at the top level.
2069 * @param string $path For internal use, as part of recursive calls.
2071 function make_categories_list(&$list, &$parents, $requiredcapability = '',
2072 $excludeid = 0, $category = NULL, $path = "") {
2074 // initialize the arrays if needed
2075 if (!is_array($list)) {
2078 if (!is_array($parents)) {
2082 if (empty($category)) {
2083 // Start at the top level.
2084 $category = new stdClass;
2087 // This is the excluded category, don't include it.
2088 if ($excludeid > 0 && $excludeid == $category->id) {
2092 $context = get_context_instance(CONTEXT_COURSECAT, $category->id);
2093 $categoryname = format_string($category->name, true, array('context' => $context));
2097 $path = $path.' / '.$categoryname;
2099 $path = $categoryname;
2102 // Add this category to $list, if the permissions check out.
2103 if (empty($requiredcapability)) {
2104 $list[$category->id] = $path;
2107 $requiredcapability = (array)$requiredcapability;
2108 if (has_all_capabilities($requiredcapability, $context)) {
2109 $list[$category->id] = $path;
2114 // Add all the children recursively, while updating the parents array.
2115 if ($categories = get_child_categories($category->id)) {
2116 foreach ($categories as $cat) {
2117 if (!empty($category->id)) {
2118 if (isset($parents[$category->id])) {
2119 $parents[$cat->id] = $parents[$category->id];
2121 $parents[$cat->id][] = $category->id;
2123 make_categories_list($list, $parents, $requiredcapability, $excludeid, $cat, $path);
2129 * This function generates a structured array of courses and categories.
2131 * The depth of categories is limited by $CFG->maxcategorydepth however there
2132 * is no limit on the number of courses!
2134 * Suitable for use with the course renderers course_category_tree method:
2135 * $renderer = $PAGE->get_renderer('core','course');
2136 * echo $renderer->course_category_tree(get_course_category_tree());
2138 * @global moodle_database $DB
2142 function get_course_category_tree($id = 0, $depth = 0) {
2144 $viewhiddencats = has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_SYSTEM));
2145 $categories = get_child_categories($id);
2146 $categoryids = array();
2147 foreach ($categories as $key => &$category) {
2148 if (!$category->visible && !$viewhiddencats) {
2149 unset($categories[$key]);
2152 $categoryids[$category->id] = $category;
2153 if (empty($CFG->maxcategorydepth) || $depth <= $CFG->maxcategorydepth) {
2154 list($category->categories, $subcategories) = get_course_category_tree($category->id, $depth+1);
2155 foreach ($subcategories as $subid=>$subcat) {
2156 $categoryids[$subid] = $subcat;
2158 $category->courses = array();
2163 // This is a recursive call so return the required array
2164 return array($categories, $categoryids);
2167 // The depth is 0 this function has just been called so we can finish it off
2169 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
2170 list($catsql, $catparams) = $DB->get_in_or_equal(array_keys($categoryids));
2172 c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary,c.category
2176 WHERE c.category $catsql ORDER BY c.sortorder ASC";
2177 if ($courses = $DB->get_records_sql($sql, $catparams)) {
2178 // loop throught them
2179 foreach ($courses as $course) {
2180 if ($course->id == SITEID) {
2183 context_instance_preload($course);
2184 if (!empty($course->visible) || has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id))) {
2185 $categoryids[$course->category]->courses[$course->id] = $course;
2193 * Recursive function to print out all the categories in a nice format
2194 * with or without courses included
2196 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true) {
2199 // maxcategorydepth == 0 meant no limit
2200 if (!empty($CFG->maxcategorydepth) && $depth >= $CFG->maxcategorydepth) {
2204 if (!$displaylist) {
2205 make_categories_list($displaylist, $parentslist);
2209 if ($category->visible or has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_SYSTEM))) {
2210 print_category_info($category, $depth, $showcourses);
2212 return; // Don't bother printing children of invisible categories
2216 $category = new stdClass();
2217 $category->id = "0";
2220 if ($categories = get_child_categories($category->id)) { // Print all the children recursively
2221 $countcats = count($categories);
2225 foreach ($categories as $cat) {
2227 if ($count == $countcats) {
2230 $up = $first ? false : true;
2231 $down = $last ? false : true;
2234 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1, $showcourses);
2240 * This function will return $options array for html_writer::select(), with whitespace to denote nesting.
2242 function make_categories_options() {
2243 make_categories_list($cats,$parents);
2244 foreach ($cats as $key => $value) {
2245 if (array_key_exists($key,$parents)) {
2246 if ($indent = count($parents[$key])) {
2247 for ($i = 0; $i < $indent; $i++) {
2248 $cats[$key] = ' '.$cats[$key];
2257 * Gets the name of a course to be displayed when showing a list of courses.
2258 * By default this is just $course->fullname but user can configure it. The
2259 * result of this function should be passed through print_string.
2260 * @param object $course Moodle course object
2261 * @return string Display name of course (either fullname or short + fullname)
2263 function get_course_display_name_for_list($course) {
2265 if (!empty($CFG->courselistshortnames)) {
2266 return $course->shortname . ' ' .$course->fullname;
2268 return $course->fullname;
2273 * Prints the category info in indented fashion
2274 * This function is only used by print_whole_category_list() above
2276 function print_category_info($category, $depth=0, $showcourses = false) {
2277 global $CFG, $DB, $OUTPUT;
2279 $strsummary = get_string('summary');
2282 if (!$category->visible) {
2283 $catlinkcss = array('class'=>'dimmed');
2285 static $coursecount = null;
2286 if (null === $coursecount) {
2287 // only need to check this once
2288 $coursecount = $DB->count_records('course') <= FRONTPAGECOURSELIMIT;
2291 if ($showcourses and $coursecount) {
2292 $catimage = '<img src="'.$OUTPUT->pix_url('i/course') . '" alt="" />';
2294 $catimage = " ";
2297 $courses = get_courses($category->id, 'c.sortorder ASC', 'c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary');
2298 $context = get_context_instance(CONTEXT_COURSECAT, $category->id);
2299 $fullname = format_string($category->name, true, array('context' => $context));
2301 if ($showcourses and $coursecount) {
2302 echo '<div class="categorylist clearfix">';
2304 $cat .= html_writer::tag('div', $catimage, array('class'=>'image'));
2305 $catlink = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
2306 $cat .= html_writer::tag('div', $catlink, array('class'=>'name'));
2310 for ($i=0; $i< $depth; $i++) {
2311 $html = html_writer::tag('div', $html . $cat, array('class'=>'indentation'));
2317 echo html_writer::tag('div', $html, array('class'=>'category'));
2318 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
2320 // does the depth exceed maxcategorydepth
2321 // maxcategorydepth == 0 or unset meant no limit
2322 $limit = !(isset($CFG->maxcategorydepth) && ($depth >= $CFG->maxcategorydepth-1));
2323 if ($courses && ($limit || $CFG->maxcategorydepth == 0)) {
2324 foreach ($courses as $course) {
2326 if (!$course->visible) {
2327 $linkcss = array('class'=>'dimmed');
2330 $coursename = get_course_display_name_for_list($course);
2331 $courselink = html_writer::link(new moodle_url('/course/view.php', array('id'=>$course->id)), format_string($coursename), $linkcss);
2335 if ($icons = enrol_get_course_info_icons($course)) {
2336 foreach ($icons as $pix_icon) {
2337 $courseicon = $OUTPUT->render($pix_icon).' ';
2341 $coursecontent = html_writer::tag('div', $courseicon.$courselink, array('class'=>'name'));
2343 if ($course->summary) {
2344 $link = new moodle_url('/course/info.php?id='.$course->id);
2345 $actionlink = $OUTPUT->action_link($link, '<img alt="'.$strsummary.'" src="'.$OUTPUT->pix_url('i/info') . '" />',
2346 new popup_action('click', $link, 'courseinfo', array('height' => 400, 'width' => 500)),
2347 array('title'=>$strsummary));
2349 $coursecontent .= html_writer::tag('div', $actionlink, array('class'=>'info'));
2353 for ($i=0; $i <= $depth; $i++) {
2354 $html = html_writer::tag('div', $html . $coursecontent , array('class'=>'indentation'));
2355 $coursecontent = '';
2357 echo html_writer::tag('div', $html, array('class'=>'course clearfloat'));
2362 echo '<div class="categorylist">';
2364 $cat = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
2365 if (count($courses) > 0) {
2366 $cat .= html_writer::tag('span', ' ('.count($courses).')', array('title'=>get_string('numberofcourses'), 'class'=>'numberofcourse'));
2370 for ($i=0; $i< $depth; $i++) {
2371 $html = html_writer::tag('div', $html .$cat, array('class'=>'indentation'));
2378 echo html_writer::tag('div', $html, array('class'=>'category'));
2379 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
2385 * Print the buttons relating to course requests.
2387 * @param object $systemcontext the system context.
2389 function print_course_request_buttons($systemcontext) {
2390 global $CFG, $DB, $OUTPUT;
2391 if (empty($CFG->enablecourserequests)) {
2394 if (!has_capability('moodle/course:create', $systemcontext) && has_capability('moodle/course:request', $systemcontext)) {
2395 /// Print a button to request a new course
2396 echo $OUTPUT->single_button('request.php', get_string('requestcourse'), 'get');
2398 /// Print a button to manage pending requests
2399 if (has_capability('moodle/site:approvecourse', $systemcontext)) {
2400 $disabled = !$DB->record_exists('course_request', array());
2401 echo $OUTPUT->single_button('pending.php', get_string('coursespending'), 'get', array('disabled'=>$disabled));
2406 * Does the user have permission to edit things in this category?
2408 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2409 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
2411 function can_edit_in_category($categoryid = 0) {
2412 $context = get_category_or_system_context($categoryid);
2413 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
2417 * Prints the turn editing on/off button on course/index.php or course/category.php.
2419 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2420 * @return string HTML of the editing button, or empty string, if this user is not allowed
2423 function update_category_button($categoryid = 0) {
2424 global $CFG, $PAGE, $OUTPUT;
2426 // Check permissions.
2427 if (!can_edit_in_category($categoryid)) {
2431 // Work out the appropriate action.
2432 if ($PAGE->user_is_editing()) {
2433 $label = get_string('turneditingoff');
2436 $label = get_string('turneditingon');
2440 // Generate the button HTML.
2441 $options = array('categoryedit' => $edit, 'sesskey' => sesskey());
2443 $options['id'] = $categoryid;
2444 $page = 'category.php';
2446 $page = 'index.php';
2448 return $OUTPUT->single_button(new moodle_url('/course/' . $page, $options), $label, 'get');
2452 * Category is 0 (for all courses) or an object
2454 function print_courses($category) {
2455 global $CFG, $OUTPUT;
2457 if (!is_object($category) && $category==0) {
2458 $categories = get_child_categories(0); // Parent = 0 ie top-level categories only
2459 if (is_array($categories) && count($categories) == 1) {
2460 $category = array_shift($categories);
2461 $courses = get_courses_wmanagers($category->id,
2463 array('summary','summaryformat'));
2465 $courses = get_courses_wmanagers('all',
2467 array('summary','summaryformat'));
2471 $courses = get_courses_wmanagers($category->id,
2473 array('summary','summaryformat'));
2477 echo html_writer::start_tag('ul', array('class'=>'unlist'));
2478 foreach ($courses as $course) {
2479 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
2480 if ($course->visible == 1 || has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2481 echo html_writer::start_tag('li');
2482 print_course($course);
2483 echo html_writer::end_tag('li');
2486 echo html_writer::end_tag('ul');
2488 echo $OUTPUT->heading(get_string("nocoursesyet"));
2489 $context = get_context_instance(CONTEXT_SYSTEM);
2490 if (has_capability('moodle/course:create', $context)) {
2492 if (!empty($category->id)) {
2493 $options['category'] = $category->id;
2495 $options['category'] = $CFG->defaultrequestcategory;
2497 echo html_writer::start_tag('div', array('class'=>'addcoursebutton'));
2498 echo $OUTPUT->single_button(new moodle_url('/course/edit.php', $options), get_string("addnewcourse"));
2499 echo html_writer::end_tag('div');
2505 * Print a description of a course, suitable for browsing in a list.
2507 * @param object $course the course object.
2508 * @param string $highlightterms (optional) some search terms that should be highlighted in the display.
2510 function print_course($course, $highlightterms = '') {
2511 global $CFG, $USER, $DB, $OUTPUT;
2513 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2515 // Rewrite file URLs so that they are correct
2516 $course->summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', NULL);
2518 echo html_writer::start_tag('div', array('class'=>'coursebox clearfix'));
2519 echo html_writer::start_tag('div', array('class'=>'info'));
2520 echo html_writer::start_tag('h3', array('class'=>'name'));
2522 $linkhref = new moodle_url('/course/view.php', array('id'=>$course->id));
2524 $coursename = get_course_display_name_for_list($course);
2525 $linktext = highlight($highlightterms, format_string($coursename));
2526 $linkparams = array('title'=>get_string('entercourse'));
2527 if (empty($course->visible)) {
2528 $linkparams['class'] = 'dimmed';
2530 echo html_writer::link($linkhref, $linktext, $linkparams);
2531 echo html_writer::end_tag('h3');
2533 /// first find all roles that are supposed to be displayed
2534 if (!empty($CFG->coursecontact)) {
2535 $managerroles = explode(',', $CFG->coursecontact);
2536 $namesarray = array();
2539 if (!isset($course->managers)) {
2540 $rusers = get_role_users($managerroles, $context, true,
2541 'ra.id AS raid, u.id, u.username, u.firstname, u.lastname,
2542 r.name AS rolename, r.sortorder, r.id AS roleid',
2543 'r.sortorder ASC, u.lastname ASC');
2545 // use the managers array if we have it for perf reasosn
2546 // populate the datastructure like output of get_role_users();
2547 foreach ($course->managers as $manager) {
2548 $u = new stdClass();
2549 $u = $manager->user;
2550 $u->roleid = $manager->roleid;
2551 $u->rolename = $manager->rolename;
2557 /// Rename some of the role names if needed
2558 if (isset($context)) {
2559 $aliasnames = $DB->get_records('role_names', array('contextid'=>$context->id), '', 'roleid,contextid,name');
2562 $namesarray = array();
2563 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2564 foreach ($rusers as $ra) {
2565 if (isset($namesarray[$ra->id])) {
2566 // only display a user once with the higest sortorder role
2570 if (isset($aliasnames[$ra->roleid])) {
2571 $ra->rolename = $aliasnames[$ra->roleid]->name;
2574 $fullname = fullname($ra, $canviewfullnames);
2575 $namesarray[$ra->id] = format_string($ra->rolename).': '.
2576 html_writer::link(new moodle_url('/user/view.php', array('id'=>$ra->id, 'course'=>SITEID)), $fullname);
2579 if (!empty($namesarray)) {
2580 echo html_writer::start_tag('ul', array('class'=>'teachers'));
2581 foreach ($namesarray as $name) {
2582 echo html_writer::tag('li', $name);
2584 echo html_writer::end_tag('ul');
2587 echo html_writer::end_tag('div'); // End of info div
2589 echo html_writer::start_tag('div', array('class'=>'summary'));
2590 $options = new stdClass();
2591 $options->noclean = true;
2592 $options->para = false;
2593 $options->overflowdiv = true;
2594 if (!isset($course->summaryformat)) {
2595 $course->summaryformat = FORMAT_MOODLE;
2597 echo highlight($highlightterms, format_text($course->summary, $course->summaryformat, $options, $course->id));
2598 if ($icons = enrol_get_course_info_icons($course)) {
2599 echo html_writer::start_tag('div', array('class'=>'enrolmenticons'));
2600 foreach ($icons as $icon) {
2601 echo $OUTPUT->render($icon);
2603 echo html_writer::end_tag('div'); // End of enrolmenticons div
2605 echo html_writer::end_tag('div'); // End of summary div
2606 echo html_writer::end_tag('div'); // End of coursebox div
2610 * Prints custom user information on the home page.
2611 * Over time this can include all sorts of information
2613 function print_my_moodle() {
2614 global $USER, $CFG, $DB, $OUTPUT;
2616 if (!isloggedin() or isguestuser()) {
2617 print_error('nopermissions', '', '', 'See My Moodle');
2620 $courses = enrol_get_my_courses('summary', 'visible DESC,sortorder ASC');
2622 $rcourses = array();
2623 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
2624 $rcourses = get_my_remotecourses($USER->id);
2625 $rhosts = get_my_remotehosts();
2628 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
2630 if (!empty($courses)) {
2631 echo '<ul class="unlist">';
2632 foreach ($courses as $course) {
2633 if ($course->id == SITEID) {
2637 print_course($course);
2644 if (!empty($rcourses)) {
2645 // at the IDP, we know of all the remote courses
2646 foreach ($rcourses as $course) {
2647 print_remote_course($course, "100%");
2649 } elseif (!empty($rhosts)) {
2650 // non-IDP, we know of all the remote servers, but not courses
2651 foreach ($rhosts as $host) {
2652 print_remote_host($host, "100%");
2658 if ($DB->count_records("course") > (count($courses) + 1) ) { // Some courses not being displayed
2659 echo "<table width=\"100%\"><tr><td align=\"center\">";
2660 print_course_search("", false, "short");
2661 echo "</td><td align=\"center\">";
2662 echo $OUTPUT->single_button("$CFG->wwwroot/course/index.php", get_string("fulllistofcourses"), "get");
2663 echo "</td></tr></table>\n";
2667 if ($DB->count_records("course_categories") > 1) {
2668 echo $OUTPUT->box_start("categorybox");
2669 print_whole_category_list();
2670 echo $OUTPUT->box_end();
2678 function print_course_search($value="", $return=false, $format="plain") {
2684 $id = 'coursesearch';
2690 $strsearchcourses= get_string("searchcourses");
2692 if ($format == 'plain') {
2693 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2694 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2695 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
2696 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" value="'.s($value).'" />';
2697 $output .= '<input type="submit" value="'.get_string('go').'" />';
2698 $output .= '</fieldset></form>';
2699 } else if ($format == 'short') {
2700 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2701 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2702 $output .= '<label for="shortsearchbox">'.$strsearchcourses.': </label>';
2703 $output .= '<input type="text" id="shortsearchbox" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2704 $output .= '<input type="submit" value="'.get_string('go').'" />';
2705 $output .= '</fieldset></form>';
2706 } else if ($format == 'navbar') {
2707 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2708 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2709 $output .= '<label for="navsearchbox">'.$strsearchcourses.': </label>';
2710 $output .= '<input type="text" id="navsearchbox" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2711 $output .= '<input type="submit" value="'.get_string('go').'" />';
2712 $output .= '</fieldset></form>';
2721 function print_remote_course($course, $width="100%") {
2726 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&wantsurl=/course/view.php?id={$course->remoteid}";
2728 echo '<div class="coursebox remotecoursebox clearfix">';
2729 echo '<div class="info">';
2730 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2731 $linkcss.' href="'.$url.'">'
2732 . format_string($course->fullname) .'</a><br />'
2733 . format_string($course->hostname) . ' : '
2734 . format_string($course->cat_name) . ' : '
2735 . format_string($course->shortname). '</div>';
2736 echo '</div><div class="summary">';
2737 $options = new stdClass();
2738 $options->noclean = true;
2739 $options->para = false;
2740 $options->overflowdiv = true;
2741 echo format_text($course->summary, $course->summaryformat, $options);
2746 function print_remote_host($host, $width="100%") {
2751 echo '<div class="coursebox clearfix">';
2752 echo '<div class="info">';
2753 echo '<div class="name">';
2754 echo '<img src="'.$OUTPUT->pix_url('i/mnethost') . '" class="icon" alt="'.get_string('course').'" />';
2755 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2756 . s($host['name']).'</a> - ';
2757 echo $host['count'] . ' ' . get_string('courses');
2764 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2766 function add_course_module($mod) {
2769 $mod->added = time();
2772 return $DB->insert_record("course_modules", $mod);
2776 * Returns course section - creates new if does not exist yet.
2777 * @param int $relative section number
2778 * @param int $courseid
2779 * @return object $course_section object
2781 function get_course_section($section, $courseid) {
2784 if ($cw = $DB->get_record("course_sections", array("section"=>$section, "course"=>$courseid))) {
2787 $cw = new stdClass();
2788 $cw->course = $courseid;
2789 $cw->section = $section;
2791 $cw->summaryformat = FORMAT_HTML;
2793 $id = $DB->insert_record("course_sections", $cw);
2794 return $DB->get_record("course_sections", array("id"=>$id));
2797 * Given a full mod object with section and course already defined, adds this module to that section.
2799 * @param object $mod
2800 * @param int $beforemod An existing ID which we will insert the new module before
2801 * @return int The course_sections ID where the mod is inserted
2803 function add_mod_to_section($mod, $beforemod=NULL) {
2806 if ($section = $DB->get_record("course_sections", array("course"=>$mod->course, "section"=>$mod->section))) {
2808 $section->sequence = trim($section->sequence);
2810 if (empty($section->sequence)) {
2811 $newsequence = "$mod->coursemodule";
2813 } else if ($beforemod) {
2814 $modarray = explode(",", $section->sequence);
2816 if ($key = array_keys($modarray, $beforemod->id)) {
2817 $insertarray = array($mod->id, $beforemod->id);
2818 array_splice($modarray, $key[0], 1, $insertarray);
2819 $newsequence = implode(",", $modarray);
2821 } else { // Just tack it on the end anyway
2822 $newsequence = "$section->sequence,$mod->coursemodule";
2826 $newsequence = "$section->sequence,$mod->coursemodule";
2829 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
2830 return $section->id; // Return course_sections ID that was used.
2832 } else { // Insert a new record
2833 $section = new stdClass();
2834 $section->course = $mod->course;
2835 $section->section = $mod->section;
2836 $section->summary = "";
2837 $section->summaryformat = FORMAT_HTML;
2838 $section->sequence = $mod->coursemodule;
2839 return $DB->insert_record("course_sections", $section);
2843 function set_coursemodule_groupmode($id, $groupmode) {
2845 return $DB->set_field("course_modules", "groupmode", $groupmode, array("id"=>$id));
2848 function set_coursemodule_idnumber($id, $idnumber) {
2850 return $DB->set_field("course_modules", "idnumber", $idnumber, array("id"=>$id));
2854 * $prevstateoverrides = true will set the visibility of the course module
2855 * to what is defined in visibleold. This enables us to remember the current
2856 * visibility when making a whole section hidden, so that when we toggle
2857 * that section back to visible, we are able to return the visibility of
2858 * the course module back to what it was originally.
2860 function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
2862 require_once($CFG->libdir.'/gradelib.php');
2864 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2867 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
2870 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2871 foreach($events as $event) {
2880 // hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there
2881 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
2883 foreach ($grade_items as $grade_item) {
2884 $grade_item->set_hidden(!$visible);
2888 if ($prevstateoverrides) {
2889 if ($visible == '0') {
2890 // Remember the current visible state so we can toggle this back.
2891 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id'=>$id));
2893 // Get the previous saved visible states.
2894 return $DB->set_field('course_modules', 'visible', $cm->visibleold, array('id'=>$id));
2897 return $DB->set_field("course_modules", "visible", $visible, array("id"=>$id));
2901 * Delete a course module and any associated data at the course level (events)
2902 * Until 1.5 this function simply marked a deleted flag ... now it
2903 * deletes it completely.
2906 function delete_course_module($id) {
2908 require_once($CFG->libdir.'/gradelib.php');
2909 require_once($CFG->dirroot.'/blog/lib.php');
2911 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2914 $modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module));
2915 //delete events from calendar
2916 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2917 foreach($events as $event) {
2918 delete_event($event->id);
2921 //delete grade items, outcome items and grades attached to modules
2922 if ($grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2923 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course))) {
2924 foreach ($grade_items as $grade_item) {
2925 $grade_item->delete('moddelete');
2928 // Delete completion and availability data; it is better to do this even if the
2929 // features are not turned on, in case they were turned on previously (these will be
2930 // very quick on an empty table)
2931 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
2932 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id));
2934 delete_context(CONTEXT_MODULE, $cm->id);
2935 return $DB->delete_records('course_modules', array('id'=>$cm->id));
2938 function delete_mod_from_section($mod, $section) {
2941 if ($section = $DB->get_record("course_sections", array("id"=>$section)) ) {
2943 $modarray = explode(",", $section->sequence);
2945 if ($key = array_keys ($modarray, $mod)) {
2946 array_splice($modarray, $key[0], 1);
2947 $newsequence = implode(",", $modarray);
2948 return $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
2958 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
2960 * @param object $course course object
2961 * @param int $section Section number (not id!!!)
2962 * @param int $move (-1 or 1)
2963 * @return boolean true if section moved successfully
2965 function move_section($course, $section, $move) {
2966 /// Moves a whole course section up and down within the course
2973 $sectiondest = $section + $move;
2975 if ($sectiondest > $course->numsections or $sectiondest < 1) {
2979 if (!$sectionrecord = $DB->get_record("course_sections", array("course"=>$course->id, "section"=>$section))) {
2983 if (!$sectiondestrecord = $DB->get_record("course_sections", array("course"=>$course->id, "section"=>$sectiondest))) {
2987 $DB->set_field("course_sections", "section", $sectiondest, array("id"=>$sectionrecord->id));
2988 $DB->set_field("course_sections", "section", $section, array("id"=>$sectiondestrecord->id));
2990 // Update highlighting if the move affects highlighted section
2991 if ($course->marker == $section) {
2992 course_set_marker($course->id, $sectiondest);
2993 } elseif ($course->marker == $sectiondest) {
2994 course_set_marker($course->id, $section);
2997 // if the focus is on the section that is being moved, then move the focus along
2998 if (course_get_display($course->id) == $section) {
2999 course_set_display($course->id, $sectiondest);
3002 // Check for duplicates and fix order if needed.
3003 // There is a very rare case that some sections in the same course have the same section id.
3004 $sections = $DB->get_records('course_sections', array('course'=>$course->id), 'section ASC');
3006 foreach ($sections as $section) {
3007 if ($section->section != $n) {
3008 $DB->set_field('course_sections', 'section', $n, array('id'=>$section->id));
3016 * Moves a section within a course, from a position to another.
3017 * Be very careful: $section and $destination refer to section number,
3020 * @param object $course
3021 * @param int $section Section number (not id!!!)
3022 * @param int $destination
3023 * @return boolean Result
3025 function move_section_to($course, $section, $destination) {
3026 /// Moves a whole course section up and down within the course
3029 if (!$destination && $destination != 0) {
3033 if ($destination > $course->numsections) {
3037 // Get all sections for this course and re-order them (2 of them should now share the same section number)
3038 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
3039 'section ASC, id ASC', 'id, section')) {
3043 $sections = reorder_sections($sections, $section, $destination);
3045 // Update all sections
3046 foreach ($sections as $id => $position) {
3047 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
3050 // if the focus is on the section that is being moved, then move the focus along
3051 if (course_get_display($course->id) == $section) {
3052 course_set_display($course->id, $destination);
3058 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
3059 * an original position number and a target position number, rebuilds the array so that the
3060 * move is made without any duplication of section positions.
3061 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
3062 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
3064 * @param array $sections
3065 * @param int $origin_position
3066 * @param int $target_position
3069 function reorder_sections($sections, $origin_position, $target_position) {
3070 if (!is_array($sections)) {
3074 // We can't move section position 0
3075 if ($origin_position < 1) {
3076 echo "We can't move section position 0";
3080 // Locate origin section in sections array
3081 if (!$origin_key = array_search($origin_position, $sections)) {
3082 echo "searched position not in sections array";
3083 return false; // searched position not in sections array
3086 // Extract origin section
3087 $origin_section = $sections[$origin_key];
3088 unset($sections[$origin_key]);
3090 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
3092 $append_array = array();
3093 foreach ($sections as $id => $position) {
3095 $append_array[$id] = $position;
3096 unset($sections[$id]);
3098 if ($position == $target_position) {
3103 // Append moved section
3104 $sections[$origin_key] = $origin_section;
3106 // Append rest of array (if applicable)
3107 if (!empty($append_array)) {
3108 foreach ($append_array as $id => $position) {
3109 $sections[$id] = $position;
3113 // Renumber positions
3115 foreach ($sections as $id => $p) {
3116 $sections[$id] = $position;
3125 * Move the module object $mod to the specified $section
3126 * If $beforemod exists then that is the module
3127 * before which $modid should be inserted
3128 * All parameters are objects
3130 function moveto_module($mod, $section, $beforemod=NULL) {
3131 global $DB, $OUTPUT;
3133 /// Remove original module from original section
3134 if (! delete_mod_from_section($mod->id, $mod->section)) {
3135 echo $OUTPUT->notification("Could not delete module from existing section");
3138 /// Update module itself if necessary
3140 if ($mod->section != $section->id) {
3141 $mod->section = $section->id;
3142 $DB->update_record("course_modules", $mod);
3143 // if moving to a hidden section then hide module
3144 if (!$section->visible) {
3145 set_coursemodule_visible($mod->id, 0);
3149 /// Add the module into the new section
3151 $mod->course = $section->course;
3152 $mod->section = $section->section; // need relative reference
3153 $mod->coursemodule = $mod->id;
3155 if (! add_mod_to_section($mod, $beforemod)) {
3163 * Produces the editing buttons for a module
3165 * @global core_renderer $OUTPUT
3166 * @staticvar type $str
3167 * @param stdClass $mod The module to produce editing buttons for
3168 * @param bool $absolute_ignored ignored - all links are absolute
3169 * @param bool $moveselect If true a move seleciton process is used (default true)
3170 * @param int $indent The current indenting
3171 * @param int $section The section to link back to
3172 * @return string XHTML for the editing buttons
3174 function make_editing_buttons(stdClass $mod, $absolute_ignored = true, $moveselect = true, $indent=-1, $section=-1) {
3175 global $CFG, $OUTPUT;
3179 $coursecontext = get_context_instance(CONTEXT_COURSE, $mod->course);
3180 $modcontext = get_context_instance(CONTEXT_MODULE, $mod->id);
3182 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
3183 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
3185 // no permission to edit anything
3186 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
3190 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
3193 $str = new stdClass;
3194 $str->assign = get_string("assignroles", 'role');
3195 $str->delete = get_string("delete");
3196 $str->move = get_string("move");
3197 $str->moveup = get_string("moveup");
3198 $str->movedown = get_string("movedown");
3199 $str->moveright = get_string("moveright");
3200 $str->moveleft = get_string("moveleft");
3201 $str->update = get_string("update");
3202 $str->duplicate = get_string("duplicate");
3203 $str->hide = get_string("hide");
3204 $str->show = get_string("show");
3205 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
3206 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
3207 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
3208 $str->forcedgroupsnone = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsnone"));
3209 $str->forcedgroupsseparate = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsseparate"));
3210 $str->forcedgroupsvisible = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsvisible"));
3213 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
3215 if ($section >= 0) {
3216 $baseurl->param('sr', $section);
3221 if ($hasmanageactivities) {
3222 if (right_to_left()) { // Exchange arrows on RTL
3223 $rightarrow = 't/left';
3224 $leftarrow = 't/right';
3226 $rightarrow = 't/right';
3227 $leftarrow = 't/left';
3231 $actions[] = new action_link(
3232 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
3233 new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall')),
3235 array('class' => 'editing_moveleft', 'title' => $str->moveleft)
3239 $actions[] = new action_link(
3240 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
3241 new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall')),
3243 array('class' => 'editing_moveright', 'title' => $str->moveright)
3249 if ($hasmanageactivities) {
3251 $actions[] = new action_link(
3252 new moodle_url($baseurl, array('copy' => $mod->id)),
3253 new pix_icon('t/move', $str->move, 'moodle', array('class' => 'iconsmall')),
3255 array('class' => 'editing_move', 'title' => $str->move)
3258 $actions[] = new action_link(
3259 new moodle_url($baseurl, array('id' => $mod->id, 'move' => '-1')),
3260 new pix_icon('t/up', $str->moveup, 'moodle', array('class' => 'iconsmall')),
3262 array('class' => 'editing_moveup', 'title' => $str->moveup)
3264 $actions[] = new action_link(
3265 new moodle_url($baseurl, array('id' => $mod->id, 'move' => '1')),
3266 new pix_icon('t/down', $str->movedown, 'moodle', array('class' => 'iconsmall')),
3268 array('class' => 'editing_movedown', 'title' => $str->movedown)
3274 if ($hasmanageactivities) {
3275 $actions[] = new action_link(
3276 new moodle_url($baseurl, array('update' => $mod->id)),
3277 new pix_icon('t/edit', $str->update, 'moodle', array('class' => 'iconsmall')),
3279 array('class' => 'editing_update', 'title' => $str->update)
3283 // Duplicate (require both target import caps to be able to duplicate, see modduplicate.php)
3284 if (has_all_capabilities($dupecaps, $coursecontext)) {
3285 $actions[] = new action_link(
3286 new moodle_url($baseurl, array('duplicate' => $mod->id)),
3287 new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall')),
3289 array('class' => 'editing_duplicate', 'title' => $str->duplicate)
3294 if ($hasmanageactivities) {
3295 $actions[] = new action_link(
3296 new moodle_url($baseurl, array('delete' => $mod->id)),
3297 new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall')),
3299 array('class' => 'editing_delete', 'title' => $str->delete)
3304 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
3305 if ($mod->visible) {
3306 $actions[] = new action_link(
3307 new moodle_url($baseurl, array('hide' => $mod->id)),
3308 new pix_icon('t/hide', $str->hide, 'moodle', array('class' => 'iconsmall')),
3310 array('class' => 'editing_hide', 'title' => $str->hide)
3313 $actions[] = new action_link(
3314 new moodle_url($baseurl, array('show' => $mod->id)),
3315 new pix_icon('t/show', $str->show, 'moodle', array('class' => 'iconsmall')),
3317 array('class' => 'editing_show', 'title' => $str->show)
3323 if ($hasmanageactivities and $mod->groupmode !== false) {
3324 if ($mod->groupmode == SEPARATEGROUPS) {
3326 $grouptitle = $str->groupsseparate;
3327 $forcedgrouptitle = $str->forcedgroupsseparate;
3328 $groupclass = 'editing_groupsseparate';
3329 $groupimage = 't/groups';
3330 } else if ($mod->groupmode == VISIBLEGROUPS) {
3332 $grouptitle = $str->groupsvisible;
3333 $forcedgrouptitle = $str->forcedgroupsvisible;
3334 $groupclass = 'editing_groupsvisible';
3335 $groupimage = 't/groupv';
3338 $grouptitle = $str->groupsnone;
3339 $forcedgrouptitle = $str->forcedgroupsnone;
3340 $groupclass = 'editing_groupsnone';
3341 $groupimage = 't/groupn';
3343 if ($mod->groupmodelink) {
3344 $actions[] = new action_link(
3345 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $groupmode)),
3346 new pix_icon($groupimage, $grouptitle, 'moodle', array('class' => 'iconsmall')),
3348 array('class' => $groupclass, 'title' => $grouptitle)
3351 $actions[] = new pix_icon($groupimage, $forcedgrouptitle, 'moodle', array('title' => $forcedgrouptitle, 'class' => 'iconsmall'));
3356 if (has_capability('moodle/role:assign', $modcontext)){
3357 $actions[] = new action_link(
3358 new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $modcontext->id)),
3359 new pix_icon('i/roles', $str->assign, 'moodle', array('class' => 'iconsmall')),
3361 array('class' => 'editing_assign', 'title' => $str->assign)
3365 $output = html_writer::start_tag('span', array('class' => 'commands'));
3366 foreach ($actions as $action) {
3367 if ($action instanceof renderable) {
3368 $output .= $OUTPUT->render($action);
3373 $output .= html_writer::end_tag('span');
3378 * given a course object with shortname & fullname, this function will
3379 * truncate the the number of chars allowed and add ... if it was too long
3381 function course_format_name ($course,$max=100) {
3383 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3384 $shortname = format_string($course->shortname, true, array('context' => $context));
3385 $fullname = format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
3386 $str = $shortname.': '. $fullname;
3387 if (textlib::strlen($str) <= $max) {
3391 return textlib::substr($str,0,$max-3).'...';
3396 * Is the user allowed to add this type of module to this course?
3397 * @param object $course the course settings. Only $course->id is used.
3398 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
3399 * @return bool whether the current user is allowed to add this type of module to this course.
3401 function course_allowed_module($course, $modname) {
3404 if (is_numeric($modname)) {
3405 throw new coding_exception('Function course_allowed_module no longer
3406 supports numeric module ids. Please update your code to pass the module name.');
3409 $capability = 'mod/' . $modname . ':addinstance';
3410 if (!get_capability_info($capability)) {
3411 // Debug warning that the capability does not exist, but no more than once per page.
3412 static $warned = array();
3413 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
3414 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
3415 debugging('The module ' . $modname . ' does not define the standard capability ' .
3416 $capability , DEBUG_DEVELOPER);
3417 $warned[$modname] = 1;
3420 // If the capability does not exist, the module can always be added.
3424 $coursecontext = context_course::instance($course->id);
3425 return has_capability($capability, $coursecontext);
3429 * Recursively delete category including all subcategories and courses.
3430 * @param stdClass $category
3431 * @param boolean $showfeedback display some notices
3432 * @return array return deleted courses
3434 function category_delete_full($category, $showfeedback=true) {
3436 require_once($CFG->libdir.'/gradelib.php');
3437 require_once($CFG->libdir.'/questionlib.php');
3438 require_once($CFG->dirroot.'/cohort/lib.php');
3440 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3441 foreach ($children as $childcat) {
3442 category_delete_full($childcat, $showfeedback);
3446 $deletedcourses = array();
3447 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC')) {
3448 foreach ($courses as $course) {
3449 if (!delete_course($course, false)) {
3450 throw new moodle_exception('cannotdeletecategorycourse','','',$course->shortname);
3452 $deletedcourses[] = $course;
3456 // move or delete cohorts in this context
3457 cohort_delete_category($category);
3459 // now delete anything that may depend on course category context
3460 grade_course_category_delete($category->id, 0, $showfeedback);
3461 if (!question_delete_course_category($category, 0, $showfeedback)) {
3462 throw new moodle_exception('cannotdeletecategoryquestions','','',$category->name);
3465 // finally delete the category and it's context
3466 $DB->delete_records('course_categories', array('id'=>$category->id));
3467 delete_context(CONTEXT_COURSECAT, $category->id);
3469 events_trigger('course_category_deleted', $category);
3471 return $deletedcourses;
3475 * Delete category, but move contents to another category.
3476 * @param object $ccategory
3477 * @param int $newparentid category id
3478 * @return bool status
3480 function category_delete_move($category, $newparentid, $showfeedback=true) {
3481 global $CFG, $DB, $OUTPUT;
3482 require_once($CFG->libdir.'/gradelib.php');
3483 require_once($CFG->libdir.'/questionlib.php');
3484 require_once($CFG->dirroot.'/cohort/lib.php');
3486 if (!$newparentcat = $DB->get_record('course_categories', array('id'=>$newparentid))) {
3490 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3491 foreach ($children as $childcat) {
3492 move_category($childcat, $newparentcat);
3496 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC', 'id')) {
3497 if (!move_courses(array_keys($courses), $newparentid)) {
3498 echo $OUTPUT->notification("Error moving courses");