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');
32 require_once($CFG->dirroot.'/course/format/lib.php');
34 define('COURSE_MAX_LOGS_PER_PAGE', 1000); // records
35 define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds
38 * Number of courses to display when summaries are included.
40 * @deprecated since 2.4, use $CFG->courseswithsummarieslimit instead.
42 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10);
44 define('COURSE_MAX_COURSES_PER_DROPDOWN',1000); // max courses in log dropdown before switching to optional
45 define('COURSE_MAX_USERS_PER_DROPDOWN',1000); // max users in log dropdown before switching to optional
46 define('FRONTPAGENEWS', '0');
47 define('FRONTPAGECOURSELIST', '1');
48 define('FRONTPAGECATEGORYNAMES', '2');
49 define('FRONTPAGETOPICONLY', '3');
50 define('FRONTPAGECATEGORYCOMBO', '4');
51 define('FRONTPAGECOURSELIMIT', 200); // maximum number of courses displayed on the frontpage
52 define('EXCELROWS', 65535);
53 define('FIRSTUSEDEXCELROW', 3);
55 define('MOD_CLASS_ACTIVITY', 0);
56 define('MOD_CLASS_RESOURCE', 1);
58 function make_log_url($module, $url) {
61 if (strpos($url, 'report/') === 0) {
62 // there is only one report type, course reports are deprecated
72 if (strpos($url, '../') === 0) {
73 $url = ltrim($url, '.');
75 $url = "/course/$url";
80 $url = "/$module/$url";
93 $url = "/message/$url";
105 $url = "/mod/$module/$url";
109 //now let's sanitise urls - there might be some ugly nasties:-(
110 $parts = explode('?', $url);
111 $script = array_shift($parts);
112 if (strpos($script, 'http') === 0) {
113 $script = clean_param($script, PARAM_URL);
115 $script = clean_param($script, PARAM_PATH);
120 $query = implode('', $parts);
121 $query = str_replace('&', '&', $query); // both & and & are stored in db :-|
122 $parts = explode('&', $query);
123 $eq = urlencode('=');
124 foreach ($parts as $key=>$part) {
125 $part = urlencode(urldecode($part));
126 $part = str_replace($eq, '=', $part);
127 $parts[$key] = $part;
129 $query = '?'.implode('&', $parts);
132 return $script.$query;
136 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
137 $modname="", $modid=0, $modaction="", $groupid=0) {
140 // It is assumed that $date is the GMT time of midnight for that day,
141 // and so the next 86400 seconds worth of logs are printed.
143 /// Setup for group handling.
145 // TODO: I don't understand group/context/etc. enough to be able to do
146 // something interesting with it here
147 // What is the context of a remote course?
149 /// If the group mode is separate, and this user does not have editing privileges,
150 /// then only the user's group can be viewed.
151 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
152 // $groupid = get_current_group($course->id);
154 /// If this course doesn't have groups, no groupid can be specified.
155 //else if (!$course->groupmode) {
164 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
166 LEFT JOIN {user} u ON l.userid = u.id
170 $where .= "l.hostid = :hostid";
171 $params['hostid'] = $hostid;
173 // TODO: Is 1 really a magic number referring to the sitename?
174 if ($course != SITEID || $modid != 0) {
175 $where .= " AND l.course=:courseid";
176 $params['courseid'] = $course;
180 $where .= " AND l.module = :modname";
181 $params['modname'] = $modname;
184 if ('site_errors' === $modid) {
185 $where .= " AND ( l.action='error' OR l.action='infected' )";
187 //TODO: This assumes that modids are the same across sites... probably
189 $where .= " AND l.cmid = :modid";
190 $params['modid'] = $modid;
194 $firstletter = substr($modaction, 0, 1);
195 if ($firstletter == '-') {
196 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
197 $params['modaction'] = '%'.substr($modaction, 1).'%';
199 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
200 $params['modaction'] = '%'.$modaction.'%';
205 $where .= " AND l.userid = :user";
206 $params['user'] = $user;
210 $enddate = $date + 86400;
211 $where .= " AND l.time > :date AND l.time < :enddate";
212 $params['date'] = $date;
213 $params['enddate'] = $enddate;
217 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
218 if(!empty($result['totalcount'])) {
219 $where .= " ORDER BY $order";
220 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
222 $result['logs'] = array();
227 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
228 $modname="", $modid=0, $modaction="", $groupid=0) {
229 global $DB, $SESSION, $USER;
230 // It is assumed that $date is the GMT time of midnight for that day,
231 // and so the next 86400 seconds worth of logs are printed.
233 /// Setup for group handling.
235 /// If the group mode is separate, and this user does not have editing privileges,
236 /// then only the user's group can be viewed.
237 if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
238 if (isset($SESSION->currentgroup[$course->id])) {
239 $groupid = $SESSION->currentgroup[$course->id];
241 $groupid = groups_get_all_groups($course->id, $USER->id);
242 if (is_array($groupid)) {
243 $groupid = array_shift(array_keys($groupid));
244 $SESSION->currentgroup[$course->id] = $groupid;
250 /// If this course doesn't have groups, no groupid can be specified.
251 else if (!$course->groupmode) {
258 if ($course->id != SITEID || $modid != 0) {
259 $joins[] = "l.course = :courseid";
260 $params['courseid'] = $course->id;
264 $joins[] = "l.module = :modname";
265 $params['modname'] = $modname;
268 if ('site_errors' === $modid) {
269 $joins[] = "( l.action='error' OR l.action='infected' )";
271 $joins[] = "l.cmid = :modid";
272 $params['modid'] = $modid;
276 $firstletter = substr($modaction, 0, 1);
277 if ($firstletter == '-') {
278 $joins[] = $DB->sql_like('l.action', ':modaction', false, true, true);
279 $params['modaction'] = '%'.substr($modaction, 1).'%';
281 $joins[] = $DB->sql_like('l.action', ':modaction', false);
282 $params['modaction'] = '%'.$modaction.'%';
287 /// Getting all members of a group.
288 if ($groupid and !$user) {
289 if ($gusers = groups_get_members($groupid)) {
290 $gusers = array_keys($gusers);
291 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
293 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
297 $joins[] = "l.userid = :userid";
298 $params['userid'] = $user;
302 $enddate = $date + 86400;
303 $joins[] = "l.time > :date AND l.time < :enddate";
304 $params['date'] = $date;
305 $params['enddate'] = $enddate;
308 $selector = implode(' AND ', $joins);
310 $totalcount = 0; // Initialise
312 $result['logs'] = get_logs($selector, $params, $order, $limitfrom, $limitnum, $totalcount);
313 $result['totalcount'] = $totalcount;
318 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
319 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
321 global $CFG, $DB, $OUTPUT;
323 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
324 $modname, $modid, $modaction, $groupid)) {
325 echo $OUTPUT->notification("No logs found!");
326 echo $OUTPUT->footer();
332 if ($course->id == SITEID) {
334 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
335 foreach ($ccc as $cc) {
336 $courses[$cc->id] = $cc->shortname;
340 $courses[$course->id] = $course->shortname;
343 $totalcount = $logs['totalcount'];
346 $tt = getdate(time());
347 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
349 $strftimedatetime = get_string("strftimedatetime");
351 echo "<div class=\"info\">\n";
352 print_string("displayingrecords", "", $totalcount);
355 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
357 $table = new html_table();
358 $table->classes = array('logtable','generalbox');
359 $table->align = array('right', 'left', 'left');
360 $table->head = array(
362 get_string('ip_address'),
363 get_string('fullnameuser'),
364 get_string('action'),
367 $table->data = array();
369 if ($course->id == SITEID) {
370 array_unshift($table->align, 'left');
371 array_unshift($table->head, get_string('course'));
374 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
375 if (empty($logs['logs'])) {
376 $logs['logs'] = array();
379 foreach ($logs['logs'] as $log) {
381 if (isset($ldcache[$log->module][$log->action])) {
382 $ld = $ldcache[$log->module][$log->action];
384 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
385 $ldcache[$log->module][$log->action] = $ld;
387 if ($ld && is_numeric($log->info)) {
388 // ugly hack to make sure fullname is shown correctly
389 if ($ld->mtable == 'user' && $ld->field == $DB->sql_concat('firstname', "' '" , 'lastname')) {
390 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
392 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
397 $log->info = format_string($log->info);
399 // If $log->url has been trimmed short by the db size restriction
400 // code in add_to_log, keep a note so we don't add a link to a broken url
401 $brokenurl=(textlib::strlen($log->url)==100 && textlib::substr($log->url,97)=='...');
404 if ($course->id == SITEID) {
405 if (empty($log->course)) {
406 $row[] = get_string('site');
408 $row[] = "<a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course])."</a>";
412 $row[] = userdate($log->time, '%a').' '.userdate($log->time, $strftimedatetime);
414 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
415 $row[] = $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 440, 'width' => 700)));
417 $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))));
419 $displayaction="$log->module $log->action";
421 $row[] = $displayaction;
423 $link = make_log_url($log->module,$log->url);
424 $row[] = $OUTPUT->action_link($link, $displayaction, new popup_action('click', $link, 'fromloglive'), array('height' => 440, 'width' => 700));
427 $table->data[] = $row;
430 echo html_writer::table($table);
431 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
435 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
436 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
438 global $CFG, $DB, $OUTPUT;
440 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
441 $modname, $modid, $modaction, $groupid)) {
442 echo $OUTPUT->notification("No logs found!");
443 echo $OUTPUT->footer();
447 if ($course->id == SITEID) {
449 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
450 foreach ($ccc as $cc) {
451 $courses[$cc->id] = $cc->shortname;
456 $totalcount = $logs['totalcount'];
459 $tt = getdate(time());
460 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
462 $strftimedatetime = get_string("strftimedatetime");
464 echo "<div class=\"info\">\n";
465 print_string("displayingrecords", "", $totalcount);
468 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
470 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
472 if ($course->id == SITEID) {
473 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
475 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
476 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
477 echo "<th class=\"c3 header\">".get_string('fullnameuser')."</th>\n";
478 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
479 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
482 if (empty($logs['logs'])) {
488 foreach ($logs['logs'] as $log) {
490 $log->info = $log->coursename;
491 $row = ($row + 1) % 2;
493 if (isset($ldcache[$log->module][$log->action])) {
494 $ld = $ldcache[$log->module][$log->action];
496 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
497 $ldcache[$log->module][$log->action] = $ld;
499 if (0 && $ld && !empty($log->info)) {
500 // ugly hack to make sure fullname is shown correctly
501 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
502 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
504 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
509 $log->info = format_string($log->info);
511 echo '<tr class="r'.$row.'">';
512 if ($course->id == SITEID) {
513 $courseshortname = format_string($courses[$log->course], true, array('context' => context_course::instance(SITEID)));
514 echo "<td class=\"r$row c0\" >\n";
515 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courseshortname."</a>\n";
518 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time, '%a').
519 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
520 echo "<td class=\"r$row c2\" >\n";
521 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
522 echo $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 400, 'width' => 700)));
524 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', context_course::instance($course->id)));
525 echo "<td class=\"r$row c3\" >\n";
526 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
528 echo "<td class=\"r$row c4\">\n";
529 echo $log->action .': '.$log->module;
531 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
536 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
540 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
541 $modid, $modaction, $groupid) {
544 require_once($CFG->libdir . '/csvlib.class.php');
546 $csvexporter = new csv_export_writer('tab');
549 $header[] = get_string('course');
550 $header[] = get_string('time');
551 $header[] = get_string('ip_address');
552 $header[] = get_string('fullnameuser');
553 $header[] = get_string('action');
554 $header[] = get_string('info');
556 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
557 $modname, $modid, $modaction, $groupid)) {
563 if ($course->id == SITEID) {
565 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
566 foreach ($ccc as $cc) {
567 $courses[$cc->id] = $cc->shortname;
571 $courses[$course->id] = $course->shortname;
576 $tt = getdate(time());
577 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
579 $strftimedatetime = get_string("strftimedatetime");
581 $csvexporter->set_filename('logs', '.txt');
582 $title = array(get_string('savedat').userdate(time(), $strftimedatetime));
583 $csvexporter->add_data($title);
584 $csvexporter->add_data($header);
586 if (empty($logs['logs'])) {
590 foreach ($logs['logs'] as $log) {
591 if (isset($ldcache[$log->module][$log->action])) {
592 $ld = $ldcache[$log->module][$log->action];
594 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
595 $ldcache[$log->module][$log->action] = $ld;
597 if ($ld && !empty($log->info)) {
598 // ugly hack to make sure fullname is shown correctly
599 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
600 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
602 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
607 $log->info = format_string($log->info);
608 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
610 $coursecontext = context_course::instance($course->id);
611 $firstField = format_string($courses[$log->course], true, array('context' => $coursecontext));
612 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
613 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
614 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action.' ('.$actionurl.')', $log->info);
615 $csvexporter->add_data($row);
617 $csvexporter->download_file();
622 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
623 $modid, $modaction, $groupid) {
627 require_once("$CFG->libdir/excellib.class.php");
629 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
630 $modname, $modid, $modaction, $groupid)) {
636 if ($course->id == SITEID) {
638 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
639 foreach ($ccc as $cc) {
640 $courses[$cc->id] = $cc->shortname;
644 $courses[$course->id] = $course->shortname;
649 $tt = getdate(time());
650 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
652 $strftimedatetime = get_string("strftimedatetime");
654 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
655 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
658 $workbook = new MoodleExcelWorkbook('-');
659 $workbook->send($filename);
661 $worksheet = array();
662 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
663 get_string('fullnameuser'), get_string('action'), get_string('info'));
665 // Creating worksheets
666 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
667 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
668 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
669 $worksheet[$wsnumber]->set_column(1, 1, 30);
670 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
671 userdate(time(), $strftimedatetime));
673 foreach ($headers as $item) {
674 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
679 if (empty($logs['logs'])) {
684 $formatDate =& $workbook->add_format();
685 $formatDate->set_num_format(get_string('log_excel_date_format'));
687 $row = FIRSTUSEDEXCELROW;
689 $myxls =& $worksheet[$wsnumber];
690 foreach ($logs['logs'] as $log) {
691 if (isset($ldcache[$log->module][$log->action])) {
692 $ld = $ldcache[$log->module][$log->action];
694 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
695 $ldcache[$log->module][$log->action] = $ld;
697 if ($ld && !empty($log->info)) {
698 // ugly hack to make sure fullname is shown correctly
699 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
700 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
702 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
707 $log->info = format_string($log->info);
708 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
711 if ($row > EXCELROWS) {
713 $myxls =& $worksheet[$wsnumber];
714 $row = FIRSTUSEDEXCELROW;
718 $coursecontext = context_course::instance($course->id);
720 $myxls->write($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)), '');
721 $myxls->write_date($row, 1, $log->time, $formatDate); // write_date() does conversion/timezone support. MDL-14934
722 $myxls->write($row, 2, $log->ip, '');
723 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
724 $myxls->write($row, 3, $fullname, '');
725 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
726 $myxls->write($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')', '');
727 $myxls->write($row, 5, $log->info, '');
736 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
737 $modid, $modaction, $groupid) {
741 require_once("$CFG->libdir/odslib.class.php");
743 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
744 $modname, $modid, $modaction, $groupid)) {
750 if ($course->id == SITEID) {
752 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
753 foreach ($ccc as $cc) {
754 $courses[$cc->id] = $cc->shortname;
758 $courses[$course->id] = $course->shortname;
763 $tt = getdate(time());
764 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
766 $strftimedatetime = get_string("strftimedatetime");
768 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
769 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
772 $workbook = new MoodleODSWorkbook('-');
773 $workbook->send($filename);
775 $worksheet = array();
776 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
777 get_string('fullnameuser'), get_string('action'), get_string('info'));
779 // Creating worksheets
780 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
781 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
782 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
783 $worksheet[$wsnumber]->set_column(1, 1, 30);
784 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
785 userdate(time(), $strftimedatetime));
787 foreach ($headers as $item) {
788 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
793 if (empty($logs['logs'])) {
798 $formatDate =& $workbook->add_format();
799 $formatDate->set_num_format(get_string('log_excel_date_format'));
801 $row = FIRSTUSEDEXCELROW;
803 $myxls =& $worksheet[$wsnumber];
804 foreach ($logs['logs'] as $log) {
805 if (isset($ldcache[$log->module][$log->action])) {
806 $ld = $ldcache[$log->module][$log->action];
808 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
809 $ldcache[$log->module][$log->action] = $ld;
811 if ($ld && !empty($log->info)) {
812 // ugly hack to make sure fullname is shown correctly
813 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
814 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
816 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
821 $log->info = format_string($log->info);
822 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
825 if ($row > EXCELROWS) {
827 $myxls =& $worksheet[$wsnumber];
828 $row = FIRSTUSEDEXCELROW;
832 $coursecontext = context_course::instance($course->id);
834 $myxls->write_string($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)));
835 $myxls->write_date($row, 1, $log->time);
836 $myxls->write_string($row, 2, $log->ip);
837 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
838 $myxls->write_string($row, 3, $fullname);
839 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
840 $myxls->write_string($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')');
841 $myxls->write_string($row, 5, $log->info);
851 function print_overview($courses, array $remote_courses=array()) {
852 global $CFG, $USER, $DB, $OUTPUT;
854 $htmlarray = array();
855 if ($modules = $DB->get_records('modules')) {
856 foreach ($modules as $mod) {
857 if (file_exists(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php')) {
858 include_once(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php');
859 $fname = $mod->name.'_print_overview';
860 if (function_exists($fname)) {
861 $fname($courses,$htmlarray);
866 foreach ($courses as $course) {
867 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
868 echo $OUTPUT->box_start('coursebox');
869 $attributes = array('title' => s($fullname));
870 if (empty($course->visible)) {
871 $attributes['class'] = 'dimmed';
873 echo $OUTPUT->heading(html_writer::link(
874 new moodle_url('/course/view.php', array('id' => $course->id)), $fullname, $attributes), 3);
875 if (array_key_exists($course->id,$htmlarray)) {
876 foreach ($htmlarray[$course->id] as $modname => $html) {
880 echo $OUTPUT->box_end();
883 if (!empty($remote_courses)) {
884 echo $OUTPUT->heading(get_string('remotecourses', 'mnet'));
886 foreach ($remote_courses as $course) {
887 echo $OUTPUT->box_start('coursebox');
888 $attributes = array('title' => s($course->fullname));
889 echo $OUTPUT->heading(html_writer::link(
890 new moodle_url('/auth/mnet/jump.php', array('hostid' => $course->hostid, 'wantsurl' => '/course/view.php?id='.$course->remoteid)),
891 format_string($course->shortname),
892 $attributes) . ' (' . format_string($course->hostname) . ')', 3);
893 echo $OUTPUT->box_end();
899 * This function trawls through the logs looking for
900 * anything new since the user's last login
902 function print_recent_activity($course) {
903 // $course is an object
904 global $CFG, $USER, $SESSION, $DB, $OUTPUT;
906 $context = context_course::instance($course->id);
908 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
910 $timestart = round(time() - COURSE_MAX_RECENT_PERIOD, -2); // better db caching for guests - 100 seconds
912 if (!isguestuser()) {
913 if (!empty($USER->lastcourseaccess[$course->id])) {
914 if ($USER->lastcourseaccess[$course->id] > $timestart) {
915 $timestart = $USER->lastcourseaccess[$course->id];
920 echo '<div class="activitydate">';
921 echo get_string('activitysince', '', userdate($timestart));
923 echo '<div class="activityhead">';
925 echo '<a href="'.$CFG->wwwroot.'/course/recent.php?id='.$course->id.'">'.get_string('recentactivityreport').'</a>';
931 /// Firstly, have there been any new enrolments?
933 $users = get_recent_enrolments($course->id, $timestart);
935 //Accessibility: new users now appear in an <OL> list.
937 echo '<div class="newusers">';
938 echo $OUTPUT->heading(get_string("newusers").':', 3);
940 echo "<ol class=\"list\">\n";
941 foreach ($users as $user) {
942 $fullname = fullname($user, $viewfullnames);
943 echo '<li class="name"><a href="'."$CFG->wwwroot/user/view.php?id=$user->id&course=$course->id\">$fullname</a></li>\n";
945 echo "</ol>\n</div>\n";
948 /// Next, have there been any modifications to the course structure?
950 $modinfo = get_fast_modinfo($course);
952 $changelist = array();
954 $logs = $DB->get_records_select('log', "time > ? AND course = ? AND
955 module = 'course' AND
956 (action = 'add mod' OR action = 'update mod' OR action = 'delete mod')",
957 array($timestart, $course->id), "id ASC");
960 $actions = array('add mod', 'update mod', 'delete mod');
961 $newgones = array(); // added and later deleted items
962 foreach ($logs as $key => $log) {
963 if (!in_array($log->action, $actions)) {
966 $info = explode(' ', $log->info);
968 // note: in most cases I replaced hardcoding of label with use of
969 // $cm->has_view() but it was not possible to do this here because
970 // we don't necessarily have the $cm for it
971 if ($info[0] == 'label') { // Labels are ignored in recent activity
975 if (count($info) != 2) {
976 debugging("Incorrect log entry info: id = ".$log->id, DEBUG_DEVELOPER);
981 $instanceid = $info[1];
983 if ($log->action == 'delete mod') {
984 // unfortunately we do not know if the mod was visible
985 if (!array_key_exists($log->info, $newgones)) {
986 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $modname));
987 $changelist[$log->info] = array ('operation' => 'delete', 'text' => $strdeleted);
990 if (!isset($modinfo->instances[$modname][$instanceid])) {
991 if ($log->action == 'add mod') {
992 // do not display added and later deleted activities
993 $newgones[$log->info] = true;
997 $cm = $modinfo->instances[$modname][$instanceid];
998 if (!$cm->uservisible) {
1002 if ($log->action == 'add mod') {
1003 $stradded = get_string('added', 'moodle', get_string('modulename', $modname));
1004 $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>");
1006 } else if ($log->action == 'update mod' and empty($changelist[$log->info])) {
1007 $strupdated = get_string('updated', 'moodle', get_string('modulename', $modname));
1008 $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>");
1014 if (!empty($changelist)) {
1015 echo $OUTPUT->heading(get_string("courseupdates").':', 3);
1017 foreach ($changelist as $changeinfo => $change) {
1018 echo '<p class="activity">'.$change['text'].'</p>';
1022 /// Now display new things from each module
1024 $usedmodules = array();
1025 foreach($modinfo->cms as $cm) {
1026 if (isset($usedmodules[$cm->modname])) {
1029 if (!$cm->uservisible) {
1032 $usedmodules[$cm->modname] = $cm->modname;
1035 foreach ($usedmodules as $modname) { // Each module gets it's own logs and prints them
1036 if (file_exists($CFG->dirroot.'/mod/'.$modname.'/lib.php')) {
1037 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
1038 $print_recent_activity = $modname.'_print_recent_activity';
1039 if (function_exists($print_recent_activity)) {
1040 // NOTE: original $isteacher (second parameter below) was replaced with $viewfullnames!
1041 $content = $print_recent_activity($course, $viewfullnames, $timestart) || $content;
1044 debugging("Missing lib.php in lib/{$modname} - please reinstall files or uninstall the module");
1049 echo '<p class="message">'.get_string('nothingnew').'</p>';
1054 * For a given course, returns an array of course activity objects
1055 * Each item in the array contains he following properties:
1057 function get_array_of_activities($courseid) {
1058 // cm - course module id
1059 // mod - name of the module (eg forum)
1060 // section - the number of the section (eg week or topic)
1061 // name - the name of the instance
1062 // visible - is the instance visible or not
1063 // groupingid - grouping id
1064 // groupmembersonly - is this instance visible to group members only
1065 // extra - contains extra string to include in any link
1067 if(!empty($CFG->enableavailability)) {
1068 require_once($CFG->libdir.'/conditionlib.php');
1071 $course = $DB->get_record('course', array('id'=>$courseid));
1073 if (empty($course)) {
1074 throw new moodle_exception('courseidnotfound');
1079 $rawmods = get_course_mods($courseid);
1080 if (empty($rawmods)) {
1081 return $mod; // always return array
1084 if ($sections = $DB->get_records("course_sections", array("course"=>$courseid), "section ASC")) {
1085 foreach ($sections as $section) {
1086 if (!empty($section->sequence)) {
1087 $sequence = explode(",", $section->sequence);
1088 foreach ($sequence as $seq) {
1089 if (empty($rawmods[$seq])) {
1092 $mod[$seq] = new stdClass();
1093 $mod[$seq]->id = $rawmods[$seq]->instance;
1094 $mod[$seq]->cm = $rawmods[$seq]->id;
1095 $mod[$seq]->mod = $rawmods[$seq]->modname;
1097 // Oh dear. Inconsistent names left here for backward compatibility.
1098 $mod[$seq]->section = $section->section;
1099 $mod[$seq]->sectionid = $rawmods[$seq]->section;
1101 $mod[$seq]->module = $rawmods[$seq]->module;
1102 $mod[$seq]->added = $rawmods[$seq]->added;
1103 $mod[$seq]->score = $rawmods[$seq]->score;
1104 $mod[$seq]->idnumber = $rawmods[$seq]->idnumber;
1105 $mod[$seq]->visible = $rawmods[$seq]->visible;
1106 $mod[$seq]->visibleold = $rawmods[$seq]->visibleold;
1107 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
1108 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
1109 $mod[$seq]->groupmembersonly = $rawmods[$seq]->groupmembersonly;
1110 $mod[$seq]->indent = $rawmods[$seq]->indent;
1111 $mod[$seq]->completion = $rawmods[$seq]->completion;
1112 $mod[$seq]->extra = "";
1113 $mod[$seq]->completiongradeitemnumber =
1114 $rawmods[$seq]->completiongradeitemnumber;
1115 $mod[$seq]->completionview = $rawmods[$seq]->completionview;
1116 $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected;
1117 $mod[$seq]->availablefrom = $rawmods[$seq]->availablefrom;
1118 $mod[$seq]->availableuntil = $rawmods[$seq]->availableuntil;
1119 $mod[$seq]->showavailability = $rawmods[$seq]->showavailability;
1120 $mod[$seq]->showdescription = $rawmods[$seq]->showdescription;
1121 if (!empty($CFG->enableavailability)) {
1122 condition_info::fill_availability_conditions($rawmods[$seq]);
1123 $mod[$seq]->conditionscompletion = $rawmods[$seq]->conditionscompletion;
1124 $mod[$seq]->conditionsgrade = $rawmods[$seq]->conditionsgrade;
1125 $mod[$seq]->conditionsfield = $rawmods[$seq]->conditionsfield;
1128 $modname = $mod[$seq]->mod;
1129 $functionname = $modname."_get_coursemodule_info";
1131 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
1135 include_once("$CFG->dirroot/mod/$modname/lib.php");
1137 if ($hasfunction = function_exists($functionname)) {
1138 if ($info = $functionname($rawmods[$seq])) {
1139 if (!empty($info->icon)) {
1140 $mod[$seq]->icon = $info->icon;
1142 if (!empty($info->iconcomponent)) {
1143 $mod[$seq]->iconcomponent = $info->iconcomponent;
1145 if (!empty($info->name)) {
1146 $mod[$seq]->name = $info->name;
1148 if ($info instanceof cached_cm_info) {
1149 // When using cached_cm_info you can include three new fields
1150 // that aren't available for legacy code
1151 if (!empty($info->content)) {
1152 $mod[$seq]->content = $info->content;
1154 if (!empty($info->extraclasses)) {
1155 $mod[$seq]->extraclasses = $info->extraclasses;
1157 if (!empty($info->iconurl)) {
1158 $mod[$seq]->iconurl = $info->iconurl;
1160 if (!empty($info->onclick)) {
1161 $mod[$seq]->onclick = $info->onclick;
1163 if (!empty($info->customdata)) {
1164 $mod[$seq]->customdata = $info->customdata;
1167 // When using a stdclass, the (horrible) deprecated ->extra field
1168 // is available for BC
1169 if (!empty($info->extra)) {
1170 $mod[$seq]->extra = $info->extra;
1175 // When there is no modname_get_coursemodule_info function,
1176 // but showdescriptions is enabled, then we use the 'intro'
1177 // and 'introformat' fields in the module table
1178 if (!$hasfunction && $rawmods[$seq]->showdescription) {
1179 if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
1180 array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
1181 // Set content from intro and introformat. Filters are disabled
1182 // because we filter it with format_text at display time
1183 $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
1184 $modvalues, $rawmods[$seq]->id, false);
1186 // To save making another query just below, put name in here
1187 $mod[$seq]->name = $modvalues->name;
1190 if (!isset($mod[$seq]->name)) {
1191 $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
1194 // Minimise the database size by unsetting default options when they are
1195 // 'empty'. This list corresponds to code in the cm_info constructor.
1196 foreach (array('idnumber', 'groupmode', 'groupingid', 'groupmembersonly',
1197 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
1198 'icon', 'iconcomponent', 'customdata', 'showavailability', 'availablefrom',
1199 'availableuntil', 'conditionscompletion', 'conditionsgrade',
1200 'completionview', 'completionexpected', 'score', 'showdescription')
1202 if (property_exists($mod[$seq], $property) &&
1203 empty($mod[$seq]->{$property})) {
1204 unset($mod[$seq]->{$property});
1207 // Special case: this value is usually set to null, but may be 0
1208 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
1209 is_null($mod[$seq]->completiongradeitemnumber)) {
1210 unset($mod[$seq]->completiongradeitemnumber);
1220 * Returns the localised human-readable names of all used modules
1222 * @param bool $plural if true returns the plural forms of the names
1223 * @return array where key is the module name (component name without 'mod_') and
1224 * the value is the human-readable string. Array sorted alphabetically by value
1226 function get_module_types_names($plural = false) {
1227 static $modnames = null;
1229 if ($modnames === null) {
1230 $modnames = array(0 => array(), 1 => array());
1231 if ($allmods = $DB->get_records("modules")) {
1232 foreach ($allmods as $mod) {
1233 if (file_exists("$CFG->dirroot/mod/$mod->name/lib.php") && $mod->visible) {
1234 $modnames[0][$mod->name] = get_string("modulename", "$mod->name");
1235 $modnames[1][$mod->name] = get_string("modulenameplural", "$mod->name");
1238 collatorlib::asort($modnames[0]);
1239 collatorlib::asort($modnames[1]);
1242 return $modnames[(int)$plural];
1246 * Set highlighted section. Only one section can be highlighted at the time.
1248 * @param int $courseid course id
1249 * @param int $marker highlight section with this number, 0 means remove higlightin
1252 function course_set_marker($courseid, $marker) {
1254 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
1258 * For a given course section, marks it visible or hidden,
1259 * and does the same for every activity in that section
1261 * @param int $courseid course id
1262 * @param int $sectionnumber The section number to adjust
1263 * @param int $visibility The new visibility
1264 * @return array A list of resources which were hidden in the section
1266 function set_section_visible($courseid, $sectionnumber, $visibility) {
1269 $resourcestotoggle = array();
1270 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
1271 $DB->set_field("course_sections", "visible", "$visibility", array("id"=>$section->id));
1272 if (!empty($section->sequence)) {
1273 $modules = explode(",", $section->sequence);
1274 foreach ($modules as $moduleid) {
1275 if ($cm = $DB->get_record('course_modules', array('id' => $moduleid), 'visible, visibleold')) {
1277 // As we unhide the section, we use the previously saved visibility stored in visibleold.
1278 set_coursemodule_visible($moduleid, $cm->visibleold);
1280 // We hide the section, so we hide the module but we store the original state in visibleold.
1281 set_coursemodule_visible($moduleid, 0);
1282 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id' => $moduleid));
1287 rebuild_course_cache($courseid, true);
1289 // Determine which modules are visible for AJAX update
1290 if (!empty($modules)) {
1291 list($insql, $params) = $DB->get_in_or_equal($modules);
1292 $select = 'id ' . $insql . ' AND visible = ?';
1293 array_push($params, $visibility);
1295 $select .= ' AND visibleold = 1';
1297 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
1300 return $resourcestotoggle;
1304 * Obtains shared data that is used in print_section when displaying a
1305 * course-module entry.
1307 * Calls format_text or format_string as appropriate, and obtains the correct icon.
1309 * This data is also used in other areas of the code.
1310 * @param cm_info $cm Course-module data (must come from get_fast_modinfo)
1311 * @param object $course Moodle course object
1312 * @return array An array with the following values in this order:
1313 * $content (optional extra content for after link),
1314 * $instancename (text of link)
1316 function get_print_section_cm_text(cm_info $cm, $course) {
1319 // Get content from modinfo if specified. Content displays either
1320 // in addition to the standard link (below), or replaces it if
1321 // the link is turned off by setting ->url to null.
1322 if (($content = $cm->get_content()) !== '') {
1323 // Improve filter performance by preloading filter setttings for all
1324 // activities on the course (this does nothing if called multiple
1326 filter_preload_activities($cm->get_modinfo());
1328 // Get module context
1329 $modulecontext = context_module::instance($cm->id);
1330 $labelformatoptions = new stdClass();
1331 $labelformatoptions->noclean = true;
1332 $labelformatoptions->overflowdiv = true;
1333 $labelformatoptions->context = $modulecontext;
1334 $content = format_text($content, FORMAT_HTML, $labelformatoptions);
1339 // Get course context
1340 $coursecontext = context_course::instance($course->id);
1341 $stringoptions = new stdClass;
1342 $stringoptions->context = $coursecontext;
1343 $instancename = format_string($cm->name, true, $stringoptions);
1344 return array($content, $instancename);
1348 * Prints a section full of activity modules
1350 * @param stdClass $course The course
1351 * @param stdClass|section_info $section The section object containing properties id and section
1352 * @param array $mods (argument not used)
1353 * @param array $modnamesused (argument not used)
1354 * @param bool $absolute All links are absolute
1355 * @param string $width Width of the container
1356 * @param bool $hidecompletion Hide completion status
1357 * @param int $sectionreturn The section to return to
1360 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%", $hidecompletion=false, $sectionreturn=null) {
1361 global $CFG, $USER, $DB, $PAGE, $OUTPUT;
1363 static $initialised;
1365 static $groupbuttons;
1366 static $groupbuttonslink;
1369 static $strmovehere;
1370 static $strmovefull;
1371 static $strunreadpostsone;
1373 if (!isset($initialised)) {
1374 $groupbuttons = ($course->groupmode or (!$course->groupmodeforce));
1375 $groupbuttonslink = (!$course->groupmodeforce);
1376 $isediting = $PAGE->user_is_editing();
1377 $ismoving = $isediting && ismoving($course->id);
1379 $strmovehere = get_string("movehere");
1380 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1382 $initialised = true;
1385 $modinfo = get_fast_modinfo($course);
1386 $completioninfo = new completion_info($course);
1388 //Accessibility: replace table with list <ul>, but don't output empty list.
1389 if (!empty($modinfo->sections[$section->section])) {
1391 // Fix bug #5027, don't want style=\"width:$width\".
1392 echo "<ul class=\"section img-text\">\n";
1394 foreach ($modinfo->sections[$section->section] as $modnumber) {
1395 $mod = $modinfo->cms[$modnumber];
1397 if ($ismoving and $mod->id == $USER->activitycopy) {
1398 // do not display moving mod
1402 // We can continue (because it will not be displayed at all)
1404 // 1) The activity is not visible to users
1406 // 2a) The 'showavailability' option is not set (if that is set,
1407 // we need to display the activity so we can show
1408 // availability info)
1410 // 2b) The 'availableinfo' is empty, i.e. the activity was
1411 // hidden in a way that leaves no info, such as using the
1413 if (!$mod->uservisible &&
1414 (empty($mod->showavailability) ||
1415 empty($mod->availableinfo))) {
1416 // visibility shortcut
1420 // In some cases the activity is visible to user, but it is
1421 // dimmed. This is done if viewhiddenactivities is true and if:
1422 // 1. the activity is not visible, or
1423 // 2. the activity has dates set which do not include current, or
1424 // 3. the activity has any other conditions set (regardless of whether
1425 // current user meets them)
1426 $modcontext = context_module::instance($mod->id);
1427 $canviewhidden = has_capability('moodle/course:viewhiddenactivities', $modcontext);
1428 $accessiblebutdim = false;
1429 if ($canviewhidden) {
1430 $accessiblebutdim = !$mod->visible;
1431 if (!empty($CFG->enableavailability)) {
1432 $accessiblebutdim = $accessiblebutdim ||
1433 $mod->availablefrom > time() ||
1434 ($mod->availableuntil && $mod->availableuntil < time()) ||
1435 count($mod->conditionsgrade) > 0 ||
1436 count($mod->conditionscompletion) > 0;
1440 $liclasses = array();
1441 $liclasses[] = 'activity';
1442 $liclasses[] = $mod->modname;
1443 $liclasses[] = 'modtype_'.$mod->modname;
1444 $extraclasses = $mod->get_extra_classes();
1445 if ($extraclasses) {
1446 $liclasses = array_merge($liclasses, explode(' ', $extraclasses));
1448 echo html_writer::start_tag('li', array('class'=>join(' ', $liclasses), 'id'=>'module-'.$modnumber));
1450 echo '<a title="'.$strmovefull.'"'.
1451 ' href="'.$CFG->wwwroot.'/course/mod.php?moveto='.$mod->id.'&sesskey='.sesskey().'">'.
1452 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1453 ' alt="'.$strmovehere.'" /></a><br />
1457 $classes = array('mod-indent');
1458 if (!empty($mod->indent)) {
1459 $classes[] = 'mod-indent-'.$mod->indent;
1460 if ($mod->indent > 15) {
1461 $classes[] = 'mod-indent-huge';
1464 echo html_writer::start_tag('div', array('class'=>join(' ', $classes)));
1466 // Get data about this course-module
1467 list($content, $instancename) =
1468 get_print_section_cm_text($modinfo->cms[$modnumber], $course);
1470 //Accessibility: for files get description via icon, this is very ugly hack!
1472 $altname = $mod->modfullname;
1473 // Avoid unnecessary duplication: if e.g. a forum name already
1474 // includes the word forum (or Forum, etc) then it is unhelpful
1475 // to include that in the accessible description that is added.
1476 if (false !== strpos(textlib::strtolower($instancename),
1477 textlib::strtolower($altname))) {
1480 // File type after name, for alphabetic lists (screen reader).
1482 $altname = get_accesshide(' '.$altname);
1485 // We may be displaying this just in order to show information
1486 // about visibility, without the actual link
1488 if ($mod->uservisible) {
1489 // Nope - in this case the link is fully working for user
1492 if ($accessiblebutdim) {
1493 $linkclasses .= ' dimmed conditionalhidden';
1494 $textclasses .= ' dimmed_text conditionalhidden';
1495 $accesstext = '<span class="accesshide">'.
1496 get_string('hiddenfromstudents').': </span>';
1501 $linkcss = 'class="activityinstance ' . trim($linkclasses) . '" ';
1503 $linkcss = 'class="activityinstance"';
1506 $textcss = 'class="' . trim($textclasses) . '" ';
1511 // Get on-click attribute value if specified
1512 $onclick = $mod->get_on_click();
1514 $onclick = ' onclick="' . $onclick . '"';
1517 if ($url = $mod->get_url()) {
1518 // Display link itself
1519 echo '<a ' . $linkcss . $mod->extra . $onclick .
1520 ' href="' . $url . '"><img src="' . $mod->get_icon_url() .
1521 '" class="iconlarge activityicon" alt="' . $mod->modfullname . '" />' .
1522 $accesstext . '<span class="instancename">' .
1523 $instancename . $altname . '</span></a>';
1525 // If specified, display extra content after link
1527 $contentpart = '<div class="' . trim('contentafterlink' . $textclasses) .
1528 '">' . $content . '</div>';
1531 // No link, so display only content
1532 $contentpart = '<div ' . $textcss . $mod->extra . '>' .
1533 $accesstext . $content . '</div>';
1536 if (!empty($mod->groupingid) && has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
1537 $groupings = groups_get_all_groupings($course->id);
1538 echo " <span class=\"groupinglabel\">(".format_string($groupings[$mod->groupingid]->name).')</span>';
1541 $textclasses = $extraclasses;
1542 $textclasses .= ' dimmed_text';
1544 $textcss = 'class="' . trim($textclasses) . '" ';
1548 $accesstext = '<span class="accesshide">' .
1549 get_string('notavailableyet', 'condition') .
1552 if ($url = $mod->get_url()) {
1553 // Display greyed-out text of link
1554 echo '<div ' . $textcss . $mod->extra .
1555 ' >' . '<img src="' . $mod->get_icon_url() .
1556 '" class="activityicon" alt="" /> <span>'. $instancename . $altname .
1559 // Do not display content after link when it is greyed out like this.
1561 // No link, so display only content (also greyed)
1562 $contentpart = '<div ' . $textcss . $mod->extra . '>' .
1563 $accesstext . $content . '</div>';
1567 // Module can put text after the link (e.g. forum unread)
1568 echo $mod->get_after_link();
1570 // If there is content but NO link (eg label), then display the
1571 // content here (BEFORE any icons). In this case cons must be
1572 // displayed after the content so that it makes more sense visually
1573 // and for accessibility reasons, e.g. if you have a one-line label
1574 // it should work similarly (at least in terms of ordering) to an
1581 if ($groupbuttons and plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
1582 if (! $mod->groupmodelink = $groupbuttonslink) {
1583 $mod->groupmode = $course->groupmode;
1587 $mod->groupmode = false;
1589 echo make_editing_buttons($mod, $absolute, true, $mod->indent, $sectionreturn);
1590 echo $mod->get_after_edit_icons();
1594 $completion = $hidecompletion
1595 ? COMPLETION_TRACKING_NONE
1596 : $completioninfo->is_enabled($mod);
1597 if ($completion!=COMPLETION_TRACKING_NONE && isloggedin() &&
1598 !isguestuser() && $mod->uservisible) {
1599 $completiondata = $completioninfo->get_data($mod,true);
1600 $completionicon = '';
1602 switch ($completion) {
1603 case COMPLETION_TRACKING_MANUAL :
1604 $completionicon = 'manual-enabled'; break;
1605 case COMPLETION_TRACKING_AUTOMATIC :
1606 $completionicon = 'auto-enabled'; break;
1609 } else if ($completion==COMPLETION_TRACKING_MANUAL) {
1610 switch($completiondata->completionstate) {
1611 case COMPLETION_INCOMPLETE:
1612 $completionicon = 'manual-n'; break;
1613 case COMPLETION_COMPLETE:
1614 $completionicon = 'manual-y'; break;
1616 } else { // Automatic
1617 switch($completiondata->completionstate) {
1618 case COMPLETION_INCOMPLETE:
1619 $completionicon = 'auto-n'; break;
1620 case COMPLETION_COMPLETE:
1621 $completionicon = 'auto-y'; break;
1622 case COMPLETION_COMPLETE_PASS:
1623 $completionicon = 'auto-pass'; break;
1624 case COMPLETION_COMPLETE_FAIL:
1625 $completionicon = 'auto-fail'; break;
1628 if ($completionicon) {
1629 $imgsrc = $OUTPUT->pix_url('i/completion-'.$completionicon);
1630 $formattedname = format_string($mod->name, true, array('context' => $modcontext));
1631 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $formattedname);
1632 if ($completion == COMPLETION_TRACKING_MANUAL && !$isediting) {
1633 $imgtitle = get_string('completion-title-' . $completionicon, 'completion', $formattedname);
1635 $completiondata->completionstate==COMPLETION_COMPLETE
1636 ? COMPLETION_INCOMPLETE
1637 : COMPLETION_COMPLETE;
1638 // In manual mode the icon is a toggle form...
1640 // If this completion state is used by the
1641 // conditional activities system, we need to turn
1643 if (!empty($CFG->enableavailability) &&
1644 condition_info::completion_value_used_as_condition($course, $mod)) {
1645 $extraclass = ' preventjs';
1650 <form class='togglecompletion$extraclass' method='post' action='".$CFG->wwwroot."/course/togglecompletion.php'><div>
1651 <input type='hidden' name='id' value='{$mod->id}' />
1652 <input type='hidden' name='modulename' value='".s($mod->name)."' />
1653 <input type='hidden' name='sesskey' value='".sesskey()."' />
1654 <input type='hidden' name='completionstate' value='$newstate' />
1655 <input type='image' src='$imgsrc' alt='$imgalt' title='$imgtitle' />
1658 // In auto mode, or when editing, the icon is just an image
1659 echo "<span class='autocompletion'>";
1660 echo "<img src='$imgsrc' alt='$imgalt' title='$imgalt' /></span>";
1665 // If there is content AND a link, then display the content here
1666 // (AFTER any icons). Otherwise it was displayed before
1671 // Show availability information (for someone who isn't allowed to
1672 // see the activity itself, or for staff)
1673 if (!$mod->uservisible) {
1674 echo '<div class="availabilityinfo">'.$mod->availableinfo.'</div>';
1675 } else if ($canviewhidden && !empty($CFG->enableavailability)) {
1676 $visibilityclass = '';
1677 if (!$mod->visible) {
1678 $visibilityclass = 'accesshide';
1680 $ci = new condition_info($mod);
1681 $fullinfo = $ci->get_full_information();
1683 echo '<div class="availabilityinfo '.$visibilityclass.'">'.get_string($mod->showavailability
1684 ? 'userrestriction_visible'
1685 : 'userrestriction_hidden','condition',
1686 $fullinfo).'</div>';
1690 echo html_writer::end_tag('div');
1691 echo html_writer::end_tag('li')."\n";
1694 } elseif ($ismoving) {
1695 echo "<ul class=\"section\">\n";
1699 echo '<li><a title="'.$strmovefull.'"'.
1700 ' href="'.$CFG->wwwroot.'/course/mod.php?movetosection='.$section->id.'&sesskey='.sesskey().'">'.
1701 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1702 ' alt="'.$strmovehere.'" /></a></li>
1705 if (!empty($modinfo->sections[$section->section]) || $ismoving) {
1706 echo "</ul><!--class='section'-->\n\n";
1711 * Prints the menus to add activities and resources.
1713 * @param stdClass $course The course
1714 * @param int $section relative section number (field course_sections.section)
1715 * @param null|array $modnames An array containing the list of modules and their names
1716 * if omitted will be taken from get_module_types_names()
1717 * @param bool $vertical Vertical orientation
1718 * @param bool $return Return the menus or send them to output
1719 * @param int $sectionreturn The section to link back to
1720 * @return void|string depending on $return
1722 function print_section_add_menus($course, $section, $modnames = null, $vertical=false, $return=false, $sectionreturn=null) {
1723 global $CFG, $OUTPUT;
1725 if ($modnames === null) {
1726 $modnames = get_module_types_names();
1729 // check to see if user can add menus and there are modules to add
1730 if (!has_capability('moodle/course:manageactivities', context_course::instance($course->id))
1731 || empty($modnames)) {
1739 // Retrieve all modules with associated metadata
1740 $modules = get_module_metadata($course, $modnames, $sectionreturn);
1742 // We'll sort resources and activities into two lists
1743 $resources = array();
1744 $activities = array();
1746 // We need to add the section section to the link for each module
1747 $sectionlink = '§ion=' . $section . '&sr=' . $sectionreturn;
1749 foreach ($modules as $module) {
1750 if (isset($module->types)) {
1751 // This module has a subtype
1752 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1753 $subtypes = array();
1754 foreach ($module->types as $subtype) {
1755 $subtypes[$subtype->link . $sectionlink] = $subtype->title;
1758 // Sort module subtypes into the list
1759 if (!empty($module->title)) {
1760 // This grouping has a name
1761 if ($module->archetype == MOD_CLASS_RESOURCE) {
1762 $resources[] = array($module->title=>$subtypes);
1764 $activities[] = array($module->title=>$subtypes);
1767 // This grouping does not have a name
1768 if ($module->archetype == MOD_CLASS_RESOURCE) {
1769 $resources = array_merge($resources, $subtypes);
1771 $activities = array_merge($activities, $subtypes);
1775 // This module has no subtypes
1776 if ($module->archetype == MOD_ARCHETYPE_RESOURCE) {
1777 $resources[$module->link . $sectionlink] = $module->title;
1778 } else if ($module->archetype === MOD_ARCHETYPE_SYSTEM) {
1779 // System modules cannot be added by user, do not add to dropdown
1781 $activities[$module->link . $sectionlink] = $module->title;
1786 $straddactivity = get_string('addactivity');
1787 $straddresource = get_string('addresource');
1788 $sectionname = get_section_name($course, $section);
1789 $strresourcelabel = get_string('addresourcetosection', null, $sectionname);
1790 $stractivitylabel = get_string('addactivitytosection', null, $sectionname);
1792 $output = html_writer::start_tag('div', array('class' => 'section_add_menus', 'id' => 'add_menus-section-' . $section));
1795 $output .= html_writer::start_tag('div', array('class' => 'horizontal'));
1798 if (!empty($resources)) {
1799 $select = new url_select($resources, '', array(''=>$straddresource), "ressection$section");
1800 $select->set_help_icon('resources');
1801 $select->set_label($strresourcelabel, array('class' => 'accesshide'));
1802 $output .= $OUTPUT->render($select);
1805 if (!empty($activities)) {
1806 $select = new url_select($activities, '', array(''=>$straddactivity), "section$section");
1807 $select->set_help_icon('activities');
1808 $select->set_label($stractivitylabel, array('class' => 'accesshide'));
1809 $output .= $OUTPUT->render($select);
1813 $output .= html_writer::end_tag('div');
1816 $output .= html_writer::end_tag('div');
1818 if (course_ajax_enabled($course)) {
1819 $straddeither = get_string('addresourceoractivity');
1820 // The module chooser link
1821 $modchooser = html_writer::start_tag('div', array('class' => 'mdl-right'));
1822 $modchooser.= html_writer::start_tag('div', array('class' => 'section-modchooser'));
1823 $icon = $OUTPUT->pix_icon('t/add', $straddeither);
1824 $span = html_writer::tag('span', $straddeither, array('class' => 'section-modchooser-text'));
1825 $modchooser .= html_writer::tag('span', $icon . $span, array('class' => 'section-modchooser-link'));
1826 $modchooser.= html_writer::end_tag('div');
1827 $modchooser.= html_writer::end_tag('div');
1829 // Wrap the normal output in a noscript div
1830 $usemodchooser = get_user_preferences('usemodchooser', $CFG->modchooserdefault);
1831 if ($usemodchooser) {
1832 $output = html_writer::tag('div', $output, array('class' => 'hiddenifjs addresourcedropdown'));
1833 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'visibleifjs addresourcemodchooser'));
1835 // If the module chooser is disabled, we need to ensure that the dropdowns are shown even if javascript is disabled
1836 $output = html_writer::tag('div', $output, array('class' => 'show addresourcedropdown'));
1837 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'hide addresourcemodchooser'));
1839 $output = $modchooser . $output;
1850 * Retrieve all metadata for the requested modules
1852 * @param object $course The Course
1853 * @param array $modnames An array containing the list of modules and their
1855 * @param int $sectionreturn The section to return to
1856 * @return array A list of stdClass objects containing metadata about each
1859 function get_module_metadata($course, $modnames, $sectionreturn = null) {
1860 global $CFG, $OUTPUT;
1862 // get_module_metadata will be called once per section on the page and courses may show
1863 // different modules to one another
1864 static $modlist = array();
1865 if (!isset($modlist[$course->id])) {
1866 $modlist[$course->id] = array();
1870 $urlbase = "/course/mod.php?id=$course->id&sesskey=".sesskey().'&sr='.$sectionreturn.'&add=';
1871 foreach($modnames as $modname => $modnamestr) {
1872 if (!course_allowed_module($course, $modname)) {
1875 if (isset($modlist[$modname])) {
1876 // This module is already cached
1877 $return[$modname] = $modlist[$course->id][$modname];
1881 // Include the module lib
1882 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1883 if (!file_exists($libfile)) {
1886 include_once($libfile);
1888 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1889 $gettypesfunc = $modname.'_get_types';
1890 if (function_exists($gettypesfunc)) {
1891 if ($types = $gettypesfunc()) {
1892 $group = new stdClass();
1893 $group->name = $modname;
1894 $group->icon = $OUTPUT->pix_icon('icon', '', $modname, array('class' => 'icon'));
1895 foreach($types as $type) {
1896 if ($type->typestr === '--') {
1899 if (strpos($type->typestr, '--') === 0) {
1900 $group->title = str_replace('--', '', $type->typestr);
1903 // Set the Sub Type metadata
1904 $subtype = new stdClass();
1905 $subtype->title = $type->typestr;
1906 $subtype->type = str_replace('&', '&', $type->type);
1907 $subtype->name = preg_replace('/.*type=/', '', $subtype->type);
1908 $subtype->archetype = $type->modclass;
1910 // The group archetype should match the subtype archetypes and all subtypes
1911 // should have the same archetype
1912 $group->archetype = $subtype->archetype;
1914 if (get_string_manager()->string_exists('help' . $subtype->name, $modname)) {
1915 $subtype->help = get_string('help' . $subtype->name, $modname);
1917 $subtype->link = $urlbase . $subtype->type;
1918 $group->types[] = $subtype;
1920 $modlist[$course->id][$modname] = $group;
1923 $module = new stdClass();
1924 $module->title = get_string('modulename', $modname);
1925 $module->name = $modname;
1926 $module->link = $urlbase . $modname;
1927 $module->icon = $OUTPUT->pix_icon('icon', '', $module->name, array('class' => 'icon'));
1928 $sm = get_string_manager();
1929 if ($sm->string_exists('modulename_help', $modname)) {
1930 $module->help = get_string('modulename_help', $modname);
1931 if ($sm->string_exists('modulename_link', $modname)) { // Link to further info in Moodle docs
1932 $link = get_string('modulename_link', $modname);
1933 $linktext = get_string('morehelp');
1934 $module->help .= html_writer::tag('div', $OUTPUT->doc_link($link, $linktext, true), array('class' => 'helpdoclink'));
1937 $module->archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1938 $modlist[$course->id][$modname] = $module;
1940 $return[$modname] = $modlist[$course->id][$modname];
1947 * Return the course category context for the category with id $categoryid, except
1948 * that if $categoryid is 0, return the system context.
1950 * @param integer $categoryid a category id or 0.
1951 * @return object the corresponding context
1953 function get_category_or_system_context($categoryid) {
1955 return context_coursecat::instance($categoryid, IGNORE_MISSING);
1957 return context_system::instance();
1962 * Gets the child categories of a given courses category. Uses a static cache
1963 * to make repeat calls efficient.
1965 * @param int $parentid the id of a course category.
1966 * @return array all the child course categories.
1968 function get_child_categories($parentid) {
1969 static $allcategories = null;
1971 // only fill in this variable the first time
1972 if (null == $allcategories) {
1973 $allcategories = array();
1975 $categories = get_categories();
1976 foreach ($categories as $category) {
1977 if (empty($allcategories[$category->parent])) {
1978 $allcategories[$category->parent] = array();
1980 $allcategories[$category->parent][] = $category;
1984 if (empty($allcategories[$parentid])) {
1987 return $allcategories[$parentid];
1992 * This function recursively travels the categories, building up a nice list
1993 * for display. It also makes an array that list all the parents for each
1996 * For example, if you have a tree of categories like:
1997 * Miscellaneous (id = 1)
1998 * Subcategory (id = 2)
1999 * Sub-subcategory (id = 4)
2000 * Other category (id = 3)
2001 * Then after calling this function you will have
2002 * $list = array(1 => 'Miscellaneous', 2 => 'Miscellaneous / Subcategory',
2003 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
2004 * 3 => 'Other category');
2005 * $parents = array(2 => array(1), 4 => array(1, 2));
2007 * If you specify $requiredcapability, then only categories where the current
2008 * user has that capability will be added to $list, although all categories
2009 * will still be added to $parents, and if you only have $requiredcapability
2010 * in a child category, not the parent, then the child catgegory will still be
2013 * If you specify the option $excluded, then that category, and all its children,
2014 * are omitted from the tree. This is useful when you are doing something like
2015 * moving categories, where you do not want to allow people to move a category
2016 * to be the child of itself.
2018 * @param array $list For output, accumulates an array categoryid => full category path name
2019 * @param array $parents For output, accumulates an array categoryid => list of parent category ids.
2020 * @param string/array $requiredcapability if given, only categories where the current
2021 * user has this capability will be added to $list. Can also be an array of capabilities,
2022 * in which case they are all required.
2023 * @param integer $excludeid Omit this category and its children from the lists built.
2024 * @param object $category Build the tree starting at this category - otherwise starts at the top level.
2025 * @param string $path For internal use, as part of recursive calls.
2027 function make_categories_list(&$list, &$parents, $requiredcapability = '',
2028 $excludeid = 0, $category = NULL, $path = "") {
2030 // initialize the arrays if needed
2031 if (!is_array($list)) {
2034 if (!is_array($parents)) {
2038 if (empty($category)) {
2039 // Start at the top level.
2040 $category = new stdClass;
2043 // This is the excluded category, don't include it.
2044 if ($excludeid > 0 && $excludeid == $category->id) {
2048 $context = context_coursecat::instance($category->id);
2049 $categoryname = format_string($category->name, true, array('context' => $context));
2053 $path = $path.' / '.$categoryname;
2055 $path = $categoryname;
2058 // Add this category to $list, if the permissions check out.
2059 if (empty($requiredcapability)) {
2060 $list[$category->id] = $path;
2063 $requiredcapability = (array)$requiredcapability;
2064 if (has_all_capabilities($requiredcapability, $context)) {
2065 $list[$category->id] = $path;
2070 // Add all the children recursively, while updating the parents array.
2071 if ($categories = get_child_categories($category->id)) {
2072 foreach ($categories as $cat) {
2073 if (!empty($category->id)) {
2074 if (isset($parents[$category->id])) {
2075 $parents[$cat->id] = $parents[$category->id];
2077 $parents[$cat->id][] = $category->id;
2079 make_categories_list($list, $parents, $requiredcapability, $excludeid, $cat, $path);
2085 * This function generates a structured array of courses and categories.
2087 * The depth of categories is limited by $CFG->maxcategorydepth however there
2088 * is no limit on the number of courses!
2090 * Suitable for use with the course renderers course_category_tree method:
2091 * $renderer = $PAGE->get_renderer('core','course');
2092 * echo $renderer->course_category_tree(get_course_category_tree());
2094 * @global moodle_database $DB
2098 function get_course_category_tree($id = 0, $depth = 0) {
2100 $viewhiddencats = has_capability('moodle/category:viewhiddencategories', context_system::instance());
2101 $categories = get_child_categories($id);
2102 $categoryids = array();
2103 foreach ($categories as $key => &$category) {
2104 if (!$category->visible && !$viewhiddencats) {
2105 unset($categories[$key]);
2108 $categoryids[$category->id] = $category;
2109 if (empty($CFG->maxcategorydepth) || $depth <= $CFG->maxcategorydepth) {
2110 list($category->categories, $subcategories) = get_course_category_tree($category->id, $depth+1);
2111 foreach ($subcategories as $subid=>$subcat) {
2112 $categoryids[$subid] = $subcat;
2114 $category->courses = array();
2119 // This is a recursive call so return the required array
2120 return array($categories, $categoryids);
2123 if (empty($categoryids)) {
2124 // No categories available (probably all hidden).
2128 // The depth is 0 this function has just been called so we can finish it off
2130 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
2131 list($catsql, $catparams) = $DB->get_in_or_equal(array_keys($categoryids));
2133 c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary,c.category
2137 WHERE c.category $catsql ORDER BY c.sortorder ASC";
2138 if ($courses = $DB->get_records_sql($sql, $catparams)) {
2139 // loop throught them
2140 foreach ($courses as $course) {
2141 if ($course->id == SITEID) {
2144 context_instance_preload($course);
2145 if (!empty($course->visible) || has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
2146 $categoryids[$course->category]->courses[$course->id] = $course;
2154 * Recursive function to print out all the categories in a nice format
2155 * with or without courses included
2157 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true) {
2160 // maxcategorydepth == 0 meant no limit
2161 if (!empty($CFG->maxcategorydepth) && $depth >= $CFG->maxcategorydepth) {
2165 if (!$displaylist) {
2166 make_categories_list($displaylist, $parentslist);
2170 if ($category->visible or has_capability('moodle/category:viewhiddencategories', context_system::instance())) {
2171 print_category_info($category, $depth, $showcourses);
2173 return; // Don't bother printing children of invisible categories
2177 $category = new stdClass();
2178 $category->id = "0";
2181 if ($categories = get_child_categories($category->id)) { // Print all the children recursively
2182 $countcats = count($categories);
2186 foreach ($categories as $cat) {
2188 if ($count == $countcats) {
2191 $up = $first ? false : true;
2192 $down = $last ? false : true;
2195 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1, $showcourses);
2201 * This function will return $options array for html_writer::select(), with whitespace to denote nesting.
2203 function make_categories_options() {
2204 make_categories_list($cats,$parents);
2205 foreach ($cats as $key => $value) {
2206 if (array_key_exists($key,$parents)) {
2207 if ($indent = count($parents[$key])) {
2208 for ($i = 0; $i < $indent; $i++) {
2209 $cats[$key] = ' '.$cats[$key];
2218 * Prints the category info in indented fashion
2219 * This function is only used by print_whole_category_list() above
2221 function print_category_info($category, $depth=0, $showcourses = false) {
2222 global $CFG, $DB, $OUTPUT;
2224 $strsummary = get_string('summary');
2227 if (!$category->visible) {
2228 $catlinkcss = array('class'=>'dimmed');
2230 static $coursecount = null;
2231 if (null === $coursecount) {
2232 // only need to check this once
2233 $coursecount = $DB->count_records('course') <= FRONTPAGECOURSELIMIT;
2236 if ($showcourses and $coursecount) {
2237 $catimage = '<img src="'.$OUTPUT->pix_url('i/course') . '" alt="" />';
2239 $catimage = " ";
2242 $courses = get_courses($category->id, 'c.sortorder ASC', 'c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary');
2243 $context = context_coursecat::instance($category->id);
2244 $fullname = format_string($category->name, true, array('context' => $context));
2246 if ($showcourses and $coursecount) {
2247 echo '<div class="categorylist clearfix">';
2249 $cat .= html_writer::tag('div', $catimage, array('class'=>'image'));
2250 $catlink = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
2251 $cat .= html_writer::tag('div', $catlink, array('class'=>'name'));
2255 for ($i=0; $i< $depth; $i++) {
2256 $html = html_writer::tag('div', $html . $cat, array('class'=>'indentation'));
2262 echo html_writer::tag('div', $html, array('class'=>'category'));
2263 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
2265 // does the depth exceed maxcategorydepth
2266 // maxcategorydepth == 0 or unset meant no limit
2267 $limit = !(isset($CFG->maxcategorydepth) && ($depth >= $CFG->maxcategorydepth-1));
2268 if ($courses && ($limit || $CFG->maxcategorydepth == 0)) {
2269 foreach ($courses as $course) {
2271 if (!$course->visible) {
2272 $linkcss = array('class'=>'dimmed');
2275 $coursename = get_course_display_name_for_list($course);
2276 $courselink = html_writer::link(new moodle_url('/course/view.php', array('id'=>$course->id)), format_string($coursename), $linkcss);
2280 if ($icons = enrol_get_course_info_icons($course)) {
2281 foreach ($icons as $pix_icon) {
2282 $courseicon = $OUTPUT->render($pix_icon).' ';
2286 $coursecontent = html_writer::tag('div', $courseicon.$courselink, array('class'=>'name'));
2288 if ($course->summary) {
2289 $link = new moodle_url('/course/info.php?id='.$course->id);
2290 $actionlink = $OUTPUT->action_link($link, '<img alt="'.$strsummary.'" src="'.$OUTPUT->pix_url('i/info') . '" />',
2291 new popup_action('click', $link, 'courseinfo', array('height' => 400, 'width' => 500)),
2292 array('title'=>$strsummary));
2294 $coursecontent .= html_writer::tag('div', $actionlink, array('class'=>'info'));
2298 for ($i=0; $i <= $depth; $i++) {
2299 $html = html_writer::tag('div', $html . $coursecontent , array('class'=>'indentation'));
2300 $coursecontent = '';
2302 echo html_writer::tag('div', $html, array('class'=>'course clearfloat'));
2307 echo '<div class="categorylist">';
2309 $cat = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
2310 if (count($courses) > 0) {
2311 $cat .= html_writer::tag('span', ' ('.count($courses).')', array('title'=>get_string('numberofcourses'), 'class'=>'numberofcourse'));
2315 for ($i=0; $i< $depth; $i++) {
2316 $html = html_writer::tag('div', $html .$cat, array('class'=>'indentation'));
2323 echo html_writer::tag('div', $html, array('class'=>'category'));
2324 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
2330 * Print the buttons relating to course requests.
2332 * @param object $systemcontext the system context.
2334 function print_course_request_buttons($systemcontext) {
2335 global $CFG, $DB, $OUTPUT;
2336 if (empty($CFG->enablecourserequests)) {
2339 if (!has_capability('moodle/course:create', $systemcontext) && has_capability('moodle/course:request', $systemcontext)) {
2340 /// Print a button to request a new course
2341 echo $OUTPUT->single_button('request.php', get_string('requestcourse'), 'get');
2343 /// Print a button to manage pending requests
2344 if (has_capability('moodle/site:approvecourse', $systemcontext)) {
2345 $disabled = !$DB->record_exists('course_request', array());
2346 echo $OUTPUT->single_button('pending.php', get_string('coursespending'), 'get', array('disabled'=>$disabled));
2351 * Does the user have permission to edit things in this category?
2353 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2354 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
2356 function can_edit_in_category($categoryid = 0) {
2357 $context = get_category_or_system_context($categoryid);
2358 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
2362 * Prints the turn editing on/off button on course/index.php or course/category.php.
2364 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2365 * @return string HTML of the editing button, or empty string, if this user is not allowed
2368 function update_category_button($categoryid = 0) {
2369 global $CFG, $PAGE, $OUTPUT;
2371 // Check permissions.
2372 if (!can_edit_in_category($categoryid)) {
2376 // Work out the appropriate action.
2377 if ($PAGE->user_is_editing()) {
2378 $label = get_string('turneditingoff');
2381 $label = get_string('turneditingon');
2385 // Generate the button HTML.
2386 $options = array('categoryedit' => $edit, 'sesskey' => sesskey());
2388 $options['id'] = $categoryid;
2389 $page = 'category.php';
2391 $page = 'index.php';
2393 return $OUTPUT->single_button(new moodle_url('/course/' . $page, $options), $label, 'get');
2397 * Category is 0 (for all courses) or an object
2399 function print_courses($category) {
2400 global $CFG, $OUTPUT;
2402 if (!is_object($category) && $category==0) {
2403 $categories = get_child_categories(0); // Parent = 0 ie top-level categories only
2404 if (is_array($categories) && count($categories) == 1) {
2405 $category = array_shift($categories);
2406 $courses = get_courses_wmanagers($category->id,
2408 array('summary','summaryformat'));
2410 $courses = get_courses_wmanagers('all',
2412 array('summary','summaryformat'));
2416 $courses = get_courses_wmanagers($category->id,
2418 array('summary','summaryformat'));
2422 echo html_writer::start_tag('ul', array('class'=>'unlist'));
2423 foreach ($courses as $course) {
2424 $coursecontext = context_course::instance($course->id);
2425 if ($course->visible == 1 || has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2426 echo html_writer::start_tag('li');
2427 print_course($course);
2428 echo html_writer::end_tag('li');
2431 echo html_writer::end_tag('ul');
2433 echo $OUTPUT->heading(get_string("nocoursesyet"));
2434 $context = context_system::instance();
2435 if (has_capability('moodle/course:create', $context)) {
2437 if (!empty($category->id)) {
2438 $options['category'] = $category->id;
2440 $options['category'] = $CFG->defaultrequestcategory;
2442 echo html_writer::start_tag('div', array('class'=>'addcoursebutton'));
2443 echo $OUTPUT->single_button(new moodle_url('/course/edit.php', $options), get_string("addnewcourse"));
2444 echo html_writer::end_tag('div');
2450 * Print a description of a course, suitable for browsing in a list.
2452 * @param object $course the course object.
2453 * @param string $highlightterms (optional) some search terms that should be highlighted in the display.
2455 function print_course($course, $highlightterms = '') {
2456 global $CFG, $USER, $DB, $OUTPUT;
2458 $context = context_course::instance($course->id);
2460 // Rewrite file URLs so that they are correct
2461 $course->summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', NULL);
2463 echo html_writer::start_tag('div', array('class'=>'coursebox clearfix'));
2464 echo html_writer::start_tag('div', array('class'=>'info'));
2465 echo html_writer::start_tag('h3', array('class'=>'name'));
2467 $linkhref = new moodle_url('/course/view.php', array('id'=>$course->id));
2469 $coursename = get_course_display_name_for_list($course);
2470 $linktext = highlight($highlightterms, format_string($coursename));
2471 $linkparams = array('title'=>get_string('entercourse'));
2472 if (empty($course->visible)) {
2473 $linkparams['class'] = 'dimmed';
2475 echo html_writer::link($linkhref, $linktext, $linkparams);
2476 echo html_writer::end_tag('h3');
2478 /// first find all roles that are supposed to be displayed
2479 if (!empty($CFG->coursecontact)) {
2480 $managerroles = explode(',', $CFG->coursecontact);
2483 if (!isset($course->managers)) {
2484 list($sort, $sortparams) = users_order_by_sql('u');
2485 $rusers = get_role_users($managerroles, $context, true,
2486 'ra.id AS raid, u.id, u.username, u.firstname, u.lastname, rn.name AS rolecoursealias,
2487 r.name AS rolename, r.sortorder, r.id AS roleid, r.shortname AS roleshortname',
2488 'r.sortorder ASC, ' . $sort, null, '', '', '', '', $sortparams);
2490 // use the managers array if we have it for perf reasosn
2491 // populate the datastructure like output of get_role_users();
2492 foreach ($course->managers as $manager) {
2493 $user = clone($manager->user);
2494 $user->roleid = $manager->roleid;
2495 $user->rolename = $manager->rolename;
2496 $user->roleshortname = $manager->roleshortname;
2497 $user->rolecoursealias = $manager->rolecoursealias;
2498 $rusers[$user->id] = $user;
2502 $namesarray = array();
2503 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2504 foreach ($rusers as $ra) {
2505 if (isset($namesarray[$ra->id])) {
2506 // only display a user once with the higest sortorder role
2510 $role = new stdClass();
2511 $role->id = $ra->roleid;
2512 $role->name = $ra->rolename;
2513 $role->shortname = $ra->roleshortname;
2514 $role->coursealias = $ra->rolecoursealias;
2515 $rolename = role_get_name($role, $context, ROLENAME_ALIAS);
2517 $fullname = fullname($ra, $canviewfullnames);
2518 $namesarray[$ra->id] = $rolename.': '.
2519 html_writer::link(new moodle_url('/user/view.php', array('id'=>$ra->id, 'course'=>SITEID)), $fullname);
2522 if (!empty($namesarray)) {
2523 echo html_writer::start_tag('ul', array('class'=>'teachers'));
2524 foreach ($namesarray as $name) {
2525 echo html_writer::tag('li', $name);
2527 echo html_writer::end_tag('ul');
2530 echo html_writer::end_tag('div'); // End of info div
2532 echo html_writer::start_tag('div', array('class'=>'summary'));
2533 $options = new stdClass();
2534 $options->noclean = true;
2535 $options->para = false;
2536 $options->overflowdiv = true;
2537 if (!isset($course->summaryformat)) {
2538 $course->summaryformat = FORMAT_MOODLE;
2540 echo highlight($highlightterms, format_text($course->summary, $course->summaryformat, $options, $course->id));
2541 if ($icons = enrol_get_course_info_icons($course)) {
2542 echo html_writer::start_tag('div', array('class'=>'enrolmenticons'));
2543 foreach ($icons as $icon) {
2544 echo $OUTPUT->render($icon);
2546 echo html_writer::end_tag('div'); // End of enrolmenticons div
2548 echo html_writer::end_tag('div'); // End of summary div
2549 echo html_writer::end_tag('div'); // End of coursebox div
2553 * Prints custom user information on the home page.
2554 * Over time this can include all sorts of information
2556 function print_my_moodle() {
2557 global $USER, $CFG, $DB, $OUTPUT;
2559 if (!isloggedin() or isguestuser()) {
2560 print_error('nopermissions', '', '', 'See My Moodle');
2563 $courses = enrol_get_my_courses('summary', 'visible DESC,sortorder ASC');
2565 $rcourses = array();
2566 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
2567 $rcourses = get_my_remotecourses($USER->id);
2568 $rhosts = get_my_remotehosts();
2571 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
2573 if (!empty($courses)) {
2574 echo '<ul class="unlist">';
2575 foreach ($courses as $course) {
2576 if ($course->id == SITEID) {
2580 print_course($course);
2587 if (!empty($rcourses)) {
2588 // at the IDP, we know of all the remote courses
2589 foreach ($rcourses as $course) {
2590 print_remote_course($course, "100%");
2592 } elseif (!empty($rhosts)) {
2593 // non-IDP, we know of all the remote servers, but not courses
2594 foreach ($rhosts as $host) {
2595 print_remote_host($host, "100%");
2601 if ($DB->count_records("course") > (count($courses) + 1) ) { // Some courses not being displayed
2602 echo "<table width=\"100%\"><tr><td align=\"center\">";
2603 print_course_search("", false, "short");
2604 echo "</td><td align=\"center\">";
2605 echo $OUTPUT->single_button("$CFG->wwwroot/course/index.php", get_string("fulllistofcourses"), "get");
2606 echo "</td></tr></table>\n";
2610 if ($DB->count_records("course_categories") > 1) {
2611 echo $OUTPUT->box_start("categorybox");
2612 print_whole_category_list();
2613 echo $OUTPUT->box_end();
2621 function print_course_search($value="", $return=false, $format="plain") {
2627 $id = 'coursesearch';
2633 $strsearchcourses= get_string("searchcourses");
2635 if ($format == 'plain') {
2636 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2637 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2638 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
2639 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" value="'.s($value).'" />';
2640 $output .= '<input type="submit" value="'.get_string('go').'" />';
2641 $output .= '</fieldset></form>';
2642 } else if ($format == 'short') {
2643 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2644 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2645 $output .= '<label for="shortsearchbox">'.$strsearchcourses.': </label>';
2646 $output .= '<input type="text" id="shortsearchbox" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2647 $output .= '<input type="submit" value="'.get_string('go').'" />';
2648 $output .= '</fieldset></form>';
2649 } else if ($format == 'navbar') {
2650 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2651 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2652 $output .= '<label for="navsearchbox">'.$strsearchcourses.': </label>';
2653 $output .= '<input type="text" id="navsearchbox" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2654 $output .= '<input type="submit" value="'.get_string('go').'" />';
2655 $output .= '</fieldset></form>';
2664 function print_remote_course($course, $width="100%") {
2669 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&wantsurl=/course/view.php?id={$course->remoteid}";
2671 echo '<div class="coursebox remotecoursebox clearfix">';
2672 echo '<div class="info">';
2673 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2674 $linkcss.' href="'.$url.'">'
2675 . format_string($course->fullname) .'</a><br />'
2676 . format_string($course->hostname) . ' : '
2677 . format_string($course->cat_name) . ' : '
2678 . format_string($course->shortname). '</div>';
2679 echo '</div><div class="summary">';
2680 $options = new stdClass();
2681 $options->noclean = true;
2682 $options->para = false;
2683 $options->overflowdiv = true;
2684 echo format_text($course->summary, $course->summaryformat, $options);
2689 function print_remote_host($host, $width="100%") {
2694 echo '<div class="coursebox clearfix">';
2695 echo '<div class="info">';
2696 echo '<div class="name">';
2697 echo '<img src="'.$OUTPUT->pix_url('i/mnethost') . '" class="icon" alt="'.get_string('course').'" />';
2698 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2699 . s($host['name']).'</a> - ';
2700 echo $host['count'] . ' ' . get_string('courses');
2707 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2709 function add_course_module($mod) {
2712 $mod->added = time();
2715 $cmid = $DB->insert_record("course_modules", $mod);
2716 rebuild_course_cache($mod->course, true);
2721 * Creates missing course section(s) and rebuilds course cache
2723 * @param int|stdClass $courseorid course id or course object
2724 * @param int|array $sections list of relative section numbers to create
2725 * @return bool if there were any sections created
2727 function course_create_sections_if_missing($courseorid, $sections) {
2729 if (!is_array($sections)) {
2730 $sections = array($sections);
2732 $existing = array_keys(get_fast_modinfo($courseorid)->get_section_info_all());
2733 if (is_object($courseorid)) {
2734 $courseorid = $courseorid->id;
2736 $coursechanged = false;
2737 foreach ($sections as $sectionnum) {
2738 if (!in_array($sectionnum, $existing)) {
2739 $cw = new stdClass();
2740 $cw->course = $courseorid;
2741 $cw->section = $sectionnum;
2743 $cw->summaryformat = FORMAT_HTML;
2745 $id = $DB->insert_record("course_sections", $cw);
2746 $coursechanged = true;
2749 if ($coursechanged) {
2750 rebuild_course_cache($courseorid, true);
2752 return $coursechanged;
2756 * Adds an existing module to the section
2758 * Updates both tables {course_sections} and {course_modules}
2760 * @param int|stdClass $courseorid course id or course object
2761 * @param int $modid id of the module already existing in course_modules table
2762 * @param int $sectionnum relative number of the section (field course_sections.section)
2763 * If section does not exist it will be created
2764 * @param int|stdClass $beforemod id or object with field id corresponding to the module
2765 * before which the module needs to be included. Null for inserting in the
2766 * end of the section
2767 * @return int The course_sections ID where the module is inserted
2769 function course_add_cm_to_section($courseorid, $modid, $sectionnum, $beforemod = null) {
2770 global $DB, $COURSE;
2771 if (is_object($beforemod)) {
2772 $beforemod = $beforemod->id;
2774 course_create_sections_if_missing($courseorid, $sectionnum);
2775 $section = get_fast_modinfo($courseorid)->get_section_info($sectionnum);
2776 $modarray = explode(",", trim($section->sequence));
2777 if (empty($section->sequence)) {
2778 $newsequence = "$modid";
2779 } else if ($beforemod && ($key = array_keys($modarray, $beforemod))) {
2780 $insertarray = array($modid, $beforemod);
2781 array_splice($modarray, $key[0], 1, $insertarray);
2782 $newsequence = implode(",", $modarray);
2784 $newsequence = "$section->sequence,$modid";
2786 $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id));
2787 $DB->set_field('course_modules', 'section', $section->id, array('id' => $modid));
2788 if (is_object($courseorid)) {
2789 rebuild_course_cache($courseorid->id, true);
2791 rebuild_course_cache($courseorid, true);
2793 return $section->id; // Return course_sections ID that was used.
2796 function set_coursemodule_groupmode($id, $groupmode) {
2798 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST);
2799 if ($cm->groupmode != $groupmode) {
2800 $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id));
2801 rebuild_course_cache($cm->course, true);
2803 return ($cm->groupmode != $groupmode);
2806 function set_coursemodule_idnumber($id, $idnumber) {
2808 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST);
2809 if ($cm->idnumber != $idnumber) {
2810 $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id));
2811 rebuild_course_cache($cm->course, true);
2813 return ($cm->idnumber != $idnumber);
2817 * Set the visibility of a module and inherent properties.
2819 * From 2.4 the parameter $prevstateoverrides has been removed, the logic it triggered
2820 * has been moved to {@link set_section_visible()} which was the only place from which
2821 * the parameter was used.
2823 * @param int $id of the module
2824 * @param int $visible state of the module
2825 * @return bool false when the module was not found, true otherwise
2827 function set_coursemodule_visible($id, $visible) {
2829 require_once($CFG->libdir.'/gradelib.php');
2831 // Trigger developer's attention when using the previously removed argument.
2832 if (func_num_args() > 2) {
2833 debugging('Wrong number of arguments passed to set_coursemodule_visible(), $prevstateoverrides
2834 has been removed.', DEBUG_DEVELOPER);
2837 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2840 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
2843 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2844 foreach($events as $event) {
2853 // hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there
2854 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
2856 foreach ($grade_items as $grade_item) {
2857 $grade_item->set_hidden(!$visible);
2861 // Updating visible and visibleold to keep them in sync. Only changing a section visibility will
2862 // affect visibleold to allow for an original visibility restore. See set_section_visible().
2863 $cminfo = new stdClass();
2865 $cminfo->visible = $visible;
2866 $cminfo->visibleold = $visible;
2867 $DB->update_record('course_modules', $cminfo);
2869 rebuild_course_cache($cm->course, true);
2874 * Delete a course module and any associated data at the course level (events)
2875 * Until 1.5 this function simply marked a deleted flag ... now it
2876 * deletes it completely.
2879 function delete_course_module($id) {
2881 require_once($CFG->libdir.'/gradelib.php');
2882 require_once($CFG->dirroot.'/blog/lib.php');
2884 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2887 $modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module));
2888 //delete events from calendar
2889 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2890 foreach($events as $event) {
2891 delete_event($event->id);
2894 //delete grade items, outcome items and grades attached to modules
2895 if ($grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2896 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course))) {
2897 foreach ($grade_items as $grade_item) {
2898 $grade_item->delete('moddelete');
2901 // Delete completion and availability data; it is better to do this even if the
2902 // features are not turned on, in case they were turned on previously (these will be
2903 // very quick on an empty table)
2904 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
2905 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id));
2906 $DB->delete_records('course_modules_avail_fields', array('coursemoduleid' => $cm->id));
2907 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
2908 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
2910 delete_context(CONTEXT_MODULE, $cm->id);
2911 $DB->delete_records('course_modules', array('id'=>$cm->id));
2912 rebuild_course_cache($cm->course, true);
2916 function delete_mod_from_section($modid, $sectionid) {
2919 if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
2921 $modarray = explode(",", $section->sequence);
2923 if ($key = array_keys ($modarray, $modid)) {
2924 array_splice($modarray, $key[0], 1);
2925 $newsequence = implode(",", $modarray);
2926 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
2927 rebuild_course_cache($section->course, true);
2938 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
2940 * @param object $course course object
2941 * @param int $section Section number (not id!!!)
2942 * @param int $move (-1 or 1)
2943 * @return boolean true if section moved successfully
2944 * @todo MDL-33379 remove this function in 2.5
2946 function move_section($course, $section, $move) {
2947 debugging('This function will be removed before 2.5 is released please use move_section_to', DEBUG_DEVELOPER);
2949 /// Moves a whole course section up and down within the course
2956 $sectiondest = $section + $move;
2958 // compartibility with course formats using field 'numsections'
2959 $courseformatoptions = course_get_format($course)->get_format_options();
2960 if (array_key_exists('numsections', $courseformatoptions) &&
2961 $sectiondest > $courseformatoptions['numsections'] or $sectiondest < 1) {
2965 $retval = move_section_to($course, $section, $sectiondest);
2970 * Moves a section within a course, from a position to another.
2971 * Be very careful: $section and $destination refer to section number,
2974 * @param object $course
2975 * @param int $section Section number (not id!!!)
2976 * @param int $destination
2977 * @return boolean Result
2979 function move_section_to($course, $section, $destination) {
2980 /// Moves a whole course section up and down within the course
2983 if (!$destination && $destination != 0) {
2987 // compartibility with course formats using field 'numsections'
2988 $courseformatoptions = course_get_format($course)->get_format_options();
2989 if ((array_key_exists('numsections', $courseformatoptions) &&
2990 ($destination > $courseformatoptions['numsections'])) || ($destination < 1)) {
2994 // Get all sections for this course and re-order them (2 of them should now share the same section number)
2995 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
2996 'section ASC, id ASC', 'id, section')) {
3000 $movedsections = reorder_sections($sections, $section, $destination);
3002 // Update all sections. Do this in 2 steps to avoid breaking database
3003 // uniqueness constraint
3004 $transaction = $DB->start_delegated_transaction();
3005 foreach ($movedsections as $id => $position) {
3006 if ($sections[$id] !== $position) {
3007 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
3010 foreach ($movedsections as $id => $position) {
3011 if ($sections[$id] !== $position) {
3012 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
3016 // If we move the highlighted section itself, then just highlight the destination.
3017 // Adjust the higlighted section location if we move something over it either direction.
3018 if ($section == $course->marker) {
3019 course_set_marker($course->id, $destination);
3020 } elseif ($section > $course->marker && $course->marker >= $destination) {
3021 course_set_marker($course->id, $course->marker+1);
3022 } elseif ($section < $course->marker && $course->marker <= $destination) {
3023 course_set_marker($course->id, $course->marker-1);
3026 $transaction->allow_commit();
3027 rebuild_course_cache($course->id, true);
3032 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
3033 * an original position number and a target position number, rebuilds the array so that the
3034 * move is made without any duplication of section positions.
3035 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
3036 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
3038 * @param array $sections
3039 * @param int $origin_position
3040 * @param int $target_position
3043 function reorder_sections($sections, $origin_position, $target_position) {
3044 if (!is_array($sections)) {
3048 // We can't move section position 0
3049 if ($origin_position < 1) {
3050 echo "We can't move section position 0";
3054 // Locate origin section in sections array
3055 if (!$origin_key = array_search($origin_position, $sections)) {
3056 echo "searched position not in sections array";
3057 return false; // searched position not in sections array
3060 // Extract origin section
3061 $origin_section = $sections[$origin_key];
3062 unset($sections[$origin_key]);
3064 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
3066 $append_array = array();
3067 foreach ($sections as $id => $position) {
3069 $append_array[$id] = $position;
3070 unset($sections[$id]);
3072 if ($position == $target_position) {
3073 if ($target_position < $origin_position) {
3074 $append_array[$id] = $position;
3075 unset($sections[$id]);
3081 // Append moved section
3082 $sections[$origin_key] = $origin_section;
3084 // Append rest of array (if applicable)
3085 if (!empty($append_array)) {
3086 foreach ($append_array as $id => $position) {
3087 $sections[$id] = $position;
3091 // Renumber positions
3093 foreach ($sections as $id => $p) {
3094 $sections[$id] = $position;
3103 * Move the module object $mod to the specified $section
3104 * If $beforemod exists then that is the module
3105 * before which $modid should be inserted
3106 * All parameters are objects
3108 function moveto_module($mod, $section, $beforemod=NULL) {
3111 /// Remove original module from original section
3112 if (! delete_mod_from_section($mod->id, $mod->section)) {
3113 echo $OUTPUT->notification("Could not delete module from existing section");
3116 // if moving to a hidden section then hide module
3117 if (!$section->visible && $mod->visible) {
3118 set_coursemodule_visible($mod->id, 0);
3121 /// Add the module into the new section
3122 course_add_cm_to_section($section->course, $mod->id, $section->section, $beforemod);
3127 * Produces the editing buttons for a module
3129 * @global core_renderer $OUTPUT
3130 * @staticvar type $str
3131 * @param stdClass $mod The module to produce editing buttons for
3132 * @param bool $absolute_ignored ignored - all links are absolute
3133 * @param bool $moveselect If true a move seleciton process is used (default true)
3134 * @param int $indent The current indenting
3135 * @param int $section The section to link back to
3136 * @return string XHTML for the editing buttons
3138 function make_editing_buttons(stdClass $mod, $absolute_ignored = true, $moveselect = true, $indent=-1, $section=null) {
3139 global $CFG, $OUTPUT, $COURSE;
3143 $coursecontext = context_course::instance($mod->course);
3144 $modcontext = context_module::instance($mod->id);
3146 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
3147 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
3149 // no permission to edit anything
3150 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
3154 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
3157 $str = new stdClass;
3158 $str->assign = get_string("assignroles", 'role');
3159 $str->delete = get_string("delete");
3160 $str->move = get_string("move");
3161 $str->moveup = get_string("moveup");
3162 $str->movedown = get_string("movedown");
3163 $str->moveright = get_string("moveright");
3164 $str->moveleft = get_string("moveleft");
3165 $str->update = get_string("update");
3166 $str->duplicate = get_string("duplicate");
3167 $str->hide = get_string("hide");
3168 $str->show = get_string("show");
3169 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
3170 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
3171 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
3172 $str->forcedgroupsnone = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsnone"));
3173 $str->forcedgroupsseparate = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsseparate"));
3174 $str->forcedgroupsvisible = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsvisible"));
3175 $str->edittitle = get_string('edittitle', 'moodle');
3178 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
3180 if ($section !== null) {
3181 $baseurl->param('sr', $section);
3186 if ($mod->modname !== 'label' && $hasmanageactivities && course_ajax_enabled($COURSE)) {
3187 $actions[] = new action_link(
3188 new moodle_url($baseurl, array('update' => $mod->id)),
3189 new pix_icon('t/editstring', $str->edittitle, 'moodle', array('class' => 'iconsmall visibleifjs', 'title' => '')),
3191 array('class' => 'editing_title', 'title' => $str->edittitle)
3196 if ($hasmanageactivities) {
3197 if (right_to_left()) { // Exchange arrows on RTL
3198 $rightarrow = 't/left';
3199 $leftarrow = 't/right';
3201 $rightarrow = 't/right';
3202 $leftarrow = 't/left';
3206 $actions[] = new action_link(
3207 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
3208 new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3210 array('class' => 'editing_moveleft', 'title' => $str->moveleft)
3214 $actions[] = new action_link(
3215 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
3216 new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3218 array('class' => 'editing_moveright', 'title' => $str->moveright)
3224 if ($hasmanageactivities) {
3226 $actions[] = new action_link(
3227 new moodle_url($baseurl, array('copy' => $mod->id)),
3228 new pix_icon('t/move', $str->move, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3230 array('class' => 'editing_move', 'title' => $str->move)
3233 $actions[] = new action_link(
3234 new moodle_url($baseurl, array('id' => $mod->id, 'move' => '-1')),
3235 new pix_icon('t/up', $str->moveup, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3237 array('class' => 'editing_moveup', 'title' => $str->moveup)
3239 $actions[] = new action_link(
3240 new moodle_url($baseurl, array('id' => $mod->id, 'move' => '1')),
3241 new pix_icon('t/down', $str->movedown, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3243 array('class' => 'editing_movedown', 'title' => $str->movedown)
3249 if ($hasmanageactivities) {
3250 $actions[] = new action_link(
3251 new moodle_url($baseurl, array('update' => $mod->id)),
3252 new pix_icon('t/edit', $str->update, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3254 array('class' => 'editing_update', 'title' => $str->update)
3258 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
3259 if (has_all_capabilities($dupecaps, $coursecontext) && plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2)) {
3260 $actions[] = new action_link(
3261 new moodle_url($baseurl, array('duplicate' => $mod->id)),
3262 new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3264 array('class' => 'editing_duplicate', 'title' => $str->duplicate)
3269 if ($hasmanageactivities) {
3270 $actions[] = new action_link(
3271 new moodle_url($baseurl, array('delete' => $mod->id)),
3272 new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3274 array('class' => 'editing_delete', 'title' => $str->delete)
3279 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
3280 if ($mod->visible) {
3281 $actions[] = new action_link(
3282 new moodle_url($baseurl, array('hide' => $mod->id)),
3283 new pix_icon('t/hide', $str->hide, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3285 array('class' => 'editing_hide', 'title' => $str->hide)
3288 $actions[] = new action_link(
3289 new moodle_url($baseurl, array('show' => $mod->id)),
3290 new pix_icon('t/show', $str->show, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3292 array('class' => 'editing_show', 'title' => $str->show)
3298 if ($hasmanageactivities and $mod->groupmode !== false) {
3299 if ($mod->groupmode == SEPARATEGROUPS) {
3301 $grouptitle = $str->groupsseparate;
3302 $forcedgrouptitle = $str->forcedgroupsseparate;
3303 $groupclass = 'editing_groupsseparate';
3304 $groupimage = 't/groups';
3305 } else if ($mod->groupmode == VISIBLEGROUPS) {
3307 $grouptitle = $str->groupsvisible;
3308 $forcedgrouptitle = $str->forcedgroupsvisible;
3309 $groupclass = 'editing_groupsvisible';
3310 $groupimage = 't/groupv';
3313 $grouptitle = $str->groupsnone;
3314 $forcedgrouptitle = $str->forcedgroupsnone;
3315 $groupclass = 'editing_groupsnone';
3316 $groupimage = 't/groupn';
3318 if ($mod->groupmodelink) {
3319 $actions[] = new action_link(
3320 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $groupmode)),
3321 new pix_icon($groupimage, $grouptitle, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3323 array('class' => $groupclass, 'title' => $grouptitle)
3326 $actions[] = new pix_icon($groupimage, $forcedgrouptitle, 'moodle', array('title' => $forcedgrouptitle, 'class' => 'iconsmall'));
3331 if (has_capability('moodle/role:assign', $modcontext)){
3332 $actions[] = new action_link(
3333 new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $modcontext->id)),
3334 new pix_icon('t/assignroles', $str->assign, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3336 array('class' => 'editing_assign', 'title' => $str->assign)
3340 $output = html_writer::start_tag('span', array('class' => 'commands'));
3341 foreach ($actions as $action) {
3342 if ($action instanceof renderable) {
3343 $output .= $OUTPUT->render($action);
3348 $output .= html_writer::end_tag('span');
3353 * given a course object with shortname & fullname, this function will
3354 * truncate the the number of chars allowed and add ... if it was too long
3356 function course_format_name ($course,$max=100) {
3358 $context = context_course::instance($course->id);
3359 $shortname = format_string($course->shortname, true, array('context' => $context));
3360 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
3361 $str = $shortname.': '. $fullname;
3362 if (textlib::strlen($str) <= $max) {
3366 return textlib::substr($str,0,$max-3).'...';
3371 * Is the user allowed to add this type of module to this course?
3372 * @param object $course the course settings. Only $course->id is used.
3373 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
3374 * @return bool whether the current user is allowed to add this type of module to this course.
3376 function course_allowed_module($course, $modname) {
3377 if (is_numeric($modname)) {
3378 throw new coding_exception('Function course_allowed_module no longer
3379 supports numeric module ids. Please update your code to pass the module name.');
3382 $capability = 'mod/' . $modname . ':addinstance';
3383 if (!get_capability_info($capability)) {
3384 // Debug warning that the capability does not exist, but no more than once per page.
3385 static $warned = array();
3386 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
3387 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
3388 debugging('The module ' . $modname . ' does not define the standard capability ' .
3389 $capability , DEBUG_DEVELOPER);
3390 $warned[$modname] = 1;
3393 // If the capability does not exist, the module can always be added.
3397 $coursecontext = context_course::instance($course->id);
3398 return has_capability($capability, $coursecontext);
3402 * Recursively delete category including all subcategories and courses.
3403 * @param stdClass $category
3404 * @param boolean $showfeedback display some notices
3405 * @return array return deleted courses
3407 function category_delete_full($category, $showfeedback=true) {
3409 require_once($CFG->libdir.'/gradelib.php');
3410 require_once($CFG->libdir.'/questionlib.php');
3411 require_once($CFG->dirroot.'/cohort/lib.php');
3413 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3414 foreach ($children as $childcat) {
3415 category_delete_full($childcat, $showfeedback);
3419 $deletedcourses = array();
3420 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC')) {
3421 foreach ($courses as $course) {
3422 if (!delete_course($course, false)) {
3423 throw new moodle_exception('cannotdeletecategorycourse','','',$course->shortname);
3425 $deletedcourses[] = $course;
3429 // move or delete cohorts in this context
3430 cohort_delete_category($category);
3432 // now delete anything that may depend on course category context
3433 grade_course_category_delete($category->id, 0, $showfeedback);
3434 if (!question_delete_course_category($category, 0, $showfeedback)) {
3435 throw new moodle_exception('cannotdeletecategoryquestions','','',$category->name);
3438 // finally delete the category and it's context
3439 $DB->delete_records('course_categories', array('id'=>$category->id));
3440 delete_context(CONTEXT_COURSECAT, $category->id);
3442 events_trigger('course_category_deleted', $category);
3444 return $deletedcourses;
3448 * Delete category, but move contents to another category.
3449 * @param object $ccategory
3450 * @param int $newparentid category id
3451 * @return bool status
3453 function category_delete_move($category, $newparentid, $showfeedback=true) {
3454 global $CFG, $DB, $OUTPUT;
3455 require_once($CFG->libdir.'/gradelib.php');
3456 require_once($CFG->libdir.'/questionlib.php');
3457 require_once($CFG->dirroot.'/cohort/lib.php');
3459 if (!$newparentcat = $DB->get_record('course_categories', array('id'=>$newparentid))) {
3463 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3464 foreach ($children as $childcat) {
3465 move_category($childcat, $newparentcat);
3469 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC', 'id')) {
3470 if (!move_courses(array_keys($courses), $newparentid)) {
3471 if ($showfeedback) {
3472 echo $OUTPUT->notification("Error moving courses");
3476 if ($showfeedback) {
3477 echo $OUTPUT->notification(get_string('coursesmovedout', '', format_string($category->name)), 'notifysuccess');