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 define('COURSE_DISPLAY_SINGLEPAGE', 0); // display all sections on one page
50 define('COURSE_DISPLAY_MULTIPAGE', 1); // split pages into a page per section
52 function make_log_url($module, $url) {
55 if (strpos($url, 'report/') === 0) {
56 // there is only one report type, course reports are deprecated
66 if (strpos($url, '../') === 0) {
67 $url = ltrim($url, '.');
69 $url = "/course/$url";
74 $url = "/$module/$url";
87 $url = "/message/$url";
99 $url = "/mod/$module/$url";
103 //now let's sanitise urls - there might be some ugly nasties:-(
104 $parts = explode('?', $url);
105 $script = array_shift($parts);
106 if (strpos($script, 'http') === 0) {
107 $script = clean_param($script, PARAM_URL);
109 $script = clean_param($script, PARAM_PATH);
114 $query = implode('', $parts);
115 $query = str_replace('&', '&', $query); // both & and & are stored in db :-|
116 $parts = explode('&', $query);
117 $eq = urlencode('=');
118 foreach ($parts as $key=>$part) {
119 $part = urlencode(urldecode($part));
120 $part = str_replace($eq, '=', $part);
121 $parts[$key] = $part;
123 $query = '?'.implode('&', $parts);
126 return $script.$query;
130 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
131 $modname="", $modid=0, $modaction="", $groupid=0) {
134 // It is assumed that $date is the GMT time of midnight for that day,
135 // and so the next 86400 seconds worth of logs are printed.
137 /// Setup for group handling.
139 // TODO: I don't understand group/context/etc. enough to be able to do
140 // something interesting with it here
141 // What is the context of a remote course?
143 /// If the group mode is separate, and this user does not have editing privileges,
144 /// then only the user's group can be viewed.
145 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
146 // $groupid = get_current_group($course->id);
148 /// If this course doesn't have groups, no groupid can be specified.
149 //else if (!$course->groupmode) {
158 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
160 LEFT JOIN {user} u ON l.userid = u.id
164 $where .= "l.hostid = :hostid";
165 $params['hostid'] = $hostid;
167 // TODO: Is 1 really a magic number referring to the sitename?
168 if ($course != SITEID || $modid != 0) {
169 $where .= " AND l.course=:courseid";
170 $params['courseid'] = $course;
174 $where .= " AND l.module = :modname";
175 $params['modname'] = $modname;
178 if ('site_errors' === $modid) {
179 $where .= " AND ( l.action='error' OR l.action='infected' )";
181 //TODO: This assumes that modids are the same across sites... probably
183 $where .= " AND l.cmid = :modid";
184 $params['modid'] = $modid;
188 $firstletter = substr($modaction, 0, 1);
189 if ($firstletter == '-') {
190 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
191 $params['modaction'] = '%'.substr($modaction, 1).'%';
193 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
194 $params['modaction'] = '%'.$modaction.'%';
199 $where .= " AND l.userid = :user";
200 $params['user'] = $user;
204 $enddate = $date + 86400;
205 $where .= " AND l.time > :date AND l.time < :enddate";
206 $params['date'] = $date;
207 $params['enddate'] = $enddate;
211 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
212 if(!empty($result['totalcount'])) {
213 $where .= " ORDER BY $order";
214 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
216 $result['logs'] = array();
221 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
222 $modname="", $modid=0, $modaction="", $groupid=0) {
223 global $DB, $SESSION, $USER;
224 // It is assumed that $date is the GMT time of midnight for that day,
225 // and so the next 86400 seconds worth of logs are printed.
227 /// Setup for group handling.
229 /// If the group mode is separate, and this user does not have editing privileges,
230 /// then only the user's group can be viewed.
231 if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
232 if (isset($SESSION->currentgroup[$course->id])) {
233 $groupid = $SESSION->currentgroup[$course->id];
235 $groupid = groups_get_all_groups($course->id, $USER->id);
236 if (is_array($groupid)) {
237 $groupid = array_shift(array_keys($groupid));
238 $SESSION->currentgroup[$course->id] = $groupid;
244 /// If this course doesn't have groups, no groupid can be specified.
245 else if (!$course->groupmode) {
252 if ($course->id != SITEID || $modid != 0) {
253 $joins[] = "l.course = :courseid";
254 $params['courseid'] = $course->id;
258 $joins[] = "l.module = :modname";
259 $params['modname'] = $modname;
262 if ('site_errors' === $modid) {
263 $joins[] = "( l.action='error' OR l.action='infected' )";
265 $joins[] = "l.cmid = :modid";
266 $params['modid'] = $modid;
270 $firstletter = substr($modaction, 0, 1);
271 if ($firstletter == '-') {
272 $joins[] = $DB->sql_like('l.action', ':modaction', false, true, true);
273 $params['modaction'] = '%'.substr($modaction, 1).'%';
275 $joins[] = $DB->sql_like('l.action', ':modaction', false);
276 $params['modaction'] = '%'.$modaction.'%';
281 /// Getting all members of a group.
282 if ($groupid and !$user) {
283 if ($gusers = groups_get_members($groupid)) {
284 $gusers = array_keys($gusers);
285 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
287 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
291 $joins[] = "l.userid = :userid";
292 $params['userid'] = $user;
296 $enddate = $date + 86400;
297 $joins[] = "l.time > :date AND l.time < :enddate";
298 $params['date'] = $date;
299 $params['enddate'] = $enddate;
302 $selector = implode(' AND ', $joins);
304 $totalcount = 0; // Initialise
306 $result['logs'] = get_logs($selector, $params, $order, $limitfrom, $limitnum, $totalcount);
307 $result['totalcount'] = $totalcount;
312 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
313 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
315 global $CFG, $DB, $OUTPUT;
317 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
318 $modname, $modid, $modaction, $groupid)) {
319 echo $OUTPUT->notification("No logs found!");
320 echo $OUTPUT->footer();
326 if ($course->id == SITEID) {
328 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
329 foreach ($ccc as $cc) {
330 $courses[$cc->id] = $cc->shortname;
334 $courses[$course->id] = $course->shortname;
337 $totalcount = $logs['totalcount'];
340 $tt = getdate(time());
341 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
343 $strftimedatetime = get_string("strftimedatetime");
345 echo "<div class=\"info\">\n";
346 print_string("displayingrecords", "", $totalcount);
349 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
351 $table = new html_table();
352 $table->classes = array('logtable','generalbox');
353 $table->align = array('right', 'left', 'left');
354 $table->head = array(
356 get_string('ip_address'),
357 get_string('fullnameuser'),
358 get_string('action'),
361 $table->data = array();
363 if ($course->id == SITEID) {
364 array_unshift($table->align, 'left');
365 array_unshift($table->head, get_string('course'));
368 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
369 if (empty($logs['logs'])) {
370 $logs['logs'] = array();
373 foreach ($logs['logs'] as $log) {
375 if (isset($ldcache[$log->module][$log->action])) {
376 $ld = $ldcache[$log->module][$log->action];
378 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
379 $ldcache[$log->module][$log->action] = $ld;
381 if ($ld && is_numeric($log->info)) {
382 // ugly hack to make sure fullname is shown correctly
383 if ($ld->mtable == 'user' && $ld->field == $DB->sql_concat('firstname', "' '" , 'lastname')) {
384 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
386 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
391 $log->info = format_string($log->info);
393 // If $log->url has been trimmed short by the db size restriction
394 // code in add_to_log, keep a note so we don't add a link to a broken url
395 $brokenurl=(textlib::strlen($log->url)==100 && textlib::substr($log->url,97)=='...');
398 if ($course->id == SITEID) {
399 if (empty($log->course)) {
400 $row[] = get_string('site');
402 $row[] = "<a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course])."</a>";
406 $row[] = userdate($log->time, '%a').' '.userdate($log->time, $strftimedatetime);
408 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
409 $row[] = $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 440, 'width' => 700)));
411 $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))));
413 $displayaction="$log->module $log->action";
415 $row[] = $displayaction;
417 $link = make_log_url($log->module,$log->url);
418 $row[] = $OUTPUT->action_link($link, $displayaction, new popup_action('click', $link, 'fromloglive'), array('height' => 440, 'width' => 700));
421 $table->data[] = $row;
424 echo html_writer::table($table);
425 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
429 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
430 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
432 global $CFG, $DB, $OUTPUT;
434 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
435 $modname, $modid, $modaction, $groupid)) {
436 echo $OUTPUT->notification("No logs found!");
437 echo $OUTPUT->footer();
441 if ($course->id == SITEID) {
443 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
444 foreach ($ccc as $cc) {
445 $courses[$cc->id] = $cc->shortname;
450 $totalcount = $logs['totalcount'];
453 $tt = getdate(time());
454 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
456 $strftimedatetime = get_string("strftimedatetime");
458 echo "<div class=\"info\">\n";
459 print_string("displayingrecords", "", $totalcount);
462 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
464 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
466 if ($course->id == SITEID) {
467 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
469 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
470 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
471 echo "<th class=\"c3 header\">".get_string('fullnameuser')."</th>\n";
472 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
473 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
476 if (empty($logs['logs'])) {
482 foreach ($logs['logs'] as $log) {
484 $log->info = $log->coursename;
485 $row = ($row + 1) % 2;
487 if (isset($ldcache[$log->module][$log->action])) {
488 $ld = $ldcache[$log->module][$log->action];
490 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
491 $ldcache[$log->module][$log->action] = $ld;
493 if (0 && $ld && !empty($log->info)) {
494 // ugly hack to make sure fullname is shown correctly
495 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
496 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
498 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
503 $log->info = format_string($log->info);
505 echo '<tr class="r'.$row.'">';
506 if ($course->id == SITEID) {
507 $courseshortname = format_string($courses[$log->course], true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
508 echo "<td class=\"r$row c0\" >\n";
509 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courseshortname."</a>\n";
512 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time, '%a').
513 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
514 echo "<td class=\"r$row c2\" >\n";
515 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
516 echo $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 400, 'width' => 700)));
518 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
519 echo "<td class=\"r$row c3\" >\n";
520 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
522 echo "<td class=\"r$row c4\">\n";
523 echo $log->action .': '.$log->module;
525 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
530 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
534 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
535 $modid, $modaction, $groupid) {
538 $text = get_string('course')."\t".get_string('time')."\t".get_string('ip_address')."\t".
539 get_string('fullnameuser')."\t".get_string('action')."\t".get_string('info');
541 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
542 $modname, $modid, $modaction, $groupid)) {
548 if ($course->id == SITEID) {
550 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
551 foreach ($ccc as $cc) {
552 $courses[$cc->id] = $cc->shortname;
556 $courses[$course->id] = $course->shortname;
561 $tt = getdate(time());
562 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
564 $strftimedatetime = get_string("strftimedatetime");
566 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
568 header("Content-Type: application/download\n");
569 header("Content-Disposition: attachment; filename=$filename");
570 header("Expires: 0");
571 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
572 header("Pragma: public");
574 echo get_string('savedat').userdate(time(), $strftimedatetime)."\n";
577 if (empty($logs['logs'])) {
581 foreach ($logs['logs'] as $log) {
582 if (isset($ldcache[$log->module][$log->action])) {
583 $ld = $ldcache[$log->module][$log->action];
585 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
586 $ldcache[$log->module][$log->action] = $ld;
588 if ($ld && !empty($log->info)) {
589 // ugly hack to make sure fullname is shown correctly
590 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
591 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
593 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
598 $log->info = format_string($log->info);
599 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
601 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
602 $firstField = format_string($courses[$log->course], true, array('context' => $coursecontext));
603 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
604 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action, $log->info);
605 $text = implode("\t", $row);
612 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
613 $modid, $modaction, $groupid) {
617 require_once("$CFG->libdir/excellib.class.php");
619 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
620 $modname, $modid, $modaction, $groupid)) {
626 if ($course->id == SITEID) {
628 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
629 foreach ($ccc as $cc) {
630 $courses[$cc->id] = $cc->shortname;
634 $courses[$course->id] = $course->shortname;
639 $tt = getdate(time());
640 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
642 $strftimedatetime = get_string("strftimedatetime");
644 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
645 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
648 $workbook = new MoodleExcelWorkbook('-');
649 $workbook->send($filename);
651 $worksheet = array();
652 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
653 get_string('fullnameuser'), get_string('action'), get_string('info'));
655 // Creating worksheets
656 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
657 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
658 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
659 $worksheet[$wsnumber]->set_column(1, 1, 30);
660 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
661 userdate(time(), $strftimedatetime));
663 foreach ($headers as $item) {
664 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
669 if (empty($logs['logs'])) {
674 $formatDate =& $workbook->add_format();
675 $formatDate->set_num_format(get_string('log_excel_date_format'));
677 $row = FIRSTUSEDEXCELROW;
679 $myxls =& $worksheet[$wsnumber];
680 foreach ($logs['logs'] as $log) {
681 if (isset($ldcache[$log->module][$log->action])) {
682 $ld = $ldcache[$log->module][$log->action];
684 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
685 $ldcache[$log->module][$log->action] = $ld;
687 if ($ld && !empty($log->info)) {
688 // ugly hack to make sure fullname is shown correctly
689 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
690 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
692 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
697 $log->info = format_string($log->info);
698 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
701 if ($row > EXCELROWS) {
703 $myxls =& $worksheet[$wsnumber];
704 $row = FIRSTUSEDEXCELROW;
708 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
710 $myxls->write($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)), '');
711 $myxls->write_date($row, 1, $log->time, $formatDate); // write_date() does conversion/timezone support. MDL-14934
712 $myxls->write($row, 2, $log->ip, '');
713 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
714 $myxls->write($row, 3, $fullname, '');
715 $myxls->write($row, 4, $log->module.' '.$log->action, '');
716 $myxls->write($row, 5, $log->info, '');
725 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
726 $modid, $modaction, $groupid) {
730 require_once("$CFG->libdir/odslib.class.php");
732 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
733 $modname, $modid, $modaction, $groupid)) {
739 if ($course->id == SITEID) {
741 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
742 foreach ($ccc as $cc) {
743 $courses[$cc->id] = $cc->shortname;
747 $courses[$course->id] = $course->shortname;
752 $tt = getdate(time());
753 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
755 $strftimedatetime = get_string("strftimedatetime");
757 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
758 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
761 $workbook = new MoodleODSWorkbook('-');
762 $workbook->send($filename);
764 $worksheet = array();
765 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
766 get_string('fullnameuser'), get_string('action'), get_string('info'));
768 // Creating worksheets
769 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
770 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
771 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
772 $worksheet[$wsnumber]->set_column(1, 1, 30);
773 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
774 userdate(time(), $strftimedatetime));
776 foreach ($headers as $item) {
777 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
782 if (empty($logs['logs'])) {
787 $formatDate =& $workbook->add_format();
788 $formatDate->set_num_format(get_string('log_excel_date_format'));
790 $row = FIRSTUSEDEXCELROW;
792 $myxls =& $worksheet[$wsnumber];
793 foreach ($logs['logs'] as $log) {
794 if (isset($ldcache[$log->module][$log->action])) {
795 $ld = $ldcache[$log->module][$log->action];
797 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
798 $ldcache[$log->module][$log->action] = $ld;
800 if ($ld && !empty($log->info)) {
801 // ugly hack to make sure fullname is shown correctly
802 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
803 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
805 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
810 $log->info = format_string($log->info);
811 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
814 if ($row > EXCELROWS) {
816 $myxls =& $worksheet[$wsnumber];
817 $row = FIRSTUSEDEXCELROW;
821 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
823 $myxls->write_string($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)));
824 $myxls->write_date($row, 1, $log->time);
825 $myxls->write_string($row, 2, $log->ip);
826 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
827 $myxls->write_string($row, 3, $fullname);
828 $myxls->write_string($row, 4, $log->module.' '.$log->action);
829 $myxls->write_string($row, 5, $log->info);
839 function print_overview($courses, array $remote_courses=array()) {
840 global $CFG, $USER, $DB, $OUTPUT;
842 $htmlarray = array();
843 if ($modules = $DB->get_records('modules')) {
844 foreach ($modules as $mod) {
845 if (file_exists(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php')) {
846 include_once(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php');
847 $fname = $mod->name.'_print_overview';
848 if (function_exists($fname)) {
849 $fname($courses,$htmlarray);
854 foreach ($courses as $course) {
855 $fullname = format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
856 echo $OUTPUT->box_start('coursebox');
857 $attributes = array('title' => s($fullname));
858 if (empty($course->visible)) {
859 $attributes['class'] = 'dimmed';
861 echo $OUTPUT->heading(html_writer::link(
862 new moodle_url('/course/view.php', array('id' => $course->id)), $fullname, $attributes), 3);
863 if (array_key_exists($course->id,$htmlarray)) {
864 foreach ($htmlarray[$course->id] as $modname => $html) {
868 echo $OUTPUT->box_end();
871 if (!empty($remote_courses)) {
872 echo $OUTPUT->heading(get_string('remotecourses', 'mnet'));
874 foreach ($remote_courses as $course) {
875 echo $OUTPUT->box_start('coursebox');
876 $attributes = array('title' => s($course->fullname));
877 echo $OUTPUT->heading(html_writer::link(
878 new moodle_url('/auth/mnet/jump.php', array('hostid' => $course->hostid, 'wantsurl' => '/course/view.php?id='.$course->remoteid)),
879 format_string($course->shortname),
880 $attributes) . ' (' . format_string($course->hostname) . ')', 3);
881 echo $OUTPUT->box_end();
887 * This function trawls through the logs looking for
888 * anything new since the user's last login
890 function print_recent_activity($course) {
891 // $course is an object
892 global $CFG, $USER, $SESSION, $DB, $OUTPUT;
894 $context = get_context_instance(CONTEXT_COURSE, $course->id);
896 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
898 $timestart = round(time() - COURSE_MAX_RECENT_PERIOD, -2); // better db caching for guests - 100 seconds
900 if (!isguestuser()) {
901 if (!empty($USER->lastcourseaccess[$course->id])) {
902 if ($USER->lastcourseaccess[$course->id] > $timestart) {
903 $timestart = $USER->lastcourseaccess[$course->id];
908 echo '<div class="activitydate">';
909 echo get_string('activitysince', '', userdate($timestart));
911 echo '<div class="activityhead">';
913 echo '<a href="'.$CFG->wwwroot.'/course/recent.php?id='.$course->id.'">'.get_string('recentactivityreport').'</a>';
919 /// Firstly, have there been any new enrolments?
921 $users = get_recent_enrolments($course->id, $timestart);
923 //Accessibility: new users now appear in an <OL> list.
925 echo '<div class="newusers">';
926 echo $OUTPUT->heading(get_string("newusers").':', 3);
928 echo "<ol class=\"list\">\n";
929 foreach ($users as $user) {
930 $fullname = fullname($user, $viewfullnames);
931 echo '<li class="name"><a href="'."$CFG->wwwroot/user/view.php?id=$user->id&course=$course->id\">$fullname</a></li>\n";
933 echo "</ol>\n</div>\n";
936 /// Next, have there been any modifications to the course structure?
938 $modinfo = get_fast_modinfo($course);
940 $changelist = array();
942 $logs = $DB->get_records_select('log', "time > ? AND course = ? AND
943 module = 'course' AND
944 (action = 'add mod' OR action = 'update mod' OR action = 'delete mod')",
945 array($timestart, $course->id), "id ASC");
948 $actions = array('add mod', 'update mod', 'delete mod');
949 $newgones = array(); // added and later deleted items
950 foreach ($logs as $key => $log) {
951 if (!in_array($log->action, $actions)) {
954 $info = explode(' ', $log->info);
956 // note: in most cases I replaced hardcoding of label with use of
957 // $cm->has_view() but it was not possible to do this here because
958 // we don't necessarily have the $cm for it
959 if ($info[0] == 'label') { // Labels are ignored in recent activity
963 if (count($info) != 2) {
964 debugging("Incorrect log entry info: id = ".$log->id, DEBUG_DEVELOPER);
969 $instanceid = $info[1];
971 if ($log->action == 'delete mod') {
972 // unfortunately we do not know if the mod was visible
973 if (!array_key_exists($log->info, $newgones)) {
974 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $modname));
975 $changelist[$log->info] = array ('operation' => 'delete', 'text' => $strdeleted);
978 if (!isset($modinfo->instances[$modname][$instanceid])) {
979 if ($log->action == 'add mod') {
980 // do not display added and later deleted activities
981 $newgones[$log->info] = true;
985 $cm = $modinfo->instances[$modname][$instanceid];
986 if (!$cm->uservisible) {
990 if ($log->action == 'add mod') {
991 $stradded = get_string('added', 'moodle', get_string('modulename', $modname));
992 $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>");
994 } else if ($log->action == 'update mod' and empty($changelist[$log->info])) {
995 $strupdated = get_string('updated', 'moodle', get_string('modulename', $modname));
996 $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>");
1002 if (!empty($changelist)) {
1003 echo $OUTPUT->heading(get_string("courseupdates").':', 3);
1005 foreach ($changelist as $changeinfo => $change) {
1006 echo '<p class="activity">'.$change['text'].'</p>';
1010 /// Now display new things from each module
1012 $usedmodules = array();
1013 foreach($modinfo->cms as $cm) {
1014 if (isset($usedmodules[$cm->modname])) {
1017 if (!$cm->uservisible) {
1020 $usedmodules[$cm->modname] = $cm->modname;
1023 foreach ($usedmodules as $modname) { // Each module gets it's own logs and prints them
1024 if (file_exists($CFG->dirroot.'/mod/'.$modname.'/lib.php')) {
1025 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
1026 $print_recent_activity = $modname.'_print_recent_activity';
1027 if (function_exists($print_recent_activity)) {
1028 // NOTE: original $isteacher (second parameter below) was replaced with $viewfullnames!
1029 $content = $print_recent_activity($course, $viewfullnames, $timestart) || $content;
1032 debugging("Missing lib.php in lib/{$modname} - please reinstall files or uninstall the module");
1037 echo '<p class="message">'.get_string('nothingnew').'</p>';
1042 * For a given course, returns an array of course activity objects
1043 * Each item in the array contains he following properties:
1045 function get_array_of_activities($courseid) {
1046 // cm - course module id
1047 // mod - name of the module (eg forum)
1048 // section - the number of the section (eg week or topic)
1049 // name - the name of the instance
1050 // visible - is the instance visible or not
1051 // groupingid - grouping id
1052 // groupmembersonly - is this instance visible to group members only
1053 // extra - contains extra string to include in any link
1055 if(!empty($CFG->enableavailability)) {
1056 require_once($CFG->libdir.'/conditionlib.php');
1059 $course = $DB->get_record('course', array('id'=>$courseid));
1061 if (empty($course)) {
1062 throw new moodle_exception('courseidnotfound');
1067 $rawmods = get_course_mods($courseid);
1068 if (empty($rawmods)) {
1069 return $mod; // always return array
1072 if ($sections = $DB->get_records("course_sections", array("course"=>$courseid), "section ASC")) {
1073 foreach ($sections as $section) {
1074 if (!empty($section->sequence)) {
1075 $sequence = explode(",", $section->sequence);
1076 foreach ($sequence as $seq) {
1077 if (empty($rawmods[$seq])) {
1080 $mod[$seq] = new stdClass();
1081 $mod[$seq]->id = $rawmods[$seq]->instance;
1082 $mod[$seq]->cm = $rawmods[$seq]->id;
1083 $mod[$seq]->mod = $rawmods[$seq]->modname;
1085 // Oh dear. Inconsistent names left here for backward compatibility.
1086 $mod[$seq]->section = $section->section;
1087 $mod[$seq]->sectionid = $rawmods[$seq]->section;
1089 $mod[$seq]->module = $rawmods[$seq]->module;
1090 $mod[$seq]->added = $rawmods[$seq]->added;
1091 $mod[$seq]->score = $rawmods[$seq]->score;
1092 $mod[$seq]->idnumber = $rawmods[$seq]->idnumber;
1093 $mod[$seq]->visible = $rawmods[$seq]->visible;
1094 $mod[$seq]->visibleold = $rawmods[$seq]->visibleold;
1095 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
1096 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
1097 $mod[$seq]->groupmembersonly = $rawmods[$seq]->groupmembersonly;
1098 $mod[$seq]->indent = $rawmods[$seq]->indent;
1099 $mod[$seq]->completion = $rawmods[$seq]->completion;
1100 $mod[$seq]->extra = "";
1101 $mod[$seq]->completiongradeitemnumber =
1102 $rawmods[$seq]->completiongradeitemnumber;
1103 $mod[$seq]->completionview = $rawmods[$seq]->completionview;
1104 $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected;
1105 $mod[$seq]->availablefrom = $rawmods[$seq]->availablefrom;
1106 $mod[$seq]->availableuntil = $rawmods[$seq]->availableuntil;
1107 $mod[$seq]->showavailability = $rawmods[$seq]->showavailability;
1108 $mod[$seq]->showdescription = $rawmods[$seq]->showdescription;
1109 if (!empty($CFG->enableavailability)) {
1110 condition_info::fill_availability_conditions($rawmods[$seq]);
1111 $mod[$seq]->conditionscompletion = $rawmods[$seq]->conditionscompletion;
1112 $mod[$seq]->conditionsgrade = $rawmods[$seq]->conditionsgrade;
1115 $modname = $mod[$seq]->mod;
1116 $functionname = $modname."_get_coursemodule_info";
1118 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
1122 include_once("$CFG->dirroot/mod/$modname/lib.php");
1124 if ($hasfunction = function_exists($functionname)) {
1125 if ($info = $functionname($rawmods[$seq])) {
1126 if (!empty($info->icon)) {
1127 $mod[$seq]->icon = $info->icon;
1129 if (!empty($info->iconcomponent)) {
1130 $mod[$seq]->iconcomponent = $info->iconcomponent;
1132 if (!empty($info->name)) {
1133 $mod[$seq]->name = $info->name;
1135 if ($info instanceof cached_cm_info) {
1136 // When using cached_cm_info you can include three new fields
1137 // that aren't available for legacy code
1138 if (!empty($info->content)) {
1139 $mod[$seq]->content = $info->content;
1141 if (!empty($info->extraclasses)) {
1142 $mod[$seq]->extraclasses = $info->extraclasses;
1144 if (!empty($info->iconurl)) {
1145 $mod[$seq]->iconurl = $info->iconurl;
1147 if (!empty($info->onclick)) {
1148 $mod[$seq]->onclick = $info->onclick;
1150 if (!empty($info->customdata)) {
1151 $mod[$seq]->customdata = $info->customdata;
1154 // When using a stdclass, the (horrible) deprecated ->extra field
1155 // is available for BC
1156 if (!empty($info->extra)) {
1157 $mod[$seq]->extra = $info->extra;
1162 // When there is no modname_get_coursemodule_info function,
1163 // but showdescriptions is enabled, then we use the 'intro'
1164 // and 'introformat' fields in the module table
1165 if (!$hasfunction && $rawmods[$seq]->showdescription) {
1166 if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
1167 array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
1168 // Set content from intro and introformat. Filters are disabled
1169 // because we filter it with format_text at display time
1170 $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
1171 $modvalues, $rawmods[$seq]->id, false);
1173 // To save making another query just below, put name in here
1174 $mod[$seq]->name = $modvalues->name;
1177 if (!isset($mod[$seq]->name)) {
1178 $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
1181 // Minimise the database size by unsetting default options when they are
1182 // 'empty'. This list corresponds to code in the cm_info constructor.
1183 foreach (array('idnumber', 'groupmode', 'groupingid', 'groupmembersonly',
1184 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
1185 'icon', 'iconcomponent', 'customdata', 'showavailability', 'availablefrom',
1186 'availableuntil', 'conditionscompletion', 'conditionsgrade',
1187 'completionview', 'completionexpected', 'score', 'showdescription')
1189 if (property_exists($mod[$seq], $property) &&
1190 empty($mod[$seq]->{$property})) {
1191 unset($mod[$seq]->{$property});
1194 // Special case: this value is usually set to null, but may be 0
1195 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
1196 is_null($mod[$seq]->completiongradeitemnumber)) {
1197 unset($mod[$seq]->completiongradeitemnumber);
1208 * Returns a number of useful structures for course displays
1210 function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
1211 global $CFG, $DB, $COURSE;
1213 $mods = array(); // course modules indexed by id
1214 $modnames = array(); // all course module names (except resource!)
1215 $modnamesplural= array(); // all course module names (plural form)
1216 $modnamesused = array(); // course module names used
1218 if ($allmods = $DB->get_records("modules")) {
1219 foreach ($allmods as $mod) {
1220 if (!file_exists("$CFG->dirroot/mod/$mod->name/lib.php")) {
1223 if ($mod->visible) {
1224 $modnames[$mod->name] = get_string("modulename", "$mod->name");
1225 $modnamesplural[$mod->name] = get_string("modulenameplural", "$mod->name");
1228 collatorlib::asort($modnames);
1230 print_error("nomodules", 'debug');
1233 $course = ($courseid==$COURSE->id) ? $COURSE : $DB->get_record('course',array('id'=>$courseid));
1234 $modinfo = get_fast_modinfo($course);
1236 if ($rawmods=$modinfo->cms) {
1237 foreach($rawmods as $mod) { // Index the mods
1238 if (empty($modnames[$mod->modname])) {
1241 $mods[$mod->id] = $mod;
1242 $mods[$mod->id]->modfullname = $modnames[$mod->modname];
1243 if (!$mod->visible and !has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_COURSE, $courseid))) {
1247 if (!groups_course_module_visible($mod)) {
1250 $modnamesused[$mod->modname] = $modnames[$mod->modname];
1252 if ($modnamesused) {
1253 collatorlib::asort($modnamesused);
1259 * Returns an array of sections for the requested course id
1261 * This function stores the sections against the course id within a staticvar encase
1262 * of subsequent requests. This is used all over + in some standard libs and course
1263 * format callbacks so subsequent requests are a reality.
1265 * @staticvar array $coursesections
1266 * @param int $courseid
1267 * @return array Array of sections
1269 function get_all_sections($courseid) {
1271 static $coursesections = array();
1272 if (!array_key_exists($courseid, $coursesections)) {
1273 $coursesections[$courseid] = $DB->get_records("course_sections", array("course"=>"$courseid"), "section",
1274 "section, id, course, name, summary, summaryformat, sequence, visible");
1276 return $coursesections[$courseid];
1280 * Set highlighted section. Only one section can be highlighted at the time.
1282 * @param int $courseid course id
1283 * @param int $marker highlight section with this number, 0 means remove higlightin
1286 function course_set_marker($courseid, $marker) {
1288 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
1292 * For a given course section, marks it visible or hidden,
1293 * and does the same for every activity in that section
1295 * @param int $courseid course id
1296 * @param int $sectionnumber The section number to adjust
1297 * @param int $visibility The new visibility
1298 * @return array A list of resources which were hidden in the section
1300 function set_section_visible($courseid, $sectionnumber, $visibility) {
1303 $resourcestotoggle = array();
1304 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
1305 $DB->set_field("course_sections", "visible", "$visibility", array("id"=>$section->id));
1306 if (!empty($section->sequence)) {
1307 $modules = explode(",", $section->sequence);
1308 foreach ($modules as $moduleid) {
1309 set_coursemodule_visible($moduleid, $visibility, true);
1312 rebuild_course_cache($courseid);
1314 // Determine which modules are visible for AJAX update
1315 if (!empty($modules)) {
1316 list($insql, $params) = $DB->get_in_or_equal($modules);
1317 $select = 'id ' . $insql . ' AND visible = ?';
1318 array_push($params, $visibility);
1320 $select .= ' AND visibleold = 1';
1322 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
1325 return $resourcestotoggle;
1329 * Obtains shared data that is used in print_section when displaying a
1330 * course-module entry.
1332 * Calls format_text or format_string as appropriate, and obtains the correct icon.
1334 * This data is also used in other areas of the code.
1335 * @param cm_info $cm Course-module data (must come from get_fast_modinfo)
1336 * @param object $course Moodle course object
1337 * @return array An array with the following values in this order:
1338 * $content (optional extra content for after link),
1339 * $instancename (text of link)
1341 function get_print_section_cm_text(cm_info $cm, $course) {
1344 // Get content from modinfo if specified. Content displays either
1345 // in addition to the standard link (below), or replaces it if
1346 // the link is turned off by setting ->url to null.
1347 if (($content = $cm->get_content()) !== '') {
1348 // Improve filter performance by preloading filter setttings for all
1349 // activities on the course (this does nothing if called multiple
1351 filter_preload_activities($cm->get_modinfo());
1353 // Get module context
1354 $modulecontext = get_context_instance(CONTEXT_MODULE, $cm->id);
1355 $labelformatoptions = new stdClass();
1356 $labelformatoptions->noclean = true;
1357 $labelformatoptions->overflowdiv = true;
1358 $labelformatoptions->context = $modulecontext;
1359 $content = format_text($content, FORMAT_HTML, $labelformatoptions);
1364 // Get course context
1365 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
1366 $stringoptions = new stdClass;
1367 $stringoptions->context = $coursecontext;
1368 $instancename = format_string($cm->name, true, $stringoptions);
1369 return array($content, $instancename);
1373 * Prints a section full of activity modules
1375 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%", $hidecompletion=false, $sectionreturn = false) {
1376 global $CFG, $USER, $DB, $PAGE, $OUTPUT;
1378 static $initialised;
1380 static $groupbuttons;
1381 static $groupbuttonslink;
1384 static $strmovehere;
1385 static $strmovefull;
1386 static $strunreadpostsone;
1388 static $modulenames;
1390 if (!isset($initialised)) {
1391 $groupbuttons = ($course->groupmode or (!$course->groupmodeforce));
1392 $groupbuttonslink = (!$course->groupmodeforce);
1393 $isediting = $PAGE->user_is_editing();
1394 $ismoving = $isediting && ismoving($course->id);
1396 $strmovehere = get_string("movehere");
1397 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1399 $modulenames = array();
1400 $initialised = true;
1403 $modinfo = get_fast_modinfo($course);
1404 $completioninfo = new completion_info($course);
1406 //Accessibility: replace table with list <ul>, but don't output empty list.
1407 if (!empty($section->sequence)) {
1409 // Fix bug #5027, don't want style=\"width:$width\".
1410 echo "<ul class=\"section img-text\">\n";
1411 $sectionmods = explode(",", $section->sequence);
1413 foreach ($sectionmods as $modnumber) {
1414 if (empty($mods[$modnumber])) {
1421 $mod = $mods[$modnumber];
1423 if ($ismoving and $mod->id == $USER->activitycopy) {
1424 // do not display moving mod
1428 if (isset($modinfo->cms[$modnumber])) {
1429 // We can continue (because it will not be displayed at all)
1431 // 1) The activity is not visible to users
1433 // 2a) The 'showavailability' option is not set (if that is set,
1434 // we need to display the activity so we can show
1435 // availability info)
1437 // 2b) The 'availableinfo' is empty, i.e. the activity was
1438 // hidden in a way that leaves no info, such as using the
1440 if (!$modinfo->cms[$modnumber]->uservisible &&
1441 (empty($modinfo->cms[$modnumber]->showavailability) ||
1442 empty($modinfo->cms[$modnumber]->availableinfo))) {
1443 // visibility shortcut
1447 if (!file_exists("$CFG->dirroot/mod/$mod->modname/lib.php")) {
1448 // module not installed
1451 if (!coursemodule_visible_for_user($mod) &&
1452 empty($mod->showavailability)) {
1453 // full visibility check
1458 if (!isset($modulenames[$mod->modname])) {
1459 $modulenames[$mod->modname] = get_string('modulename', $mod->modname);
1461 $modulename = $modulenames[$mod->modname];
1463 // In some cases the activity is visible to user, but it is
1464 // dimmed. This is done if viewhiddenactivities is true and if:
1465 // 1. the activity is not visible, or
1466 // 2. the activity has dates set which do not include current, or
1467 // 3. the activity has any other conditions set (regardless of whether
1468 // current user meets them)
1469 $canviewhidden = has_capability(
1470 'moodle/course:viewhiddenactivities',
1471 get_context_instance(CONTEXT_MODULE, $mod->id));
1472 $accessiblebutdim = false;
1473 if ($canviewhidden) {
1474 $accessiblebutdim = !$mod->visible;
1475 if (!empty($CFG->enableavailability)) {
1476 $accessiblebutdim = $accessiblebutdim ||
1477 $mod->availablefrom > time() ||
1478 ($mod->availableuntil && $mod->availableuntil < time()) ||
1479 count($mod->conditionsgrade) > 0 ||
1480 count($mod->conditionscompletion) > 0;
1484 $liclasses = array();
1485 $liclasses[] = 'activity';
1486 $liclasses[] = $mod->modname;
1487 $liclasses[] = 'modtype_'.$mod->modname;
1488 $extraclasses = $mod->get_extra_classes();
1489 if ($extraclasses) {
1490 $liclasses = array_merge($liclasses, explode(' ', $extraclasses));
1492 echo html_writer::start_tag('li', array('class'=>join(' ', $liclasses), 'id'=>'module-'.$modnumber));
1494 echo '<a title="'.$strmovefull.'"'.
1495 ' href="'.$CFG->wwwroot.'/course/mod.php?moveto='.$mod->id.'&sesskey='.sesskey().'">'.
1496 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1497 ' alt="'.$strmovehere.'" /></a><br />
1501 $classes = array('mod-indent');
1502 if (!empty($mod->indent)) {
1503 $classes[] = 'mod-indent-'.$mod->indent;
1504 if ($mod->indent > 15) {
1505 $classes[] = 'mod-indent-huge';
1508 echo html_writer::start_tag('div', array('class'=>join(' ', $classes)));
1510 // Get data about this course-module
1511 list($content, $instancename) =
1512 get_print_section_cm_text($modinfo->cms[$modnumber], $course);
1514 //Accessibility: for files get description via icon, this is very ugly hack!
1516 $altname = $mod->modfullname;
1517 if (!empty($customicon)) {
1518 $archetype = plugin_supports('mod', $mod->modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1519 if ($archetype == MOD_ARCHETYPE_RESOURCE) {
1520 $mimetype = mimeinfo_from_icon('type', $customicon);
1521 $altname = get_mimetype_description($mimetype);
1524 // Avoid unnecessary duplication: if e.g. a forum name already
1525 // includes the word forum (or Forum, etc) then it is unhelpful
1526 // to include that in the accessible description that is added.
1527 if (false !== strpos(textlib::strtolower($instancename),
1528 textlib::strtolower($altname))) {
1531 // File type after name, for alphabetic lists (screen reader).
1533 $altname = get_accesshide(' '.$altname);
1536 // We may be displaying this just in order to show information
1537 // about visibility, without the actual link
1539 if ($mod->uservisible) {
1540 // Nope - in this case the link is fully working for user
1543 if ($accessiblebutdim) {
1544 $linkclasses .= ' dimmed';
1545 $textclasses .= ' dimmed_text';
1546 $accesstext = '<span class="accesshide">'.
1547 get_string('hiddenfromstudents').': </span>';
1552 $linkcss = 'class="' . trim($linkclasses) . '" ';
1557 $textcss = 'class="' . trim($textclasses) . '" ';
1562 // Get on-click attribute value if specified
1563 $onclick = $mod->get_on_click();
1565 $onclick = ' onclick="' . $onclick . '"';
1568 if ($url = $mod->get_url()) {
1569 // Display link itself
1570 echo '<a ' . $linkcss . $mod->extra . $onclick .
1571 ' href="' . $url . '"><img src="' . $mod->get_icon_url() .
1572 '" class="activityicon" alt="' .
1573 $modulename . '" /> ' .
1574 $accesstext . '<span class="instancename">' .
1575 $instancename . $altname . '</span></a>';
1577 // If specified, display extra content after link
1579 $contentpart = '<div class="' . trim('contentafterlink' . $textclasses) .
1580 '">' . $content . '</div>';
1583 // No link, so display only content
1584 $contentpart = '<div ' . $textcss . $mod->extra . '>' .
1585 $accesstext . $content . '</div>';
1588 if (!empty($mod->groupingid) && has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
1589 if (!isset($groupings)) {
1590 $groupings = groups_get_all_groupings($course->id);
1592 echo " <span class=\"groupinglabel\">(".format_string($groupings[$mod->groupingid]->name).')</span>';
1595 $textclasses = $extraclasses;
1596 $textclasses .= ' dimmed_text';
1598 $textcss = 'class="' . trim($textclasses) . '" ';
1602 $accesstext = '<span class="accesshide">' .
1603 get_string('notavailableyet', 'condition') .
1606 if ($url = $mod->get_url()) {
1607 // Display greyed-out text of link
1608 echo '<div ' . $textcss . $mod->extra .
1609 ' >' . '<img src="' . $mod->get_icon_url() .
1610 '" class="activityicon" alt="' .
1612 '" /> <span>'. $instancename . $altname .
1615 // Do not display content after link when it is greyed out like this.
1617 // No link, so display only content (also greyed)
1618 $contentpart = '<div ' . $textcss . $mod->extra . '>' .
1619 $accesstext . $content . '</div>';
1623 // Module can put text after the link (e.g. forum unread)
1624 echo $mod->get_after_link();
1626 // If there is content but NO link (eg label), then display the
1627 // content here (BEFORE any icons). In this case cons must be
1628 // displayed after the content so that it makes more sense visually
1629 // and for accessibility reasons, e.g. if you have a one-line label
1630 // it should work similarly (at least in terms of ordering) to an
1637 if ($groupbuttons and plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
1638 if (! $mod->groupmodelink = $groupbuttonslink) {
1639 $mod->groupmode = $course->groupmode;
1643 $mod->groupmode = false;
1645 echo ' ';
1647 if ($sectionreturn) {
1648 echo make_editing_buttons($mod, $absolute, true, $mod->indent, $section->section);
1650 echo make_editing_buttons($mod, $absolute, true, $mod->indent, 0);
1652 echo $mod->get_after_edit_icons();
1656 $completion = $hidecompletion
1657 ? COMPLETION_TRACKING_NONE
1658 : $completioninfo->is_enabled($mod);
1659 if ($completion!=COMPLETION_TRACKING_NONE && isloggedin() &&
1660 !isguestuser() && $mod->uservisible) {
1661 $completiondata = $completioninfo->get_data($mod,true);
1662 $completionicon = '';
1664 switch ($completion) {
1665 case COMPLETION_TRACKING_MANUAL :
1666 $completionicon = 'manual-enabled'; break;
1667 case COMPLETION_TRACKING_AUTOMATIC :
1668 $completionicon = 'auto-enabled'; break;
1671 } else if ($completion==COMPLETION_TRACKING_MANUAL) {
1672 switch($completiondata->completionstate) {
1673 case COMPLETION_INCOMPLETE:
1674 $completionicon = 'manual-n'; break;
1675 case COMPLETION_COMPLETE:
1676 $completionicon = 'manual-y'; break;
1678 } else { // Automatic
1679 switch($completiondata->completionstate) {
1680 case COMPLETION_INCOMPLETE:
1681 $completionicon = 'auto-n'; break;
1682 case COMPLETION_COMPLETE:
1683 $completionicon = 'auto-y'; break;
1684 case COMPLETION_COMPLETE_PASS:
1685 $completionicon = 'auto-pass'; break;
1686 case COMPLETION_COMPLETE_FAIL:
1687 $completionicon = 'auto-fail'; break;
1690 if ($completionicon) {
1691 $imgsrc = $OUTPUT->pix_url('i/completion-'.$completionicon);
1692 $imgalt = s(get_string('completion-alt-'.$completionicon, 'completion', $mod->name));
1693 if ($completion == COMPLETION_TRACKING_MANUAL && !$isediting) {
1694 $imgtitle = s(get_string('completion-title-'.$completionicon, 'completion', $mod->name));
1696 $completiondata->completionstate==COMPLETION_COMPLETE
1697 ? COMPLETION_INCOMPLETE
1698 : COMPLETION_COMPLETE;
1699 // In manual mode the icon is a toggle form...
1701 // If this completion state is used by the
1702 // conditional activities system, we need to turn
1704 if (!empty($CFG->enableavailability) &&
1705 condition_info::completion_value_used_as_condition($course, $mod)) {
1706 $extraclass = ' preventjs';
1711 <form class='togglecompletion$extraclass' method='post' action='".$CFG->wwwroot."/course/togglecompletion.php'><div>
1712 <input type='hidden' name='id' value='{$mod->id}' />
1713 <input type='hidden' name='modulename' value='".s($mod->name)."' />
1714 <input type='hidden' name='sesskey' value='".sesskey()."' />
1715 <input type='hidden' name='completionstate' value='$newstate' />
1716 <input type='image' src='$imgsrc' alt='$imgalt' title='$imgtitle' />
1719 // In auto mode, or when editing, the icon is just an image
1720 echo "<span class='autocompletion'>";
1721 echo "<img src='$imgsrc' alt='$imgalt' title='$imgalt' /></span>";
1726 // If there is content AND a link, then display the content here
1727 // (AFTER any icons). Otherwise it was displayed before
1732 // Show availability information (for someone who isn't allowed to
1733 // see the activity itself, or for staff)
1734 if (!$mod->uservisible) {
1735 echo '<div class="availabilityinfo">'.$mod->availableinfo.'</div>';
1736 } else if ($canviewhidden && !empty($CFG->enableavailability)) {
1737 $ci = new condition_info($mod);
1738 $fullinfo = $ci->get_full_information();
1740 echo '<div class="availabilityinfo">'.get_string($mod->showavailability
1741 ? 'userrestriction_visible'
1742 : 'userrestriction_hidden','condition',
1743 $fullinfo).'</div>';
1747 echo html_writer::end_tag('div');
1748 echo html_writer::end_tag('li')."\n";
1751 } elseif ($ismoving) {
1752 echo "<ul class=\"section\">\n";
1756 echo '<li><a title="'.$strmovefull.'"'.
1757 ' href="'.$CFG->wwwroot.'/course/mod.php?movetosection='.$section->id.'&sesskey='.sesskey().'">'.
1758 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1759 ' alt="'.$strmovehere.'" /></a></li>
1762 if (!empty($section->sequence) || $ismoving) {
1763 echo "</ul><!--class='section'-->\n\n";
1768 * Prints the menus to add activities and resources.
1770 function print_section_add_menus($course, $section, $modnames, $vertical=false, $return=false) {
1771 global $CFG, $OUTPUT;
1773 // check to see if user can add menus
1774 if (!has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $course->id))) {
1778 // Retrieve all modules with associated metadata
1779 $modules = get_module_metadata($course, $modnames);
1781 // We'll sort resources and activities into two lists
1782 $resources = array();
1783 $activities = array();
1785 // We need to add the section section to the link for each module
1786 $sectionlink = '§ion=' . $section;
1788 foreach ($modules as $module) {
1789 if (isset($module->types)) {
1790 // This module has a subtype
1791 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1792 $subtypes = array();
1793 foreach ($module->types as $subtype) {
1794 $subtypes[$subtype->link . $sectionlink] = $subtype->title;
1797 // Sort module subtypes into the list
1798 if (!empty($module->title)) {
1799 // This grouping has a name
1800 if ($module->archetype == MOD_CLASS_RESOURCE) {
1801 $resources[] = array($module->title=>$subtypes);
1803 $activities[] = array($module->title=>$subtypes);
1806 // This grouping does not have a name
1807 if ($module->archetype == MOD_CLASS_RESOURCE) {
1808 $resources = array_merge($resources, $subtypes);
1810 $activities = array_merge($activities, $subtypes);
1814 // This module has no subtypes
1815 if ($module->archetype == MOD_ARCHETYPE_RESOURCE) {
1816 $resources[$module->link . $sectionlink] = $module->title;
1817 } else if ($module->archetype === MOD_ARCHETYPE_SYSTEM) {
1818 // System modules cannot be added by user, do not add to dropdown
1820 $activities[$module->link . $sectionlink] = $module->title;
1825 $straddactivity = get_string('addactivity');
1826 $straddresource = get_string('addresource');
1828 $output = '<div class="section_add_menus">';
1831 $output .= '<div class="horizontal">';
1834 if (!empty($resources)) {
1835 $select = new url_select($resources, '', array(''=>$straddresource), "ressection$section");
1836 $select->set_help_icon('resources');
1837 $output .= $OUTPUT->render($select);
1840 if (!empty($activities)) {
1841 $select = new url_select($activities, '', array(''=>$straddactivity), "section$section");
1842 $select->set_help_icon('activities');
1843 $output .= $OUTPUT->render($select);
1847 $output .= '</div>';
1850 $output .= '</div>';
1860 * Retrieve all metadata for the requested modules
1862 * @param object $course The Course
1863 * @param array $modnames An array containing the list of modules and their
1865 * @return array A list of stdClass objects containing metadata about each
1868 function get_module_metadata($course, $modnames) {
1869 global $CFG, $OUTPUT;
1871 // get_module_metadata will be called once per section on the page and courses may show
1872 // different modules to one another
1873 static $modlist = array();
1874 if (!isset($modlist[$course->id])) {
1875 $modlist[$course->id] = array();
1879 $urlbase = "/course/mod.php?id=$course->id&sesskey=".sesskey().'&add=';
1880 foreach($modnames as $modname => $modnamestr) {
1881 if (!course_allowed_module($course, $modname)) {
1884 if (isset($modlist[$modname])) {
1885 // This module is already cached
1886 $return[$modname] = $modlist[$course->id][$modname];
1890 // Include the module lib
1891 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1892 if (!file_exists($libfile)) {
1895 include_once($libfile);
1897 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1898 $gettypesfunc = $modname.'_get_types';
1899 if (function_exists($gettypesfunc)) {
1900 if ($types = $gettypesfunc()) {
1901 $group = new stdClass();
1902 $group->name = $modname;
1903 $group->icon = $OUTPUT->pix_icon('icon', '', $modname, array('class' => 'icon'));
1904 foreach($types as $type) {
1905 if ($type->typestr === '--') {
1908 if (strpos($type->typestr, '--') === 0) {
1909 $group->title = str_replace('--', '', $type->typestr);
1912 // Set the Sub Type metadata
1913 $subtype = new stdClass();
1914 $subtype->title = $type->typestr;
1915 $subtype->type = str_replace('&', '&', $type->type);
1916 $subtype->name = preg_replace('/.*type=/', '', $subtype->type);
1917 $subtype->archetype = $type->modclass;
1919 // The group archetype should match the subtype archetypes and all subtypes
1920 // should have the same archetype
1921 $group->archetype = $subtype->archetype;
1923 if (get_string_manager()->string_exists('help' . $subtype->name, $modname)) {
1924 $subtype->help = get_string('help' . $subtype->name, $modname);
1926 $subtype->link = $urlbase . $subtype->type;
1927 $group->types[] = $subtype;
1929 $modlist[$course->id][$modname] = $group;
1932 $module = new stdClass();
1933 $module->title = get_string('modulename', $modname);
1934 $module->name = $modname;
1935 $module->link = $urlbase . $modname;
1936 $module->icon = $OUTPUT->pix_icon('icon', '', $module->name, array('class' => 'icon'));
1937 if (get_string_manager()->string_exists('modulename_help', $modname)) {
1938 $module->help = get_string('modulename_help', $modname);
1940 $module->archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1941 $modlist[$course->id][$modname] = $module;
1943 $return[$modname] = $modlist[$course->id][$modname];
1950 * Return the course category context for the category with id $categoryid, except
1951 * that if $categoryid is 0, return the system context.
1953 * @param integer $categoryid a category id or 0.
1954 * @return object the corresponding context
1956 function get_category_or_system_context($categoryid) {
1958 return get_context_instance(CONTEXT_COURSECAT, $categoryid);
1960 return get_context_instance(CONTEXT_SYSTEM);
1965 * Gets the child categories of a given courses category. Uses a static cache
1966 * to make repeat calls efficient.
1968 * @param int $parentid the id of a course category.
1969 * @return array all the child course categories.
1971 function get_child_categories($parentid) {
1972 static $allcategories = null;
1974 // only fill in this variable the first time
1975 if (null == $allcategories) {
1976 $allcategories = array();
1978 $categories = get_categories();
1979 foreach ($categories as $category) {
1980 if (empty($allcategories[$category->parent])) {
1981 $allcategories[$category->parent] = array();
1983 $allcategories[$category->parent][] = $category;
1987 if (empty($allcategories[$parentid])) {
1990 return $allcategories[$parentid];
1995 * This function recursively travels the categories, building up a nice list
1996 * for display. It also makes an array that list all the parents for each
1999 * For example, if you have a tree of categories like:
2000 * Miscellaneous (id = 1)
2001 * Subcategory (id = 2)
2002 * Sub-subcategory (id = 4)
2003 * Other category (id = 3)
2004 * Then after calling this function you will have
2005 * $list = array(1 => 'Miscellaneous', 2 => 'Miscellaneous / Subcategory',
2006 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
2007 * 3 => 'Other category');
2008 * $parents = array(2 => array(1), 4 => array(1, 2));
2010 * If you specify $requiredcapability, then only categories where the current
2011 * user has that capability will be added to $list, although all categories
2012 * will still be added to $parents, and if you only have $requiredcapability
2013 * in a child category, not the parent, then the child catgegory will still be
2016 * If you specify the option $excluded, then that category, and all its children,
2017 * are omitted from the tree. This is useful when you are doing something like
2018 * moving categories, where you do not want to allow people to move a category
2019 * to be the child of itself.
2021 * @param array $list For output, accumulates an array categoryid => full category path name
2022 * @param array $parents For output, accumulates an array categoryid => list of parent category ids.
2023 * @param string/array $requiredcapability if given, only categories where the current
2024 * user has this capability will be added to $list. Can also be an array of capabilities,
2025 * in which case they are all required.
2026 * @param integer $excludeid Omit this category and its children from the lists built.
2027 * @param object $category Build the tree starting at this category - otherwise starts at the top level.
2028 * @param string $path For internal use, as part of recursive calls.
2030 function make_categories_list(&$list, &$parents, $requiredcapability = '',
2031 $excludeid = 0, $category = NULL, $path = "") {
2033 // initialize the arrays if needed
2034 if (!is_array($list)) {
2037 if (!is_array($parents)) {
2041 if (empty($category)) {
2042 // Start at the top level.
2043 $category = new stdClass;
2046 // This is the excluded category, don't include it.
2047 if ($excludeid > 0 && $excludeid == $category->id) {
2051 $context = get_context_instance(CONTEXT_COURSECAT, $category->id);
2052 $categoryname = format_string($category->name, true, array('context' => $context));
2056 $path = $path.' / '.$categoryname;
2058 $path = $categoryname;
2061 // Add this category to $list, if the permissions check out.
2062 if (empty($requiredcapability)) {
2063 $list[$category->id] = $path;
2066 $requiredcapability = (array)$requiredcapability;
2067 if (has_all_capabilities($requiredcapability, $context)) {
2068 $list[$category->id] = $path;
2073 // Add all the children recursively, while updating the parents array.
2074 if ($categories = get_child_categories($category->id)) {
2075 foreach ($categories as $cat) {
2076 if (!empty($category->id)) {
2077 if (isset($parents[$category->id])) {
2078 $parents[$cat->id] = $parents[$category->id];
2080 $parents[$cat->id][] = $category->id;
2082 make_categories_list($list, $parents, $requiredcapability, $excludeid, $cat, $path);
2088 * This function generates a structured array of courses and categories.
2090 * The depth of categories is limited by $CFG->maxcategorydepth however there
2091 * is no limit on the number of courses!
2093 * Suitable for use with the course renderers course_category_tree method:
2094 * $renderer = $PAGE->get_renderer('core','course');
2095 * echo $renderer->course_category_tree(get_course_category_tree());
2097 * @global moodle_database $DB
2101 function get_course_category_tree($id = 0, $depth = 0) {
2103 $viewhiddencats = has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_SYSTEM));
2104 $categories = get_child_categories($id);
2105 $categoryids = array();
2106 foreach ($categories as $key => &$category) {
2107 if (!$category->visible && !$viewhiddencats) {
2108 unset($categories[$key]);
2111 $categoryids[$category->id] = $category;
2112 if (empty($CFG->maxcategorydepth) || $depth <= $CFG->maxcategorydepth) {
2113 list($category->categories, $subcategories) = get_course_category_tree($category->id, $depth+1);
2114 foreach ($subcategories as $subid=>$subcat) {
2115 $categoryids[$subid] = $subcat;
2117 $category->courses = array();
2122 // This is a recursive call so return the required array
2123 return array($categories, $categoryids);
2126 // The depth is 0 this function has just been called so we can finish it off
2128 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
2129 list($catsql, $catparams) = $DB->get_in_or_equal(array_keys($categoryids));
2131 c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary,c.category
2135 WHERE c.category $catsql ORDER BY c.sortorder ASC";
2136 if ($courses = $DB->get_records_sql($sql, $catparams)) {
2137 // loop throught them
2138 foreach ($courses as $course) {
2139 if ($course->id == SITEID) {
2142 context_instance_preload($course);
2143 if (!empty($course->visible) || has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id))) {
2144 $categoryids[$course->category]->courses[$course->id] = $course;
2152 * Recursive function to print out all the categories in a nice format
2153 * with or without courses included
2155 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true) {
2158 // maxcategorydepth == 0 meant no limit
2159 if (!empty($CFG->maxcategorydepth) && $depth >= $CFG->maxcategorydepth) {
2163 if (!$displaylist) {
2164 make_categories_list($displaylist, $parentslist);
2168 if ($category->visible or has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_SYSTEM))) {
2169 print_category_info($category, $depth, $showcourses);
2171 return; // Don't bother printing children of invisible categories
2175 $category = new stdClass();
2176 $category->id = "0";
2179 if ($categories = get_child_categories($category->id)) { // Print all the children recursively
2180 $countcats = count($categories);
2184 foreach ($categories as $cat) {
2186 if ($count == $countcats) {
2189 $up = $first ? false : true;
2190 $down = $last ? false : true;
2193 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1, $showcourses);
2199 * This function will return $options array for html_writer::select(), with whitespace to denote nesting.
2201 function make_categories_options() {
2202 make_categories_list($cats,$parents);
2203 foreach ($cats as $key => $value) {
2204 if (array_key_exists($key,$parents)) {
2205 if ($indent = count($parents[$key])) {
2206 for ($i = 0; $i < $indent; $i++) {
2207 $cats[$key] = ' '.$cats[$key];
2216 * Gets the name of a course to be displayed when showing a list of courses.
2217 * By default this is just $course->fullname but user can configure it. The
2218 * result of this function should be passed through print_string.
2219 * @param object $course Moodle course object
2220 * @return string Display name of course (either fullname or short + fullname)
2222 function get_course_display_name_for_list($course) {
2224 if (!empty($CFG->courselistshortnames)) {
2225 return $course->shortname . ' ' .$course->fullname;
2227 return $course->fullname;
2232 * Prints the category info in indented fashion
2233 * This function is only used by print_whole_category_list() above
2235 function print_category_info($category, $depth=0, $showcourses = false) {
2236 global $CFG, $DB, $OUTPUT;
2238 $strsummary = get_string('summary');
2241 if (!$category->visible) {
2242 $catlinkcss = array('class'=>'dimmed');
2244 static $coursecount = null;
2245 if (null === $coursecount) {
2246 // only need to check this once
2247 $coursecount = $DB->count_records('course') <= FRONTPAGECOURSELIMIT;
2250 if ($showcourses and $coursecount) {
2251 $catimage = '<img src="'.$OUTPUT->pix_url('i/course') . '" alt="" />';
2253 $catimage = " ";
2256 $courses = get_courses($category->id, 'c.sortorder ASC', 'c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary');
2257 $context = get_context_instance(CONTEXT_COURSECAT, $category->id);
2258 $fullname = format_string($category->name, true, array('context' => $context));
2260 if ($showcourses and $coursecount) {
2261 echo '<div class="categorylist clearfix">';
2263 $cat .= html_writer::tag('div', $catimage, array('class'=>'image'));
2264 $catlink = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
2265 $cat .= html_writer::tag('div', $catlink, array('class'=>'name'));
2269 for ($i=0; $i< $depth; $i++) {
2270 $html = html_writer::tag('div', $html . $cat, array('class'=>'indentation'));
2276 echo html_writer::tag('div', $html, array('class'=>'category'));
2277 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
2279 // does the depth exceed maxcategorydepth
2280 // maxcategorydepth == 0 or unset meant no limit
2281 $limit = !(isset($CFG->maxcategorydepth) && ($depth >= $CFG->maxcategorydepth-1));
2282 if ($courses && ($limit || $CFG->maxcategorydepth == 0)) {
2283 foreach ($courses as $course) {
2285 if (!$course->visible) {
2286 $linkcss = array('class'=>'dimmed');
2289 $coursename = get_course_display_name_for_list($course);
2290 $courselink = html_writer::link(new moodle_url('/course/view.php', array('id'=>$course->id)), format_string($coursename), $linkcss);
2294 if ($icons = enrol_get_course_info_icons($course)) {
2295 foreach ($icons as $pix_icon) {
2296 $courseicon = $OUTPUT->render($pix_icon).' ';
2300 $coursecontent = html_writer::tag('div', $courseicon.$courselink, array('class'=>'name'));
2302 if ($course->summary) {
2303 $link = new moodle_url('/course/info.php?id='.$course->id);
2304 $actionlink = $OUTPUT->action_link($link, '<img alt="'.$strsummary.'" src="'.$OUTPUT->pix_url('i/info') . '" />',
2305 new popup_action('click', $link, 'courseinfo', array('height' => 400, 'width' => 500)),
2306 array('title'=>$strsummary));
2308 $coursecontent .= html_writer::tag('div', $actionlink, array('class'=>'info'));
2312 for ($i=0; $i <= $depth; $i++) {
2313 $html = html_writer::tag('div', $html . $coursecontent , array('class'=>'indentation'));
2314 $coursecontent = '';
2316 echo html_writer::tag('div', $html, array('class'=>'course clearfloat'));
2321 echo '<div class="categorylist">';
2323 $cat = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
2324 if (count($courses) > 0) {
2325 $cat .= html_writer::tag('span', ' ('.count($courses).')', array('title'=>get_string('numberofcourses'), 'class'=>'numberofcourse'));
2329 for ($i=0; $i< $depth; $i++) {
2330 $html = html_writer::tag('div', $html .$cat, array('class'=>'indentation'));
2337 echo html_writer::tag('div', $html, array('class'=>'category'));
2338 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
2344 * Print the buttons relating to course requests.
2346 * @param object $systemcontext the system context.
2348 function print_course_request_buttons($systemcontext) {
2349 global $CFG, $DB, $OUTPUT;
2350 if (empty($CFG->enablecourserequests)) {
2353 if (!has_capability('moodle/course:create', $systemcontext) && has_capability('moodle/course:request', $systemcontext)) {
2354 /// Print a button to request a new course
2355 echo $OUTPUT->single_button('request.php', get_string('requestcourse'), 'get');
2357 /// Print a button to manage pending requests
2358 if (has_capability('moodle/site:approvecourse', $systemcontext)) {
2359 $disabled = !$DB->record_exists('course_request', array());
2360 echo $OUTPUT->single_button('pending.php', get_string('coursespending'), 'get', array('disabled'=>$disabled));
2365 * Does the user have permission to edit things in this category?
2367 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2368 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
2370 function can_edit_in_category($categoryid = 0) {
2371 $context = get_category_or_system_context($categoryid);
2372 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
2376 * Prints the turn editing on/off button on course/index.php or course/category.php.
2378 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2379 * @return string HTML of the editing button, or empty string, if this user is not allowed
2382 function update_category_button($categoryid = 0) {
2383 global $CFG, $PAGE, $OUTPUT;
2385 // Check permissions.
2386 if (!can_edit_in_category($categoryid)) {
2390 // Work out the appropriate action.
2391 if ($PAGE->user_is_editing()) {
2392 $label = get_string('turneditingoff');
2395 $label = get_string('turneditingon');
2399 // Generate the button HTML.
2400 $options = array('categoryedit' => $edit, 'sesskey' => sesskey());
2402 $options['id'] = $categoryid;
2403 $page = 'category.php';
2405 $page = 'index.php';
2407 return $OUTPUT->single_button(new moodle_url('/course/' . $page, $options), $label, 'get');
2411 * Category is 0 (for all courses) or an object
2413 function print_courses($category) {
2414 global $CFG, $OUTPUT;
2416 if (!is_object($category) && $category==0) {
2417 $categories = get_child_categories(0); // Parent = 0 ie top-level categories only
2418 if (is_array($categories) && count($categories) == 1) {
2419 $category = array_shift($categories);
2420 $courses = get_courses_wmanagers($category->id,
2422 array('summary','summaryformat'));
2424 $courses = get_courses_wmanagers('all',
2426 array('summary','summaryformat'));
2430 $courses = get_courses_wmanagers($category->id,
2432 array('summary','summaryformat'));
2436 echo html_writer::start_tag('ul', array('class'=>'unlist'));
2437 foreach ($courses as $course) {
2438 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
2439 if ($course->visible == 1 || has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2440 echo html_writer::start_tag('li');
2441 print_course($course);
2442 echo html_writer::end_tag('li');
2445 echo html_writer::end_tag('ul');
2447 echo $OUTPUT->heading(get_string("nocoursesyet"));
2448 $context = get_context_instance(CONTEXT_SYSTEM);
2449 if (has_capability('moodle/course:create', $context)) {
2451 if (!empty($category->id)) {
2452 $options['category'] = $category->id;
2454 $options['category'] = $CFG->defaultrequestcategory;
2456 echo html_writer::start_tag('div', array('class'=>'addcoursebutton'));
2457 echo $OUTPUT->single_button(new moodle_url('/course/edit.php', $options), get_string("addnewcourse"));
2458 echo html_writer::end_tag('div');
2464 * Print a description of a course, suitable for browsing in a list.
2466 * @param object $course the course object.
2467 * @param string $highlightterms (optional) some search terms that should be highlighted in the display.
2469 function print_course($course, $highlightterms = '') {
2470 global $CFG, $USER, $DB, $OUTPUT;
2472 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2474 // Rewrite file URLs so that they are correct
2475 $course->summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', NULL);
2477 echo html_writer::start_tag('div', array('class'=>'coursebox clearfix'));
2478 echo html_writer::start_tag('div', array('class'=>'info'));
2479 echo html_writer::start_tag('h3', array('class'=>'name'));
2481 $linkhref = new moodle_url('/course/view.php', array('id'=>$course->id));
2483 $coursename = get_course_display_name_for_list($course);
2484 $linktext = highlight($highlightterms, format_string($coursename));
2485 $linkparams = array('title'=>get_string('entercourse'));
2486 if (empty($course->visible)) {
2487 $linkparams['class'] = 'dimmed';
2489 echo html_writer::link($linkhref, $linktext, $linkparams);
2490 echo html_writer::end_tag('h3');
2492 /// first find all roles that are supposed to be displayed
2493 if (!empty($CFG->coursecontact)) {
2494 $managerroles = explode(',', $CFG->coursecontact);
2495 $namesarray = array();
2498 if (!isset($course->managers)) {
2499 $rusers = get_role_users($managerroles, $context, true,
2500 'ra.id AS raid, u.id, u.username, u.firstname, u.lastname,
2501 r.name AS rolename, r.sortorder, r.id AS roleid',
2502 'r.sortorder ASC, u.lastname ASC');
2504 // use the managers array if we have it for perf reasosn
2505 // populate the datastructure like output of get_role_users();
2506 foreach ($course->managers as $manager) {
2507 $u = new stdClass();
2508 $u = $manager->user;
2509 $u->roleid = $manager->roleid;
2510 $u->rolename = $manager->rolename;
2516 /// Rename some of the role names if needed
2517 if (isset($context)) {
2518 $aliasnames = $DB->get_records('role_names', array('contextid'=>$context->id), '', 'roleid,contextid,name');
2521 $namesarray = array();
2522 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2523 foreach ($rusers as $ra) {
2524 if (isset($namesarray[$ra->id])) {
2525 // only display a user once with the higest sortorder role
2529 if (isset($aliasnames[$ra->roleid])) {
2530 $ra->rolename = $aliasnames[$ra->roleid]->name;
2533 $fullname = fullname($ra, $canviewfullnames);
2534 $namesarray[$ra->id] = format_string($ra->rolename).': '.
2535 html_writer::link(new moodle_url('/user/view.php', array('id'=>$ra->id, 'course'=>SITEID)), $fullname);
2538 if (!empty($namesarray)) {
2539 echo html_writer::start_tag('ul', array('class'=>'teachers'));
2540 foreach ($namesarray as $name) {
2541 echo html_writer::tag('li', $name);
2543 echo html_writer::end_tag('ul');
2546 echo html_writer::end_tag('div'); // End of info div
2548 echo html_writer::start_tag('div', array('class'=>'summary'));
2549 $options = new stdClass();
2550 $options->noclean = true;
2551 $options->para = false;
2552 $options->overflowdiv = true;
2553 if (!isset($course->summaryformat)) {
2554 $course->summaryformat = FORMAT_MOODLE;
2556 echo highlight($highlightterms, format_text($course->summary, $course->summaryformat, $options, $course->id));
2557 if ($icons = enrol_get_course_info_icons($course)) {
2558 echo html_writer::start_tag('div', array('class'=>'enrolmenticons'));
2559 foreach ($icons as $icon) {
2560 echo $OUTPUT->render($icon);
2562 echo html_writer::end_tag('div'); // End of enrolmenticons div
2564 echo html_writer::end_tag('div'); // End of summary div
2565 echo html_writer::end_tag('div'); // End of coursebox div
2569 * Prints custom user information on the home page.
2570 * Over time this can include all sorts of information
2572 function print_my_moodle() {
2573 global $USER, $CFG, $DB, $OUTPUT;
2575 if (!isloggedin() or isguestuser()) {
2576 print_error('nopermissions', '', '', 'See My Moodle');
2579 $courses = enrol_get_my_courses('summary', 'visible DESC,sortorder ASC');
2581 $rcourses = array();
2582 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
2583 $rcourses = get_my_remotecourses($USER->id);
2584 $rhosts = get_my_remotehosts();
2587 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
2589 if (!empty($courses)) {
2590 echo '<ul class="unlist">';
2591 foreach ($courses as $course) {
2592 if ($course->id == SITEID) {
2596 print_course($course);
2603 if (!empty($rcourses)) {
2604 // at the IDP, we know of all the remote courses
2605 foreach ($rcourses as $course) {
2606 print_remote_course($course, "100%");
2608 } elseif (!empty($rhosts)) {
2609 // non-IDP, we know of all the remote servers, but not courses
2610 foreach ($rhosts as $host) {
2611 print_remote_host($host, "100%");
2617 if ($DB->count_records("course") > (count($courses) + 1) ) { // Some courses not being displayed
2618 echo "<table width=\"100%\"><tr><td align=\"center\">";
2619 print_course_search("", false, "short");
2620 echo "</td><td align=\"center\">";
2621 echo $OUTPUT->single_button("$CFG->wwwroot/course/index.php", get_string("fulllistofcourses"), "get");
2622 echo "</td></tr></table>\n";
2626 if ($DB->count_records("course_categories") > 1) {
2627 echo $OUTPUT->box_start("categorybox");
2628 print_whole_category_list();
2629 echo $OUTPUT->box_end();
2637 function print_course_search($value="", $return=false, $format="plain") {
2643 $id = 'coursesearch';
2649 $strsearchcourses= get_string("searchcourses");
2651 if ($format == 'plain') {
2652 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2653 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2654 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
2655 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" value="'.s($value).'" />';
2656 $output .= '<input type="submit" value="'.get_string('go').'" />';
2657 $output .= '</fieldset></form>';
2658 } else if ($format == 'short') {
2659 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2660 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2661 $output .= '<label for="shortsearchbox">'.$strsearchcourses.': </label>';
2662 $output .= '<input type="text" id="shortsearchbox" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2663 $output .= '<input type="submit" value="'.get_string('go').'" />';
2664 $output .= '</fieldset></form>';
2665 } else if ($format == 'navbar') {
2666 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2667 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2668 $output .= '<label for="navsearchbox">'.$strsearchcourses.': </label>';
2669 $output .= '<input type="text" id="navsearchbox" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2670 $output .= '<input type="submit" value="'.get_string('go').'" />';
2671 $output .= '</fieldset></form>';
2680 function print_remote_course($course, $width="100%") {
2685 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&wantsurl=/course/view.php?id={$course->remoteid}";
2687 echo '<div class="coursebox remotecoursebox clearfix">';
2688 echo '<div class="info">';
2689 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2690 $linkcss.' href="'.$url.'">'
2691 . format_string($course->fullname) .'</a><br />'
2692 . format_string($course->hostname) . ' : '
2693 . format_string($course->cat_name) . ' : '
2694 . format_string($course->shortname). '</div>';
2695 echo '</div><div class="summary">';
2696 $options = new stdClass();
2697 $options->noclean = true;
2698 $options->para = false;
2699 $options->overflowdiv = true;
2700 echo format_text($course->summary, $course->summaryformat, $options);
2705 function print_remote_host($host, $width="100%") {
2710 echo '<div class="coursebox clearfix">';
2711 echo '<div class="info">';
2712 echo '<div class="name">';
2713 echo '<img src="'.$OUTPUT->pix_url('i/mnethost') . '" class="icon" alt="'.get_string('course').'" />';
2714 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2715 . s($host['name']).'</a> - ';
2716 echo $host['count'] . ' ' . get_string('courses');
2723 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2725 function add_course_module($mod) {
2728 $mod->added = time();
2731 return $DB->insert_record("course_modules", $mod);
2735 * Returns course section - creates new if does not exist yet.
2736 * @param int $relative section number
2737 * @param int $courseid
2738 * @return object $course_section object
2740 function get_course_section($section, $courseid) {
2743 if ($cw = $DB->get_record("course_sections", array("section"=>$section, "course"=>$courseid))) {
2746 $cw = new stdClass();
2747 $cw->course = $courseid;
2748 $cw->section = $section;
2750 $cw->summaryformat = FORMAT_HTML;
2752 $id = $DB->insert_record("course_sections", $cw);
2753 return $DB->get_record("course_sections", array("id"=>$id));
2756 * Given a full mod object with section and course already defined, adds this module to that section.
2758 * @param object $mod
2759 * @param int $beforemod An existing ID which we will insert the new module before
2760 * @return int The course_sections ID where the mod is inserted
2762 function add_mod_to_section($mod, $beforemod=NULL) {
2765 if ($section = $DB->get_record("course_sections", array("course"=>$mod->course, "section"=>$mod->section))) {
2767 $section->sequence = trim($section->sequence);
2769 if (empty($section->sequence)) {
2770 $newsequence = "$mod->coursemodule";
2772 } else if ($beforemod) {
2773 $modarray = explode(",", $section->sequence);
2775 if ($key = array_keys($modarray, $beforemod->id)) {
2776 $insertarray = array($mod->id, $beforemod->id);
2777 array_splice($modarray, $key[0], 1, $insertarray);
2778 $newsequence = implode(",", $modarray);
2780 } else { // Just tack it on the end anyway
2781 $newsequence = "$section->sequence,$mod->coursemodule";
2785 $newsequence = "$section->sequence,$mod->coursemodule";
2788 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
2789 return $section->id; // Return course_sections ID that was used.
2791 } else { // Insert a new record
2792 $section = new stdClass();
2793 $section->course = $mod->course;
2794 $section->section = $mod->section;
2795 $section->summary = "";
2796 $section->summaryformat = FORMAT_HTML;
2797 $section->sequence = $mod->coursemodule;
2798 return $DB->insert_record("course_sections", $section);
2802 function set_coursemodule_groupmode($id, $groupmode) {
2804 return $DB->set_field("course_modules", "groupmode", $groupmode, array("id"=>$id));
2807 function set_coursemodule_idnumber($id, $idnumber) {
2809 return $DB->set_field("course_modules", "idnumber", $idnumber, array("id"=>$id));
2813 * $prevstateoverrides = true will set the visibility of the course module
2814 * to what is defined in visibleold. This enables us to remember the current
2815 * visibility when making a whole section hidden, so that when we toggle
2816 * that section back to visible, we are able to return the visibility of
2817 * the course module back to what it was originally.
2819 function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
2821 require_once($CFG->libdir.'/gradelib.php');
2823 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2826 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
2829 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2830 foreach($events as $event) {
2839 // hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there
2840 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
2842 foreach ($grade_items as $grade_item) {
2843 $grade_item->set_hidden(!$visible);
2847 if ($prevstateoverrides) {
2848 if ($visible == '0') {
2849 // Remember the current visible state so we can toggle this back.
2850 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id'=>$id));
2852 // Get the previous saved visible states.
2853 return $DB->set_field('course_modules', 'visible', $cm->visibleold, array('id'=>$id));
2856 return $DB->set_field("course_modules", "visible", $visible, array("id"=>$id));
2860 * Delete a course module and any associated data at the course level (events)
2861 * Until 1.5 this function simply marked a deleted flag ... now it
2862 * deletes it completely.
2865 function delete_course_module($id) {
2867 require_once($CFG->libdir.'/gradelib.php');
2868 require_once($CFG->dirroot.'/blog/lib.php');
2870 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2873 $modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module));
2874 //delete events from calendar
2875 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2876 foreach($events as $event) {
2877 delete_event($event->id);
2880 //delete grade items, outcome items and grades attached to modules
2881 if ($grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2882 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course))) {
2883 foreach ($grade_items as $grade_item) {
2884 $grade_item->delete('moddelete');
2887 // Delete completion and availability data; it is better to do this even if the
2888 // features are not turned on, in case they were turned on previously (these will be
2889 // very quick on an empty table)
2890 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
2891 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id));
2892 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
2893 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
2895 delete_context(CONTEXT_MODULE, $cm->id);
2896 return $DB->delete_records('course_modules', array('id'=>$cm->id));
2899 function delete_mod_from_section($mod, $section) {
2902 if ($section = $DB->get_record("course_sections", array("id"=>$section)) ) {
2904 $modarray = explode(",", $section->sequence);
2906 if ($key = array_keys ($modarray, $mod)) {
2907 array_splice($modarray, $key[0], 1);
2908 $newsequence = implode(",", $modarray);
2909 return $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
2919 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
2921 * @param object $course course object
2922 * @param int $section Section number (not id!!!)
2923 * @param int $move (-1 or 1)
2924 * @return boolean true if section moved successfully
2926 function move_section($course, $section, $move) {
2927 /// Moves a whole course section up and down within the course
2934 $sectiondest = $section + $move;
2936 if ($sectiondest > $course->numsections or $sectiondest < 1) {
2940 if (!$sectionrecord = $DB->get_record("course_sections", array("course"=>$course->id, "section"=>$section))) {
2944 if (!$sectiondestrecord = $DB->get_record("course_sections", array("course"=>$course->id, "section"=>$sectiondest))) {
2948 // Three-step change ensures that the section always remains unique (there is
2949 // a unique index now)
2950 $DB->set_field("course_sections", "section", -$sectiondest, array("id"=>$sectionrecord->id));
2951 $DB->set_field("course_sections", "section", $section, array("id"=>$sectiondestrecord->id));
2952 $DB->set_field("course_sections", "section", $sectiondest, array("id"=>$sectionrecord->id));
2954 // Update highlighting if the move affects highlighted section
2955 if ($course->marker == $section) {
2956 course_set_marker($course->id, $sectiondest);
2957 } elseif ($course->marker == $sectiondest) {
2958 course_set_marker($course->id, $section);
2962 // Fix order if needed. The database prevents duplicate sections, but it is
2963 // possible there could be a gap in the numbering.
2964 $sections = $DB->get_records('course_sections', array('course'=>$course->id), 'section ASC');
2966 foreach ($sections as $section) {
2967 if ($section->section != $n) {
2968 $DB->set_field('course_sections', 'section', $n, array('id'=>$section->id));
2976 * Moves a section within a course, from a position to another.
2977 * Be very careful: $section and $destination refer to section number,
2980 * @param object $course
2981 * @param int $section Section number (not id!!!)
2982 * @param int $destination
2983 * @return boolean Result
2985 function move_section_to($course, $section, $destination) {
2986 /// Moves a whole course section up and down within the course
2989 if (!$destination && $destination != 0) {
2993 if ($destination > $course->numsections) {
2997 // Get all sections for this course and re-order them (2 of them should now share the same section number)
2998 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
2999 'section ASC, id ASC', 'id, section')) {
3003 $movedsections = reorder_sections($sections, $section, $destination);
3005 // Update all sections. Do this in 2 steps to avoid breaking database
3006 // uniqueness constraint
3007 $transaction = $DB->start_delegated_transaction();
3008 foreach ($movedsections as $id => $position) {
3009 if ($sections[$id] !== $position) {
3010 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
3013 foreach ($movedsections as $id => $position) {
3014 if ($sections[$id] !== $position) {
3015 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
3019 // Adjust destination to reflect the actual section
3021 if ($section > $destination) {
3026 // If we move the highlighted section itself, then just highlight the destination.
3027 // Adjust the higlighted section location if we move something over it either direction.
3028 if ($section == $course->marker) {
3029 course_set_marker($course, $destination);
3030 } elseif ($moveup && $section > $course->marker && $course->marker >= $destination) {
3031 course_set_marker($course, $course->marker+1);
3032 } elseif (!$moveup && $section < $course->marker && $course->marker <= $destination) {
3033 course_set_marker($course, $course->marker-1);
3036 $transaction->allow_commit();
3041 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
3042 * an original position number and a target position number, rebuilds the array so that the
3043 * move is made without any duplication of section positions.
3044 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
3045 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
3047 * @param array $sections
3048 * @param int $origin_position
3049 * @param int $target_position
3052 function reorder_sections($sections, $origin_position, $target_position) {
3053 if (!is_array($sections)) {
3057 // We can't move section position 0
3058 if ($origin_position < 1) {
3059 echo "We can't move section position 0";
3063 // Locate origin section in sections array
3064 if (!$origin_key = array_search($origin_position, $sections)) {
3065 echo "searched position not in sections array";
3066 return false; // searched position not in sections array
3069 // Extract origin section
3070 $origin_section = $sections[$origin_key];
3071 unset($sections[$origin_key]);
3073 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
3075 $append_array = array();
3076 foreach ($sections as $id => $position) {
3078 $append_array[$id] = $position;
3079 unset($sections[$id]);
3081 if ($position == $target_position) {
3086 // Append moved section
3087 $sections[$origin_key] = $origin_section;
3089 // Append rest of array (if applicable)
3090 if (!empty($append_array)) {
3091 foreach ($append_array as $id => $position) {
3092 $sections[$id] = $position;
3096 // Renumber positions
3098 foreach ($sections as $id => $p) {
3099 $sections[$id] = $position;
3108 * Move the module object $mod to the specified $section
3109 * If $beforemod exists then that is the module
3110 * before which $modid should be inserted
3111 * All parameters are objects
3113 function moveto_module($mod, $section, $beforemod=NULL) {
3114 global $DB, $OUTPUT;
3116 /// Remove original module from original section
3117 if (! delete_mod_from_section($mod->id, $mod->section)) {
3118 echo $OUTPUT->notification("Could not delete module from existing section");
3121 /// Update module itself if necessary
3123 if ($mod->section != $section->id) {
3124 $mod->section = $section->id;
3125 $DB->update_record("course_modules", $mod);
3126 // if moving to a hidden section then hide module
3127 if (!$section->visible) {
3128 set_coursemodule_visible($mod->id, 0);
3132 /// Add the module into the new section
3134 $mod->course = $section->course;
3135 $mod->section = $section->section; // need relative reference
3136 $mod->coursemodule = $mod->id;
3138 if (! add_mod_to_section($mod, $beforemod)) {
3146 * Produces the editing buttons for a module
3148 * @global core_renderer $OUTPUT
3149 * @staticvar type $str
3150 * @param stdClass $mod The module to produce editing buttons for
3151 * @param bool $absolute_ignored ignored - all links are absolute
3152 * @param bool $moveselect If true a move seleciton process is used (default true)
3153 * @param int $indent The current indenting
3154 * @param int $section The section to link back to
3155 * @return string XHTML for the editing buttons
3157 function make_editing_buttons(stdClass $mod, $absolute_ignored = true, $moveselect = true, $indent=-1, $section=-1) {
3158 global $CFG, $OUTPUT;
3162 $coursecontext = get_context_instance(CONTEXT_COURSE, $mod->course);
3163 $modcontext = get_context_instance(CONTEXT_MODULE, $mod->id);
3165 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
3166 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
3168 // no permission to edit anything
3169 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
3173 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
3176 $str = new stdClass;
3177 $str->assign = get_string("assignroles", 'role');
3178 $str->delete = get_string("delete");
3179 $str->move = get_string("move");
3180 $str->moveup = get_string("moveup");
3181 $str->movedown = get_string("movedown");
3182 $str->moveright = get_string("moveright");
3183 $str->moveleft = get_string("moveleft");
3184 $str->update = get_string("update");
3185 $str->duplicate = get_string("duplicate");
3186 $str->hide = get_string("hide");
3187 $str->show = get_string("show");
3188 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
3189 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
3190 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
3191 $str->forcedgroupsnone = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsnone"));
3192 $str->forcedgroupsseparate = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsseparate"));
3193 $str->forcedgroupsvisible = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsvisible"));
3196 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
3198 if ($section >= 0) {
3199 $baseurl->param('sr', $section);
3204 if ($hasmanageactivities) {
3205 if (right_to_left()) { // Exchange arrows on RTL
3206 $rightarrow = 't/left';
3207 $leftarrow = 't/right';
3209 $rightarrow = 't/right';
3210 $leftarrow = 't/left';
3214 $actions[] = new action_link(
3215 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
3216 new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall')),
3218 array('class' => 'editing_moveleft', 'title' => $str->moveleft)
3222 $actions[] = new action_link(
3223 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
3224 new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall')),
3226 array('class' => 'editing_moveright', 'title' => $str->moveright)
3232 if ($hasmanageactivities) {
3234 $actions[] = new action_link(
3235 new moodle_url($baseurl, array('copy' => $mod->id)),
3236 new pix_icon('t/move', $str->move, 'moodle', array('class' => 'iconsmall')),
3238 array('class' => 'editing_move', 'title' => $str->move)
3241 $actions[] = new action_link(
3242 new moodle_url($baseurl, array('id' => $mod->id, 'move' => '-1')),
3243 new pix_icon('t/up', $str->moveup, 'moodle', array('class' => 'iconsmall')),
3245 array('class' => 'editing_moveup', 'title' => $str->moveup)
3247 $actions[] = new action_link(
3248 new moodle_url($baseurl, array('id' => $mod->id, 'move' => '1')),
3249 new pix_icon('t/down', $str->movedown, 'moodle', array('class' => 'iconsmall')),
3251 array('class' => 'editing_movedown', 'title' => $str->movedown)
3257 if ($hasmanageactivities) {
3258 $actions[] = new action_link(
3259 new moodle_url($baseurl, array('update' => $mod->id)),
3260 new pix_icon('t/edit', $str->update, 'moodle', array('class' => 'iconsmall')),
3262 array('class' => 'editing_update', 'title' => $str->update)
3266 // Duplicate (require both target import caps to be able to duplicate, see modduplicate.php)
3267 if (has_all_capabilities($dupecaps, $coursecontext)) {
3268 $actions[] = new action_link(
3269 new moodle_url($baseurl, array('duplicate' => $mod->id)),
3270 new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall')),
3272 array('class' => 'editing_duplicate', 'title' => $str->duplicate)
3277 if ($hasmanageactivities) {
3278 $actions[] = new action_link(
3279 new moodle_url($baseurl, array('delete' => $mod->id)),
3280 new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall')),
3282 array('class' => 'editing_delete', 'title' => $str->delete)
3287 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
3288 if ($mod->visible) {
3289 $actions[] = new action_link(
3290 new moodle_url($baseurl, array('hide' => $mod->id)),
3291 new pix_icon('t/hide', $str->hide, 'moodle', array('class' => 'iconsmall')),
3293 array('class' => 'editing_hide', 'title' => $str->hide)
3296 $actions[] = new action_link(
3297 new moodle_url($baseurl, array('show' => $mod->id)),
3298 new pix_icon('t/show', $str->show, 'moodle', array('class' => 'iconsmall')),
3300 array('class' => 'editing_show', 'title' => $str->show)
3306 if ($hasmanageactivities and $mod->groupmode !== false) {
3307 if ($mod->groupmode == SEPARATEGROUPS) {
3309 $grouptitle = $str->groupsseparate;
3310 $forcedgrouptitle = $str->forcedgroupsseparate;
3311 $groupclass = 'editing_groupsseparate';
3312 $groupimage = 't/groups';
3313 } else if ($mod->groupmode == VISIBLEGROUPS) {
3315 $grouptitle = $str->groupsvisible;
3316 $forcedgrouptitle = $str->forcedgroupsvisible;
3317 $groupclass = 'editing_groupsvisible';
3318 $groupimage = 't/groupv';
3321 $grouptitle = $str->groupsnone;
3322 $forcedgrouptitle = $str->forcedgroupsnone;
3323 $groupclass = 'editing_groupsnone';
3324 $groupimage = 't/groupn';
3326 if ($mod->groupmodelink) {
3327 $actions[] = new action_link(
3328 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $groupmode)),
3329 new pix_icon($groupimage, $grouptitle, 'moodle', array('class' => 'iconsmall')),
3331 array('class' => $groupclass, 'title' => $grouptitle)
3334 $actions[] = new pix_icon($groupimage, $forcedgrouptitle, 'moodle', array('title' => $forcedgrouptitle, 'class' => 'iconsmall'));
3339 if (has_capability('moodle/role:assign', $modcontext)){
3340 $actions[] = new action_link(
3341 new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $modcontext->id)),
3342 new pix_icon('i/roles', $str->assign, 'moodle', array('class' => 'iconsmall')),
3344 array('class' => 'editing_assign', 'title' => $str->assign)
3348 $output = html_writer::start_tag('span', array('class' => 'commands'));
3349 foreach ($actions as $action) {
3350 if ($action instanceof renderable) {
3351 $output .= $OUTPUT->render($action);
3356 $output .= html_writer::end_tag('span');
3361 * given a course object with shortname & fullname, this function will
3362 * truncate the the number of chars allowed and add ... if it was too long
3364 function course_format_name ($course,$max=100) {
3366 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3367 $shortname = format_string($course->shortname, true, array('context' => $context));
3368 $fullname = format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
3369 $str = $shortname.': '. $fullname;
3370 if (textlib::strlen($str) <= $max) {
3374 return textlib::substr($str,0,$max-3).'...';
3379 * Is the user allowed to add this type of module to this course?
3380 * @param object $course the course settings. Only $course->id is used.
3381 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
3382 * @return bool whether the current user is allowed to add this type of module to this course.
3384 function course_allowed_module($course, $modname) {
3387 if (is_numeric($modname)) {
3388 throw new coding_exception('Function course_allowed_module no longer
3389 supports numeric module ids. Please update your code to pass the module name.');
3392 $capability = 'mod/' . $modname . ':addinstance';
3393 if (!get_capability_info($capability)) {
3394 // Debug warning that the capability does not exist, but no more than once per page.
3395 static $warned = array();
3396 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
3397 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
3398 debugging('The module ' . $modname . ' does not define the standard capability ' .
3399 $capability , DEBUG_DEVELOPER);
3400 $warned[$modname] = 1;
3403 // If the capability does not exist, the module can always be added.
3407 $coursecontext = context_course::instance($course->id);
3408 return has_capability($capability, $coursecontext);
3412 * Recursively delete category including all subcategories and courses.
3413 * @param stdClass $category
3414 * @param boolean $showfeedback display some notices
3415 * @return array return deleted courses
3417 function category_delete_full($category, $showfeedback=true) {
3419 require_once($CFG->libdir.'/gradelib.php');
3420 require_once($CFG->libdir.'/questionlib.php');
3421 require_once($CFG->dirroot.'/cohort/lib.php');
3423 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3424 foreach ($children as $childcat) {
3425 category_delete_full($childcat, $showfeedback);
3429 $deletedcourses = array();
3430 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC')) {
3431 foreach ($courses as $course) {
3432 if (!delete_course($course, false)) {
3433 throw new moodle_exception('cannotdeletecategorycourse','','',$course->shortname);
3435 $deletedcourses[] = $course;
3439 // move or delete cohorts in this context
3440 cohort_delete_category($category);
3442 // now delete anything that may depend on course category context
3443 grade_course_category_delete($category->id, 0, $showfeedback);
3444 if (!question_delete_course_category($category, 0, $showfeedback)) {
3445 throw new moodle_exception('cannotdeletecategoryquestions','','',$category->name);
3448 // finally delete the category and it's context
3449 $DB->delete_records('course_categories', array('id'=>$category->id));
3450 delete_context(CONTEXT_COURSECAT, $category->id);
3452 events_trigger('course_category_deleted', $category);
3454 return $deletedcourses;
3458 * Delete category, but move contents to another category.
3459 * @param object $ccategory
3460 * @param int $newparentid category id
3461 * @return bool status
3463 function category_delete_move($category, $newparentid, $showfeedback=true) {
3464 global $CFG, $DB, $OUTPUT;
3465 require_once($CFG->libdir.'/gradelib.php');
3466 require_once($CFG->libdir.'/questionlib.php');
3467 require_once($CFG->dirroot.'/cohort/lib.php');
3469 if (!$newparentcat = $DB->get_record('course_categories', array('id'=>$newparentid))) {
3473 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3474 foreach ($children as $childcat) {
3475 move_category($childcat, $newparentcat);
3479 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC', 'id')) {
3480 if (!move_courses(array_keys($courses), $newparentid)) {
3481 echo $OUTPUT->notification("Error moving courses");
3484 echo $OUTPUT->notification(get_string('coursesmovedout', '', format_string($category->name)), 'notifysuccess');
3487 // move or delete cohorts in this context
3488 cohort_delete_category($category);
3490 // now delete anything that may depend on course category context
3491 grade_course_category_delete($category->id, $newparentid, $showfeedback);
3492 if (!question_delete_course_category($category, $newparentcat, $showfeedback)) {