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', context_course::instance($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', context_course::instance($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', context_course::instance($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' => context_course::instance(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', context_course::instance($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 && !empty($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 = context_course::instance($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 $text = implode("\t", $row);
610 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
611 $modid, $modaction, $groupid) {
615 require_once("$CFG->libdir/excellib.class.php");
617 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
618 $modname, $modid, $modaction, $groupid)) {
624 if ($course->id == SITEID) {
626 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
627 foreach ($ccc as $cc) {
628 $courses[$cc->id] = $cc->shortname;
632 $courses[$course->id] = $course->shortname;
637 $tt = getdate(time());
638 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
640 $strftimedatetime = get_string("strftimedatetime");
642 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
643 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
646 $workbook = new MoodleExcelWorkbook('-');
647 $workbook->send($filename);
649 $worksheet = array();
650 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
651 get_string('fullnameuser'), get_string('action'), get_string('info'));
653 // Creating worksheets
654 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
655 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
656 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
657 $worksheet[$wsnumber]->set_column(1, 1, 30);
658 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
659 userdate(time(), $strftimedatetime));
661 foreach ($headers as $item) {
662 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
667 if (empty($logs['logs'])) {
672 $formatDate =& $workbook->add_format();
673 $formatDate->set_num_format(get_string('log_excel_date_format'));
675 $row = FIRSTUSEDEXCELROW;
677 $myxls =& $worksheet[$wsnumber];
678 foreach ($logs['logs'] as $log) {
679 if (isset($ldcache[$log->module][$log->action])) {
680 $ld = $ldcache[$log->module][$log->action];
682 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
683 $ldcache[$log->module][$log->action] = $ld;
685 if ($ld && !empty($log->info)) {
686 // ugly hack to make sure fullname is shown correctly
687 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
688 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
690 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
695 $log->info = format_string($log->info);
696 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
699 if ($row > EXCELROWS) {
701 $myxls =& $worksheet[$wsnumber];
702 $row = FIRSTUSEDEXCELROW;
706 $coursecontext = context_course::instance($course->id);
708 $myxls->write($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)), '');
709 $myxls->write_date($row, 1, $log->time, $formatDate); // write_date() does conversion/timezone support. MDL-14934
710 $myxls->write($row, 2, $log->ip, '');
711 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
712 $myxls->write($row, 3, $fullname, '');
713 $myxls->write($row, 4, $log->module.' '.$log->action, '');
714 $myxls->write($row, 5, $log->info, '');
723 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
724 $modid, $modaction, $groupid) {
728 require_once("$CFG->libdir/odslib.class.php");
730 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
731 $modname, $modid, $modaction, $groupid)) {
737 if ($course->id == SITEID) {
739 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
740 foreach ($ccc as $cc) {
741 $courses[$cc->id] = $cc->shortname;
745 $courses[$course->id] = $course->shortname;
750 $tt = getdate(time());
751 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
753 $strftimedatetime = get_string("strftimedatetime");
755 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
756 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
759 $workbook = new MoodleODSWorkbook('-');
760 $workbook->send($filename);
762 $worksheet = array();
763 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
764 get_string('fullnameuser'), get_string('action'), get_string('info'));
766 // Creating worksheets
767 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
768 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
769 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
770 $worksheet[$wsnumber]->set_column(1, 1, 30);
771 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
772 userdate(time(), $strftimedatetime));
774 foreach ($headers as $item) {
775 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
780 if (empty($logs['logs'])) {
785 $formatDate =& $workbook->add_format();
786 $formatDate->set_num_format(get_string('log_excel_date_format'));
788 $row = FIRSTUSEDEXCELROW;
790 $myxls =& $worksheet[$wsnumber];
791 foreach ($logs['logs'] as $log) {
792 if (isset($ldcache[$log->module][$log->action])) {
793 $ld = $ldcache[$log->module][$log->action];
795 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
796 $ldcache[$log->module][$log->action] = $ld;
798 if ($ld && !empty($log->info)) {
799 // ugly hack to make sure fullname is shown correctly
800 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
801 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
803 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
808 $log->info = format_string($log->info);
809 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
812 if ($row > EXCELROWS) {
814 $myxls =& $worksheet[$wsnumber];
815 $row = FIRSTUSEDEXCELROW;
819 $coursecontext = context_course::instance($course->id);
821 $myxls->write_string($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)));
822 $myxls->write_date($row, 1, $log->time);
823 $myxls->write_string($row, 2, $log->ip);
824 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
825 $myxls->write_string($row, 3, $fullname);
826 $myxls->write_string($row, 4, $log->module.' '.$log->action);
827 $myxls->write_string($row, 5, $log->info);
837 function print_overview($courses, array $remote_courses=array()) {
838 global $CFG, $USER, $DB, $OUTPUT;
840 $htmlarray = array();
841 if ($modules = $DB->get_records('modules')) {
842 foreach ($modules as $mod) {
843 if (file_exists(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php')) {
844 include_once(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php');
845 $fname = $mod->name.'_print_overview';
846 if (function_exists($fname)) {
847 $fname($courses,$htmlarray);
852 foreach ($courses as $course) {
853 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
854 echo $OUTPUT->box_start('coursebox');
855 $attributes = array('title' => s($fullname));
856 if (empty($course->visible)) {
857 $attributes['class'] = 'dimmed';
859 echo $OUTPUT->heading(html_writer::link(
860 new moodle_url('/course/view.php', array('id' => $course->id)), $fullname, $attributes), 3);
861 if (array_key_exists($course->id,$htmlarray)) {
862 foreach ($htmlarray[$course->id] as $modname => $html) {
866 echo $OUTPUT->box_end();
869 if (!empty($remote_courses)) {
870 echo $OUTPUT->heading(get_string('remotecourses', 'mnet'));
872 foreach ($remote_courses as $course) {
873 echo $OUTPUT->box_start('coursebox');
874 $attributes = array('title' => s($course->fullname));
875 echo $OUTPUT->heading(html_writer::link(
876 new moodle_url('/auth/mnet/jump.php', array('hostid' => $course->hostid, 'wantsurl' => '/course/view.php?id='.$course->remoteid)),
877 format_string($course->shortname),
878 $attributes) . ' (' . format_string($course->hostname) . ')', 3);
879 echo $OUTPUT->box_end();
885 * This function trawls through the logs looking for
886 * anything new since the user's last login
888 function print_recent_activity($course) {
889 // $course is an object
890 global $CFG, $USER, $SESSION, $DB, $OUTPUT;
892 $context = context_course::instance($course->id);
894 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
896 $timestart = round(time() - COURSE_MAX_RECENT_PERIOD, -2); // better db caching for guests - 100 seconds
898 if (!isguestuser()) {
899 if (!empty($USER->lastcourseaccess[$course->id])) {
900 if ($USER->lastcourseaccess[$course->id] > $timestart) {
901 $timestart = $USER->lastcourseaccess[$course->id];
906 echo '<div class="activitydate">';
907 echo get_string('activitysince', '', userdate($timestart));
909 echo '<div class="activityhead">';
911 echo '<a href="'.$CFG->wwwroot.'/course/recent.php?id='.$course->id.'">'.get_string('recentactivityreport').'</a>';
917 /// Firstly, have there been any new enrolments?
919 $users = get_recent_enrolments($course->id, $timestart);
921 //Accessibility: new users now appear in an <OL> list.
923 echo '<div class="newusers">';
924 echo $OUTPUT->heading(get_string("newusers").':', 3);
926 echo "<ol class=\"list\">\n";
927 foreach ($users as $user) {
928 $fullname = fullname($user, $viewfullnames);
929 echo '<li class="name"><a href="'."$CFG->wwwroot/user/view.php?id=$user->id&course=$course->id\">$fullname</a></li>\n";
931 echo "</ol>\n</div>\n";
934 /// Next, have there been any modifications to the course structure?
936 $modinfo = get_fast_modinfo($course);
938 $changelist = array();
940 $logs = $DB->get_records_select('log', "time > ? AND course = ? AND
941 module = 'course' AND
942 (action = 'add mod' OR action = 'update mod' OR action = 'delete mod')",
943 array($timestart, $course->id), "id ASC");
946 $actions = array('add mod', 'update mod', 'delete mod');
947 $newgones = array(); // added and later deleted items
948 foreach ($logs as $key => $log) {
949 if (!in_array($log->action, $actions)) {
952 $info = explode(' ', $log->info);
954 // note: in most cases I replaced hardcoding of label with use of
955 // $cm->has_view() but it was not possible to do this here because
956 // we don't necessarily have the $cm for it
957 if ($info[0] == 'label') { // Labels are ignored in recent activity
961 if (count($info) != 2) {
962 debugging("Incorrect log entry info: id = ".$log->id, DEBUG_DEVELOPER);
967 $instanceid = $info[1];
969 if ($log->action == 'delete mod') {
970 // unfortunately we do not know if the mod was visible
971 if (!array_key_exists($log->info, $newgones)) {
972 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $modname));
973 $changelist[$log->info] = array ('operation' => 'delete', 'text' => $strdeleted);
976 if (!isset($modinfo->instances[$modname][$instanceid])) {
977 if ($log->action == 'add mod') {
978 // do not display added and later deleted activities
979 $newgones[$log->info] = true;
983 $cm = $modinfo->instances[$modname][$instanceid];
984 if (!$cm->uservisible) {
988 if ($log->action == 'add mod') {
989 $stradded = get_string('added', 'moodle', get_string('modulename', $modname));
990 $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>");
992 } else if ($log->action == 'update mod' and empty($changelist[$log->info])) {
993 $strupdated = get_string('updated', 'moodle', get_string('modulename', $modname));
994 $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>");
1000 if (!empty($changelist)) {
1001 echo $OUTPUT->heading(get_string("courseupdates").':', 3);
1003 foreach ($changelist as $changeinfo => $change) {
1004 echo '<p class="activity">'.$change['text'].'</p>';
1008 /// Now display new things from each module
1010 $usedmodules = array();
1011 foreach($modinfo->cms as $cm) {
1012 if (isset($usedmodules[$cm->modname])) {
1015 if (!$cm->uservisible) {
1018 $usedmodules[$cm->modname] = $cm->modname;
1021 foreach ($usedmodules as $modname) { // Each module gets it's own logs and prints them
1022 if (file_exists($CFG->dirroot.'/mod/'.$modname.'/lib.php')) {
1023 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
1024 $print_recent_activity = $modname.'_print_recent_activity';
1025 if (function_exists($print_recent_activity)) {
1026 // NOTE: original $isteacher (second parameter below) was replaced with $viewfullnames!
1027 $content = $print_recent_activity($course, $viewfullnames, $timestart) || $content;
1030 debugging("Missing lib.php in lib/{$modname} - please reinstall files or uninstall the module");
1035 echo '<p class="message">'.get_string('nothingnew').'</p>';
1040 * For a given course, returns an array of course activity objects
1041 * Each item in the array contains he following properties:
1043 function get_array_of_activities($courseid) {
1044 // cm - course module id
1045 // mod - name of the module (eg forum)
1046 // section - the number of the section (eg week or topic)
1047 // name - the name of the instance
1048 // visible - is the instance visible or not
1049 // groupingid - grouping id
1050 // groupmembersonly - is this instance visible to group members only
1051 // extra - contains extra string to include in any link
1053 if(!empty($CFG->enableavailability)) {
1054 require_once($CFG->libdir.'/conditionlib.php');
1057 $course = $DB->get_record('course', array('id'=>$courseid));
1059 if (empty($course)) {
1060 throw new moodle_exception('courseidnotfound');
1065 $rawmods = get_course_mods($courseid);
1066 if (empty($rawmods)) {
1067 return $mod; // always return array
1070 if ($sections = $DB->get_records("course_sections", array("course"=>$courseid), "section ASC")) {
1071 foreach ($sections as $section) {
1072 if (!empty($section->sequence)) {
1073 $sequence = explode(",", $section->sequence);
1074 foreach ($sequence as $seq) {
1075 if (empty($rawmods[$seq])) {
1078 $mod[$seq] = new stdClass();
1079 $mod[$seq]->id = $rawmods[$seq]->instance;
1080 $mod[$seq]->cm = $rawmods[$seq]->id;
1081 $mod[$seq]->mod = $rawmods[$seq]->modname;
1083 // Oh dear. Inconsistent names left here for backward compatibility.
1084 $mod[$seq]->section = $section->section;
1085 $mod[$seq]->sectionid = $rawmods[$seq]->section;
1087 $mod[$seq]->module = $rawmods[$seq]->module;
1088 $mod[$seq]->added = $rawmods[$seq]->added;
1089 $mod[$seq]->score = $rawmods[$seq]->score;
1090 $mod[$seq]->idnumber = $rawmods[$seq]->idnumber;
1091 $mod[$seq]->visible = $rawmods[$seq]->visible;
1092 $mod[$seq]->visibleold = $rawmods[$seq]->visibleold;
1093 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
1094 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
1095 $mod[$seq]->groupmembersonly = $rawmods[$seq]->groupmembersonly;
1096 $mod[$seq]->indent = $rawmods[$seq]->indent;
1097 $mod[$seq]->completion = $rawmods[$seq]->completion;
1098 $mod[$seq]->extra = "";
1099 $mod[$seq]->completiongradeitemnumber =
1100 $rawmods[$seq]->completiongradeitemnumber;
1101 $mod[$seq]->completionview = $rawmods[$seq]->completionview;
1102 $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected;
1103 $mod[$seq]->availablefrom = $rawmods[$seq]->availablefrom;
1104 $mod[$seq]->availableuntil = $rawmods[$seq]->availableuntil;
1105 $mod[$seq]->showavailability = $rawmods[$seq]->showavailability;
1106 $mod[$seq]->showdescription = $rawmods[$seq]->showdescription;
1107 if (!empty($CFG->enableavailability)) {
1108 condition_info::fill_availability_conditions($rawmods[$seq]);
1109 $mod[$seq]->conditionscompletion = $rawmods[$seq]->conditionscompletion;
1110 $mod[$seq]->conditionsgrade = $rawmods[$seq]->conditionsgrade;
1111 $mod[$seq]->conditionsfield = $rawmods[$seq]->conditionsfield;
1114 $modname = $mod[$seq]->mod;
1115 $functionname = $modname."_get_coursemodule_info";
1117 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
1121 include_once("$CFG->dirroot/mod/$modname/lib.php");
1123 if ($hasfunction = function_exists($functionname)) {
1124 if ($info = $functionname($rawmods[$seq])) {
1125 if (!empty($info->icon)) {
1126 $mod[$seq]->icon = $info->icon;
1128 if (!empty($info->iconcomponent)) {
1129 $mod[$seq]->iconcomponent = $info->iconcomponent;
1131 if (!empty($info->name)) {
1132 $mod[$seq]->name = $info->name;
1134 if ($info instanceof cached_cm_info) {
1135 // When using cached_cm_info you can include three new fields
1136 // that aren't available for legacy code
1137 if (!empty($info->content)) {
1138 $mod[$seq]->content = $info->content;
1140 if (!empty($info->extraclasses)) {
1141 $mod[$seq]->extraclasses = $info->extraclasses;
1143 if (!empty($info->iconurl)) {
1144 $mod[$seq]->iconurl = $info->iconurl;
1146 if (!empty($info->onclick)) {
1147 $mod[$seq]->onclick = $info->onclick;
1149 if (!empty($info->customdata)) {
1150 $mod[$seq]->customdata = $info->customdata;
1153 // When using a stdclass, the (horrible) deprecated ->extra field
1154 // is available for BC
1155 if (!empty($info->extra)) {
1156 $mod[$seq]->extra = $info->extra;
1161 // When there is no modname_get_coursemodule_info function,
1162 // but showdescriptions is enabled, then we use the 'intro'
1163 // and 'introformat' fields in the module table
1164 if (!$hasfunction && $rawmods[$seq]->showdescription) {
1165 if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
1166 array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
1167 // Set content from intro and introformat. Filters are disabled
1168 // because we filter it with format_text at display time
1169 $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
1170 $modvalues, $rawmods[$seq]->id, false);
1172 // To save making another query just below, put name in here
1173 $mod[$seq]->name = $modvalues->name;
1176 if (!isset($mod[$seq]->name)) {
1177 $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
1180 // Minimise the database size by unsetting default options when they are
1181 // 'empty'. This list corresponds to code in the cm_info constructor.
1182 foreach (array('idnumber', 'groupmode', 'groupingid', 'groupmembersonly',
1183 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
1184 'icon', 'iconcomponent', 'customdata', 'showavailability', 'availablefrom',
1185 'availableuntil', 'conditionscompletion', 'conditionsgrade',
1186 'completionview', 'completionexpected', 'score', 'showdescription')
1188 if (property_exists($mod[$seq], $property) &&
1189 empty($mod[$seq]->{$property})) {
1190 unset($mod[$seq]->{$property});
1193 // Special case: this value is usually set to null, but may be 0
1194 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
1195 is_null($mod[$seq]->completiongradeitemnumber)) {
1196 unset($mod[$seq]->completiongradeitemnumber);
1207 * Returns a number of useful structures for course displays
1209 function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
1210 global $CFG, $DB, $COURSE;
1212 $mods = array(); // course modules indexed by id
1213 $modnames = array(); // all course module names (except resource!)
1214 $modnamesplural= array(); // all course module names (plural form)
1215 $modnamesused = array(); // course module names used
1217 if ($allmods = $DB->get_records("modules")) {
1218 foreach ($allmods as $mod) {
1219 if (!file_exists("$CFG->dirroot/mod/$mod->name/lib.php")) {
1222 if ($mod->visible) {
1223 $modnames[$mod->name] = get_string("modulename", "$mod->name");
1224 $modnamesplural[$mod->name] = get_string("modulenameplural", "$mod->name");
1227 collatorlib::asort($modnames);
1229 print_error("nomodules", 'debug');
1232 $course = ($courseid==$COURSE->id) ? $COURSE : $DB->get_record('course',array('id'=>$courseid));
1233 $modinfo = get_fast_modinfo($course);
1235 if ($rawmods=$modinfo->cms) {
1236 foreach($rawmods as $mod) { // Index the mods
1237 if (empty($modnames[$mod->modname])) {
1240 $mods[$mod->id] = $mod;
1241 $mods[$mod->id]->modfullname = $modnames[$mod->modname];
1242 if (!$mod->visible and !has_capability('moodle/course:viewhiddenactivities', context_course::instance($courseid))) {
1246 if (!groups_course_module_visible($mod)) {
1249 $modnamesused[$mod->modname] = $modnames[$mod->modname];
1251 if ($modnamesused) {
1252 collatorlib::asort($modnamesused);
1258 * Returns an array of sections for the requested course id
1260 * This function stores the sections against the course id within a staticvar encase
1261 * of subsequent requests. This is used all over + in some standard libs and course
1262 * format callbacks so subsequent requests are a reality.
1264 * Note: Since Moodle 2.3, it is more efficient to get this data by calling
1265 * get_fast_modinfo, then using $modinfo->get_section_info or get_section_info_all.
1267 * @staticvar array $coursesections
1268 * @param int $courseid
1269 * @return array Array of sections
1271 function get_all_sections($courseid) {
1273 static $coursesections = array();
1274 if (!array_key_exists($courseid, $coursesections)) {
1275 $coursesections[$courseid] = $DB->get_records("course_sections", array("course"=>"$courseid"), "section",
1276 'section, id, course, name, summary, summaryformat, sequence, visible, ' .
1277 'availablefrom, availableuntil, showavailability, groupingid');
1279 return $coursesections[$courseid];
1283 * Set highlighted section. Only one section can be highlighted at the time.
1285 * @param int $courseid course id
1286 * @param int $marker highlight section with this number, 0 means remove higlightin
1289 function course_set_marker($courseid, $marker) {
1291 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
1295 * For a given course section, marks it visible or hidden,
1296 * and does the same for every activity in that section
1298 * @param int $courseid course id
1299 * @param int $sectionnumber The section number to adjust
1300 * @param int $visibility The new visibility
1301 * @return array A list of resources which were hidden in the section
1303 function set_section_visible($courseid, $sectionnumber, $visibility) {
1306 $resourcestotoggle = array();
1307 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
1308 $DB->set_field("course_sections", "visible", "$visibility", array("id"=>$section->id));
1309 if (!empty($section->sequence)) {
1310 $modules = explode(",", $section->sequence);
1311 foreach ($modules as $moduleid) {
1312 set_coursemodule_visible($moduleid, $visibility, true);
1315 rebuild_course_cache($courseid);
1317 // Determine which modules are visible for AJAX update
1318 if (!empty($modules)) {
1319 list($insql, $params) = $DB->get_in_or_equal($modules);
1320 $select = 'id ' . $insql . ' AND visible = ?';
1321 array_push($params, $visibility);
1323 $select .= ' AND visibleold = 1';
1325 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
1328 return $resourcestotoggle;
1332 * Obtains shared data that is used in print_section when displaying a
1333 * course-module entry.
1335 * Calls format_text or format_string as appropriate, and obtains the correct icon.
1337 * This data is also used in other areas of the code.
1338 * @param cm_info $cm Course-module data (must come from get_fast_modinfo)
1339 * @param object $course Moodle course object
1340 * @return array An array with the following values in this order:
1341 * $content (optional extra content for after link),
1342 * $instancename (text of link)
1344 function get_print_section_cm_text(cm_info $cm, $course) {
1347 // Get content from modinfo if specified. Content displays either
1348 // in addition to the standard link (below), or replaces it if
1349 // the link is turned off by setting ->url to null.
1350 if (($content = $cm->get_content()) !== '') {
1351 // Improve filter performance by preloading filter setttings for all
1352 // activities on the course (this does nothing if called multiple
1354 filter_preload_activities($cm->get_modinfo());
1356 // Get module context
1357 $modulecontext = context_module::instance($cm->id);
1358 $labelformatoptions = new stdClass();
1359 $labelformatoptions->noclean = true;
1360 $labelformatoptions->overflowdiv = true;
1361 $labelformatoptions->context = $modulecontext;
1362 $content = format_text($content, FORMAT_HTML, $labelformatoptions);
1367 // Get course context
1368 $coursecontext = context_course::instance($course->id);
1369 $stringoptions = new stdClass;
1370 $stringoptions->context = $coursecontext;
1371 $instancename = format_string($cm->name, true, $stringoptions);
1372 return array($content, $instancename);
1376 * Prints a section full of activity modules
1378 * @param stdClass $course The course
1379 * @param stdClass $section The section
1380 * @param array $mods The modules in the section
1381 * @param array $modnamesused An array containing the list of modules and their names
1382 * @param bool $absolute All links are absolute
1383 * @param string $width Width of the container
1384 * @param bool $hidecompletion Hide completion status
1385 * @param int $sectionreturn The section to return to
1388 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%", $hidecompletion=false, $sectionreturn=0) {
1389 global $CFG, $USER, $DB, $PAGE, $OUTPUT;
1391 static $initialised;
1393 static $groupbuttons;
1394 static $groupbuttonslink;
1397 static $strmovehere;
1398 static $strmovefull;
1399 static $strunreadpostsone;
1400 static $modulenames;
1402 if (!isset($initialised)) {
1403 $groupbuttons = ($course->groupmode or (!$course->groupmodeforce));
1404 $groupbuttonslink = (!$course->groupmodeforce);
1405 $isediting = $PAGE->user_is_editing();
1406 $ismoving = $isediting && ismoving($course->id);
1408 $strmovehere = get_string("movehere");
1409 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1411 $modulenames = array();
1412 $initialised = true;
1415 $modinfo = get_fast_modinfo($course);
1416 $completioninfo = new completion_info($course);
1418 //Accessibility: replace table with list <ul>, but don't output empty list.
1419 if (!empty($section->sequence)) {
1421 // Fix bug #5027, don't want style=\"width:$width\".
1422 echo "<ul class=\"section img-text\">\n";
1423 $sectionmods = explode(",", $section->sequence);
1425 foreach ($sectionmods as $modnumber) {
1426 if (empty($mods[$modnumber])) {
1433 $mod = $mods[$modnumber];
1435 if ($ismoving and $mod->id == $USER->activitycopy) {
1436 // do not display moving mod
1440 if (isset($modinfo->cms[$modnumber])) {
1441 // We can continue (because it will not be displayed at all)
1443 // 1) The activity is not visible to users
1445 // 2a) The 'showavailability' option is not set (if that is set,
1446 // we need to display the activity so we can show
1447 // availability info)
1449 // 2b) The 'availableinfo' is empty, i.e. the activity was
1450 // hidden in a way that leaves no info, such as using the
1452 if (!$modinfo->cms[$modnumber]->uservisible &&
1453 (empty($modinfo->cms[$modnumber]->showavailability) ||
1454 empty($modinfo->cms[$modnumber]->availableinfo))) {
1455 // visibility shortcut
1459 if (!file_exists("$CFG->dirroot/mod/$mod->modname/lib.php")) {
1460 // module not installed
1463 if (!coursemodule_visible_for_user($mod) &&
1464 empty($mod->showavailability)) {
1465 // full visibility check
1470 if (!isset($modulenames[$mod->modname])) {
1471 $modulenames[$mod->modname] = get_string('modulename', $mod->modname);
1473 $modulename = $modulenames[$mod->modname];
1475 // In some cases the activity is visible to user, but it is
1476 // dimmed. This is done if viewhiddenactivities is true and if:
1477 // 1. the activity is not visible, or
1478 // 2. the activity has dates set which do not include current, or
1479 // 3. the activity has any other conditions set (regardless of whether
1480 // current user meets them)
1481 $modcontext = context_module::instance($mod->id);
1482 $canviewhidden = has_capability('moodle/course:viewhiddenactivities', $modcontext);
1483 $accessiblebutdim = false;
1484 if ($canviewhidden) {
1485 $accessiblebutdim = !$mod->visible;
1486 if (!empty($CFG->enableavailability)) {
1487 $accessiblebutdim = $accessiblebutdim ||
1488 $mod->availablefrom > time() ||
1489 ($mod->availableuntil && $mod->availableuntil < time()) ||
1490 count($mod->conditionsgrade) > 0 ||
1491 count($mod->conditionscompletion) > 0;
1495 $liclasses = array();
1496 $liclasses[] = 'activity';
1497 $liclasses[] = $mod->modname;
1498 $liclasses[] = 'modtype_'.$mod->modname;
1499 $extraclasses = $mod->get_extra_classes();
1500 if ($extraclasses) {
1501 $liclasses = array_merge($liclasses, explode(' ', $extraclasses));
1503 echo html_writer::start_tag('li', array('class'=>join(' ', $liclasses), 'id'=>'module-'.$modnumber));
1505 echo '<a title="'.$strmovefull.'"'.
1506 ' href="'.$CFG->wwwroot.'/course/mod.php?moveto='.$mod->id.'&sesskey='.sesskey().'">'.
1507 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1508 ' alt="'.$strmovehere.'" /></a><br />
1512 $classes = array('mod-indent');
1513 if (!empty($mod->indent)) {
1514 $classes[] = 'mod-indent-'.$mod->indent;
1515 if ($mod->indent > 15) {
1516 $classes[] = 'mod-indent-huge';
1519 echo html_writer::start_tag('div', array('class'=>join(' ', $classes)));
1521 // Get data about this course-module
1522 list($content, $instancename) =
1523 get_print_section_cm_text($modinfo->cms[$modnumber], $course);
1525 //Accessibility: for files get description via icon, this is very ugly hack!
1527 $altname = $mod->modfullname;
1528 // Avoid unnecessary duplication: if e.g. a forum name already
1529 // includes the word forum (or Forum, etc) then it is unhelpful
1530 // to include that in the accessible description that is added.
1531 if (false !== strpos(textlib::strtolower($instancename),
1532 textlib::strtolower($altname))) {
1535 // File type after name, for alphabetic lists (screen reader).
1537 $altname = get_accesshide(' '.$altname);
1540 // We may be displaying this just in order to show information
1541 // about visibility, without the actual link
1543 if ($mod->uservisible) {
1544 // Nope - in this case the link is fully working for user
1547 if ($accessiblebutdim) {
1548 $linkclasses .= ' dimmed';
1549 $textclasses .= ' dimmed_text';
1550 $accesstext = '<span class="accesshide">'.
1551 get_string('hiddenfromstudents').': </span>';
1556 $linkcss = 'class="' . trim($linkclasses) . '" ';
1561 $textcss = 'class="' . trim($textclasses) . '" ';
1566 // Get on-click attribute value if specified
1567 $onclick = $mod->get_on_click();
1569 $onclick = ' onclick="' . $onclick . '"';
1572 if ($url = $mod->get_url()) {
1573 // Display link itself
1574 echo '<a ' . $linkcss . $mod->extra . $onclick .
1575 ' href="' . $url . '"><img src="' . $mod->get_icon_url() .
1576 '" class="activityicon" alt="' .
1577 $modulename . '" /> ' .
1578 $accesstext . '<span class="instancename">' .
1579 $instancename . $altname . '</span></a>';
1581 // If specified, display extra content after link
1583 $contentpart = '<div class="' . trim('contentafterlink' . $textclasses) .
1584 '">' . $content . '</div>';
1587 // No link, so display only content
1588 $contentpart = '<div ' . $textcss . $mod->extra . '>' .
1589 $accesstext . $content . '</div>';
1592 if (!empty($mod->groupingid) && has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
1593 $groupings = groups_get_all_groupings($course->id);
1594 echo " <span class=\"groupinglabel\">(".format_string($groupings[$mod->groupingid]->name).')</span>';
1597 $textclasses = $extraclasses;
1598 $textclasses .= ' dimmed_text';
1600 $textcss = 'class="' . trim($textclasses) . '" ';
1604 $accesstext = '<span class="accesshide">' .
1605 get_string('notavailableyet', 'condition') .
1608 if ($url = $mod->get_url()) {
1609 // Display greyed-out text of link
1610 echo '<div ' . $textcss . $mod->extra .
1611 ' >' . '<img src="' . $mod->get_icon_url() .
1612 '" class="activityicon" alt="' .
1614 '" /> <span>'. $instancename . $altname .
1617 // Do not display content after link when it is greyed out like this.
1619 // No link, so display only content (also greyed)
1620 $contentpart = '<div ' . $textcss . $mod->extra . '>' .
1621 $accesstext . $content . '</div>';
1625 // Module can put text after the link (e.g. forum unread)
1626 echo $mod->get_after_link();
1628 // If there is content but NO link (eg label), then display the
1629 // content here (BEFORE any icons). In this case cons must be
1630 // displayed after the content so that it makes more sense visually
1631 // and for accessibility reasons, e.g. if you have a one-line label
1632 // it should work similarly (at least in terms of ordering) to an
1639 if ($groupbuttons and plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
1640 if (! $mod->groupmodelink = $groupbuttonslink) {
1641 $mod->groupmode = $course->groupmode;
1645 $mod->groupmode = false;
1647 echo ' ';
1648 echo make_editing_buttons($mod, $absolute, true, $mod->indent, $sectionreturn);
1649 echo $mod->get_after_edit_icons();
1653 $completion = $hidecompletion
1654 ? COMPLETION_TRACKING_NONE
1655 : $completioninfo->is_enabled($mod);
1656 if ($completion!=COMPLETION_TRACKING_NONE && isloggedin() &&
1657 !isguestuser() && $mod->uservisible) {
1658 $completiondata = $completioninfo->get_data($mod,true);
1659 $completionicon = '';
1661 switch ($completion) {
1662 case COMPLETION_TRACKING_MANUAL :
1663 $completionicon = 'manual-enabled'; break;
1664 case COMPLETION_TRACKING_AUTOMATIC :
1665 $completionicon = 'auto-enabled'; break;
1668 } else if ($completion==COMPLETION_TRACKING_MANUAL) {
1669 switch($completiondata->completionstate) {
1670 case COMPLETION_INCOMPLETE:
1671 $completionicon = 'manual-n'; break;
1672 case COMPLETION_COMPLETE:
1673 $completionicon = 'manual-y'; break;
1675 } else { // Automatic
1676 switch($completiondata->completionstate) {
1677 case COMPLETION_INCOMPLETE:
1678 $completionicon = 'auto-n'; break;
1679 case COMPLETION_COMPLETE:
1680 $completionicon = 'auto-y'; break;
1681 case COMPLETION_COMPLETE_PASS:
1682 $completionicon = 'auto-pass'; break;
1683 case COMPLETION_COMPLETE_FAIL:
1684 $completionicon = 'auto-fail'; break;
1687 if ($completionicon) {
1688 $imgsrc = $OUTPUT->pix_url('i/completion-'.$completionicon);
1689 $formattedname = format_string($mod->name, true, array('context' => $modcontext));
1690 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $formattedname);
1691 if ($completion == COMPLETION_TRACKING_MANUAL && !$isediting) {
1692 $imgtitle = get_string('completion-title-' . $completionicon, 'completion', $formattedname);
1694 $completiondata->completionstate==COMPLETION_COMPLETE
1695 ? COMPLETION_INCOMPLETE
1696 : COMPLETION_COMPLETE;
1697 // In manual mode the icon is a toggle form...
1699 // If this completion state is used by the
1700 // conditional activities system, we need to turn
1702 if (!empty($CFG->enableavailability) &&
1703 condition_info::completion_value_used_as_condition($course, $mod)) {
1704 $extraclass = ' preventjs';
1709 <form class='togglecompletion$extraclass' method='post' action='".$CFG->wwwroot."/course/togglecompletion.php'><div>
1710 <input type='hidden' name='id' value='{$mod->id}' />
1711 <input type='hidden' name='modulename' value='".s($mod->name)."' />
1712 <input type='hidden' name='sesskey' value='".sesskey()."' />
1713 <input type='hidden' name='completionstate' value='$newstate' />
1714 <input type='image' src='$imgsrc' alt='$imgalt' title='$imgtitle' />
1717 // In auto mode, or when editing, the icon is just an image
1718 echo "<span class='autocompletion'>";
1719 echo "<img src='$imgsrc' alt='$imgalt' title='$imgalt' /></span>";
1724 // If there is content AND a link, then display the content here
1725 // (AFTER any icons). Otherwise it was displayed before
1730 // Show availability information (for someone who isn't allowed to
1731 // see the activity itself, or for staff)
1732 if (!$mod->uservisible) {
1733 echo '<div class="availabilityinfo">'.$mod->availableinfo.'</div>';
1734 } else if ($canviewhidden && !empty($CFG->enableavailability) && $mod->visible) {
1735 $ci = new condition_info($mod);
1736 $fullinfo = $ci->get_full_information();
1738 echo '<div class="availabilityinfo">'.get_string($mod->showavailability
1739 ? 'userrestriction_visible'
1740 : 'userrestriction_hidden','condition',
1741 $fullinfo).'</div>';
1745 echo html_writer::end_tag('div');
1746 echo html_writer::end_tag('li')."\n";
1749 } elseif ($ismoving) {
1750 echo "<ul class=\"section\">\n";
1754 echo '<li><a title="'.$strmovefull.'"'.
1755 ' href="'.$CFG->wwwroot.'/course/mod.php?movetosection='.$section->id.'&sesskey='.sesskey().'">'.
1756 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1757 ' alt="'.$strmovehere.'" /></a></li>
1760 if (!empty($section->sequence) || $ismoving) {
1761 echo "</ul><!--class='section'-->\n\n";
1766 * Prints the menus to add activities and resources.
1768 * @param stdClass $course The course
1769 * @param stdClass $section The section
1770 * @param array $modnames An array containing the list of modules and their names
1771 * @param bool $vertical Vertical orientation
1772 * @param bool $return Return the menus or send them to output
1773 * @param int $sectionreturn The section to link back to
1774 * @return void|string depending on $return
1776 function print_section_add_menus($course, $section, $modnames, $vertical=false, $return=false, $sectionreturn=0) {
1777 global $CFG, $OUTPUT;
1779 // check to see if user can add menus
1780 if (!has_capability('moodle/course:manageactivities', context_course::instance($course->id))) {
1784 // Retrieve all modules with associated metadata
1785 $modules = get_module_metadata($course, $modnames);
1787 // We'll sort resources and activities into two lists
1788 $resources = array();
1789 $activities = array();
1791 // We need to add the section section to the link for each module
1792 $sectionlink = '§ion=' . $section . '&sr=' . $sectionreturn;
1794 foreach ($modules as $module) {
1795 if (isset($module->types)) {
1796 // This module has a subtype
1797 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1798 $subtypes = array();
1799 foreach ($module->types as $subtype) {
1800 $subtypes[$subtype->link . $sectionlink] = $subtype->title;
1803 // Sort module subtypes into the list
1804 if (!empty($module->title)) {
1805 // This grouping has a name
1806 if ($module->archetype == MOD_CLASS_RESOURCE) {
1807 $resources[] = array($module->title=>$subtypes);
1809 $activities[] = array($module->title=>$subtypes);
1812 // This grouping does not have a name
1813 if ($module->archetype == MOD_CLASS_RESOURCE) {
1814 $resources = array_merge($resources, $subtypes);
1816 $activities = array_merge($activities, $subtypes);
1820 // This module has no subtypes
1821 if ($module->archetype == MOD_ARCHETYPE_RESOURCE) {
1822 $resources[$module->link . $sectionlink] = $module->title;
1823 } else if ($module->archetype === MOD_ARCHETYPE_SYSTEM) {
1824 // System modules cannot be added by user, do not add to dropdown
1826 $activities[$module->link . $sectionlink] = $module->title;
1831 $straddactivity = get_string('addactivity');
1832 $straddresource = get_string('addresource');
1834 $output = html_writer::start_tag('div', array('class' => 'section_add_menus', 'id' => 'add_menus-section-' . $section));
1837 $output .= html_writer::start_tag('div', array('class' => 'horizontal'));
1840 if (!empty($resources)) {
1841 $select = new url_select($resources, '', array(''=>$straddresource), "ressection$section");
1842 $select->set_help_icon('resources');
1843 $output .= $OUTPUT->render($select);
1846 if (!empty($activities)) {
1847 $select = new url_select($activities, '', array(''=>$straddactivity), "section$section");
1848 $select->set_help_icon('activities');
1849 $output .= $OUTPUT->render($select);
1853 $output .= html_writer::end_tag('div');
1856 $output .= html_writer::end_tag('div');
1858 if (course_ajax_enabled($course)) {
1859 $straddeither = get_string('addresourceoractivity');
1860 // The module chooser link
1861 $modchooser = html_writer::start_tag('div', array('class' => 'mdl-right'));
1862 $modchooser.= html_writer::start_tag('div', array('class' => 'section-modchooser'));
1863 $icon = $OUTPUT->pix_icon('t/add', $straddeither);
1864 $span = html_writer::tag('span', $straddeither, array('class' => 'section-modchooser-text'));
1865 $modchooser .= html_writer::tag('span', $icon . $span, array('class' => 'section-modchooser-link'));
1866 $modchooser.= html_writer::end_tag('div');
1867 $modchooser.= html_writer::end_tag('div');
1869 // Wrap the normal output in a noscript div
1870 $usemodchooser = get_user_preferences('usemodchooser', $CFG->modchooserdefault);
1871 if ($usemodchooser) {
1872 $output = html_writer::tag('div', $output, array('class' => 'hiddenifjs addresourcedropdown'));
1873 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'visibleifjs addresourcemodchooser'));
1875 $output = html_writer::tag('div', $output, array('class' => 'visibleifjs addresourcedropdown'));
1876 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'hiddenifjs addresourcemodchooser'));
1878 $output = $modchooser . $output;
1889 * Retrieve all metadata for the requested modules
1891 * @param object $course The Course
1892 * @param array $modnames An array containing the list of modules and their
1894 * @param int $sectionreturn The section to return to
1895 * @return array A list of stdClass objects containing metadata about each
1898 function get_module_metadata($course, $modnames, $sectionreturn = 0) {
1899 global $CFG, $OUTPUT;
1901 // get_module_metadata will be called once per section on the page and courses may show
1902 // different modules to one another
1903 static $modlist = array();
1904 if (!isset($modlist[$course->id])) {
1905 $modlist[$course->id] = array();
1909 $urlbase = "/course/mod.php?id=$course->id&sesskey=".sesskey().'&sr='.$sectionreturn.'&add=';
1910 foreach($modnames as $modname => $modnamestr) {
1911 if (!course_allowed_module($course, $modname)) {
1914 if (isset($modlist[$modname])) {
1915 // This module is already cached
1916 $return[$modname] = $modlist[$course->id][$modname];
1920 // Include the module lib
1921 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1922 if (!file_exists($libfile)) {
1925 include_once($libfile);
1927 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1928 $gettypesfunc = $modname.'_get_types';
1929 if (function_exists($gettypesfunc)) {
1930 if ($types = $gettypesfunc()) {
1931 $group = new stdClass();
1932 $group->name = $modname;
1933 $group->icon = $OUTPUT->pix_icon('icon', '', $modname, array('class' => 'icon'));
1934 foreach($types as $type) {
1935 if ($type->typestr === '--') {
1938 if (strpos($type->typestr, '--') === 0) {
1939 $group->title = str_replace('--', '', $type->typestr);
1942 // Set the Sub Type metadata
1943 $subtype = new stdClass();
1944 $subtype->title = $type->typestr;
1945 $subtype->type = str_replace('&', '&', $type->type);
1946 $subtype->name = preg_replace('/.*type=/', '', $subtype->type);
1947 $subtype->archetype = $type->modclass;
1949 // The group archetype should match the subtype archetypes and all subtypes
1950 // should have the same archetype
1951 $group->archetype = $subtype->archetype;
1953 if (get_string_manager()->string_exists('help' . $subtype->name, $modname)) {
1954 $subtype->help = get_string('help' . $subtype->name, $modname);
1956 $subtype->link = $urlbase . $subtype->type;
1957 $group->types[] = $subtype;
1959 $modlist[$course->id][$modname] = $group;
1962 $module = new stdClass();
1963 $module->title = get_string('modulename', $modname);
1964 $module->name = $modname;
1965 $module->link = $urlbase . $modname;
1966 $module->icon = $OUTPUT->pix_icon('icon', '', $module->name, array('class' => 'icon'));
1967 $sm = get_string_manager();
1968 if ($sm->string_exists('modulename_help', $modname)) {
1969 $module->help = get_string('modulename_help', $modname);
1970 if ($sm->string_exists('modulename_link', $modname)) { // Link to further info in Moodle docs
1971 $link = get_string('modulename_link', $modname);
1972 $linktext = get_string('morehelp');
1973 $module->help .= html_writer::tag('div', $OUTPUT->doc_link($link, $linktext), array('class' => 'helpdoclink'));
1976 $module->archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1977 $modlist[$course->id][$modname] = $module;
1979 $return[$modname] = $modlist[$course->id][$modname];
1986 * Return the course category context for the category with id $categoryid, except
1987 * that if $categoryid is 0, return the system context.
1989 * @param integer $categoryid a category id or 0.
1990 * @return object the corresponding context
1992 function get_category_or_system_context($categoryid) {
1994 return context_coursecat::instance($categoryid, IGNORE_MISSING);
1996 return context_system::instance();
2001 * Gets the child categories of a given courses category. Uses a static cache
2002 * to make repeat calls efficient.
2004 * @param int $parentid the id of a course category.
2005 * @return array all the child course categories.
2007 function get_child_categories($parentid) {
2008 static $allcategories = null;
2010 // only fill in this variable the first time
2011 if (null == $allcategories) {
2012 $allcategories = array();
2014 $categories = get_categories();
2015 foreach ($categories as $category) {
2016 if (empty($allcategories[$category->parent])) {
2017 $allcategories[$category->parent] = array();
2019 $allcategories[$category->parent][] = $category;
2023 if (empty($allcategories[$parentid])) {
2026 return $allcategories[$parentid];
2031 * This function recursively travels the categories, building up a nice list
2032 * for display. It also makes an array that list all the parents for each
2035 * For example, if you have a tree of categories like:
2036 * Miscellaneous (id = 1)
2037 * Subcategory (id = 2)
2038 * Sub-subcategory (id = 4)
2039 * Other category (id = 3)
2040 * Then after calling this function you will have
2041 * $list = array(1 => 'Miscellaneous', 2 => 'Miscellaneous / Subcategory',
2042 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
2043 * 3 => 'Other category');
2044 * $parents = array(2 => array(1), 4 => array(1, 2));
2046 * If you specify $requiredcapability, then only categories where the current
2047 * user has that capability will be added to $list, although all categories
2048 * will still be added to $parents, and if you only have $requiredcapability
2049 * in a child category, not the parent, then the child catgegory will still be
2052 * If you specify the option $excluded, then that category, and all its children,
2053 * are omitted from the tree. This is useful when you are doing something like
2054 * moving categories, where you do not want to allow people to move a category
2055 * to be the child of itself.
2057 * @param array $list For output, accumulates an array categoryid => full category path name
2058 * @param array $parents For output, accumulates an array categoryid => list of parent category ids.
2059 * @param string/array $requiredcapability if given, only categories where the current
2060 * user has this capability will be added to $list. Can also be an array of capabilities,
2061 * in which case they are all required.
2062 * @param integer $excludeid Omit this category and its children from the lists built.
2063 * @param object $category Build the tree starting at this category - otherwise starts at the top level.
2064 * @param string $path For internal use, as part of recursive calls.
2066 function make_categories_list(&$list, &$parents, $requiredcapability = '',
2067 $excludeid = 0, $category = NULL, $path = "") {
2069 // initialize the arrays if needed
2070 if (!is_array($list)) {
2073 if (!is_array($parents)) {
2077 if (empty($category)) {
2078 // Start at the top level.
2079 $category = new stdClass;
2082 // This is the excluded category, don't include it.
2083 if ($excludeid > 0 && $excludeid == $category->id) {
2087 $context = context_coursecat::instance($category->id);
2088 $categoryname = format_string($category->name, true, array('context' => $context));
2092 $path = $path.' / '.$categoryname;
2094 $path = $categoryname;
2097 // Add this category to $list, if the permissions check out.
2098 if (empty($requiredcapability)) {
2099 $list[$category->id] = $path;
2102 $requiredcapability = (array)$requiredcapability;
2103 if (has_all_capabilities($requiredcapability, $context)) {
2104 $list[$category->id] = $path;
2109 // Add all the children recursively, while updating the parents array.
2110 if ($categories = get_child_categories($category->id)) {
2111 foreach ($categories as $cat) {
2112 if (!empty($category->id)) {
2113 if (isset($parents[$category->id])) {
2114 $parents[$cat->id] = $parents[$category->id];
2116 $parents[$cat->id][] = $category->id;
2118 make_categories_list($list, $parents, $requiredcapability, $excludeid, $cat, $path);
2124 * This function generates a structured array of courses and categories.
2126 * The depth of categories is limited by $CFG->maxcategorydepth however there
2127 * is no limit on the number of courses!
2129 * Suitable for use with the course renderers course_category_tree method:
2130 * $renderer = $PAGE->get_renderer('core','course');
2131 * echo $renderer->course_category_tree(get_course_category_tree());
2133 * @global moodle_database $DB
2137 function get_course_category_tree($id = 0, $depth = 0) {
2139 $viewhiddencats = has_capability('moodle/category:viewhiddencategories', context_system::instance());
2140 $categories = get_child_categories($id);
2141 $categoryids = array();
2142 foreach ($categories as $key => &$category) {
2143 if (!$category->visible && !$viewhiddencats) {
2144 unset($categories[$key]);
2147 $categoryids[$category->id] = $category;
2148 if (empty($CFG->maxcategorydepth) || $depth <= $CFG->maxcategorydepth) {
2149 list($category->categories, $subcategories) = get_course_category_tree($category->id, $depth+1);
2150 foreach ($subcategories as $subid=>$subcat) {
2151 $categoryids[$subid] = $subcat;
2153 $category->courses = array();
2158 // This is a recursive call so return the required array
2159 return array($categories, $categoryids);
2162 if (empty($categoryids)) {
2163 // No categories available (probably all hidden).
2167 // The depth is 0 this function has just been called so we can finish it off
2169 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
2170 list($catsql, $catparams) = $DB->get_in_or_equal(array_keys($categoryids));
2172 c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary,c.category
2176 WHERE c.category $catsql ORDER BY c.sortorder ASC";
2177 if ($courses = $DB->get_records_sql($sql, $catparams)) {
2178 // loop throught them
2179 foreach ($courses as $course) {
2180 if ($course->id == SITEID) {
2183 context_instance_preload($course);
2184 if (!empty($course->visible) || has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
2185 $categoryids[$course->category]->courses[$course->id] = $course;
2193 * Recursive function to print out all the categories in a nice format
2194 * with or without courses included
2196 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true) {
2199 // maxcategorydepth == 0 meant no limit
2200 if (!empty($CFG->maxcategorydepth) && $depth >= $CFG->maxcategorydepth) {
2204 if (!$displaylist) {
2205 make_categories_list($displaylist, $parentslist);
2209 if ($category->visible or has_capability('moodle/category:viewhiddencategories', context_system::instance())) {
2210 print_category_info($category, $depth, $showcourses);
2212 return; // Don't bother printing children of invisible categories
2216 $category = new stdClass();
2217 $category->id = "0";
2220 if ($categories = get_child_categories($category->id)) { // Print all the children recursively
2221 $countcats = count($categories);
2225 foreach ($categories as $cat) {
2227 if ($count == $countcats) {
2230 $up = $first ? false : true;
2231 $down = $last ? false : true;
2234 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1, $showcourses);
2240 * This function will return $options array for html_writer::select(), with whitespace to denote nesting.
2242 function make_categories_options() {
2243 make_categories_list($cats,$parents);
2244 foreach ($cats as $key => $value) {
2245 if (array_key_exists($key,$parents)) {
2246 if ($indent = count($parents[$key])) {
2247 for ($i = 0; $i < $indent; $i++) {
2248 $cats[$key] = ' '.$cats[$key];
2257 * Prints the category info in indented fashion
2258 * This function is only used by print_whole_category_list() above
2260 function print_category_info($category, $depth=0, $showcourses = false) {
2261 global $CFG, $DB, $OUTPUT;
2263 $strsummary = get_string('summary');
2266 if (!$category->visible) {
2267 $catlinkcss = array('class'=>'dimmed');
2269 static $coursecount = null;
2270 if (null === $coursecount) {
2271 // only need to check this once
2272 $coursecount = $DB->count_records('course') <= FRONTPAGECOURSELIMIT;
2275 if ($showcourses and $coursecount) {
2276 $catimage = '<img src="'.$OUTPUT->pix_url('i/course') . '" alt="" />';
2278 $catimage = " ";
2281 $courses = get_courses($category->id, 'c.sortorder ASC', 'c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary');
2282 $context = context_coursecat::instance($category->id);
2283 $fullname = format_string($category->name, true, array('context' => $context));
2285 if ($showcourses and $coursecount) {
2286 echo '<div class="categorylist clearfix">';
2288 $cat .= html_writer::tag('div', $catimage, array('class'=>'image'));
2289 $catlink = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
2290 $cat .= html_writer::tag('div', $catlink, array('class'=>'name'));
2294 for ($i=0; $i< $depth; $i++) {
2295 $html = html_writer::tag('div', $html . $cat, array('class'=>'indentation'));
2301 echo html_writer::tag('div', $html, array('class'=>'category'));
2302 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
2304 // does the depth exceed maxcategorydepth
2305 // maxcategorydepth == 0 or unset meant no limit
2306 $limit = !(isset($CFG->maxcategorydepth) && ($depth >= $CFG->maxcategorydepth-1));
2307 if ($courses && ($limit || $CFG->maxcategorydepth == 0)) {
2308 foreach ($courses as $course) {
2310 if (!$course->visible) {
2311 $linkcss = array('class'=>'dimmed');
2314 $coursename = get_course_display_name_for_list($course);
2315 $courselink = html_writer::link(new moodle_url('/course/view.php', array('id'=>$course->id)), format_string($coursename), $linkcss);
2319 if ($icons = enrol_get_course_info_icons($course)) {
2320 foreach ($icons as $pix_icon) {
2321 $courseicon = $OUTPUT->render($pix_icon).' ';
2325 $coursecontent = html_writer::tag('div', $courseicon.$courselink, array('class'=>'name'));
2327 if ($course->summary) {
2328 $link = new moodle_url('/course/info.php?id='.$course->id);
2329 $actionlink = $OUTPUT->action_link($link, '<img alt="'.$strsummary.'" src="'.$OUTPUT->pix_url('i/info') . '" />',
2330 new popup_action('click', $link, 'courseinfo', array('height' => 400, 'width' => 500)),
2331 array('title'=>$strsummary));
2333 $coursecontent .= html_writer::tag('div', $actionlink, array('class'=>'info'));
2337 for ($i=0; $i <= $depth; $i++) {
2338 $html = html_writer::tag('div', $html . $coursecontent , array('class'=>'indentation'));
2339 $coursecontent = '';
2341 echo html_writer::tag('div', $html, array('class'=>'course clearfloat'));
2346 echo '<div class="categorylist">';
2348 $cat = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
2349 if (count($courses) > 0) {
2350 $cat .= html_writer::tag('span', ' ('.count($courses).')', array('title'=>get_string('numberofcourses'), 'class'=>'numberofcourse'));
2354 for ($i=0; $i< $depth; $i++) {
2355 $html = html_writer::tag('div', $html .$cat, array('class'=>'indentation'));
2362 echo html_writer::tag('div', $html, array('class'=>'category'));
2363 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
2369 * Print the buttons relating to course requests.
2371 * @param object $systemcontext the system context.
2373 function print_course_request_buttons($systemcontext) {
2374 global $CFG, $DB, $OUTPUT;
2375 if (empty($CFG->enablecourserequests)) {
2378 if (!has_capability('moodle/course:create', $systemcontext) && has_capability('moodle/course:request', $systemcontext)) {
2379 /// Print a button to request a new course
2380 echo $OUTPUT->single_button('request.php', get_string('requestcourse'), 'get');
2382 /// Print a button to manage pending requests
2383 if (has_capability('moodle/site:approvecourse', $systemcontext)) {
2384 $disabled = !$DB->record_exists('course_request', array());
2385 echo $OUTPUT->single_button('pending.php', get_string('coursespending'), 'get', array('disabled'=>$disabled));
2390 * Does the user have permission to edit things in this category?
2392 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2393 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
2395 function can_edit_in_category($categoryid = 0) {
2396 $context = get_category_or_system_context($categoryid);
2397 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
2401 * Prints the turn editing on/off button on course/index.php or course/category.php.
2403 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2404 * @return string HTML of the editing button, or empty string, if this user is not allowed
2407 function update_category_button($categoryid = 0) {
2408 global $CFG, $PAGE, $OUTPUT;
2410 // Check permissions.
2411 if (!can_edit_in_category($categoryid)) {
2415 // Work out the appropriate action.
2416 if ($PAGE->user_is_editing()) {
2417 $label = get_string('turneditingoff');
2420 $label = get_string('turneditingon');
2424 // Generate the button HTML.
2425 $options = array('categoryedit' => $edit, 'sesskey' => sesskey());
2427 $options['id'] = $categoryid;
2428 $page = 'category.php';
2430 $page = 'index.php';
2432 return $OUTPUT->single_button(new moodle_url('/course/' . $page, $options), $label, 'get');
2436 * Category is 0 (for all courses) or an object
2438 function print_courses($category) {
2439 global $CFG, $OUTPUT;
2441 if (!is_object($category) && $category==0) {
2442 $categories = get_child_categories(0); // Parent = 0 ie top-level categories only
2443 if (is_array($categories) && count($categories) == 1) {
2444 $category = array_shift($categories);
2445 $courses = get_courses_wmanagers($category->id,
2447 array('summary','summaryformat'));
2449 $courses = get_courses_wmanagers('all',
2451 array('summary','summaryformat'));
2455 $courses = get_courses_wmanagers($category->id,
2457 array('summary','summaryformat'));
2461 echo html_writer::start_tag('ul', array('class'=>'unlist'));
2462 foreach ($courses as $course) {
2463 $coursecontext = context_course::instance($course->id);
2464 if ($course->visible == 1 || has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2465 echo html_writer::start_tag('li');
2466 print_course($course);
2467 echo html_writer::end_tag('li');
2470 echo html_writer::end_tag('ul');
2472 echo $OUTPUT->heading(get_string("nocoursesyet"));
2473 $context = context_system::instance();
2474 if (has_capability('moodle/course:create', $context)) {
2476 if (!empty($category->id)) {
2477 $options['category'] = $category->id;
2479 $options['category'] = $CFG->defaultrequestcategory;
2481 echo html_writer::start_tag('div', array('class'=>'addcoursebutton'));
2482 echo $OUTPUT->single_button(new moodle_url('/course/edit.php', $options), get_string("addnewcourse"));
2483 echo html_writer::end_tag('div');
2489 * Print a description of a course, suitable for browsing in a list.
2491 * @param object $course the course object.
2492 * @param string $highlightterms (optional) some search terms that should be highlighted in the display.
2494 function print_course($course, $highlightterms = '') {
2495 global $CFG, $USER, $DB, $OUTPUT;
2497 $context = context_course::instance($course->id);
2499 // Rewrite file URLs so that they are correct
2500 $course->summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', NULL);
2502 echo html_writer::start_tag('div', array('class'=>'coursebox clearfix'));
2503 echo html_writer::start_tag('div', array('class'=>'info'));
2504 echo html_writer::start_tag('h3', array('class'=>'name'));
2506 $linkhref = new moodle_url('/course/view.php', array('id'=>$course->id));
2508 $coursename = get_course_display_name_for_list($course);
2509 $linktext = highlight($highlightterms, format_string($coursename));
2510 $linkparams = array('title'=>get_string('entercourse'));
2511 if (empty($course->visible)) {
2512 $linkparams['class'] = 'dimmed';
2514 echo html_writer::link($linkhref, $linktext, $linkparams);
2515 echo html_writer::end_tag('h3');
2517 /// first find all roles that are supposed to be displayed
2518 if (!empty($CFG->coursecontact)) {
2519 $managerroles = explode(',', $CFG->coursecontact);
2522 if (!isset($course->managers)) {
2523 $rusers = get_role_users($managerroles, $context, true,
2524 'ra.id AS raid, u.id, u.username, u.firstname, u.lastname, rn.name AS rolecoursealias,
2525 r.name AS rolename, r.sortorder, r.id AS roleid, r.shortname AS roleshortname',
2526 'r.sortorder ASC, u.lastname ASC');
2528 // use the managers array if we have it for perf reasosn
2529 // populate the datastructure like output of get_role_users();
2530 foreach ($course->managers as $manager) {
2531 $user = clone($manager->user);
2532 $user->roleid = $manager->roleid;
2533 $user->rolename = $manager->rolename;
2534 $user->roleshortname = $manager->roleshortname;
2535 $user->rolecoursealias = $manager->rolecoursealias;
2536 $rusers[$user->id] = $user;
2540 $namesarray = array();
2541 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2542 foreach ($rusers as $ra) {
2543 if (isset($namesarray[$ra->id])) {
2544 // only display a user once with the higest sortorder role
2548 $role = new stdClass();
2549 $role->id = $ra->roleid;
2550 $role->name = $ra->rolename;
2551 $role->shortname = $ra->roleshortname;
2552 $role->coursealias = $ra->rolecoursealias;
2553 $rolename = role_get_name($role, $context, ROLENAME_ALIAS);
2555 $fullname = fullname($ra, $canviewfullnames);
2556 $namesarray[$ra->id] = $rolename.': '.
2557 html_writer::link(new moodle_url('/user/view.php', array('id'=>$ra->id, 'course'=>SITEID)), $fullname);
2560 if (!empty($namesarray)) {
2561 echo html_writer::start_tag('ul', array('class'=>'teachers'));
2562 foreach ($namesarray as $name) {
2563 echo html_writer::tag('li', $name);
2565 echo html_writer::end_tag('ul');
2568 echo html_writer::end_tag('div'); // End of info div
2570 echo html_writer::start_tag('div', array('class'=>'summary'));
2571 $options = new stdClass();
2572 $options->noclean = true;
2573 $options->para = false;
2574 $options->overflowdiv = true;
2575 if (!isset($course->summaryformat)) {
2576 $course->summaryformat = FORMAT_MOODLE;
2578 echo highlight($highlightterms, format_text($course->summary, $course->summaryformat, $options, $course->id));
2579 if ($icons = enrol_get_course_info_icons($course)) {
2580 echo html_writer::start_tag('div', array('class'=>'enrolmenticons'));
2581 foreach ($icons as $icon) {
2582 echo $OUTPUT->render($icon);
2584 echo html_writer::end_tag('div'); // End of enrolmenticons div
2586 echo html_writer::end_tag('div'); // End of summary div
2587 echo html_writer::end_tag('div'); // End of coursebox div
2591 * Prints custom user information on the home page.
2592 * Over time this can include all sorts of information
2594 function print_my_moodle() {
2595 global $USER, $CFG, $DB, $OUTPUT;
2597 if (!isloggedin() or isguestuser()) {
2598 print_error('nopermissions', '', '', 'See My Moodle');
2601 $courses = enrol_get_my_courses('summary', 'visible DESC,sortorder ASC');
2603 $rcourses = array();
2604 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
2605 $rcourses = get_my_remotecourses($USER->id);
2606 $rhosts = get_my_remotehosts();
2609 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
2611 if (!empty($courses)) {
2612 echo '<ul class="unlist">';
2613 foreach ($courses as $course) {
2614 if ($course->id == SITEID) {
2618 print_course($course);
2625 if (!empty($rcourses)) {
2626 // at the IDP, we know of all the remote courses
2627 foreach ($rcourses as $course) {
2628 print_remote_course($course, "100%");
2630 } elseif (!empty($rhosts)) {
2631 // non-IDP, we know of all the remote servers, but not courses
2632 foreach ($rhosts as $host) {
2633 print_remote_host($host, "100%");
2639 if ($DB->count_records("course") > (count($courses) + 1) ) { // Some courses not being displayed
2640 echo "<table width=\"100%\"><tr><td align=\"center\">";
2641 print_course_search("", false, "short");
2642 echo "</td><td align=\"center\">";
2643 echo $OUTPUT->single_button("$CFG->wwwroot/course/index.php", get_string("fulllistofcourses"), "get");
2644 echo "</td></tr></table>\n";
2648 if ($DB->count_records("course_categories") > 1) {
2649 echo $OUTPUT->box_start("categorybox");
2650 print_whole_category_list();
2651 echo $OUTPUT->box_end();
2659 function print_course_search($value="", $return=false, $format="plain") {
2665 $id = 'coursesearch';
2671 $strsearchcourses= get_string("searchcourses");
2673 if ($format == 'plain') {
2674 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2675 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2676 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
2677 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" value="'.s($value).'" />';
2678 $output .= '<input type="submit" value="'.get_string('go').'" />';
2679 $output .= '</fieldset></form>';
2680 } else if ($format == 'short') {
2681 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2682 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2683 $output .= '<label for="shortsearchbox">'.$strsearchcourses.': </label>';
2684 $output .= '<input type="text" id="shortsearchbox" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2685 $output .= '<input type="submit" value="'.get_string('go').'" />';
2686 $output .= '</fieldset></form>';
2687 } else if ($format == 'navbar') {
2688 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2689 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2690 $output .= '<label for="navsearchbox">'.$strsearchcourses.': </label>';
2691 $output .= '<input type="text" id="navsearchbox" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2692 $output .= '<input type="submit" value="'.get_string('go').'" />';
2693 $output .= '</fieldset></form>';
2702 function print_remote_course($course, $width="100%") {
2707 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&wantsurl=/course/view.php?id={$course->remoteid}";
2709 echo '<div class="coursebox remotecoursebox clearfix">';
2710 echo '<div class="info">';
2711 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2712 $linkcss.' href="'.$url.'">'
2713 . format_string($course->fullname) .'</a><br />'
2714 . format_string($course->hostname) . ' : '
2715 . format_string($course->cat_name) . ' : '
2716 . format_string($course->shortname). '</div>';
2717 echo '</div><div class="summary">';
2718 $options = new stdClass();
2719 $options->noclean = true;
2720 $options->para = false;
2721 $options->overflowdiv = true;
2722 echo format_text($course->summary, $course->summaryformat, $options);
2727 function print_remote_host($host, $width="100%") {
2732 echo '<div class="coursebox clearfix">';
2733 echo '<div class="info">';
2734 echo '<div class="name">';
2735 echo '<img src="'.$OUTPUT->pix_url('i/mnethost') . '" class="icon" alt="'.get_string('course').'" />';
2736 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2737 . s($host['name']).'</a> - ';
2738 echo $host['count'] . ' ' . get_string('courses');
2745 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2747 function add_course_module($mod) {
2750 $mod->added = time();
2753 return $DB->insert_record("course_modules", $mod);
2757 * Returns course section - creates new if does not exist yet.
2758 * @param int $relative section number
2759 * @param int $courseid
2760 * @return object $course_section object
2762 function get_course_section($section, $courseid) {
2765 if ($cw = $DB->get_record("course_sections", array("section"=>$section, "course"=>$courseid))) {
2768 $cw = new stdClass();
2769 $cw->course = $courseid;
2770 $cw->section = $section;
2772 $cw->summaryformat = FORMAT_HTML;
2774 $id = $DB->insert_record("course_sections", $cw);
2775 rebuild_course_cache($courseid, true);
2776 return $DB->get_record("course_sections", array("id"=>$id));
2780 * Given a full mod object with section and course already defined, adds this module to that section.
2782 * @param object $mod
2783 * @param int $beforemod An existing ID which we will insert the new module before
2784 * @return int The course_sections ID where the mod is inserted
2786 function add_mod_to_section($mod, $beforemod=NULL) {
2789 if ($section = $DB->get_record("course_sections", array("course"=>$mod->course, "section"=>$mod->section))) {
2791 $section->sequence = trim($section->sequence);
2793 if (empty($section->sequence)) {
2794 $newsequence = "$mod->coursemodule";
2796 } else if ($beforemod) {
2797 $modarray = explode(",", $section->sequence);
2799 if ($key = array_keys($modarray, $beforemod->id)) {
2800 $insertarray = array($mod->id, $beforemod->id);
2801 array_splice($modarray, $key[0], 1, $insertarray);
2802 $newsequence = implode(",", $modarray);
2804 } else { // Just tack it on the end anyway
2805 $newsequence = "$section->sequence,$mod->coursemodule";
2809 $newsequence = "$section->sequence,$mod->coursemodule";
2812 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
2813 return $section->id; // Return course_sections ID that was used.
2815 } else { // Insert a new record
2816 $section = new stdClass();
2817 $section->course = $mod->course;
2818 $section->section = $mod->section;
2819 $section->summary = "";
2820 $section->summaryformat = FORMAT_HTML;
2821 $section->sequence = $mod->coursemodule;
2822 return $DB->insert_record("course_sections", $section);
2826 function set_coursemodule_groupmode($id, $groupmode) {
2828 return $DB->set_field("course_modules", "groupmode", $groupmode, array("id"=>$id));
2831 function set_coursemodule_idnumber($id, $idnumber) {
2833 return $DB->set_field("course_modules", "idnumber", $idnumber, array("id"=>$id));
2837 * $prevstateoverrides = true will set the visibility of the course module
2838 * to what is defined in visibleold. This enables us to remember the current
2839 * visibility when making a whole section hidden, so that when we toggle
2840 * that section back to visible, we are able to return the visibility of
2841 * the course module back to what it was originally.
2843 function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
2845 require_once($CFG->libdir.'/gradelib.php');
2847 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2850 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
2853 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2854 foreach($events as $event) {
2863 // hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there
2864 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
2866 foreach ($grade_items as $grade_item) {
2867 $grade_item->set_hidden(!$visible);
2871 if ($prevstateoverrides) {
2872 if ($visible == '0') {
2873 // Remember the current visible state so we can toggle this back.
2874 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id'=>$id));
2876 // Get the previous saved visible states.
2877 return $DB->set_field('course_modules', 'visible', $cm->visibleold, array('id'=>$id));
2880 return $DB->set_field("course_modules", "visible", $visible, array("id"=>$id));
2884 * Delete a course module and any associated data at the course level (events)
2885 * Until 1.5 this function simply marked a deleted flag ... now it
2886 * deletes it completely.
2889 function delete_course_module($id) {
2891 require_once($CFG->libdir.'/gradelib.php');
2892 require_once($CFG->dirroot.'/blog/lib.php');
2894 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2897 $modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module));
2898 //delete events from calendar
2899 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2900 foreach($events as $event) {
2901 delete_event($event->id);
2904 //delete grade items, outcome items and grades attached to modules
2905 if ($grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2906 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course))) {
2907 foreach ($grade_items as $grade_item) {
2908 $grade_item->delete('moddelete');
2911 // Delete completion and availability data; it is better to do this even if the
2912 // features are not turned on, in case they were turned on previously (these will be
2913 // very quick on an empty table)
2914 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
2915 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id));
2916 $DB->delete_records('course_modules_avail_fields', array('coursemoduleid' => $cm->id));
2917 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
2918 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
2920 delete_context(CONTEXT_MODULE, $cm->id);
2921 return $DB->delete_records('course_modules', array('id'=>$cm->id));
2924 function delete_mod_from_section($mod, $section) {
2927 if ($section = $DB->get_record("course_sections", array("id"=>$section)) ) {
2929 $modarray = explode(",", $section->sequence);
2931 if ($key = array_keys ($modarray, $mod)) {
2932 array_splice($modarray, $key[0], 1);
2933 $newsequence = implode(",", $modarray);
2934 return $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
2944 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
2946 * @param object $course course object
2947 * @param int $section Section number (not id!!!)
2948 * @param int $move (-1 or 1)
2949 * @return boolean true if section moved successfully
2950 * @todo MDL-33379 remove this function in 2.5
2952 function move_section($course, $section, $move) {
2953 debugging('This function will be removed before 2.5 is released please use move_section_to', DEBUG_DEVELOPER);
2955 /// Moves a whole course section up and down within the course
2962 $sectiondest = $section + $move;
2964 if ($sectiondest > $course->numsections or $sectiondest < 1) {
2968 $retval = move_section_to($course, $section, $sectiondest);
2969 // If section moved, then rebuild course cache.
2971 rebuild_course_cache($course->id, true);
2977 * Moves a section within a course, from a position to another.
2978 * Be very careful: $section and $destination refer to section number,
2981 * @param object $course
2982 * @param int $section Section number (not id!!!)
2983 * @param int $destination
2984 * @return boolean Result
2986 function move_section_to($course, $section, $destination) {
2987 /// Moves a whole course section up and down within the course
2990 if (!$destination && $destination != 0) {
2994 if (($destination > $course->numsections) || ($destination < 1)) {
2998 // Get all sections for this course and re-order them (2 of them should now share the same section number)
2999 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
3000 'section ASC, id ASC', 'id, section')) {
3004 $movedsections = reorder_sections($sections, $section, $destination);
3006 // Update all sections. Do this in 2 steps to avoid breaking database
3007 // uniqueness constraint
3008 $transaction = $DB->start_delegated_transaction();
3009 foreach ($movedsections as $id => $position) {
3010 if ($sections[$id] !== $position) {
3011 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
3014 foreach ($movedsections as $id => $position) {
3015 if ($sections[$id] !== $position) {
3016 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
3020 // If we move the highlighted section itself, then just highlight the destination.
3021 // Adjust the higlighted section location if we move something over it either direction.
3022 if ($section == $course->marker) {
3023 course_set_marker($course->id, $destination);
3024 } elseif ($section > $course->marker && $course->marker >= $destination) {
3025 course_set_marker($course->id, $course->marker+1);
3026 } elseif ($section < $course->marker && $course->marker <= $destination) {
3027 course_set_marker($course->id, $course->marker-1);
3030 $transaction->allow_commit();
3035 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
3036 * an original position number and a target position number, rebuilds the array so that the
3037 * move is made without any duplication of section positions.
3038 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
3039 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
3041 * @param array $sections
3042 * @param int $origin_position
3043 * @param int $target_position
3046 function reorder_sections($sections, $origin_position, $target_position) {
3047 if (!is_array($sections)) {
3051 // We can't move section position 0
3052 if ($origin_position < 1) {
3053 echo "We can't move section position 0";
3057 // Locate origin section in sections array
3058 if (!$origin_key = array_search($origin_position, $sections)) {
3059 echo "searched position not in sections array";
3060 return false; // searched position not in sections array
3063 // Extract origin section
3064 $origin_section = $sections[$origin_key];
3065 unset($sections[$origin_key]);
3067 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
3069 $append_array = array();
3070 foreach ($sections as $id => $position) {
3072 $append_array[$id] = $position;
3073 unset($sections[$id]);
3075 if ($position == $target_position) {
3076 if ($target_position < $origin_position) {
3077 $append_array[$id] = $position;
3078 unset($sections[$id]);
3084 // Append moved section
3085 $sections[$origin_key] = $origin_section;
3087 // Append rest of array (if applicable)
3088 if (!empty($append_array)) {
3089 foreach ($append_array as $id => $position) {
3090 $sections[$id] = $position;
3094 // Renumber positions
3096 foreach ($sections as $id => $p) {
3097 $sections[$id] = $position;
3106 * Move the module object $mod to the specified $section
3107 * If $beforemod exists then that is the module
3108 * before which $modid should be inserted
3109 * All parameters are objects
3111 function moveto_module($mod, $section, $beforemod=NULL) {
3112 global $DB, $OUTPUT;
3114 /// Remove original module from original section
3115 if (! delete_mod_from_section($mod->id, $mod->section)) {
3116 echo $OUTPUT->notification("Could not delete module from existing section");
3119 /// Update module itself if necessary
3121 if ($mod->section != $section->id) {
3122 $mod->section = $section->id;
3123 $DB->update_record("course_modules", $mod);
3124 // if moving to a hidden section then hide module
3125 if (!$section->visible) {
3126 set_coursemodule_visible($mod->id, 0);
3130 /// Add the module into the new section
3132 $mod->course = $section->course;
3133 $mod->section = $section->section; // need relative reference
3134 $mod->coursemodule = $mod->id;
3136 if (! add_mod_to_section($mod, $beforemod)) {
3144 * Produces the editing buttons for a module
3146 * @global core_renderer $OUTPUT
3147 * @staticvar type $str
3148 * @param stdClass $mod The module to produce editing buttons for
3149 * @param bool $absolute_ignored ignored - all links are absolute
3150 * @param bool $moveselect If true a move seleciton process is used (default true)
3151 * @param int $indent The current indenting
3152 * @param int $section The section to link back to
3153 * @return string XHTML for the editing buttons
3155 function make_editing_buttons(stdClass $mod, $absolute_ignored = true, $moveselect = true, $indent=-1, $section=-1) {
3156 global $CFG, $OUTPUT, $COURSE;
3160 $coursecontext = context_course::instance($mod->course);
3161 $modcontext = context_module::instance($mod->id);
3163 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
3164 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
3166 // no permission to edit anything
3167 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
3171 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
3174 $str = new stdClass;
3175 $str->assign = get_string("assignroles", 'role');
3176 $str->delete = get_string("delete");
3177 $str->move = get_string("move");
3178 $str->moveup = get_string("moveup");
3179 $str->movedown = get_string("movedown");
3180 $str->moveright = get_string("moveright");
3181 $str->moveleft = get_string("moveleft");
3182 $str->update = get_string("update");
3183 $str->duplicate = get_string("duplicate");
3184 $str->hide = get_string("hide");
3185 $str->show = get_string("show");
3186 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
3187 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
3188 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
3189 $str->forcedgroupsnone = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsnone"));
3190 $str->forcedgroupsseparate = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsseparate"));
3191 $str->forcedgroupsvisible = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsvisible"));
3192 $str->edittitle = get_string('edittitle', 'moodle');
3195 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
3197 if ($section >= 0) {
3198 $baseurl->param('sr', $section);
3203 if ($mod->modname !== 'label' && $hasmanageactivities && course_ajax_enabled($COURSE)) {
3204 $actions[] = new action_link(
3205 new moodle_url($baseurl, array('update' => $mod->id)),
3206 new pix_icon('t/editstring', $str->edittitle, 'moodle', array('class' => 'iconsmall visibleifjs')),
3208 array('class' => 'editing_title', 'title' => $str->edittitle)
3213 if ($hasmanageactivities) {
3214 if (right_to_left()) { // Exchange arrows on RTL
3215 $rightarrow = 't/left';
3216 $leftarrow = 't/right';
3218 $rightarrow = 't/right';
3219 $leftarrow = 't/left';
3223 $actions[] = new action_link(
3224 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
3225 new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall')),
3227 array('class' => 'editing_moveleft', 'title' => $str->moveleft)
3231 $actions[] = new action_link(
3232 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
3233 new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall')),
3235 array('class' => 'editing_moveright', 'title' => $str->moveright)
3241 if ($hasmanageactivities) {
3243 $actions[] = new action_link(
3244 new moodle_url($baseurl, array('copy' => $mod->id)),
3245 new pix_icon('t/move', $str->move, 'moodle', array('class' => 'iconsmall')),
3247 array('class' => 'editing_move', 'title' => $str->move)
3250 $actions[] = new action_link(
3251 new moodle_url($baseurl, array('id' => $mod->id, 'move' => '-1')),
3252 new pix_icon('t/up', $str->moveup, 'moodle', array('class' => 'iconsmall')),
3254 array('class' => 'editing_moveup', 'title' => $str->moveup)
3256 $actions[] = new action_link(
3257 new moodle_url($baseurl, array('id' => $mod->id, 'move' => '1')),
3258 new pix_icon('t/down', $str->movedown, 'moodle', array('class' => 'iconsmall')),
3260 array('class' => 'editing_movedown', 'title' => $str->movedown)
3266 if ($hasmanageactivities) {
3267 $actions[] = new action_link(
3268 new moodle_url($baseurl, array('update' => $mod->id)),
3269 new pix_icon('t/edit', $str->update, 'moodle', array('class' => 'iconsmall')),
3271 array('class' => 'editing_update', 'title' => $str->update)
3275 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
3276 if (has_all_capabilities($dupecaps, $coursecontext) && plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2)) {
3277 $actions[] = new action_link(
3278 new moodle_url($baseurl, array('duplicate' => $mod->id)),
3279 new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall')),
3281 array('class' => 'editing_duplicate', 'title' => $str->duplicate)
3286 if ($hasmanageactivities) {
3287 $actions[] = new action_link(
3288 new moodle_url($baseurl, array('delete' => $mod->id)),
3289 new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall')),
3291 array('class' => 'editing_delete', 'title' => $str->delete)
3296 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
3297 if ($mod->visible) {
3298 $actions[] = new action_link(
3299 new moodle_url($baseurl, array('hide' => $mod->id)),
3300 new pix_icon('t/hide', $str->hide, 'moodle', array('class' => 'iconsmall')),
3302 array('class' => 'editing_hide', 'title' => $str->hide)
3305 $actions[] = new action_link(
3306 new moodle_url($baseurl, array('show' => $mod->id)),
3307 new pix_icon('t/show', $str->show, 'moodle', array('class' => 'iconsmall')),
3309 array('class' => 'editing_show', 'title' => $str->show)
3315 if ($hasmanageactivities and $mod->groupmode !== false) {
3316 if ($mod->groupmode == SEPARATEGROUPS) {
3318 $grouptitle = $str->groupsseparate;
3319 $forcedgrouptitle = $str->forcedgroupsseparate;
3320 $groupclass = 'editing_groupsseparate';
3321 $groupimage = 't/groups';
3322 } else if ($mod->groupmode == VISIBLEGROUPS) {
3324 $grouptitle = $str->groupsvisible;
3325 $forcedgrouptitle = $str->forcedgroupsvisible;
3326 $groupclass = 'editing_groupsvisible';
3327 $groupimage = 't/groupv';
3330 $grouptitle = $str->groupsnone;
3331 $forcedgrouptitle = $str->forcedgroupsnone;
3332 $groupclass = 'editing_groupsnone';
3333 $groupimage = 't/groupn';
3335 if ($mod->groupmodelink) {
3336 $actions[] = new action_link(
3337 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $groupmode)),
3338 new pix_icon($groupimage, $grouptitle, 'moodle', array('class' => 'iconsmall')),
3340 array('class' => $groupclass, 'title' => $grouptitle)
3343 $actions[] = new pix_icon($groupimage, $forcedgrouptitle, 'moodle', array('title' => $forcedgrouptitle, 'class' => 'iconsmall'));
3348 if (has_capability('moodle/role:assign', $modcontext)){
3349 $actions[] = new action_link(
3350 new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $modcontext->id)),
3351 new pix_icon('i/roles', $str->assign, 'moodle', array('class' => 'iconsmall')),
3353 array('class' => 'editing_assign', 'title' => $str->assign)
3357 $output = html_writer::start_tag('span', array('class' => 'commands'));
3358 foreach ($actions as $action) {
3359 if ($action instanceof renderable) {
3360 $output .= $OUTPUT->render($action);
3365 $output .= html_writer::end_tag('span');
3370 * given a course object with shortname & fullname, this function will
3371 * truncate the the number of chars allowed and add ... if it was too long
3373 function course_format_name ($course,$max=100) {
3375 $context = context_course::instance($course->id);
3376 $shortname = format_string($course->shortname, true, array('context' => $context));
3377 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
3378 $str = $shortname.': '. $fullname;
3379 if (textlib::strlen($str) <= $max) {
3383 return textlib::substr($str,0,$max-3).'...';
3388 * Is the user allowed to add this type of module to this course?
3389 * @param object $course the course settings. Only $course->id is used.
3390 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
3391 * @return bool whether the current user is allowed to add this type of module to this course.
3393 function course_allowed_module($course, $modname) {
3396 if (is_numeric($modname)) {
3397 throw new coding_exception('Function course_allowed_module no longer
3398 supports numeric module ids. Please update your code to pass the module name.');
3401 $capability = 'mod/' . $modname . ':addinstance';
3402 if (!get_capability_info($capability)) {
3403 // Debug warning that the capability does not exist, but no more than once per page.
3404 static $warned = array();
3405 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
3406 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
3407 debugging('The module ' . $modname . ' does not define the standard capability ' .
3408 $capability , DEBUG_DEVELOPER);
3409 $warned[$modname] = 1;
3412 // If the capability does not exist, the module can always be added.
3416 $coursecontext = context_course::instance($course->id);
3417 return has_capability($capability, $coursecontext);
3421 * Recursively delete category including all subcategories and courses.
3422 * @param stdClass $category
3423 * @param boolean $showfeedback display some notices
3424 * @return array return deleted courses
3426 function category_delete_full($category, $showfeedback=true) {
3428 require_once($CFG->libdir.'/gradelib.php');
3429 require_once($CFG->libdir.'/questionlib.php');
3430 require_once($CFG->dirroot.'/cohort/lib.php');
3432 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3433 foreach ($children as $childcat) {
3434 category_delete_full($childcat, $showfeedback);
3438 $deletedcourses = array();
3439 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC')) {
3440 foreach ($courses as $course) {
3441 if (!delete_course($course, false)) {
3442 throw new moodle_exception('cannotdeletecategorycourse','','',$course->shortname);
3444 $deletedcourses[] = $course;
3448 // move or delete cohorts in this context
3449 cohort_delete_category($category);
3451 // now delete anything that may depend on course category context
3452 grade_course_category_delete($category->id, 0, $showfeedback);
3453 if (!question_delete_course_category($category, 0, $showfeedback)) {
3454 throw new moodle_exception('cannotdeletecategoryquestions','','',$category->name);
3457 // finally delete the category and it's context
3458 $DB->delete_records('course_categories', array('id'=>$category->id));
3459 delete_context(CONTEXT_COURSECAT, $category->id);
3461 events_trigger('course_category_deleted', $category);
3463 return $deletedcourses;
3467 * Delete category, but move contents to another category.
3468 * @param object $ccategory
3469 * @param int $newparentid category id
3470 * @return bool status
3472 function category_delete_move($category, $newparentid, $showfeedback=true) {
3473 global $CFG, $DB, $OUTPUT;
3474 require_once($CFG->libdir.'/gradelib.php');
3475 require_once($CFG->libdir.'/questionlib.php');
3476 require_once($CFG->dirroot.'/cohort/lib.php');
3478 if (!$newparentcat = $DB->get_record('course_categories', array('id'=>$newparentid))) {
3482 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3483 foreach ($children as $childcat) {
3484 move_category($childcat, $newparentcat);