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');
31 require_once($CFG->dirroot.'/course/dnduploadlib.php');
33 define('COURSE_MAX_LOGS_PER_PAGE', 1000); // records
34 define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds
35 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10); // courses
36 define('COURSE_MAX_COURSES_PER_DROPDOWN',1000); // max courses in log dropdown before switching to optional
37 define('COURSE_MAX_USERS_PER_DROPDOWN',1000); // max users in log dropdown before switching to optional
38 define('FRONTPAGENEWS', '0');
39 define('FRONTPAGECOURSELIST', '1');
40 define('FRONTPAGECATEGORYNAMES', '2');
41 define('FRONTPAGETOPICONLY', '3');
42 define('FRONTPAGECATEGORYCOMBO', '4');
43 define('FRONTPAGECOURSELIMIT', 200); // maximum number of courses displayed on the frontpage
44 define('EXCELROWS', 65535);
45 define('FIRSTUSEDEXCELROW', 3);
47 define('MOD_CLASS_ACTIVITY', 0);
48 define('MOD_CLASS_RESOURCE', 1);
50 function make_log_url($module, $url) {
53 if (strpos($url, 'report/') === 0) {
54 // there is only one report type, course reports are deprecated
64 if (strpos($url, '../') === 0) {
65 $url = ltrim($url, '.');
67 $url = "/course/$url";
72 $url = "/$module/$url";
85 $url = "/message/$url";
97 $url = "/mod/$module/$url";
101 //now let's sanitise urls - there might be some ugly nasties:-(
102 $parts = explode('?', $url);
103 $script = array_shift($parts);
104 if (strpos($script, 'http') === 0) {
105 $script = clean_param($script, PARAM_URL);
107 $script = clean_param($script, PARAM_PATH);
112 $query = implode('', $parts);
113 $query = str_replace('&', '&', $query); // both & and & are stored in db :-|
114 $parts = explode('&', $query);
115 $eq = urlencode('=');
116 foreach ($parts as $key=>$part) {
117 $part = urlencode(urldecode($part));
118 $part = str_replace($eq, '=', $part);
119 $parts[$key] = $part;
121 $query = '?'.implode('&', $parts);
124 return $script.$query;
128 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
129 $modname="", $modid=0, $modaction="", $groupid=0) {
132 // It is assumed that $date is the GMT time of midnight for that day,
133 // and so the next 86400 seconds worth of logs are printed.
135 /// Setup for group handling.
137 // TODO: I don't understand group/context/etc. enough to be able to do
138 // something interesting with it here
139 // What is the context of a remote course?
141 /// If the group mode is separate, and this user does not have editing privileges,
142 /// then only the user's group can be viewed.
143 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
144 // $groupid = get_current_group($course->id);
146 /// If this course doesn't have groups, no groupid can be specified.
147 //else if (!$course->groupmode) {
156 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
158 LEFT JOIN {user} u ON l.userid = u.id
162 $where .= "l.hostid = :hostid";
163 $params['hostid'] = $hostid;
165 // TODO: Is 1 really a magic number referring to the sitename?
166 if ($course != SITEID || $modid != 0) {
167 $where .= " AND l.course=:courseid";
168 $params['courseid'] = $course;
172 $where .= " AND l.module = :modname";
173 $params['modname'] = $modname;
176 if ('site_errors' === $modid) {
177 $where .= " AND ( l.action='error' OR l.action='infected' )";
179 //TODO: This assumes that modids are the same across sites... probably
181 $where .= " AND l.cmid = :modid";
182 $params['modid'] = $modid;
186 $firstletter = substr($modaction, 0, 1);
187 if ($firstletter == '-') {
188 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
189 $params['modaction'] = '%'.substr($modaction, 1).'%';
191 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
192 $params['modaction'] = '%'.$modaction.'%';
197 $where .= " AND l.userid = :user";
198 $params['user'] = $user;
202 $enddate = $date + 86400;
203 $where .= " AND l.time > :date AND l.time < :enddate";
204 $params['date'] = $date;
205 $params['enddate'] = $enddate;
209 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
210 if(!empty($result['totalcount'])) {
211 $where .= " ORDER BY $order";
212 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
214 $result['logs'] = array();
219 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
220 $modname="", $modid=0, $modaction="", $groupid=0) {
221 global $DB, $SESSION, $USER;
222 // It is assumed that $date is the GMT time of midnight for that day,
223 // and so the next 86400 seconds worth of logs are printed.
225 /// Setup for group handling.
227 /// If the group mode is separate, and this user does not have editing privileges,
228 /// then only the user's group can be viewed.
229 if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
230 if (isset($SESSION->currentgroup[$course->id])) {
231 $groupid = $SESSION->currentgroup[$course->id];
233 $groupid = groups_get_all_groups($course->id, $USER->id);
234 if (is_array($groupid)) {
235 $groupid = array_shift(array_keys($groupid));
236 $SESSION->currentgroup[$course->id] = $groupid;
242 /// If this course doesn't have groups, no groupid can be specified.
243 else if (!$course->groupmode) {
250 if ($course->id != SITEID || $modid != 0) {
251 $joins[] = "l.course = :courseid";
252 $params['courseid'] = $course->id;
256 $joins[] = "l.module = :modname";
257 $params['modname'] = $modname;
260 if ('site_errors' === $modid) {
261 $joins[] = "( l.action='error' OR l.action='infected' )";
263 $joins[] = "l.cmid = :modid";
264 $params['modid'] = $modid;
268 $firstletter = substr($modaction, 0, 1);
269 if ($firstletter == '-') {
270 $joins[] = $DB->sql_like('l.action', ':modaction', false, true, true);
271 $params['modaction'] = '%'.substr($modaction, 1).'%';
273 $joins[] = $DB->sql_like('l.action', ':modaction', false);
274 $params['modaction'] = '%'.$modaction.'%';
279 /// Getting all members of a group.
280 if ($groupid and !$user) {
281 if ($gusers = groups_get_members($groupid)) {
282 $gusers = array_keys($gusers);
283 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
285 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
289 $joins[] = "l.userid = :userid";
290 $params['userid'] = $user;
294 $enddate = $date + 86400;
295 $joins[] = "l.time > :date AND l.time < :enddate";
296 $params['date'] = $date;
297 $params['enddate'] = $enddate;
300 $selector = implode(' AND ', $joins);
302 $totalcount = 0; // Initialise
304 $result['logs'] = get_logs($selector, $params, $order, $limitfrom, $limitnum, $totalcount);
305 $result['totalcount'] = $totalcount;
310 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
311 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
313 global $CFG, $DB, $OUTPUT;
315 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
316 $modname, $modid, $modaction, $groupid)) {
317 echo $OUTPUT->notification("No logs found!");
318 echo $OUTPUT->footer();
324 if ($course->id == SITEID) {
326 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
327 foreach ($ccc as $cc) {
328 $courses[$cc->id] = $cc->shortname;
332 $courses[$course->id] = $course->shortname;
335 $totalcount = $logs['totalcount'];
338 $tt = getdate(time());
339 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
341 $strftimedatetime = get_string("strftimedatetime");
343 echo "<div class=\"info\">\n";
344 print_string("displayingrecords", "", $totalcount);
347 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
349 $table = new html_table();
350 $table->classes = array('logtable','generalbox');
351 $table->align = array('right', 'left', 'left');
352 $table->head = array(
354 get_string('ip_address'),
355 get_string('fullnameuser'),
356 get_string('action'),
359 $table->data = array();
361 if ($course->id == SITEID) {
362 array_unshift($table->align, 'left');
363 array_unshift($table->head, get_string('course'));
366 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
367 if (empty($logs['logs'])) {
368 $logs['logs'] = array();
371 foreach ($logs['logs'] as $log) {
373 if (isset($ldcache[$log->module][$log->action])) {
374 $ld = $ldcache[$log->module][$log->action];
376 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
377 $ldcache[$log->module][$log->action] = $ld;
379 if ($ld && is_numeric($log->info)) {
380 // ugly hack to make sure fullname is shown correctly
381 if ($ld->mtable == 'user' && $ld->field == $DB->sql_concat('firstname', "' '" , 'lastname')) {
382 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
384 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
389 $log->info = format_string($log->info);
391 // If $log->url has been trimmed short by the db size restriction
392 // code in add_to_log, keep a note so we don't add a link to a broken url
393 $brokenurl=(textlib::strlen($log->url)==100 && textlib::substr($log->url,97)=='...');
396 if ($course->id == SITEID) {
397 if (empty($log->course)) {
398 $row[] = get_string('site');
400 $row[] = "<a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course])."</a>";
404 $row[] = userdate($log->time, '%a').' '.userdate($log->time, $strftimedatetime);
406 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
407 $row[] = $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 440, 'width' => 700)));
409 $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))));
411 $displayaction="$log->module $log->action";
413 $row[] = $displayaction;
415 $link = make_log_url($log->module,$log->url);
416 $row[] = $OUTPUT->action_link($link, $displayaction, new popup_action('click', $link, 'fromloglive'), array('height' => 440, 'width' => 700));
419 $table->data[] = $row;
422 echo html_writer::table($table);
423 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
427 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
428 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
430 global $CFG, $DB, $OUTPUT;
432 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
433 $modname, $modid, $modaction, $groupid)) {
434 echo $OUTPUT->notification("No logs found!");
435 echo $OUTPUT->footer();
439 if ($course->id == SITEID) {
441 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
442 foreach ($ccc as $cc) {
443 $courses[$cc->id] = $cc->shortname;
448 $totalcount = $logs['totalcount'];
451 $tt = getdate(time());
452 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
454 $strftimedatetime = get_string("strftimedatetime");
456 echo "<div class=\"info\">\n";
457 print_string("displayingrecords", "", $totalcount);
460 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
462 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
464 if ($course->id == SITEID) {
465 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
467 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
468 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
469 echo "<th class=\"c3 header\">".get_string('fullnameuser')."</th>\n";
470 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
471 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
474 if (empty($logs['logs'])) {
480 foreach ($logs['logs'] as $log) {
482 $log->info = $log->coursename;
483 $row = ($row + 1) % 2;
485 if (isset($ldcache[$log->module][$log->action])) {
486 $ld = $ldcache[$log->module][$log->action];
488 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
489 $ldcache[$log->module][$log->action] = $ld;
491 if (0 && $ld && !empty($log->info)) {
492 // ugly hack to make sure fullname is shown correctly
493 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
494 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
496 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
501 $log->info = format_string($log->info);
503 echo '<tr class="r'.$row.'">';
504 if ($course->id == SITEID) {
505 $courseshortname = format_string($courses[$log->course], true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
506 echo "<td class=\"r$row c0\" >\n";
507 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courseshortname."</a>\n";
510 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time, '%a').
511 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
512 echo "<td class=\"r$row c2\" >\n";
513 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
514 echo $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 400, 'width' => 700)));
516 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
517 echo "<td class=\"r$row c3\" >\n";
518 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
520 echo "<td class=\"r$row c4\">\n";
521 echo $log->action .': '.$log->module;
523 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
528 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
532 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
533 $modid, $modaction, $groupid) {
536 $text = get_string('course')."\t".get_string('time')."\t".get_string('ip_address')."\t".
537 get_string('fullnameuser')."\t".get_string('action')."\t".get_string('info');
539 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
540 $modname, $modid, $modaction, $groupid)) {
546 if ($course->id == SITEID) {
548 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
549 foreach ($ccc as $cc) {
550 $courses[$cc->id] = $cc->shortname;
554 $courses[$course->id] = $course->shortname;
559 $tt = getdate(time());
560 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
562 $strftimedatetime = get_string("strftimedatetime");
564 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
566 header("Content-Type: application/download\n");
567 header("Content-Disposition: attachment; filename=\"$filename\"");
568 header("Expires: 0");
569 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
570 header("Pragma: public");
572 echo get_string('savedat').userdate(time(), $strftimedatetime)."\n";
575 if (empty($logs['logs'])) {
579 foreach ($logs['logs'] as $log) {
580 if (isset($ldcache[$log->module][$log->action])) {
581 $ld = $ldcache[$log->module][$log->action];
583 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
584 $ldcache[$log->module][$log->action] = $ld;
586 if ($ld && is_numeric($log->info)) {
587 // ugly hack to make sure fullname is shown correctly
588 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
589 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
591 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
596 $log->info = format_string($log->info);
597 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
599 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
600 $firstField = format_string($courses[$log->course], true, array('context' => $coursecontext));
601 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
602 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action, $log->info);
603 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
604 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action.' ('.$actionurl.')', $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 && is_numeric($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 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
716 $myxls->write($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')', '');
717 $myxls->write($row, 5, $log->info, '');
726 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
727 $modid, $modaction, $groupid) {
731 require_once("$CFG->libdir/odslib.class.php");
733 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
734 $modname, $modid, $modaction, $groupid)) {
740 if ($course->id == SITEID) {
742 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
743 foreach ($ccc as $cc) {
744 $courses[$cc->id] = $cc->shortname;
748 $courses[$course->id] = $course->shortname;
753 $tt = getdate(time());
754 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
756 $strftimedatetime = get_string("strftimedatetime");
758 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
759 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
762 $workbook = new MoodleODSWorkbook('-');
763 $workbook->send($filename);
765 $worksheet = array();
766 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
767 get_string('fullnameuser'), get_string('action'), get_string('info'));
769 // Creating worksheets
770 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
771 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
772 $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle);
773 $worksheet[$wsnumber]->set_column(1, 1, 30);
774 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
775 userdate(time(), $strftimedatetime));
777 foreach ($headers as $item) {
778 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
783 if (empty($logs['logs'])) {
788 $formatDate =& $workbook->add_format();
789 $formatDate->set_num_format(get_string('log_excel_date_format'));
791 $row = FIRSTUSEDEXCELROW;
793 $myxls =& $worksheet[$wsnumber];
794 foreach ($logs['logs'] as $log) {
795 if (isset($ldcache[$log->module][$log->action])) {
796 $ld = $ldcache[$log->module][$log->action];
798 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
799 $ldcache[$log->module][$log->action] = $ld;
801 if ($ld && is_numeric($log->info)) {
802 // ugly hack to make sure fullname is shown correctly
803 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
804 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
806 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
811 $log->info = format_string($log->info);
812 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
815 if ($row > EXCELROWS) {
817 $myxls =& $worksheet[$wsnumber];
818 $row = FIRSTUSEDEXCELROW;
822 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
824 $myxls->write_string($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)));
825 $myxls->write_date($row, 1, $log->time);
826 $myxls->write_string($row, 2, $log->ip);
827 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
828 $myxls->write_string($row, 3, $fullname);
829 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
830 $myxls->write_string($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')');
831 $myxls->write_string($row, 5, $log->info);
841 function print_overview($courses, array $remote_courses=array()) {
842 global $CFG, $USER, $DB, $OUTPUT;
844 $htmlarray = array();
845 if ($modules = $DB->get_records('modules')) {
846 foreach ($modules as $mod) {
847 if (file_exists(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php')) {
848 include_once(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php');
849 $fname = $mod->name.'_print_overview';
850 if (function_exists($fname)) {
851 $fname($courses,$htmlarray);
856 foreach ($courses as $course) {
857 $fullname = format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
858 echo $OUTPUT->box_start('coursebox');
859 $attributes = array('title' => s($fullname));
860 if (empty($course->visible)) {
861 $attributes['class'] = 'dimmed';
863 echo $OUTPUT->heading(html_writer::link(
864 new moodle_url('/course/view.php', array('id' => $course->id)), $fullname, $attributes), 3);
865 if (array_key_exists($course->id,$htmlarray)) {
866 foreach ($htmlarray[$course->id] as $modname => $html) {
870 echo $OUTPUT->box_end();
873 if (!empty($remote_courses)) {
874 echo $OUTPUT->heading(get_string('remotecourses', 'mnet'));
876 foreach ($remote_courses as $course) {
877 echo $OUTPUT->box_start('coursebox');
878 $attributes = array('title' => s($course->fullname));
879 echo $OUTPUT->heading(html_writer::link(
880 new moodle_url('/auth/mnet/jump.php', array('hostid' => $course->hostid, 'wantsurl' => '/course/view.php?id='.$course->remoteid)),
881 format_string($course->shortname),
882 $attributes) . ' (' . format_string($course->hostname) . ')', 3);
883 echo $OUTPUT->box_end();
889 * This function trawls through the logs looking for
890 * anything new since the user's last login
892 function print_recent_activity($course) {
893 // $course is an object
894 global $CFG, $USER, $SESSION, $DB, $OUTPUT;
896 $context = get_context_instance(CONTEXT_COURSE, $course->id);
898 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
900 $timestart = round(time() - COURSE_MAX_RECENT_PERIOD, -2); // better db caching for guests - 100 seconds
902 if (!isguestuser()) {
903 if (!empty($USER->lastcourseaccess[$course->id])) {
904 if ($USER->lastcourseaccess[$course->id] > $timestart) {
905 $timestart = $USER->lastcourseaccess[$course->id];
910 echo '<div class="activitydate">';
911 echo get_string('activitysince', '', userdate($timestart));
913 echo '<div class="activityhead">';
915 echo '<a href="'.$CFG->wwwroot.'/course/recent.php?id='.$course->id.'">'.get_string('recentactivityreport').'</a>';
921 /// Firstly, have there been any new enrolments?
923 $users = get_recent_enrolments($course->id, $timestart);
925 //Accessibility: new users now appear in an <OL> list.
927 echo '<div class="newusers">';
928 echo $OUTPUT->heading(get_string("newusers").':', 3);
930 echo "<ol class=\"list\">\n";
931 foreach ($users as $user) {
932 $fullname = fullname($user, $viewfullnames);
933 echo '<li class="name"><a href="'."$CFG->wwwroot/user/view.php?id=$user->id&course=$course->id\">$fullname</a></li>\n";
935 echo "</ol>\n</div>\n";
938 /// Next, have there been any modifications to the course structure?
940 $modinfo = get_fast_modinfo($course);
942 $changelist = array();
944 $logs = $DB->get_records_select('log', "time > ? AND course = ? AND
945 module = 'course' AND
946 (action = 'add mod' OR action = 'update mod' OR action = 'delete mod')",
947 array($timestart, $course->id), "id ASC");
950 $actions = array('add mod', 'update mod', 'delete mod');
951 $newgones = array(); // added and later deleted items
952 foreach ($logs as $key => $log) {
953 if (!in_array($log->action, $actions)) {
956 $info = explode(' ', $log->info);
958 // note: in most cases I replaced hardcoding of label with use of
959 // $cm->has_view() but it was not possible to do this here because
960 // we don't necessarily have the $cm for it
961 if ($info[0] == 'label') { // Labels are ignored in recent activity
965 if (count($info) != 2) {
966 debugging("Incorrect log entry info: id = ".$log->id, DEBUG_DEVELOPER);
971 $instanceid = $info[1];
973 if ($log->action == 'delete mod') {
974 // unfortunately we do not know if the mod was visible
975 if (!array_key_exists($log->info, $newgones)) {
976 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $modname));
977 $changelist[$log->info] = array ('operation' => 'delete', 'text' => $strdeleted);
980 if (!isset($modinfo->instances[$modname][$instanceid])) {
981 if ($log->action == 'add mod') {
982 // do not display added and later deleted activities
983 $newgones[$log->info] = true;
987 $cm = $modinfo->instances[$modname][$instanceid];
988 if (!$cm->uservisible) {
992 if ($log->action == 'add mod') {
993 $stradded = get_string('added', 'moodle', get_string('modulename', $modname));
994 $changelist[$log->info] = array('operation' => 'add', 'text' => "$stradded:<br /><a href=\"$CFG->wwwroot/mod/$cm->modname/view.php?id={$cm->id}\">".format_string($cm->name, true)."</a>");
996 } else if ($log->action == 'update mod' and empty($changelist[$log->info])) {
997 $strupdated = get_string('updated', 'moodle', get_string('modulename', $modname));
998 $changelist[$log->info] = array('operation' => 'update', 'text' => "$strupdated:<br /><a href=\"$CFG->wwwroot/mod/$cm->modname/view.php?id={$cm->id}\">".format_string($cm->name, true)."</a>");
1004 if (!empty($changelist)) {
1005 echo $OUTPUT->heading(get_string("courseupdates").':', 3);
1007 foreach ($changelist as $changeinfo => $change) {
1008 echo '<p class="activity">'.$change['text'].'</p>';
1012 /// Now display new things from each module
1014 $usedmodules = array();
1015 foreach($modinfo->cms as $cm) {
1016 if (isset($usedmodules[$cm->modname])) {
1019 if (!$cm->uservisible) {
1022 $usedmodules[$cm->modname] = $cm->modname;
1025 foreach ($usedmodules as $modname) { // Each module gets it's own logs and prints them
1026 if (file_exists($CFG->dirroot.'/mod/'.$modname.'/lib.php')) {
1027 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
1028 $print_recent_activity = $modname.'_print_recent_activity';
1029 if (function_exists($print_recent_activity)) {
1030 // NOTE: original $isteacher (second parameter below) was replaced with $viewfullnames!
1031 $content = $print_recent_activity($course, $viewfullnames, $timestart) || $content;
1034 debugging("Missing lib.php in lib/{$modname} - please reinstall files or uninstall the module");
1039 echo '<p class="message">'.get_string('nothingnew').'</p>';
1044 * For a given course, returns an array of course activity objects
1045 * Each item in the array contains he following properties:
1047 function get_array_of_activities($courseid) {
1048 // cm - course module id
1049 // mod - name of the module (eg forum)
1050 // section - the number of the section (eg week or topic)
1051 // name - the name of the instance
1052 // visible - is the instance visible or not
1053 // groupingid - grouping id
1054 // groupmembersonly - is this instance visible to group members only
1055 // extra - contains extra string to include in any link
1057 if(!empty($CFG->enableavailability)) {
1058 require_once($CFG->libdir.'/conditionlib.php');
1061 $course = $DB->get_record('course', array('id'=>$courseid));
1063 if (empty($course)) {
1064 throw new moodle_exception('courseidnotfound');
1069 $rawmods = get_course_mods($courseid);
1070 if (empty($rawmods)) {
1071 return $mod; // always return array
1074 if ($sections = $DB->get_records("course_sections", array("course"=>$courseid), "section ASC")) {
1075 foreach ($sections as $section) {
1076 if (!empty($section->sequence)) {
1077 $sequence = explode(",", $section->sequence);
1078 foreach ($sequence as $seq) {
1079 if (empty($rawmods[$seq])) {
1082 $mod[$seq] = new stdClass();
1083 $mod[$seq]->id = $rawmods[$seq]->instance;
1084 $mod[$seq]->cm = $rawmods[$seq]->id;
1085 $mod[$seq]->mod = $rawmods[$seq]->modname;
1087 // Oh dear. Inconsistent names left here for backward compatibility.
1088 $mod[$seq]->section = $section->section;
1089 $mod[$seq]->sectionid = $rawmods[$seq]->section;
1091 $mod[$seq]->module = $rawmods[$seq]->module;
1092 $mod[$seq]->added = $rawmods[$seq]->added;
1093 $mod[$seq]->score = $rawmods[$seq]->score;
1094 $mod[$seq]->idnumber = $rawmods[$seq]->idnumber;
1095 $mod[$seq]->visible = $rawmods[$seq]->visible;
1096 $mod[$seq]->visibleold = $rawmods[$seq]->visibleold;
1097 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
1098 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
1099 $mod[$seq]->groupmembersonly = $rawmods[$seq]->groupmembersonly;
1100 $mod[$seq]->indent = $rawmods[$seq]->indent;
1101 $mod[$seq]->completion = $rawmods[$seq]->completion;
1102 $mod[$seq]->extra = "";
1103 $mod[$seq]->completiongradeitemnumber =
1104 $rawmods[$seq]->completiongradeitemnumber;
1105 $mod[$seq]->completionview = $rawmods[$seq]->completionview;
1106 $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected;
1107 $mod[$seq]->availablefrom = $rawmods[$seq]->availablefrom;
1108 $mod[$seq]->availableuntil = $rawmods[$seq]->availableuntil;
1109 $mod[$seq]->showavailability = $rawmods[$seq]->showavailability;
1110 $mod[$seq]->showdescription = $rawmods[$seq]->showdescription;
1111 if (!empty($CFG->enableavailability)) {
1112 condition_info::fill_availability_conditions($rawmods[$seq]);
1113 $mod[$seq]->conditionscompletion = $rawmods[$seq]->conditionscompletion;
1114 $mod[$seq]->conditionsgrade = $rawmods[$seq]->conditionsgrade;
1117 $modname = $mod[$seq]->mod;
1118 $functionname = $modname."_get_coursemodule_info";
1120 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
1124 include_once("$CFG->dirroot/mod/$modname/lib.php");
1126 if ($hasfunction = function_exists($functionname)) {
1127 if ($info = $functionname($rawmods[$seq])) {
1128 if (!empty($info->icon)) {
1129 $mod[$seq]->icon = $info->icon;
1131 if (!empty($info->iconcomponent)) {
1132 $mod[$seq]->iconcomponent = $info->iconcomponent;
1134 if (!empty($info->name)) {
1135 $mod[$seq]->name = $info->name;
1137 if ($info instanceof cached_cm_info) {
1138 // When using cached_cm_info you can include three new fields
1139 // that aren't available for legacy code
1140 if (!empty($info->content)) {
1141 $mod[$seq]->content = $info->content;
1143 if (!empty($info->extraclasses)) {
1144 $mod[$seq]->extraclasses = $info->extraclasses;
1146 if (!empty($info->iconurl)) {
1147 $mod[$seq]->iconurl = $info->iconurl;
1149 if (!empty($info->onclick)) {
1150 $mod[$seq]->onclick = $info->onclick;
1152 if (!empty($info->customdata)) {
1153 $mod[$seq]->customdata = $info->customdata;
1156 // When using a stdclass, the (horrible) deprecated ->extra field
1157 // is available for BC
1158 if (!empty($info->extra)) {
1159 $mod[$seq]->extra = $info->extra;
1164 // When there is no modname_get_coursemodule_info function,
1165 // but showdescriptions is enabled, then we use the 'intro'
1166 // and 'introformat' fields in the module table
1167 if (!$hasfunction && $rawmods[$seq]->showdescription) {
1168 if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
1169 array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
1170 // Set content from intro and introformat. Filters are disabled
1171 // because we filter it with format_text at display time
1172 $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
1173 $modvalues, $rawmods[$seq]->id, false);
1175 // To save making another query just below, put name in here
1176 $mod[$seq]->name = $modvalues->name;
1179 if (!isset($mod[$seq]->name)) {
1180 $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
1183 // Minimise the database size by unsetting default options when they are
1184 // 'empty'. This list corresponds to code in the cm_info constructor.
1185 foreach (array('idnumber', 'groupmode', 'groupingid', 'groupmembersonly',
1186 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
1187 'icon', 'iconcomponent', 'customdata', 'showavailability', 'availablefrom',
1188 'availableuntil', 'conditionscompletion', 'conditionsgrade',
1189 'completionview', 'completionexpected', 'score', 'showdescription')
1191 if (property_exists($mod[$seq], $property) &&
1192 empty($mod[$seq]->{$property})) {
1193 unset($mod[$seq]->{$property});
1196 // Special case: this value is usually set to null, but may be 0
1197 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
1198 is_null($mod[$seq]->completiongradeitemnumber)) {
1199 unset($mod[$seq]->completiongradeitemnumber);
1210 * Returns a number of useful structures for course displays
1212 function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
1213 global $CFG, $DB, $COURSE;
1215 $mods = array(); // course modules indexed by id
1216 $modnames = array(); // all course module names (except resource!)
1217 $modnamesplural= array(); // all course module names (plural form)
1218 $modnamesused = array(); // course module names used
1220 if ($allmods = $DB->get_records("modules")) {
1221 foreach ($allmods as $mod) {
1222 if (!file_exists("$CFG->dirroot/mod/$mod->name/lib.php")) {
1225 if ($mod->visible) {
1226 $modnames[$mod->name] = get_string("modulename", "$mod->name");
1227 $modnamesplural[$mod->name] = get_string("modulenameplural", "$mod->name");
1230 collatorlib::asort($modnames);
1232 print_error("nomodules", 'debug');
1235 $course = ($courseid==$COURSE->id) ? $COURSE : $DB->get_record('course',array('id'=>$courseid));
1236 $modinfo = get_fast_modinfo($course);
1238 if ($rawmods=$modinfo->cms) {
1239 foreach($rawmods as $mod) { // Index the mods
1240 if (empty($modnames[$mod->modname])) {
1243 $mods[$mod->id] = $mod;
1244 $mods[$mod->id]->modfullname = $modnames[$mod->modname];
1245 if (!$mod->visible and !has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_COURSE, $courseid))) {
1249 if (!groups_course_module_visible($mod)) {
1252 $modnamesused[$mod->modname] = $modnames[$mod->modname];
1254 if ($modnamesused) {
1255 collatorlib::asort($modnamesused);
1261 * Returns an array of sections for the requested course id
1263 * This function stores the sections against the course id within a staticvar encase
1264 * of subsequent requests. This is used all over + in some standard libs and course
1265 * format callbacks so subsequent requests are a reality.
1267 * Note: Since Moodle 2.3, it is more efficient to get this data by calling
1268 * get_fast_modinfo, then using $modinfo->get_section_info or get_section_info_all.
1270 * @staticvar array $coursesections
1271 * @param int $courseid
1272 * @return array Array of sections
1274 function get_all_sections($courseid) {
1276 static $coursesections = array();
1277 if (!array_key_exists($courseid, $coursesections)) {
1278 $coursesections[$courseid] = $DB->get_records("course_sections", array("course"=>"$courseid"), "section",
1279 'section, id, course, name, summary, summaryformat, sequence, visible, ' .
1280 'availablefrom, availableuntil, showavailability, groupingid');
1282 return $coursesections[$courseid];
1286 * Set highlighted section. Only one section can be highlighted at the time.
1288 * @param int $courseid course id
1289 * @param int $marker highlight section with this number, 0 means remove higlightin
1292 function course_set_marker($courseid, $marker) {
1294 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
1298 * For a given course section, marks it visible or hidden,
1299 * and does the same for every activity in that section
1301 * @param int $courseid course id
1302 * @param int $sectionnumber The section number to adjust
1303 * @param int $visibility The new visibility
1304 * @return array A list of resources which were hidden in the section
1306 function set_section_visible($courseid, $sectionnumber, $visibility) {
1309 $resourcestotoggle = array();
1310 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
1311 $DB->set_field("course_sections", "visible", "$visibility", array("id"=>$section->id));
1312 if (!empty($section->sequence)) {
1313 $modules = explode(",", $section->sequence);
1314 foreach ($modules as $moduleid) {
1315 set_coursemodule_visible($moduleid, $visibility, true);
1318 rebuild_course_cache($courseid);
1320 // Determine which modules are visible for AJAX update
1321 if (!empty($modules)) {
1322 list($insql, $params) = $DB->get_in_or_equal($modules);
1323 $select = 'id ' . $insql . ' AND visible = ?';
1324 array_push($params, $visibility);
1326 $select .= ' AND visibleold = 1';
1328 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
1331 return $resourcestotoggle;
1335 * Obtains shared data that is used in print_section when displaying a
1336 * course-module entry.
1338 * Calls format_text or format_string as appropriate, and obtains the correct icon.
1340 * This data is also used in other areas of the code.
1341 * @param cm_info $cm Course-module data (must come from get_fast_modinfo)
1342 * @param object $course Moodle course object
1343 * @return array An array with the following values in this order:
1344 * $content (optional extra content for after link),
1345 * $instancename (text of link)
1347 function get_print_section_cm_text(cm_info $cm, $course) {
1350 // Get content from modinfo if specified. Content displays either
1351 // in addition to the standard link (below), or replaces it if
1352 // the link is turned off by setting ->url to null.
1353 if (($content = $cm->get_content()) !== '') {
1354 // Improve filter performance by preloading filter setttings for all
1355 // activities on the course (this does nothing if called multiple
1357 filter_preload_activities($cm->get_modinfo());
1359 // Get module context
1360 $modulecontext = get_context_instance(CONTEXT_MODULE, $cm->id);
1361 $labelformatoptions = new stdClass();
1362 $labelformatoptions->noclean = true;
1363 $labelformatoptions->overflowdiv = true;
1364 $labelformatoptions->context = $modulecontext;
1365 $content = format_text($content, FORMAT_HTML, $labelformatoptions);
1370 // Get course context
1371 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
1372 $stringoptions = new stdClass;
1373 $stringoptions->context = $coursecontext;
1374 $instancename = format_string($cm->name, true, $stringoptions);
1375 return array($content, $instancename);
1379 * Prints a section full of activity modules
1381 * @param stdClass $course The course
1382 * @param stdClass $section The section
1383 * @param array $mods The modules in the section
1384 * @param array $modnamesused An array containing the list of modules and their names
1385 * @param bool $absolute All links are absolute
1386 * @param string $width Width of the container
1387 * @param bool $hidecompletion Hide completion status
1388 * @param int $sectionreturn The section to return to
1391 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%", $hidecompletion=false, $sectionreturn=null) {
1392 global $CFG, $USER, $DB, $PAGE, $OUTPUT;
1394 static $initialised;
1396 static $groupbuttons;
1397 static $groupbuttonslink;
1400 static $strmovehere;
1401 static $strmovefull;
1402 static $strunreadpostsone;
1403 static $modulenames;
1405 if (!isset($initialised)) {
1406 $groupbuttons = ($course->groupmode or (!$course->groupmodeforce));
1407 $groupbuttonslink = (!$course->groupmodeforce);
1408 $isediting = $PAGE->user_is_editing();
1409 $ismoving = $isediting && ismoving($course->id);
1411 $strmovehere = get_string("movehere");
1412 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1414 $modulenames = array();
1415 $initialised = true;
1418 $modinfo = get_fast_modinfo($course);
1419 $completioninfo = new completion_info($course);
1421 //Accessibility: replace table with list <ul>, but don't output empty list.
1422 if (!empty($section->sequence)) {
1424 // Fix bug #5027, don't want style=\"width:$width\".
1425 echo "<ul class=\"section img-text\">\n";
1426 $sectionmods = explode(",", $section->sequence);
1428 foreach ($sectionmods as $modnumber) {
1429 if (empty($mods[$modnumber])) {
1436 $mod = $mods[$modnumber];
1438 if ($ismoving and $mod->id == $USER->activitycopy) {
1439 // do not display moving mod
1443 if (isset($modinfo->cms[$modnumber])) {
1444 // We can continue (because it will not be displayed at all)
1446 // 1) The activity is not visible to users
1448 // 2a) The 'showavailability' option is not set (if that is set,
1449 // we need to display the activity so we can show
1450 // availability info)
1452 // 2b) The 'availableinfo' is empty, i.e. the activity was
1453 // hidden in a way that leaves no info, such as using the
1455 if (!$modinfo->cms[$modnumber]->uservisible &&
1456 (empty($modinfo->cms[$modnumber]->showavailability) ||
1457 empty($modinfo->cms[$modnumber]->availableinfo))) {
1458 // visibility shortcut
1462 if (!file_exists("$CFG->dirroot/mod/$mod->modname/lib.php")) {
1463 // module not installed
1466 if (!coursemodule_visible_for_user($mod) &&
1467 empty($mod->showavailability)) {
1468 // full visibility check
1473 if (!isset($modulenames[$mod->modname])) {
1474 $modulenames[$mod->modname] = get_string('modulename', $mod->modname);
1476 $modulename = $modulenames[$mod->modname];
1478 // In some cases the activity is visible to user, but it is
1479 // dimmed. This is done if viewhiddenactivities is true and if:
1480 // 1. the activity is not visible, or
1481 // 2. the activity has dates set which do not include current, or
1482 // 3. the activity has any other conditions set (regardless of whether
1483 // current user meets them)
1484 $modcontext = context_module::instance($mod->id);
1485 $canviewhidden = has_capability('moodle/course:viewhiddenactivities', $modcontext);
1486 $accessiblebutdim = false;
1487 $conditionalhidden = false;
1488 if ($canviewhidden) {
1489 $accessiblebutdim = !$mod->visible;
1490 if (!empty($CFG->enableavailability)) {
1491 $conditionalhidden = $mod->availablefrom > time() ||
1492 ($mod->availableuntil && $mod->availableuntil < time()) ||
1493 count($mod->conditionsgrade) > 0 ||
1494 count($mod->conditionscompletion) > 0;
1496 $accessiblebutdim = $conditionalhidden || $accessiblebutdim;
1499 $liclasses = array();
1500 $liclasses[] = 'activity';
1501 $liclasses[] = $mod->modname;
1502 $liclasses[] = 'modtype_'.$mod->modname;
1503 $extraclasses = $mod->get_extra_classes();
1504 if ($extraclasses) {
1505 $liclasses = array_merge($liclasses, explode(' ', $extraclasses));
1507 echo html_writer::start_tag('li', array('class'=>join(' ', $liclasses), 'id'=>'module-'.$modnumber));
1509 echo '<a title="'.$strmovefull.'"'.
1510 ' href="'.$CFG->wwwroot.'/course/mod.php?moveto='.$mod->id.'&sesskey='.sesskey().'">'.
1511 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1512 ' alt="'.$strmovehere.'" /></a><br />
1516 $classes = array('mod-indent');
1517 if (!empty($mod->indent)) {
1518 $classes[] = 'mod-indent-'.$mod->indent;
1519 if ($mod->indent > 15) {
1520 $classes[] = 'mod-indent-huge';
1523 echo html_writer::start_tag('div', array('class'=>join(' ', $classes)));
1525 // Get data about this course-module
1526 list($content, $instancename) =
1527 get_print_section_cm_text($modinfo->cms[$modnumber], $course);
1529 //Accessibility: for files get description via icon, this is very ugly hack!
1531 $altname = $mod->modfullname;
1532 // Avoid unnecessary duplication: if e.g. a forum name already
1533 // includes the word forum (or Forum, etc) then it is unhelpful
1534 // to include that in the accessible description that is added.
1535 if (false !== strpos(textlib::strtolower($instancename),
1536 textlib::strtolower($altname))) {
1539 // File type after name, for alphabetic lists (screen reader).
1541 $altname = get_accesshide(' '.$altname);
1544 // We may be displaying this just in order to show information
1545 // about visibility, without the actual link
1547 if ($mod->uservisible) {
1548 // Nope - in this case the link is fully working for user
1551 if ($accessiblebutdim) {
1552 $linkclasses .= ' dimmed';
1553 $textclasses .= ' dimmed_text';
1554 if ($conditionalhidden) {
1555 $linkclasses .= ' conditionalhidden';
1556 $textclasses .= ' conditionalhidden';
1558 $accesstext = '<span class="accesshide">'.
1559 get_string('hiddenfromstudents').': </span>';
1564 $linkcss = 'class="' . trim($linkclasses) . '" ';
1569 $textcss = 'class="' . trim($textclasses) . '" ';
1574 // Get on-click attribute value if specified
1575 $onclick = $mod->get_on_click();
1577 $onclick = ' onclick="' . $onclick . '"';
1580 if ($url = $mod->get_url()) {
1581 // Display link itself
1582 echo '<a ' . $linkcss . $mod->extra . $onclick .
1583 ' href="' . $url . '"><img src="' . $mod->get_icon_url() .
1584 '" class="activityicon" alt="' . $modulename . '" /> ' .
1585 $accesstext . '<span class="instancename">' .
1586 $instancename . $altname . '</span></a>';
1588 // If specified, display extra content after link
1590 $contentpart = '<div class="' . trim('contentafterlink' . $textclasses) .
1591 '">' . $content . '</div>';
1594 // No link, so display only content
1595 $contentpart = '<div ' . $textcss . $mod->extra . '>' .
1596 $accesstext . $content . '</div>';
1599 if (!empty($mod->groupingid) && has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
1600 $groupings = groups_get_all_groupings($course->id);
1601 echo " <span class=\"groupinglabel\">(".format_string($groupings[$mod->groupingid]->name).')</span>';
1604 $textclasses = $extraclasses;
1605 $textclasses .= ' dimmed_text';
1607 $textcss = 'class="' . trim($textclasses) . '" ';
1611 $accesstext = '<span class="accesshide">' .
1612 get_string('notavailableyet', 'condition') .
1615 if ($url = $mod->get_url()) {
1616 // Display greyed-out text of link
1617 echo '<div ' . $textcss . $mod->extra .
1618 ' >' . '<img src="' . $mod->get_icon_url() .
1619 '" class="activityicon" alt="" /> <span>'. $instancename . $altname .
1622 // Do not display content after link when it is greyed out like this.
1624 // No link, so display only content (also greyed)
1625 $contentpart = '<div ' . $textcss . $mod->extra . '>' .
1626 $accesstext . $content . '</div>';
1630 // Module can put text after the link (e.g. forum unread)
1631 echo $mod->get_after_link();
1633 // If there is content but NO link (eg label), then display the
1634 // content here (BEFORE any icons). In this case cons must be
1635 // displayed after the content so that it makes more sense visually
1636 // and for accessibility reasons, e.g. if you have a one-line label
1637 // it should work similarly (at least in terms of ordering) to an
1644 if ($groupbuttons and plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
1645 if (! $mod->groupmodelink = $groupbuttonslink) {
1646 $mod->groupmode = $course->groupmode;
1650 $mod->groupmode = false;
1652 echo ' ';
1653 echo make_editing_buttons($mod, $absolute, true, $mod->indent, $sectionreturn);
1654 echo $mod->get_after_edit_icons();
1658 $completion = $hidecompletion
1659 ? COMPLETION_TRACKING_NONE
1660 : $completioninfo->is_enabled($mod);
1661 if ($completion!=COMPLETION_TRACKING_NONE && isloggedin() &&
1662 !isguestuser() && $mod->uservisible) {
1663 $completiondata = $completioninfo->get_data($mod,true);
1664 $completionicon = '';
1666 switch ($completion) {
1667 case COMPLETION_TRACKING_MANUAL :
1668 $completionicon = 'manual-enabled'; break;
1669 case COMPLETION_TRACKING_AUTOMATIC :
1670 $completionicon = 'auto-enabled'; break;
1673 } else if ($completion==COMPLETION_TRACKING_MANUAL) {
1674 switch($completiondata->completionstate) {
1675 case COMPLETION_INCOMPLETE:
1676 $completionicon = 'manual-n'; break;
1677 case COMPLETION_COMPLETE:
1678 $completionicon = 'manual-y'; break;
1680 } else { // Automatic
1681 switch($completiondata->completionstate) {
1682 case COMPLETION_INCOMPLETE:
1683 $completionicon = 'auto-n'; break;
1684 case COMPLETION_COMPLETE:
1685 $completionicon = 'auto-y'; break;
1686 case COMPLETION_COMPLETE_PASS:
1687 $completionicon = 'auto-pass'; break;
1688 case COMPLETION_COMPLETE_FAIL:
1689 $completionicon = 'auto-fail'; break;
1692 if ($completionicon) {
1693 $imgsrc = $OUTPUT->pix_url('i/completion-'.$completionicon);
1694 $formattedname = format_string($mod->name, true, array('context' => $modcontext));
1695 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $formattedname);
1696 if ($completion == COMPLETION_TRACKING_MANUAL && !$isediting) {
1697 $imgtitle = get_string('completion-title-' . $completionicon, 'completion', $formattedname);
1699 $completiondata->completionstate==COMPLETION_COMPLETE
1700 ? COMPLETION_INCOMPLETE
1701 : COMPLETION_COMPLETE;
1702 // In manual mode the icon is a toggle form...
1704 // If this completion state is used by the
1705 // conditional activities system, we need to turn
1707 if (!empty($CFG->enableavailability) &&
1708 condition_info::completion_value_used_as_condition($course, $mod)) {
1709 $extraclass = ' preventjs';
1713 echo html_writer::start_tag('form', array(
1714 'class' => 'togglecompletion' . $extraclass,
1716 'action' => $CFG->wwwroot . '/course/togglecompletion.php'));
1717 echo html_writer::start_tag('div');
1718 echo html_writer::empty_tag('input', array(
1719 'type' => 'hidden', 'name' => 'id', 'value' => $mod->id));
1720 echo html_writer::empty_tag('input', array(
1721 'type' => 'hidden', 'name' => 'modulename',
1722 'value' => $mod->name));
1723 echo html_writer::empty_tag('input', array(
1724 'type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey()));
1725 echo html_writer::empty_tag('input', array(
1726 'type' => 'hidden', 'name' => 'completionstate',
1727 'value' => $newstate));
1728 echo html_writer::empty_tag('input', array(
1729 'type' => 'image', 'src' => $imgsrc, 'alt' => $imgalt, 'title' => $imgtitle));
1730 echo html_writer::end_tag('div');
1731 echo html_writer::end_tag('form');
1733 // In auto mode, or when editing, the icon is just an image
1734 echo "<span class='autocompletion'>";
1735 echo "<img src='$imgsrc' alt='$imgalt' title='$imgalt' /></span>";
1740 // If there is content AND a link, then display the content here
1741 // (AFTER any icons). Otherwise it was displayed before
1746 // Show availability information (for someone who isn't allowed to
1747 // see the activity itself, or for staff)
1748 if (!$mod->uservisible) {
1749 echo '<div class="availabilityinfo">'.$mod->availableinfo.'</div>';
1750 } else if ($canviewhidden && !empty($CFG->enableavailability)) {
1751 // Don't add availability information if user is not editing and activity is hidden.
1752 if ($mod->visible || $PAGE->user_is_editing()) {
1754 if (!$mod->visible) {
1755 $hidinfoclass = 'hide';
1757 $ci = new condition_info($mod);
1758 $fullinfo = $ci->get_full_information();
1760 echo '<div class="availabilityinfo '.$hidinfoclass.'">'.get_string($mod->showavailability
1761 ? 'userrestriction_visible'
1762 : 'userrestriction_hidden','condition',
1763 $fullinfo).'</div>';
1768 echo html_writer::end_tag('div');
1769 echo html_writer::end_tag('li')."\n";
1772 } elseif ($ismoving) {
1773 echo "<ul class=\"section\">\n";
1777 echo '<li><a title="'.$strmovefull.'"'.
1778 ' href="'.$CFG->wwwroot.'/course/mod.php?movetosection='.$section->id.'&sesskey='.sesskey().'">'.
1779 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1780 ' alt="'.$strmovehere.'" /></a></li>
1783 if (!empty($section->sequence) || $ismoving) {
1784 echo "</ul><!--class='section'-->\n\n";
1789 * Prints the menus to add activities and resources.
1791 * @param stdClass $course The course
1792 * @param int $section relative section number (field course_sections.section)
1793 * @param array $modnames An array containing the list of modules and their names
1794 * @param bool $vertical Vertical orientation
1795 * @param bool $return Return the menus or send them to output
1796 * @param int $sectionreturn The section to link back to
1797 * @return void|string depending on $return
1799 function print_section_add_menus($course, $section, $modnames, $vertical=false, $return=false, $sectionreturn=null) {
1800 global $CFG, $OUTPUT;
1802 // check to see if user can add menus
1803 if (!has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $course->id))) {
1807 // Retrieve all modules with associated metadata
1808 $modules = get_module_metadata($course, $modnames, $sectionreturn);
1810 // We'll sort resources and activities into two lists
1811 $resources = array();
1812 $activities = array();
1814 // We need to add the section section to the link for each module
1815 $sectionlink = '§ion=' . $section . '&sr=' . $sectionreturn;
1817 foreach ($modules as $module) {
1818 if (isset($module->types)) {
1819 // This module has a subtype
1820 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1821 $subtypes = array();
1822 foreach ($module->types as $subtype) {
1823 $subtypes[$subtype->link . $sectionlink] = $subtype->title;
1826 // Sort module subtypes into the list
1827 if (!empty($module->title)) {
1828 // This grouping has a name
1829 if ($module->archetype == MOD_CLASS_RESOURCE) {
1830 $resources[] = array($module->title=>$subtypes);
1832 $activities[] = array($module->title=>$subtypes);
1835 // This grouping does not have a name
1836 if ($module->archetype == MOD_CLASS_RESOURCE) {
1837 $resources = array_merge($resources, $subtypes);
1839 $activities = array_merge($activities, $subtypes);
1843 // This module has no subtypes
1844 if ($module->archetype == MOD_ARCHETYPE_RESOURCE) {
1845 $resources[$module->link . $sectionlink] = $module->title;
1846 } else if ($module->archetype === MOD_ARCHETYPE_SYSTEM) {
1847 // System modules cannot be added by user, do not add to dropdown
1849 $activities[$module->link . $sectionlink] = $module->title;
1854 $straddactivity = get_string('addactivity');
1855 $straddresource = get_string('addresource');
1857 $output = html_writer::start_tag('div', array('class' => 'section_add_menus', 'id' => 'add_menus-section-' . $section));
1860 $output .= html_writer::start_tag('div', array('class' => 'horizontal'));
1863 if (!empty($resources)) {
1864 $select = new url_select($resources, '', array(''=>$straddresource), "ressection$section");
1865 $select->set_help_icon('resources');
1866 $output .= $OUTPUT->render($select);
1869 if (!empty($activities)) {
1870 $select = new url_select($activities, '', array(''=>$straddactivity), "section$section");
1871 $select->set_help_icon('activities');
1872 $output .= $OUTPUT->render($select);
1876 $output .= html_writer::end_tag('div');
1879 $output .= html_writer::end_tag('div');
1881 if (course_ajax_enabled($course)) {
1882 $straddeither = get_string('addresourceoractivity');
1883 // The module chooser link
1884 $modchooser = html_writer::start_tag('div', array('class' => 'mdl-right'));
1885 $modchooser.= html_writer::start_tag('div', array('class' => 'section-modchooser'));
1886 $icon = $OUTPUT->pix_icon('t/add', '');
1887 $span = html_writer::tag('span', $straddeither, array('class' => 'section-modchooser-text'));
1888 $modchooser .= html_writer::tag('span', $icon . $span, array('class' => 'section-modchooser-link'));
1889 $modchooser.= html_writer::end_tag('div');
1890 $modchooser.= html_writer::end_tag('div');
1892 // Wrap the normal output in a noscript div
1893 $usemodchooser = get_user_preferences('usemodchooser', $CFG->modchooserdefault);
1894 if ($usemodchooser) {
1895 $output = html_writer::tag('div', $output, array('class' => 'hiddenifjs addresourcedropdown'));
1896 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'visibleifjs addresourcemodchooser'));
1898 // If the module chooser is disabled, we need to ensure that the dropdowns are shown even if javascript is disabled
1899 $output = html_writer::tag('div', $output, array('class' => 'show addresourcedropdown'));
1900 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'hide addresourcemodchooser'));
1902 $output = $modchooser . $output;
1913 * Retrieve all metadata for the requested modules
1915 * @param object $course The Course
1916 * @param array $modnames An array containing the list of modules and their
1918 * @param int $sectionreturn The section to return to
1919 * @return array A list of stdClass objects containing metadata about each
1922 function get_module_metadata($course, $modnames, $sectionreturn = null) {
1923 global $CFG, $OUTPUT;
1925 // get_module_metadata will be called once per section on the page and courses may show
1926 // different modules to one another
1927 static $modlist = array();
1928 if (!isset($modlist[$course->id])) {
1929 $modlist[$course->id] = array();
1933 $urlbase = "/course/mod.php?id=$course->id&sesskey=".sesskey().'&sr='.$sectionreturn.'&add=';
1934 foreach($modnames as $modname => $modnamestr) {
1935 if (!course_allowed_module($course, $modname)) {
1938 if (isset($modlist[$course->id][$modname])) {
1939 // This module is already cached
1940 $return[$modname] = $modlist[$course->id][$modname];
1944 // Include the module lib
1945 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1946 if (!file_exists($libfile)) {
1949 include_once($libfile);
1951 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1952 $gettypesfunc = $modname.'_get_types';
1953 if (function_exists($gettypesfunc)) {
1954 if ($types = $gettypesfunc()) {
1955 $group = new stdClass();
1956 $group->name = $modname;
1957 $group->icon = $OUTPUT->pix_icon('icon', '', $modname, array('class' => 'icon'));
1958 foreach($types as $type) {
1959 if ($type->typestr === '--') {
1962 if (strpos($type->typestr, '--') === 0) {
1963 $group->title = str_replace('--', '', $type->typestr);
1966 // Set the Sub Type metadata
1967 $subtype = new stdClass();
1968 $subtype->title = $type->typestr;
1969 $subtype->type = str_replace('&', '&', $type->type);
1970 $subtype->name = preg_replace('/.*type=/', '', $subtype->type);
1971 $subtype->archetype = $type->modclass;
1973 // The group archetype should match the subtype archetypes and all subtypes
1974 // should have the same archetype
1975 $group->archetype = $subtype->archetype;
1977 if (get_string_manager()->string_exists('help' . $subtype->name, $modname)) {
1978 $subtype->help = get_string('help' . $subtype->name, $modname);
1980 $subtype->link = $urlbase . $subtype->type;
1981 $group->types[] = $subtype;
1983 $modlist[$course->id][$modname] = $group;
1986 $module = new stdClass();
1987 $module->title = get_string('modulename', $modname);
1988 $module->name = $modname;
1989 $module->link = $urlbase . $modname;
1990 $module->icon = $OUTPUT->pix_icon('icon', '', $module->name, array('class' => 'icon'));
1991 $sm = get_string_manager();
1992 if ($sm->string_exists('modulename_help', $modname)) {
1993 $module->help = get_string('modulename_help', $modname);
1994 if ($sm->string_exists('modulename_link', $modname)) { // Link to further info in Moodle docs
1995 $link = get_string('modulename_link', $modname);
1996 $linktext = get_string('morehelp');
1997 $module->help .= html_writer::tag('div', $OUTPUT->doc_link($link, $linktext, true), array('class' => 'helpdoclink'));
2000 $module->archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
2001 $modlist[$course->id][$modname] = $module;
2003 $return[$modname] = $modlist[$course->id][$modname];
2010 * Return the course category context for the category with id $categoryid, except
2011 * that if $categoryid is 0, return the system context.
2013 * @param integer $categoryid a category id or 0.
2014 * @return object the corresponding context
2016 function get_category_or_system_context($categoryid) {
2018 return get_context_instance(CONTEXT_COURSECAT, $categoryid);
2020 return get_context_instance(CONTEXT_SYSTEM);
2025 * Gets the child categories of a given courses category. Uses a static cache
2026 * to make repeat calls efficient.
2028 * @param int $parentid the id of a course category.
2029 * @return array all the child course categories.
2031 function get_child_categories($parentid) {
2032 static $allcategories = null;
2034 // only fill in this variable the first time
2035 if (null == $allcategories) {
2036 $allcategories = array();
2038 $categories = get_categories();
2039 foreach ($categories as $category) {
2040 if (empty($allcategories[$category->parent])) {
2041 $allcategories[$category->parent] = array();
2043 $allcategories[$category->parent][] = $category;
2047 if (empty($allcategories[$parentid])) {
2050 return $allcategories[$parentid];
2055 * This function recursively travels the categories, building up a nice list
2056 * for display. It also makes an array that list all the parents for each
2059 * For example, if you have a tree of categories like:
2060 * Miscellaneous (id = 1)
2061 * Subcategory (id = 2)
2062 * Sub-subcategory (id = 4)
2063 * Other category (id = 3)
2064 * Then after calling this function you will have
2065 * $list = array(1 => 'Miscellaneous', 2 => 'Miscellaneous / Subcategory',
2066 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
2067 * 3 => 'Other category');
2068 * $parents = array(2 => array(1), 4 => array(1, 2));
2070 * If you specify $requiredcapability, then only categories where the current
2071 * user has that capability will be added to $list, although all categories
2072 * will still be added to $parents, and if you only have $requiredcapability
2073 * in a child category, not the parent, then the child catgegory will still be
2076 * If you specify the option $excluded, then that category, and all its children,
2077 * are omitted from the tree. This is useful when you are doing something like
2078 * moving categories, where you do not want to allow people to move a category
2079 * to be the child of itself.
2081 * @param array $list For output, accumulates an array categoryid => full category path name
2082 * @param array $parents For output, accumulates an array categoryid => list of parent category ids.
2083 * @param string/array $requiredcapability if given, only categories where the current
2084 * user has this capability will be added to $list. Can also be an array of capabilities,
2085 * in which case they are all required.
2086 * @param integer $excludeid Omit this category and its children from the lists built.
2087 * @param object $category Build the tree starting at this category - otherwise starts at the top level.
2088 * @param string $path For internal use, as part of recursive calls.
2090 function make_categories_list(&$list, &$parents, $requiredcapability = '',
2091 $excludeid = 0, $category = NULL, $path = "") {
2093 // initialize the arrays if needed
2094 if (!is_array($list)) {
2097 if (!is_array($parents)) {
2101 if (empty($category)) {
2102 // Start at the top level.
2103 $category = new stdClass;
2106 // This is the excluded category, don't include it.
2107 if ($excludeid > 0 && $excludeid == $category->id) {
2111 $context = get_context_instance(CONTEXT_COURSECAT, $category->id);
2112 $categoryname = format_string($category->name, true, array('context' => $context));
2116 $path = $path.' / '.$categoryname;
2118 $path = $categoryname;
2121 // Add this category to $list, if the permissions check out.
2122 if (empty($requiredcapability)) {
2123 $list[$category->id] = $path;
2126 $requiredcapability = (array)$requiredcapability;
2127 if (has_all_capabilities($requiredcapability, $context)) {
2128 $list[$category->id] = $path;
2133 // Add all the children recursively, while updating the parents array.
2134 if ($categories = get_child_categories($category->id)) {
2135 foreach ($categories as $cat) {
2136 if (!empty($category->id)) {
2137 if (isset($parents[$category->id])) {
2138 $parents[$cat->id] = $parents[$category->id];
2140 $parents[$cat->id][] = $category->id;
2142 make_categories_list($list, $parents, $requiredcapability, $excludeid, $cat, $path);
2148 * This function generates a structured array of courses and categories.
2150 * The depth of categories is limited by $CFG->maxcategorydepth however there
2151 * is no limit on the number of courses!
2153 * Suitable for use with the course renderers course_category_tree method:
2154 * $renderer = $PAGE->get_renderer('core','course');
2155 * echo $renderer->course_category_tree(get_course_category_tree());
2157 * @global moodle_database $DB
2161 function get_course_category_tree($id = 0, $depth = 0) {
2163 $viewhiddencats = has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_SYSTEM));
2164 $categories = get_child_categories($id);
2165 $categoryids = array();
2166 foreach ($categories as $key => &$category) {
2167 if (!$category->visible && !$viewhiddencats) {
2168 unset($categories[$key]);
2171 $categoryids[$category->id] = $category;
2172 if (empty($CFG->maxcategorydepth) || $depth <= $CFG->maxcategorydepth) {
2173 list($category->categories, $subcategories) = get_course_category_tree($category->id, $depth+1);
2174 foreach ($subcategories as $subid=>$subcat) {
2175 $categoryids[$subid] = $subcat;
2177 $category->courses = array();
2182 // This is a recursive call so return the required array
2183 return array($categories, $categoryids);
2186 if (empty($categoryids)) {
2187 // No categories available (probably all hidden).
2191 // The depth is 0 this function has just been called so we can finish it off
2193 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
2194 list($catsql, $catparams) = $DB->get_in_or_equal(array_keys($categoryids));
2196 c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary,c.category
2200 WHERE c.category $catsql ORDER BY c.sortorder ASC";
2201 if ($courses = $DB->get_records_sql($sql, $catparams)) {
2202 // loop throught them
2203 foreach ($courses as $course) {
2204 if ($course->id == SITEID) {
2207 context_instance_preload($course);
2208 if (!empty($course->visible) || has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id))) {
2209 $categoryids[$course->category]->courses[$course->id] = $course;
2217 * Recursive function to print out all the categories in a nice format
2218 * with or without courses included
2220 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true) {
2223 // maxcategorydepth == 0 meant no limit
2224 if (!empty($CFG->maxcategorydepth) && $depth >= $CFG->maxcategorydepth) {
2228 if (!$displaylist) {
2229 make_categories_list($displaylist, $parentslist);
2233 if ($category->visible or has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_SYSTEM))) {
2234 print_category_info($category, $depth, $showcourses);
2236 return; // Don't bother printing children of invisible categories
2240 $category = new stdClass();
2241 $category->id = "0";
2244 if ($categories = get_child_categories($category->id)) { // Print all the children recursively
2245 $countcats = count($categories);
2249 foreach ($categories as $cat) {
2251 if ($count == $countcats) {
2254 $up = $first ? false : true;
2255 $down = $last ? false : true;
2258 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1, $showcourses);
2264 * This function will return $options array for html_writer::select(), with whitespace to denote nesting.
2266 function make_categories_options() {
2267 make_categories_list($cats,$parents);
2268 foreach ($cats as $key => $value) {
2269 if (array_key_exists($key,$parents)) {
2270 if ($indent = count($parents[$key])) {
2271 for ($i = 0; $i < $indent; $i++) {
2272 $cats[$key] = ' '.$cats[$key];
2281 * Prints the category info in indented fashion
2282 * This function is only used by print_whole_category_list() above
2284 function print_category_info($category, $depth=0, $showcourses = false) {
2285 global $CFG, $DB, $OUTPUT;
2287 $strsummary = get_string('summary');
2290 if (!$category->visible) {
2291 $catlinkcss = array('class'=>'dimmed');
2293 static $coursecount = null;
2294 if (null === $coursecount) {
2295 // only need to check this once
2296 $coursecount = $DB->count_records('course') <= FRONTPAGECOURSELIMIT;
2299 if ($showcourses and $coursecount) {
2300 $catimage = '<img src="'.$OUTPUT->pix_url('i/course') . '" alt="" />';
2302 $catimage = " ";
2305 $courses = get_courses($category->id, 'c.sortorder ASC', 'c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary');
2306 $context = get_context_instance(CONTEXT_COURSECAT, $category->id);
2307 $fullname = format_string($category->name, true, array('context' => $context));
2309 if ($showcourses and $coursecount) {
2310 echo '<div class="categorylist clearfix">';
2312 $cat .= html_writer::tag('div', $catimage, array('class'=>'image'));
2313 $catlink = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
2314 $cat .= html_writer::tag('div', $catlink, array('class'=>'name'));
2318 for ($i=0; $i< $depth; $i++) {
2319 $html = html_writer::tag('div', $html . $cat, array('class'=>'indentation'));
2325 echo html_writer::tag('div', $html, array('class'=>'category'));
2326 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
2328 // does the depth exceed maxcategorydepth
2329 // maxcategorydepth == 0 or unset meant no limit
2330 $limit = !(isset($CFG->maxcategorydepth) && ($depth >= $CFG->maxcategorydepth-1));
2331 if ($courses && ($limit || $CFG->maxcategorydepth == 0)) {
2332 foreach ($courses as $course) {
2334 if (!$course->visible) {
2335 $linkcss = array('class'=>'dimmed');
2338 $coursename = get_course_display_name_for_list($course);
2339 $courselink = html_writer::link(new moodle_url('/course/view.php', array('id'=>$course->id)), format_string($coursename), $linkcss);
2343 if ($icons = enrol_get_course_info_icons($course)) {
2344 foreach ($icons as $pix_icon) {
2345 $courseicon = $OUTPUT->render($pix_icon).' ';
2349 $coursecontent = html_writer::tag('div', $courseicon.$courselink, array('class'=>'name'));
2351 if ($course->summary) {
2352 $link = new moodle_url('/course/info.php?id='.$course->id);
2353 $actionlink = $OUTPUT->action_link($link, '<img alt="'.$strsummary.'" src="'.$OUTPUT->pix_url('i/info') . '" />',
2354 new popup_action('click', $link, 'courseinfo', array('height' => 400, 'width' => 500)),
2355 array('title'=>$strsummary));
2357 $coursecontent .= html_writer::tag('div', $actionlink, array('class'=>'info'));
2361 for ($i=0; $i <= $depth; $i++) {
2362 $html = html_writer::tag('div', $html . $coursecontent , array('class'=>'indentation'));
2363 $coursecontent = '';
2365 echo html_writer::tag('div', $html, array('class'=>'course clearfloat'));
2370 echo '<div class="categorylist">';
2372 $cat = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
2373 if (count($courses) > 0) {
2374 $cat .= html_writer::tag('span', ' ('.count($courses).')', array('title'=>get_string('numberofcourses'), 'class'=>'numberofcourse'));
2378 for ($i=0; $i< $depth; $i++) {
2379 $html = html_writer::tag('div', $html .$cat, array('class'=>'indentation'));
2386 echo html_writer::tag('div', $html, array('class'=>'category'));
2387 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
2393 * Print the buttons relating to course requests.
2395 * @param object $systemcontext the system context.
2397 function print_course_request_buttons($systemcontext) {
2398 global $CFG, $DB, $OUTPUT;
2399 if (empty($CFG->enablecourserequests)) {
2402 if (!has_capability('moodle/course:create', $systemcontext) && has_capability('moodle/course:request', $systemcontext)) {
2403 /// Print a button to request a new course
2404 echo $OUTPUT->single_button('request.php', get_string('requestcourse'), 'get');
2406 /// Print a button to manage pending requests
2407 if (has_capability('moodle/site:approvecourse', $systemcontext)) {
2408 $disabled = !$DB->record_exists('course_request', array());
2409 echo $OUTPUT->single_button('pending.php', get_string('coursespending'), 'get', array('disabled'=>$disabled));
2414 * Does the user have permission to edit things in this category?
2416 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2417 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
2419 function can_edit_in_category($categoryid = 0) {
2420 $context = get_category_or_system_context($categoryid);
2421 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
2425 * Prints the turn editing on/off button on course/index.php or course/category.php.
2427 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2428 * @return string HTML of the editing button, or empty string, if this user is not allowed
2431 function update_category_button($categoryid = 0) {
2432 global $CFG, $PAGE, $OUTPUT;
2434 // Check permissions.
2435 if (!can_edit_in_category($categoryid)) {
2439 // Work out the appropriate action.
2440 if ($PAGE->user_is_editing()) {
2441 $label = get_string('turneditingoff');
2444 $label = get_string('turneditingon');
2448 // Generate the button HTML.
2449 $options = array('categoryedit' => $edit, 'sesskey' => sesskey());
2451 $options['id'] = $categoryid;
2452 $page = 'category.php';
2454 $page = 'index.php';
2456 return $OUTPUT->single_button(new moodle_url('/course/' . $page, $options), $label, 'get');
2460 * Category is 0 (for all courses) or an object
2462 function print_courses($category) {
2463 global $CFG, $OUTPUT;
2465 if (!is_object($category) && $category==0) {
2466 $categories = get_child_categories(0); // Parent = 0 ie top-level categories only
2467 if (is_array($categories) && count($categories) == 1) {
2468 $category = array_shift($categories);
2469 $courses = get_courses_wmanagers($category->id,
2471 array('summary','summaryformat'));
2473 $courses = get_courses_wmanagers('all',
2475 array('summary','summaryformat'));
2479 $courses = get_courses_wmanagers($category->id,
2481 array('summary','summaryformat'));
2485 echo html_writer::start_tag('ul', array('class'=>'unlist'));
2486 foreach ($courses as $course) {
2487 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
2488 if ($course->visible == 1 || has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2489 echo html_writer::start_tag('li');
2490 print_course($course);
2491 echo html_writer::end_tag('li');
2494 echo html_writer::end_tag('ul');
2496 echo $OUTPUT->heading(get_string("nocoursesyet"));
2497 $context = get_context_instance(CONTEXT_SYSTEM);
2498 if (has_capability('moodle/course:create', $context)) {
2500 if (!empty($category->id)) {
2501 $options['category'] = $category->id;
2503 $options['category'] = $CFG->defaultrequestcategory;
2505 echo html_writer::start_tag('div', array('class'=>'addcoursebutton'));
2506 echo $OUTPUT->single_button(new moodle_url('/course/edit.php', $options), get_string("addnewcourse"));
2507 echo html_writer::end_tag('div');
2513 * Print a description of a course, suitable for browsing in a list.
2515 * @param object $course the course object.
2516 * @param string $highlightterms (optional) some search terms that should be highlighted in the display.
2518 function print_course($course, $highlightterms = '') {
2519 global $CFG, $USER, $DB, $OUTPUT;
2521 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2523 // Rewrite file URLs so that they are correct
2524 $course->summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', NULL);
2526 echo html_writer::start_tag('div', array('class'=>'coursebox clearfix'));
2527 echo html_writer::start_tag('div', array('class'=>'info'));
2528 echo html_writer::start_tag('h3', array('class'=>'name'));
2530 $linkhref = new moodle_url('/course/view.php', array('id'=>$course->id));
2532 $coursename = get_course_display_name_for_list($course);
2533 $linktext = highlight($highlightterms, format_string($coursename));
2534 $linkparams = array('title'=>get_string('entercourse'));
2535 if (empty($course->visible)) {
2536 $linkparams['class'] = 'dimmed';
2538 echo html_writer::link($linkhref, $linktext, $linkparams);
2539 echo html_writer::end_tag('h3');
2541 /// first find all roles that are supposed to be displayed
2542 if (!empty($CFG->coursecontact)) {
2543 $managerroles = explode(',', $CFG->coursecontact);
2544 $namesarray = array();
2547 if (!isset($course->managers)) {
2548 $rusers = get_role_users($managerroles, $context, true,
2549 'ra.id AS raid, u.id, u.username, u.firstname, u.lastname,
2550 r.name AS rolename, r.sortorder, r.id AS roleid',
2551 'r.sortorder ASC, u.lastname ASC');
2553 // use the managers array if we have it for perf reasosn
2554 // populate the datastructure like output of get_role_users();
2555 foreach ($course->managers as $manager) {
2556 $u = new stdClass();
2557 $u = $manager->user;
2558 $u->roleid = $manager->roleid;
2559 $u->rolename = $manager->rolename;
2565 /// Rename some of the role names if needed
2566 if (isset($context)) {
2567 $aliasnames = $DB->get_records('role_names', array('contextid'=>$context->id), '', 'roleid,contextid,name');
2570 $namesarray = array();
2571 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2572 foreach ($rusers as $ra) {
2573 if (isset($namesarray[$ra->id])) {
2574 // only display a user once with the higest sortorder role
2578 if (isset($aliasnames[$ra->roleid])) {
2579 $ra->rolename = $aliasnames[$ra->roleid]->name;
2582 $fullname = fullname($ra, $canviewfullnames);
2583 $namesarray[$ra->id] = format_string($ra->rolename).': '.
2584 html_writer::link(new moodle_url('/user/view.php', array('id'=>$ra->id, 'course'=>SITEID)), $fullname);
2587 if (!empty($namesarray)) {
2588 echo html_writer::start_tag('ul', array('class'=>'teachers'));
2589 foreach ($namesarray as $name) {
2590 echo html_writer::tag('li', $name);
2592 echo html_writer::end_tag('ul');
2595 echo html_writer::end_tag('div'); // End of info div
2597 echo html_writer::start_tag('div', array('class'=>'summary'));
2598 $options = new stdClass();
2599 $options->noclean = true;
2600 $options->para = false;
2601 $options->overflowdiv = true;
2602 if (!isset($course->summaryformat)) {
2603 $course->summaryformat = FORMAT_MOODLE;
2605 echo highlight($highlightterms, format_text($course->summary, $course->summaryformat, $options, $course->id));
2606 if ($icons = enrol_get_course_info_icons($course)) {
2607 echo html_writer::start_tag('div', array('class'=>'enrolmenticons'));
2608 foreach ($icons as $icon) {
2609 echo $OUTPUT->render($icon);
2611 echo html_writer::end_tag('div'); // End of enrolmenticons div
2613 echo html_writer::end_tag('div'); // End of summary div
2614 echo html_writer::end_tag('div'); // End of coursebox div
2618 * Prints custom user information on the home page.
2619 * Over time this can include all sorts of information
2621 function print_my_moodle() {
2622 global $USER, $CFG, $DB, $OUTPUT;
2624 if (!isloggedin() or isguestuser()) {
2625 print_error('nopermissions', '', '', 'See My Moodle');
2628 $courses = enrol_get_my_courses('summary', 'visible DESC,sortorder ASC');
2630 $rcourses = array();
2631 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
2632 $rcourses = get_my_remotecourses($USER->id);
2633 $rhosts = get_my_remotehosts();
2636 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
2638 if (!empty($courses)) {
2639 echo '<ul class="unlist">';
2640 foreach ($courses as $course) {
2641 if ($course->id == SITEID) {
2645 print_course($course);
2652 if (!empty($rcourses)) {
2653 // at the IDP, we know of all the remote courses
2654 foreach ($rcourses as $course) {
2655 print_remote_course($course, "100%");
2657 } elseif (!empty($rhosts)) {
2658 // non-IDP, we know of all the remote servers, but not courses
2659 foreach ($rhosts as $host) {
2660 print_remote_host($host, "100%");
2666 if ($DB->count_records("course") > (count($courses) + 1) ) { // Some courses not being displayed
2667 echo "<table width=\"100%\"><tr><td align=\"center\">";
2668 print_course_search("", false, "short");
2669 echo "</td><td align=\"center\">";
2670 echo $OUTPUT->single_button("$CFG->wwwroot/course/index.php", get_string("fulllistofcourses"), "get");
2671 echo "</td></tr></table>\n";
2675 if ($DB->count_records("course_categories") > 1) {
2676 echo $OUTPUT->box_start("categorybox");
2677 print_whole_category_list();
2678 echo $OUTPUT->box_end();
2686 function print_course_search($value="", $return=false, $format="plain") {
2692 $id = 'coursesearch';
2698 $strsearchcourses= get_string("searchcourses");
2700 if ($format == 'plain') {
2701 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2702 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2703 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
2704 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" value="'.s($value).'" />';
2705 $output .= '<input type="submit" value="'.get_string('go').'" />';
2706 $output .= '</fieldset></form>';
2707 } else if ($format == 'short') {
2708 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2709 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2710 $output .= '<label for="shortsearchbox">'.$strsearchcourses.': </label>';
2711 $output .= '<input type="text" id="shortsearchbox" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2712 $output .= '<input type="submit" value="'.get_string('go').'" />';
2713 $output .= '</fieldset></form>';
2714 } else if ($format == 'navbar') {
2715 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2716 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2717 $output .= '<label for="navsearchbox">'.$strsearchcourses.': </label>';
2718 $output .= '<input type="text" id="navsearchbox" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2719 $output .= '<input type="submit" value="'.get_string('go').'" />';
2720 $output .= '</fieldset></form>';
2729 function print_remote_course($course, $width="100%") {
2734 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&wantsurl=/course/view.php?id={$course->remoteid}";
2736 echo '<div class="coursebox remotecoursebox clearfix">';
2737 echo '<div class="info">';
2738 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2739 $linkcss.' href="'.$url.'">'
2740 . format_string($course->fullname) .'</a><br />'
2741 . format_string($course->hostname) . ' : '
2742 . format_string($course->cat_name) . ' : '
2743 . format_string($course->shortname). '</div>';
2744 echo '</div><div class="summary">';
2745 $options = new stdClass();
2746 $options->noclean = true;
2747 $options->para = false;
2748 $options->overflowdiv = true;
2749 echo format_text($course->summary, $course->summaryformat, $options);
2754 function print_remote_host($host, $width="100%") {
2759 echo '<div class="coursebox clearfix">';
2760 echo '<div class="info">';
2761 echo '<div class="name">';
2762 echo '<img src="'.$OUTPUT->pix_url('i/mnethost') . '" class="icon" alt="'.get_string('course').'" />';
2763 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2764 . s($host['name']).'</a> - ';
2765 echo $host['count'] . ' ' . get_string('courses');
2772 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2774 function add_course_module($mod) {
2777 $mod->added = time();
2780 return $DB->insert_record("course_modules", $mod);
2784 * Returns course section - creates new if does not exist yet.
2785 * @param int $relative section number
2786 * @param int $courseid
2787 * @return object $course_section object
2789 function get_course_section($section, $courseid) {
2792 if ($cw = $DB->get_record("course_sections", array("section"=>$section, "course"=>$courseid))) {
2795 $cw = new stdClass();
2796 $cw->course = $courseid;
2797 $cw->section = $section;
2799 $cw->summaryformat = FORMAT_HTML;
2801 $id = $DB->insert_record("course_sections", $cw);
2802 rebuild_course_cache($courseid, true);
2803 return $DB->get_record("course_sections", array("id"=>$id));
2807 * Given a full mod object with section and course already defined, adds this module to that section.
2809 * @param object $mod
2810 * @param int $beforemod An existing ID which we will insert the new module before
2811 * @return int The course_sections ID where the mod is inserted
2813 function add_mod_to_section($mod, $beforemod=NULL) {
2816 if ($section = $DB->get_record("course_sections", array("course"=>$mod->course, "section"=>$mod->section))) {
2818 $section->sequence = trim($section->sequence);
2820 if (empty($section->sequence)) {
2821 $newsequence = "$mod->coursemodule";
2823 } else if ($beforemod) {
2824 $modarray = explode(",", $section->sequence);
2826 if ($key = array_keys($modarray, $beforemod->id)) {
2827 $insertarray = array($mod->id, $beforemod->id);
2828 array_splice($modarray, $key[0], 1, $insertarray);
2829 $newsequence = implode(",", $modarray);
2831 } else { // Just tack it on the end anyway
2832 $newsequence = "$section->sequence,$mod->coursemodule";
2836 $newsequence = "$section->sequence,$mod->coursemodule";
2839 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
2840 return $section->id; // Return course_sections ID that was used.
2842 } else { // Insert a new record
2843 $section = new stdClass();
2844 $section->course = $mod->course;
2845 $section->section = $mod->section;
2846 $section->summary = "";
2847 $section->summaryformat = FORMAT_HTML;
2848 $section->sequence = $mod->coursemodule;
2849 return $DB->insert_record("course_sections", $section);
2853 function set_coursemodule_groupmode($id, $groupmode) {
2855 return $DB->set_field("course_modules", "groupmode", $groupmode, array("id"=>$id));
2858 function set_coursemodule_idnumber($id, $idnumber) {
2860 return $DB->set_field("course_modules", "idnumber", $idnumber, array("id"=>$id));
2864 * $prevstateoverrides = true will set the visibility of the course module
2865 * to what is defined in visibleold. This enables us to remember the current
2866 * visibility when making a whole section hidden, so that when we toggle
2867 * that section back to visible, we are able to return the visibility of
2868 * the course module back to what it was originally.
2870 function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
2872 require_once($CFG->libdir.'/gradelib.php');
2874 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2877 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
2880 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2881 foreach($events as $event) {
2890 // hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there
2891 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
2893 foreach ($grade_items as $grade_item) {
2894 $grade_item->set_hidden(!$visible);
2898 if ($prevstateoverrides) {
2899 if ($visible == '0') {
2900 // Remember the current visible state so we can toggle this back.
2901 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id'=>$id));
2903 // Get the previous saved visible states.
2904 return $DB->set_field('course_modules', 'visible', $cm->visibleold, array('id'=>$id));
2907 return $DB->set_field("course_modules", "visible", $visible, array("id"=>$id));
2911 * Delete a course module and any associated data at the course level (events)
2912 * Until 1.5 this function simply marked a deleted flag ... now it
2913 * deletes it completely.
2916 function delete_course_module($id) {
2918 require_once($CFG->libdir.'/gradelib.php');
2919 require_once($CFG->dirroot.'/blog/lib.php');
2921 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2924 $modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module));
2925 //delete events from calendar
2926 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2927 foreach($events as $event) {
2928 delete_event($event->id);
2931 //delete grade items, outcome items and grades attached to modules
2932 if ($grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2933 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course))) {
2934 foreach ($grade_items as $grade_item) {
2935 $grade_item->delete('moddelete');
2938 // Delete completion and availability data; it is better to do this even if the
2939 // features are not turned on, in case they were turned on previously (these will be
2940 // very quick on an empty table)
2941 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
2942 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id));
2943 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
2944 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
2946 delete_context(CONTEXT_MODULE, $cm->id);
2947 return $DB->delete_records('course_modules', array('id'=>$cm->id));
2950 function delete_mod_from_section($mod, $section) {
2953 if ($section = $DB->get_record("course_sections", array("id"=>$section)) ) {
2955 $modarray = explode(",", $section->sequence);
2957 if ($key = array_keys ($modarray, $mod)) {
2958 array_splice($modarray, $key[0], 1);
2959 $newsequence = implode(",", $modarray);
2960 return $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
2970 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
2972 * @param object $course course object
2973 * @param int $section Section number (not id!!!)
2974 * @param int $move (-1 or 1)
2975 * @return boolean true if section moved successfully
2976 * @todo MDL-33379 remove this function in 2.5
2978 function move_section($course, $section, $move) {
2979 debugging('This function will be removed before 2.5 is released please use move_section_to', DEBUG_DEVELOPER);
2981 /// Moves a whole course section up and down within the course
2988 $sectiondest = $section + $move;
2990 if ($sectiondest > $course->numsections or $sectiondest < 1) {
2994 $retval = move_section_to($course, $section, $sectiondest);
2995 // If section moved, then rebuild course cache.
2997 rebuild_course_cache($course->id, true);
3003 * Moves a section within a course, from a position to another.
3004 * Be very careful: $section and $destination refer to section number,
3007 * @param object $course
3008 * @param int $section Section number (not id!!!)
3009 * @param int $destination
3010 * @return boolean Result
3012 function move_section_to($course, $section, $destination) {
3013 /// Moves a whole course section up and down within the course
3016 if (!$destination && $destination != 0) {
3020 if (($destination > $course->numsections) || ($destination < 1)) {
3024 // Get all sections for this course and re-order them (2 of them should now share the same section number)
3025 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
3026 'section ASC, id ASC', 'id, section')) {
3030 $movedsections = reorder_sections($sections, $section, $destination);
3032 // Update all sections. Do this in 2 steps to avoid breaking database
3033 // uniqueness constraint
3034 $transaction = $DB->start_delegated_transaction();
3035 foreach ($movedsections as $id => $position) {
3036 if ($sections[$id] !== $position) {
3037 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
3040 foreach ($movedsections as $id => $position) {
3041 if ($sections[$id] !== $position) {
3042 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
3046 // If we move the highlighted section itself, then just highlight the destination.
3047 // Adjust the higlighted section location if we move something over it either direction.
3048 if ($section == $course->marker) {
3049 course_set_marker($course->id, $destination);
3050 } elseif ($section > $course->marker && $course->marker >= $destination) {
3051 course_set_marker($course->id, $course->marker+1);
3052 } elseif ($section < $course->marker && $course->marker <= $destination) {
3053 course_set_marker($course->id, $course->marker-1);
3056 $transaction->allow_commit();
3061 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
3062 * an original position number and a target position number, rebuilds the array so that the
3063 * move is made without any duplication of section positions.
3064 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
3065 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
3067 * @param array $sections
3068 * @param int $origin_position
3069 * @param int $target_position
3072 function reorder_sections($sections, $origin_position, $target_position) {
3073 if (!is_array($sections)) {
3077 // We can't move section position 0
3078 if ($origin_position < 1) {
3079 echo "We can't move section position 0";
3083 // Locate origin section in sections array
3084 if (!$origin_key = array_search($origin_position, $sections)) {
3085 echo "searched position not in sections array";
3086 return false; // searched position not in sections array
3089 // Extract origin section
3090 $origin_section = $sections[$origin_key];
3091 unset($sections[$origin_key]);
3093 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
3095 $append_array = array();
3096 foreach ($sections as $id => $position) {
3098 $append_array[$id] = $position;
3099 unset($sections[$id]);
3101 if ($position == $target_position) {
3102 if ($target_position < $origin_position) {
3103 $append_array[$id] = $position;
3104 unset($sections[$id]);
3110 // Append moved section
3111 $sections[$origin_key] = $origin_section;
3113 // Append rest of array (if applicable)
3114 if (!empty($append_array)) {
3115 foreach ($append_array as $id => $position) {
3116 $sections[$id] = $position;
3120 // Renumber positions
3122 foreach ($sections as $id => $p) {
3123 $sections[$id] = $position;
3132 * Move the module object $mod to the specified $section
3133 * If $beforemod exists then that is the module
3134 * before which $modid should be inserted
3135 * All parameters are objects
3137 function moveto_module($mod, $section, $beforemod=NULL) {
3138 global $DB, $OUTPUT;
3140 /// Remove original module from original section
3141 if (! delete_mod_from_section($mod->id, $mod->section)) {
3142 echo $OUTPUT->notification("Could not delete module from existing section");
3145 /// Update module itself if necessary
3147 if ($mod->section != $section->id) {
3148 $mod->section = $section->id;
3149 $DB->update_record("course_modules", $mod);
3150 // if moving to a hidden section then hide module
3151 if (!$section->visible) {
3152 set_coursemodule_visible($mod->id, 0);
3156 /// Add the module into the new section
3158 $mod->course = $section->course;
3159 $mod->section = $section->section; // need relative reference
3160 $mod->coursemodule = $mod->id;
3162 if (! add_mod_to_section($mod, $beforemod)) {
3170 * Produces the editing buttons for a module
3172 * @global core_renderer $OUTPUT
3173 * @staticvar type $str
3174 * @param stdClass $mod The module to produce editing buttons for
3175 * @param bool $absolute_ignored ignored - all links are absolute
3176 * @param bool $moveselect If true a move seleciton process is used (default true)
3177 * @param int $indent The current indenting
3178 * @param int $section The section to link back to
3179 * @return string XHTML for the editing buttons
3181 function make_editing_buttons(stdClass $mod, $absolute_ignored = true, $moveselect = true, $indent=-1, $section=null) {
3182 global $CFG, $OUTPUT, $COURSE;
3186 $coursecontext = get_context_instance(CONTEXT_COURSE, $mod->course);
3187 $modcontext = get_context_instance(CONTEXT_MODULE, $mod->id);
3189 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
3190 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
3192 // no permission to edit anything
3193 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
3197 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
3200 $str = new stdClass;
3201 $str->assign = get_string("assignroles", 'role');
3202 $str->delete = get_string("delete");
3203 $str->move = get_string("move");
3204 $str->moveup = get_string("moveup");
3205 $str->movedown = get_string("movedown");
3206 $str->moveright = get_string("moveright");
3207 $str->moveleft = get_string("moveleft");
3208 $str->update = get_string("update");
3209 $str->duplicate = get_string("duplicate");
3210 $str->hide = get_string("hide");
3211 $str->show = get_string("show");
3212 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
3213 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
3214 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
3215 $str->forcedgroupsnone = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsnone"));
3216 $str->forcedgroupsseparate = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsseparate"));
3217 $str->forcedgroupsvisible = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsvisible"));
3218 $str->edittitle = get_string('edittitle', 'moodle');
3221 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
3223 if ($section !== null) {
3224 $baseurl->param('sr', $section);
3229 if ($mod->modname !== 'label' && $hasmanageactivities && course_ajax_enabled($COURSE)) {
3230 $actions[] = new action_link(
3231 new moodle_url($baseurl, array('update' => $mod->id)),
3232 new pix_icon('t/editstring', $str->edittitle, 'moodle', array('class' => 'iconsmall visibleifjs', 'title' => '')),
3234 array('class' => 'editing_title', 'title' => $str->edittitle)
3239 if ($hasmanageactivities) {
3240 if (right_to_left()) { // Exchange arrows on RTL
3241 $rightarrow = 't/left';
3242 $leftarrow = 't/right';
3244 $rightarrow = 't/right';
3245 $leftarrow = 't/left';
3249 $actions[] = new action_link(
3250 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
3251 new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3253 array('class' => 'editing_moveleft', 'title' => $str->moveleft)
3257 $actions[] = new action_link(
3258 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
3259 new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3261 array('class' => 'editing_moveright', 'title' => $str->moveright)
3267 if ($hasmanageactivities) {
3269 $actions[] = new action_link(
3270 new moodle_url($baseurl, array('copy' => $mod->id)),
3271 new pix_icon('t/move', $str->move, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3273 array('class' => 'editing_move', 'title' => $str->move)
3276 $actions[] = new action_link(
3277 new moodle_url($baseurl, array('id' => $mod->id, 'move' => '-1')),
3278 new pix_icon('t/up', $str->moveup, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3280 array('class' => 'editing_moveup', 'title' => $str->moveup)
3282 $actions[] = new action_link(
3283 new moodle_url($baseurl, array('id' => $mod->id, 'move' => '1')),
3284 new pix_icon('t/down', $str->movedown, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3286 array('class' => 'editing_movedown', 'title' => $str->movedown)
3292 if ($hasmanageactivities) {
3293 $actions[] = new action_link(
3294 new moodle_url($baseurl, array('update' => $mod->id)),
3295 new pix_icon('t/edit', $str->update, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3297 array('class' => 'editing_update', 'title' => $str->update)
3301 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
3302 if (has_all_capabilities($dupecaps, $coursecontext) && plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2)) {
3303 $actions[] = new action_link(
3304 new moodle_url($baseurl, array('duplicate' => $mod->id)),
3305 new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3307 array('class' => 'editing_duplicate', 'title' => $str->duplicate)
3312 if ($hasmanageactivities) {
3313 $actions[] = new action_link(
3314 new moodle_url($baseurl, array('delete' => $mod->id)),
3315 new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3317 array('class' => 'editing_delete', 'title' => $str->delete)
3322 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
3323 if ($mod->visible) {
3324 $actions[] = new action_link(
3325 new moodle_url($baseurl, array('hide' => $mod->id)),
3326 new pix_icon('t/hide', $str->hide, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3328 array('class' => 'editing_hide', 'title' => $str->hide)
3331 $actions[] = new action_link(
3332 new moodle_url($baseurl, array('show' => $mod->id)),
3333 new pix_icon('t/show', $str->show, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3335 array('class' => 'editing_show', 'title' => $str->show)
3341 if ($hasmanageactivities and $mod->groupmode !== false) {
3342 if ($mod->groupmode == SEPARATEGROUPS) {
3344 $grouptitle = $str->groupsseparate;
3345 $forcedgrouptitle = $str->forcedgroupsseparate;
3346 $groupclass = 'editing_groupsseparate';
3347 $groupimage = 't/groups';
3348 } else if ($mod->groupmode == VISIBLEGROUPS) {
3350 $grouptitle = $str->groupsvisible;
3351 $forcedgrouptitle = $str->forcedgroupsvisible;
3352 $groupclass = 'editing_groupsvisible';
3353 $groupimage = 't/groupv';
3356 $grouptitle = $str->groupsnone;
3357 $forcedgrouptitle = $str->forcedgroupsnone;
3358 $groupclass = 'editing_groupsnone';
3359 $groupimage = 't/groupn';
3361 if ($mod->groupmodelink) {
3362 $actions[] = new action_link(
3363 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $groupmode)),
3364 new pix_icon($groupimage, $grouptitle, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3366 array('class' => $groupclass, 'title' => $grouptitle)
3369 $actions[] = new pix_icon($groupimage, $forcedgrouptitle, 'moodle', array('title' => $forcedgrouptitle, 'class' => 'iconsmall'));
3374 if (has_capability('moodle/role:assign', $modcontext)){
3375 $actions[] = new action_link(
3376 new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $modcontext->id)),
3377 new pix_icon('i/roles', $str->assign, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3379 array('class' => 'editing_assign', 'title' => $str->assign)
3383 $output = html_writer::start_tag('span', array('class' => 'commands'));
3384 foreach ($actions as $action) {
3385 if ($action instanceof renderable) {
3386 $output .= $OUTPUT->render($action);
3391 $output .= html_writer::end_tag('span');
3396 * given a course object with shortname & fullname, this function will
3397 * truncate the the number of chars allowed and add ... if it was too long
3399 function course_format_name ($course,$max=100) {
3401 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3402 $shortname = format_string($course->shortname, true, array('context' => $context));
3403 $fullname = format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
3404 $str = $shortname.': '. $fullname;
3405 if (textlib::strlen($str) <= $max) {
3409 return textlib::substr($str,0,$max-3).'...';
3414 * Is the user allowed to add this type of module to this course?
3415 * @param object $course the course settings. Only $course->id is used.
3416 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
3417 * @return bool whether the current user is allowed to add this type of module to this course.
3419 function course_allowed_module($course, $modname) {
3422 if (is_numeric($modname)) {
3423 throw new coding_exception('Function course_allowed_module no longer
3424 supports numeric module ids. Please update your code to pass the module name.');
3427 $capability = 'mod/' . $modname . ':addinstance';
3428 if (!get_capability_info($capability)) {
3429 // Debug warning that the capability does not exist, but no more than once per page.
3430 static $warned = array();
3431 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
3432 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
3433 debugging('The module ' . $modname . ' does not define the standard capability ' .
3434 $capability , DEBUG_DEVELOPER);
3435 $warned[$modname] = 1;
3438 // If the capability does not exist, the module can always be added.
3442 $coursecontext = context_course::instance($course->id);
3443 return has_capability($capability, $coursecontext);
3447 * Recursively delete category including all subcategories and courses.
3448 * @param stdClass $category
3449 * @param boolean $showfeedback display some notices
3450 * @return array return deleted courses
3452 function category_delete_full($category, $showfeedback=true) {
3454 require_once($CFG->libdir.'/gradelib.php');
3455 require_once($CFG->libdir.'/questionlib.php');
3456 require_once($CFG->dirroot.'/cohort/lib.php');
3458 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3459 foreach ($children as $childcat) {
3460 category_delete_full($childcat, $showfeedback);
3464 $deletedcourses = array();
3465 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC')) {
3466 foreach ($courses as $course) {
3467 if (!delete_course($course, false)) {
3468 throw new moodle_exception('cannotdeletecategorycourse','','',$course->shortname);