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 && is_numeric($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 && is_numeric($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 && is_numeric($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));
1255 format_base::reset_course_cache($courseid);
1259 * For a given course section, marks it visible or hidden,
1260 * and does the same for every activity in that section
1262 * @param int $courseid course id
1263 * @param int $sectionnumber The section number to adjust
1264 * @param int $visibility The new visibility
1265 * @return array A list of resources which were hidden in the section
1267 function set_section_visible($courseid, $sectionnumber, $visibility) {
1270 $resourcestotoggle = array();
1271 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
1272 $DB->set_field("course_sections", "visible", "$visibility", array("id"=>$section->id));
1273 if (!empty($section->sequence)) {
1274 $modules = explode(",", $section->sequence);
1275 foreach ($modules as $moduleid) {
1276 if ($cm = $DB->get_record('course_modules', array('id' => $moduleid), 'visible, visibleold')) {
1278 // As we unhide the section, we use the previously saved visibility stored in visibleold.
1279 set_coursemodule_visible($moduleid, $cm->visibleold);
1281 // We hide the section, so we hide the module but we store the original state in visibleold.
1282 set_coursemodule_visible($moduleid, 0);
1283 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id' => $moduleid));
1288 rebuild_course_cache($courseid, true);
1290 // Determine which modules are visible for AJAX update
1291 if (!empty($modules)) {
1292 list($insql, $params) = $DB->get_in_or_equal($modules);
1293 $select = 'id ' . $insql . ' AND visible = ?';
1294 array_push($params, $visibility);
1296 $select .= ' AND visibleold = 1';
1298 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
1301 return $resourcestotoggle;
1305 * Obtains shared data that is used in print_section when displaying a
1306 * course-module entry.
1308 * Calls format_text or format_string as appropriate, and obtains the correct icon.
1310 * @deprecated since 2.5
1312 * This data is also used in other areas of the code.
1313 * @param cm_info $cm Course-module data (must come from get_fast_modinfo)
1314 * @param object $course (argument not used)
1315 * @return array An array with the following values in this order:
1316 * $content (optional extra content for after link),
1317 * $instancename (text of link)
1319 function get_print_section_cm_text(cm_info $cm, $course) {
1320 return array($cm->get_formatted_content(array('overflowdiv' => true, 'noclean' => true)),
1321 $cm->get_formatted_name());
1325 * Prints a section full of activity modules
1327 * @param stdClass $course The course
1328 * @param stdClass|section_info $section The section object containing properties id and section
1329 * @param array $mods (argument not used)
1330 * @param array $modnamesused (argument not used)
1331 * @param bool $absolute All links are absolute
1332 * @param string $width (argument not used)
1333 * @param bool $hidecompletion Hide completion status
1334 * @param int $sectionreturn The section to return to
1337 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%", $hidecompletion=false, $sectionreturn=null) {
1338 global $CFG, $USER, $DB, $PAGE, $OUTPUT;
1340 static $initialised;
1342 static $groupbuttons;
1343 static $groupbuttonslink;
1347 static $strmovefull;
1348 static $strunreadpostsone;
1350 if (!isset($initialised)) {
1351 $groupbuttons = ($course->groupmode or (!$course->groupmodeforce));
1352 $groupbuttonslink = (!$course->groupmodeforce);
1353 $isediting = $PAGE->user_is_editing();
1354 $ismoving = $isediting && ismoving($course->id);
1356 $movingpix = new pix_icon('movehere', get_string('movehere'), 'moodle', array('class' => 'movetarget'));
1357 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1359 $initialised = true;
1362 $modinfo = get_fast_modinfo($course);
1363 $completioninfo = new completion_info($course);
1364 $courserenderer = $PAGE->get_renderer('core', 'course');
1366 // Get the list of modules visible to user (excluding the module being moved if there is one)
1367 $moduleslist = array();
1368 if (!empty($modinfo->sections[$section->section])) {
1369 foreach ($modinfo->sections[$section->section] as $modnumber) {
1370 $mod = $modinfo->cms[$modnumber];
1372 if ($ismoving and $mod->id == $USER->activitycopy) {
1373 // do not display moving mod
1376 // We can continue (because it will not be displayed at all)
1378 // 1) The activity is not visible to users
1380 // 2a) The 'showavailability' option is not set (if that is set,
1381 // we need to display the activity so we can show
1382 // availability info)
1384 // 2b) The 'availableinfo' is empty, i.e. the activity was
1385 // hidden in a way that leaves no info, such as using the
1387 if (!$mod->uservisible &&
1388 (empty($mod->showavailability) ||
1389 empty($mod->availableinfo))) {
1390 // visibility shortcut
1394 $moduleslist[$modnumber] = $mod;
1398 if (!empty($moduleslist) || $ismoving) {
1400 echo html_writer::start_tag('ul', array('class' => 'section img-text'));
1402 foreach ($moduleslist as $modnumber => $mod) {
1404 // In some cases the activity is visible to user, but it is
1405 // dimmed. This is done if viewhiddenactivities is true and if:
1406 // 1. the activity is not visible, or
1407 // 2. the activity has dates set which do not include current, or
1408 // 3. the activity has any other conditions set (regardless of whether
1409 // current user meets them)
1410 $modcontext = context_module::instance($mod->id);
1411 $canviewhidden = has_capability('moodle/course:viewhiddenactivities', $modcontext);
1412 $accessiblebutdim = !$mod->uservisible;
1413 $conditionalhidden = false;
1414 if (!$accessiblebutdim && $canviewhidden) {
1415 $accessiblebutdim = !$mod->visible;
1416 if (!empty($CFG->enableavailability)) {
1417 $conditionalhidden = $mod->availablefrom > time() ||
1418 ($mod->availableuntil && $mod->availableuntil < time()) ||
1419 count($mod->conditionsgrade) > 0 ||
1420 count($mod->conditionscompletion) > 0;
1422 $accessiblebutdim = $conditionalhidden || $accessiblebutdim;
1425 $modclasses = 'activity '. $mod->modname. 'modtype_'.$mod->modname. ' '. $mod->get_extra_classes();
1427 $movingurl = new moodle_url('/course/mod.php', array('moveto' => $mod->id, 'sesskey' => sesskey()));
1428 echo html_writer::tag('li', html_writer::link($movingurl, $OUTPUT->render($movingpix)), array('class' => 'movehere'));
1431 echo html_writer::start_tag('li', array('class' => $modclasses, 'id' => 'module-'. $modnumber));
1432 $indentclasses = 'mod-indent';
1433 if (!empty($mod->indent)) {
1434 $indentclasses .= ' mod-indent-'.$mod->indent;
1435 if ($mod->indent > 15) {
1436 $indentclasses .= ' mod-indent-huge';
1439 echo html_writer::start_tag('div', array('class' => $indentclasses));
1441 // Get data about this course-module
1442 $content = $mod->get_formatted_content(array('overflowdiv' => true, 'noclean' => true));
1443 $instancename = $mod->get_formatted_name();
1445 //Accessibility: for files get description via icon, this is very ugly hack!
1447 $altname = $mod->modfullname;
1448 // Avoid unnecessary duplication: if e.g. a forum name already
1449 // includes the word forum (or Forum, etc) then it is unhelpful
1450 // to include that in the accessible description that is added.
1451 if (false !== strpos(textlib::strtolower($instancename),
1452 textlib::strtolower($altname))) {
1455 // File type after name, for alphabetic lists (screen reader).
1457 $altname = get_accesshide(' '.$altname);
1460 // Start the div for the activity title, excluding the edit icons.
1461 echo html_writer::start_tag('div', array('class' => 'activityinstance'));
1463 // We may be displaying this just in order to show information
1464 // about visibility, without the actual link ($mod->uservisible)
1469 if ($accessiblebutdim) {
1470 $linkclasses .= ' dimmed';
1471 $textclasses .= ' dimmed_text';
1472 if ($conditionalhidden) {
1473 $linkclasses .= ' conditionalhidden';
1474 $textclasses .= ' conditionalhidden';
1476 if ($mod->uservisible) {
1477 // show accessibility note only if user can access the module himself
1478 $accesstext = get_accesshide(get_string('hiddenfromstudents').': ');
1482 // Get on-click attribute value if specified and decode the onclick - it
1483 // has already been encoded for display (puke).
1484 $onclick = htmlspecialchars_decode($mod->get_on_click(), ENT_QUOTES);
1486 $groupinglabel = '';
1487 if (!empty($mod->groupingid) && has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
1488 $groupings = groups_get_all_groupings($course->id);
1489 $groupinglabel = html_writer::tag('span', '('.format_string($groupings[$mod->groupingid]->name).')',
1490 array('class' => 'groupinglabel '.$textclasses));
1493 if ($url = $mod->get_url()) {
1494 // Display link itself.
1495 $activitylink = html_writer::empty_tag('img', array('src' => $mod->get_icon_url(),
1496 'class' => 'iconlarge activityicon', 'alt' => $mod->modfullname)) . $accesstext .
1497 html_writer::tag('span', $instancename . $altname, array('class' => 'instancename'));
1498 if ($mod->uservisible) {
1499 echo html_writer::link($url, $activitylink, array('class' => $linkclasses, 'onclick' => $onclick)) .
1502 echo html_writer::tag('div', $activitylink, array('class' => $textclasses)) .
1506 // If specified, display extra content after link.
1508 $contentpart = html_writer::tag('div', $content, array('class' =>
1509 trim('contentafterlink ' . $textclasses)));
1512 // No link, so display only content.
1513 $contentpart = html_writer::tag('div', $accesstext . $content, array('class' => $textclasses));
1516 // Module can put text after the link (e.g. forum unread)
1517 echo $mod->get_after_link();
1519 // Closing the tag which contains everything but edit icons. $contentpart should not be part of this.
1520 echo html_writer::end_tag('div');
1522 // If there is content but NO link (eg label), then display the
1523 // content here (BEFORE any icons). In this case cons must be
1524 // displayed after the content so that it makes more sense visually
1525 // and for accessibility reasons, e.g. if you have a one-line label
1526 // it should work similarly (at least in terms of ordering) to an
1533 if ($groupbuttons and plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
1534 if (! $mod->groupmodelink = $groupbuttonslink) {
1535 $mod->groupmode = $course->groupmode;
1539 $mod->groupmode = false;
1541 echo make_editing_buttons($mod, $absolute, true, $mod->indent, $sectionreturn);
1542 echo $mod->get_after_edit_icons();
1546 $completion = $hidecompletion
1547 ? COMPLETION_TRACKING_NONE
1548 : $completioninfo->is_enabled($mod);
1549 if ($completion!=COMPLETION_TRACKING_NONE && isloggedin() &&
1550 !isguestuser() && $mod->uservisible) {
1551 $completiondata = $completioninfo->get_data($mod,true);
1552 $completionicon = '';
1554 switch ($completion) {
1555 case COMPLETION_TRACKING_MANUAL :
1556 $completionicon = 'manual-enabled'; break;
1557 case COMPLETION_TRACKING_AUTOMATIC :
1558 $completionicon = 'auto-enabled'; break;
1561 } else if ($completion==COMPLETION_TRACKING_MANUAL) {
1562 switch($completiondata->completionstate) {
1563 case COMPLETION_INCOMPLETE:
1564 $completionicon = 'manual-n'; break;
1565 case COMPLETION_COMPLETE:
1566 $completionicon = 'manual-y'; break;
1568 } else { // Automatic
1569 switch($completiondata->completionstate) {
1570 case COMPLETION_INCOMPLETE:
1571 $completionicon = 'auto-n'; break;
1572 case COMPLETION_COMPLETE:
1573 $completionicon = 'auto-y'; break;
1574 case COMPLETION_COMPLETE_PASS:
1575 $completionicon = 'auto-pass'; break;
1576 case COMPLETION_COMPLETE_FAIL:
1577 $completionicon = 'auto-fail'; break;
1580 if ($completionicon) {
1581 $imgsrc = $OUTPUT->pix_url('i/completion-'.$completionicon);
1582 $formattedname = format_string($mod->name, true, array('context' => $modcontext));
1583 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $formattedname);
1584 if ($completion == COMPLETION_TRACKING_MANUAL && !$isediting) {
1585 $imgtitle = get_string('completion-title-' . $completionicon, 'completion', $formattedname);
1587 $completiondata->completionstate==COMPLETION_COMPLETE
1588 ? COMPLETION_INCOMPLETE
1589 : COMPLETION_COMPLETE;
1590 // In manual mode the icon is a toggle form...
1592 // If this completion state is used by the
1593 // conditional activities system, we need to turn
1595 if (!empty($CFG->enableavailability) &&
1596 condition_info::completion_value_used_as_condition($course, $mod)) {
1597 $extraclass = ' preventjs';
1601 echo html_writer::start_tag('form', array(
1602 'class' => 'togglecompletion' . $extraclass,
1604 'action' => $CFG->wwwroot . '/course/togglecompletion.php'));
1605 echo html_writer::start_tag('div');
1606 echo html_writer::empty_tag('input', array(
1607 'type' => 'hidden', 'name' => 'id', 'value' => $mod->id));
1608 echo html_writer::empty_tag('input', array(
1609 'type' => 'hidden', 'name' => 'modulename',
1610 'value' => $mod->name));
1611 echo html_writer::empty_tag('input', array(
1612 'type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey()));
1613 echo html_writer::empty_tag('input', array(
1614 'type' => 'hidden', 'name' => 'completionstate',
1615 'value' => $newstate));
1616 echo html_writer::empty_tag('input', array(
1617 'type' => 'image', 'src' => $imgsrc, 'alt' => $imgalt, 'title' => $imgtitle));
1618 echo html_writer::end_tag('div');
1619 echo html_writer::end_tag('form');
1621 // In auto mode, or when editing, the icon is just an image
1622 echo "<span class='autocompletion'>";
1623 echo "<img src='$imgsrc' alt='$imgalt' title='$imgalt' /></span>";
1628 // If there is content AND a link, then display the content here
1629 // (AFTER any icons). Otherwise it was displayed before
1634 // Show availability information (for someone who isn't allowed to
1635 // see the activity itself, or for staff)
1636 if (!$mod->uservisible) {
1637 echo '<div class="availabilityinfo">'.$mod->availableinfo.'</div>';
1638 } else if ($canviewhidden && !empty($CFG->enableavailability)) {
1639 // Don't add availability information if user is not editing and activity is hidden.
1640 if ($mod->visible || $PAGE->user_is_editing()) {
1642 if (!$mod->visible) {
1643 $hidinfoclass = 'hide';
1645 $ci = new condition_info($mod);
1646 $fullinfo = $ci->get_full_information();
1648 echo '<div class="availabilityinfo '.$hidinfoclass.'">'.get_string($mod->showavailability
1649 ? 'userrestriction_visible'
1650 : 'userrestriction_hidden','condition',
1651 $fullinfo).'</div>';
1656 echo html_writer::end_tag('div');
1657 echo html_writer::end_tag('li')."\n";
1661 $movingurl = new moodle_url('/course/mod.php', array('movetosection' => $section->id, 'sesskey' => sesskey()));
1662 echo html_writer::tag('li', html_writer::link($movingurl, $OUTPUT->render($movingpix)), array('class' => 'movehere'));
1665 echo html_writer::end_tag('ul'); // .section
1670 * Prints the menus to add activities and resources.
1672 * @param stdClass $course The course
1673 * @param int $section relative section number (field course_sections.section)
1674 * @param null|array $modnames An array containing the list of modules and their names
1675 * if omitted will be taken from get_module_types_names()
1676 * @param bool $vertical Vertical orientation
1677 * @param bool $return Return the menus or send them to output
1678 * @param int $sectionreturn The section to link back to
1679 * @return void|string depending on $return
1681 function print_section_add_menus($course, $section, $modnames = null, $vertical=false, $return=false, $sectionreturn=null) {
1682 global $PAGE, $CFG, $OUTPUT;
1683 if ($course->id != $PAGE->course->id) {
1684 debugging('print_section_add_menus() can be called only for the course set on the page', DEBUG_DEVELOPER);
1688 if ($modnames === null) {
1689 $modnames = get_module_types_names();
1692 // check to see if user can add menus and there are modules to add
1693 if (!has_capability('moodle/course:manageactivities', context_course::instance($course->id))
1694 || !$PAGE->user_is_editing()
1695 || empty($modnames)) {
1703 // Retrieve all modules with associated metadata
1704 $modules = get_module_metadata($course, $modnames, $sectionreturn);
1706 // We'll sort resources and activities into two lists
1707 $resources = array();
1708 $activities = array();
1710 foreach ($modules as $module) {
1711 if (isset($module->types)) {
1712 // This module has a subtype
1713 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1714 $subtypes = array();
1715 foreach ($module->types as $subtype) {
1716 $link = $subtype->link->out(true, array('section' => $section));
1717 $subtypes[$link] = $subtype->title;
1720 // Sort module subtypes into the list
1721 if (!empty($module->title)) {
1722 // This grouping has a name
1723 if ($module->archetype == MOD_CLASS_RESOURCE) {
1724 $resources[] = array($module->title=>$subtypes);
1726 $activities[] = array($module->title=>$subtypes);
1729 // This grouping does not have a name
1730 if ($module->archetype == MOD_CLASS_RESOURCE) {
1731 $resources = array_merge($resources, $subtypes);
1733 $activities = array_merge($activities, $subtypes);
1737 // This module has no subtypes
1738 if ($module->archetype == MOD_ARCHETYPE_RESOURCE) {
1739 $link = $module->link->out(true, array('section' => $section));
1740 $resources[$link] = $module->title;
1741 } else if ($module->archetype === MOD_ARCHETYPE_SYSTEM) {
1742 // System modules cannot be added by user, do not add to dropdown
1744 $link = $module->link->out(true, array('section' => $section));
1745 $activities[$link] = $module->title;
1750 $straddactivity = get_string('addactivity');
1751 $straddresource = get_string('addresource');
1752 $sectionname = get_section_name($course, $section);
1753 $strresourcelabel = get_string('addresourcetosection', null, $sectionname);
1754 $stractivitylabel = get_string('addactivitytosection', null, $sectionname);
1756 $output = html_writer::start_tag('div', array('class' => 'section_add_menus', 'id' => 'add_menus-section-' . $section));
1759 $output .= html_writer::start_tag('div', array('class' => 'horizontal'));
1762 if (!empty($resources)) {
1763 $select = new url_select($resources, '', array(''=>$straddresource), "ressection$section");
1764 $select->set_help_icon('resources');
1765 $select->set_label($strresourcelabel, array('class' => 'accesshide'));
1766 $output .= $OUTPUT->render($select);
1769 if (!empty($activities)) {
1770 $select = new url_select($activities, '', array(''=>$straddactivity), "section$section");
1771 $select->set_help_icon('activities');
1772 $select->set_label($stractivitylabel, array('class' => 'accesshide'));
1773 $output .= $OUTPUT->render($select);
1777 $output .= html_writer::end_tag('div');
1780 $output .= html_writer::end_tag('div');
1782 if (course_ajax_enabled($course)) {
1783 $straddeither = get_string('addresourceoractivity');
1784 // The module chooser link
1785 $modchooser = html_writer::start_tag('div', array('class' => 'mdl-right'));
1786 $modchooser.= html_writer::start_tag('div', array('class' => 'section-modchooser'));
1787 $icon = $OUTPUT->pix_icon('t/add', '');
1788 $span = html_writer::tag('span', $straddeither, array('class' => 'section-modchooser-text'));
1789 $modchooser .= html_writer::tag('span', $icon . $span, array('class' => 'section-modchooser-link'));
1790 $modchooser.= html_writer::end_tag('div');
1791 $modchooser.= html_writer::end_tag('div');
1793 // Wrap the normal output in a noscript div
1794 $usemodchooser = get_user_preferences('usemodchooser', $CFG->modchooserdefault);
1795 if ($usemodchooser) {
1796 $output = html_writer::tag('div', $output, array('class' => 'hiddenifjs addresourcedropdown'));
1797 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'visibleifjs addresourcemodchooser'));
1799 // If the module chooser is disabled, we need to ensure that the dropdowns are shown even if javascript is disabled
1800 $output = html_writer::tag('div', $output, array('class' => 'show addresourcedropdown'));
1801 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'hide addresourcemodchooser'));
1803 $courserenderer = $PAGE->get_renderer('core', 'course');
1804 $output = $courserenderer->course_modchooser($modules, $course) . $modchooser . $output;
1815 * Retrieve all metadata for the requested modules
1817 * @param object $course The Course
1818 * @param array $modnames An array containing the list of modules and their
1820 * @param int $sectionreturn The section to return to
1821 * @return array A list of stdClass objects containing metadata about each
1824 function get_module_metadata($course, $modnames, $sectionreturn = null) {
1825 global $CFG, $OUTPUT;
1827 // get_module_metadata will be called once per section on the page and courses may show
1828 // different modules to one another
1829 static $modlist = array();
1830 if (!isset($modlist[$course->id])) {
1831 $modlist[$course->id] = array();
1835 $urlbase = new moodle_url('/course/mod.php', array('id' => $course->id, 'sesskey' => sesskey()));
1836 if ($sectionreturn !== null) {
1837 $urlbase->param('sr', $sectionreturn);
1839 foreach($modnames as $modname => $modnamestr) {
1840 if (!course_allowed_module($course, $modname)) {
1843 if (isset($modlist[$course->id][$modname])) {
1844 // This module is already cached
1845 $return[$modname] = $modlist[$course->id][$modname];
1849 // Include the module lib
1850 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1851 if (!file_exists($libfile)) {
1854 include_once($libfile);
1856 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1857 $gettypesfunc = $modname.'_get_types';
1858 if (function_exists($gettypesfunc)) {
1859 if ($types = $gettypesfunc()) {
1860 $group = new stdClass();
1861 $group->name = $modname;
1862 $group->icon = $OUTPUT->pix_icon('icon', '', $modname, array('class' => 'icon'));
1863 foreach($types as $type) {
1864 if ($type->typestr === '--') {
1867 if (strpos($type->typestr, '--') === 0) {
1868 $group->title = str_replace('--', '', $type->typestr);
1871 // Set the Sub Type metadata
1872 $subtype = new stdClass();
1873 $subtype->title = $type->typestr;
1874 $subtype->type = str_replace('&', '&', $type->type);
1875 $subtype->name = preg_replace('/.*type=/', '', $subtype->type);
1876 $subtype->archetype = $type->modclass;
1878 // The group archetype should match the subtype archetypes and all subtypes
1879 // should have the same archetype
1880 $group->archetype = $subtype->archetype;
1882 if (get_string_manager()->string_exists('help' . $subtype->name, $modname)) {
1883 $subtype->help = get_string('help' . $subtype->name, $modname);
1885 $subtype->link = new moodle_url($urlbase, array('add' => $subtype->type));
1886 $group->types[] = $subtype;
1888 $modlist[$course->id][$modname] = $group;
1891 $module = new stdClass();
1892 $module->title = $modnamestr;
1893 $module->name = $modname;
1894 $module->link = new moodle_url($urlbase, array('add' => $modname));
1895 $module->icon = $OUTPUT->pix_icon('icon', '', $module->name, array('class' => 'icon'));
1896 $sm = get_string_manager();
1897 if ($sm->string_exists('modulename_help', $modname)) {
1898 $module->help = get_string('modulename_help', $modname);
1899 if ($sm->string_exists('modulename_link', $modname)) { // Link to further info in Moodle docs
1900 $link = get_string('modulename_link', $modname);
1901 $linktext = get_string('morehelp');
1902 $module->help .= html_writer::tag('div', $OUTPUT->doc_link($link, $linktext, true), array('class' => 'helpdoclink'));
1905 $module->archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1906 $modlist[$course->id][$modname] = $module;
1908 $return[$modname] = $modlist[$course->id][$modname];
1915 * Return the course category context for the category with id $categoryid, except
1916 * that if $categoryid is 0, return the system context.
1918 * @param integer $categoryid a category id or 0.
1919 * @return object the corresponding context
1921 function get_category_or_system_context($categoryid) {
1923 return context_coursecat::instance($categoryid, IGNORE_MISSING);
1925 return context_system::instance();
1930 * Gets the child categories of a given courses category. Uses a static cache
1931 * to make repeat calls efficient.
1933 * @param int $parentid the id of a course category.
1934 * @return array all the child course categories.
1936 function get_child_categories($parentid) {
1937 static $allcategories = null;
1939 // only fill in this variable the first time
1940 if (null == $allcategories) {
1941 $allcategories = array();
1943 $categories = get_categories();
1944 foreach ($categories as $category) {
1945 if (empty($allcategories[$category->parent])) {
1946 $allcategories[$category->parent] = array();
1948 $allcategories[$category->parent][] = $category;
1952 if (empty($allcategories[$parentid])) {
1955 return $allcategories[$parentid];
1960 * This function recursively travels the categories, building up a nice list
1961 * for display. It also makes an array that list all the parents for each
1964 * For example, if you have a tree of categories like:
1965 * Miscellaneous (id = 1)
1966 * Subcategory (id = 2)
1967 * Sub-subcategory (id = 4)
1968 * Other category (id = 3)
1969 * Then after calling this function you will have
1970 * $list = array(1 => 'Miscellaneous', 2 => 'Miscellaneous / Subcategory',
1971 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
1972 * 3 => 'Other category');
1973 * $parents = array(2 => array(1), 4 => array(1, 2));
1975 * If you specify $requiredcapability, then only categories where the current
1976 * user has that capability will be added to $list, although all categories
1977 * will still be added to $parents, and if you only have $requiredcapability
1978 * in a child category, not the parent, then the child catgegory will still be
1981 * If you specify the option $excluded, then that category, and all its children,
1982 * are omitted from the tree. This is useful when you are doing something like
1983 * moving categories, where you do not want to allow people to move a category
1984 * to be the child of itself.
1986 * @param array $list For output, accumulates an array categoryid => full category path name
1987 * @param array $parents For output, accumulates an array categoryid => list of parent category ids.
1988 * @param string/array $requiredcapability if given, only categories where the current
1989 * user has this capability will be added to $list. Can also be an array of capabilities,
1990 * in which case they are all required.
1991 * @param integer $excludeid Omit this category and its children from the lists built.
1992 * @param object $category Build the tree starting at this category - otherwise starts at the top level.
1993 * @param string $path For internal use, as part of recursive calls.
1995 function make_categories_list(&$list, &$parents, $requiredcapability = '',
1996 $excludeid = 0, $category = NULL, $path = "") {
1998 // initialize the arrays if needed
1999 if (!is_array($list)) {
2002 if (!is_array($parents)) {
2006 if (empty($category)) {
2007 // Start at the top level.
2008 $category = new stdClass;
2011 // This is the excluded category, don't include it.
2012 if ($excludeid > 0 && $excludeid == $category->id) {
2016 $context = context_coursecat::instance($category->id);
2017 $categoryname = format_string($category->name, true, array('context' => $context));
2021 $path = $path.' / '.$categoryname;
2023 $path = $categoryname;
2026 // Add this category to $list, if the permissions check out.
2027 if (empty($requiredcapability)) {
2028 $list[$category->id] = $path;
2031 $requiredcapability = (array)$requiredcapability;
2032 if (has_all_capabilities($requiredcapability, $context)) {
2033 $list[$category->id] = $path;
2038 // Add all the children recursively, while updating the parents array.
2039 if ($categories = get_child_categories($category->id)) {
2040 foreach ($categories as $cat) {
2041 if (!empty($category->id)) {
2042 if (isset($parents[$category->id])) {
2043 $parents[$cat->id] = $parents[$category->id];
2045 $parents[$cat->id][] = $category->id;
2047 make_categories_list($list, $parents, $requiredcapability, $excludeid, $cat, $path);
2053 * This function generates a structured array of courses and categories.
2055 * The depth of categories is limited by $CFG->maxcategorydepth however there
2056 * is no limit on the number of courses!
2058 * Suitable for use with the course renderers course_category_tree method:
2059 * $renderer = $PAGE->get_renderer('core','course');
2060 * echo $renderer->course_category_tree(get_course_category_tree());
2062 * @global moodle_database $DB
2066 function get_course_category_tree($id = 0, $depth = 0) {
2068 $viewhiddencats = has_capability('moodle/category:viewhiddencategories', context_system::instance());
2069 $categories = get_child_categories($id);
2070 $categoryids = array();
2071 foreach ($categories as $key => &$category) {
2072 if (!$category->visible && !$viewhiddencats) {
2073 unset($categories[$key]);
2076 $categoryids[$category->id] = $category;
2077 if (empty($CFG->maxcategorydepth) || $depth <= $CFG->maxcategorydepth) {
2078 list($category->categories, $subcategories) = get_course_category_tree($category->id, $depth+1);
2079 foreach ($subcategories as $subid=>$subcat) {
2080 $categoryids[$subid] = $subcat;
2082 $category->courses = array();
2087 // This is a recursive call so return the required array
2088 return array($categories, $categoryids);
2091 if (empty($categoryids)) {
2092 // No categories available (probably all hidden).
2096 // The depth is 0 this function has just been called so we can finish it off
2098 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
2099 list($catsql, $catparams) = $DB->get_in_or_equal(array_keys($categoryids));
2101 c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary,c.category
2105 WHERE c.category $catsql ORDER BY c.sortorder ASC";
2106 if ($courses = $DB->get_records_sql($sql, $catparams)) {
2107 // loop throught them
2108 foreach ($courses as $course) {
2109 if ($course->id == SITEID) {
2112 context_instance_preload($course);
2113 if (!empty($course->visible) || has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
2114 $categoryids[$course->category]->courses[$course->id] = $course;
2122 * Recursive function to print out all the categories in a nice format
2123 * with or without courses included
2125 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true) {
2128 // maxcategorydepth == 0 meant no limit
2129 if (!empty($CFG->maxcategorydepth) && $depth >= $CFG->maxcategorydepth) {
2133 if (!$displaylist) {
2134 make_categories_list($displaylist, $parentslist);
2138 if ($category->visible or has_capability('moodle/category:viewhiddencategories', context_system::instance())) {
2139 print_category_info($category, $depth, $showcourses);
2141 return; // Don't bother printing children of invisible categories
2145 $category = new stdClass();
2146 $category->id = "0";
2149 if ($categories = get_child_categories($category->id)) { // Print all the children recursively
2150 $countcats = count($categories);
2154 foreach ($categories as $cat) {
2156 if ($count == $countcats) {
2159 $up = $first ? false : true;
2160 $down = $last ? false : true;
2163 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1, $showcourses);
2169 * This function will return $options array for html_writer::select(), with whitespace to denote nesting.
2171 function make_categories_options() {
2172 make_categories_list($cats,$parents);
2173 foreach ($cats as $key => $value) {
2174 if (array_key_exists($key,$parents)) {
2175 if ($indent = count($parents[$key])) {
2176 for ($i = 0; $i < $indent; $i++) {
2177 $cats[$key] = ' '.$cats[$key];
2186 * Prints the category info in indented fashion
2187 * This function is only used by print_whole_category_list() above
2189 function print_category_info($category, $depth=0, $showcourses = false) {
2190 global $CFG, $DB, $OUTPUT;
2192 $strsummary = get_string('summary');
2195 if (!$category->visible) {
2196 $catlinkcss = array('class'=>'dimmed');
2198 static $coursecount = null;
2199 if (null === $coursecount) {
2200 // only need to check this once
2201 $coursecount = $DB->count_records('course') <= FRONTPAGECOURSELIMIT;
2204 if ($showcourses and $coursecount) {
2205 $catimage = '<img src="'.$OUTPUT->pix_url('i/course') . '" alt="" />';
2207 $catimage = " ";
2210 $courses = get_courses($category->id, 'c.sortorder ASC', 'c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary');
2211 $context = context_coursecat::instance($category->id);
2212 $fullname = format_string($category->name, true, array('context' => $context));
2214 if ($showcourses and $coursecount) {
2215 echo '<div class="categorylist clearfix">';
2217 $cat .= html_writer::tag('div', $catimage, array('class'=>'image'));
2218 $catlink = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
2219 $cat .= html_writer::tag('div', $catlink, array('class'=>'name'));
2223 for ($i=0; $i< $depth; $i++) {
2224 $html = html_writer::tag('div', $html . $cat, array('class'=>'indentation'));
2230 echo html_writer::tag('div', $html, array('class'=>'category'));
2231 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
2233 // does the depth exceed maxcategorydepth
2234 // maxcategorydepth == 0 or unset meant no limit
2235 $limit = !(isset($CFG->maxcategorydepth) && ($depth >= $CFG->maxcategorydepth-1));
2236 if ($courses && ($limit || $CFG->maxcategorydepth == 0)) {
2237 foreach ($courses as $course) {
2239 if (!$course->visible) {
2240 $linkcss = array('class'=>'dimmed');
2243 $coursename = get_course_display_name_for_list($course);
2244 $courselink = html_writer::link(new moodle_url('/course/view.php', array('id'=>$course->id)), format_string($coursename), $linkcss);
2248 if ($icons = enrol_get_course_info_icons($course)) {
2249 foreach ($icons as $pix_icon) {
2250 $courseicon = $OUTPUT->render($pix_icon);
2254 $coursecontent = html_writer::tag('div', $courseicon.$courselink, array('class'=>'name'));
2256 if ($course->summary) {
2257 $link = new moodle_url('/course/info.php?id='.$course->id);
2258 $actionlink = $OUTPUT->action_link($link, '<img alt="'.$strsummary.'" src="'.$OUTPUT->pix_url('i/info') . '" />',
2259 new popup_action('click', $link, 'courseinfo', array('height' => 400, 'width' => 500)),
2260 array('title'=>$strsummary));
2262 $coursecontent .= html_writer::tag('div', $actionlink, array('class'=>'info'));
2266 for ($i=0; $i <= $depth; $i++) {
2267 $html = html_writer::tag('div', $html . $coursecontent , array('class'=>'indentation'));
2268 $coursecontent = '';
2270 echo html_writer::tag('div', $html, array('class'=>'course clearfloat'));
2275 echo '<div class="categorylist">';
2277 $cat = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
2278 if (count($courses) > 0) {
2279 $cat .= html_writer::tag('span', ' ('.count($courses).')', array('title'=>get_string('numberofcourses'), 'class'=>'numberofcourse'));
2283 for ($i=0; $i< $depth; $i++) {
2284 $html = html_writer::tag('div', $html .$cat, array('class'=>'indentation'));
2291 echo html_writer::tag('div', $html, array('class'=>'category'));
2292 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
2298 * Print the buttons relating to course requests.
2300 * @param object $systemcontext the system context.
2302 function print_course_request_buttons($systemcontext) {
2303 global $CFG, $DB, $OUTPUT;
2304 if (empty($CFG->enablecourserequests)) {
2307 if (!has_capability('moodle/course:create', $systemcontext) && has_capability('moodle/course:request', $systemcontext)) {
2308 /// Print a button to request a new course
2309 echo $OUTPUT->single_button('request.php', get_string('requestcourse'), 'get');
2311 /// Print a button to manage pending requests
2312 if (has_capability('moodle/site:approvecourse', $systemcontext)) {
2313 $disabled = !$DB->record_exists('course_request', array());
2314 echo $OUTPUT->single_button('pending.php', get_string('coursespending'), 'get', array('disabled'=>$disabled));
2319 * Does the user have permission to edit things in this category?
2321 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2322 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
2324 function can_edit_in_category($categoryid = 0) {
2325 $context = get_category_or_system_context($categoryid);
2326 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
2330 * Prints the turn editing on/off button on course/index.php or course/category.php.
2332 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2333 * @return string HTML of the editing button, or empty string, if this user is not allowed
2336 function update_category_button($categoryid = 0) {
2337 global $CFG, $PAGE, $OUTPUT;
2339 // Check permissions.
2340 if (!can_edit_in_category($categoryid)) {
2344 // Work out the appropriate action.
2345 if ($PAGE->user_is_editing()) {
2346 $label = get_string('turneditingoff');
2349 $label = get_string('turneditingon');
2353 // Generate the button HTML.
2354 $options = array('categoryedit' => $edit, 'sesskey' => sesskey());
2356 $options['id'] = $categoryid;
2357 $page = 'category.php';
2359 $page = 'index.php';
2361 return $OUTPUT->single_button(new moodle_url('/course/' . $page, $options), $label, 'get');
2365 * Category is 0 (for all courses) or an object
2367 function print_courses($category) {
2368 global $CFG, $OUTPUT;
2370 if (!is_object($category) && $category==0) {
2371 $categories = get_child_categories(0); // Parent = 0 ie top-level categories only
2372 if (is_array($categories) && count($categories) == 1) {
2373 $category = array_shift($categories);
2374 $courses = get_courses_wmanagers($category->id,
2376 array('summary','summaryformat'));
2378 $courses = get_courses_wmanagers('all',
2380 array('summary','summaryformat'));
2384 $courses = get_courses_wmanagers($category->id,
2386 array('summary','summaryformat'));
2390 echo html_writer::start_tag('ul', array('class'=>'unlist'));
2391 foreach ($courses as $course) {
2392 $coursecontext = context_course::instance($course->id);
2393 if ($course->visible == 1 || has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2394 echo html_writer::start_tag('li');
2395 print_course($course);
2396 echo html_writer::end_tag('li');
2399 echo html_writer::end_tag('ul');
2401 echo $OUTPUT->heading(get_string("nocoursesyet"));
2402 $context = context_system::instance();
2403 if (has_capability('moodle/course:create', $context)) {
2405 if (!empty($category->id)) {
2406 $options['category'] = $category->id;
2408 $options['category'] = $CFG->defaultrequestcategory;
2410 echo html_writer::start_tag('div', array('class'=>'addcoursebutton'));
2411 echo $OUTPUT->single_button(new moodle_url('/course/edit.php', $options), get_string("addnewcourse"));
2412 echo html_writer::end_tag('div');
2418 * Print a description of a course, suitable for browsing in a list.
2420 * @param object $course the course object.
2421 * @param string $highlightterms (optional) some search terms that should be highlighted in the display.
2423 function print_course($course, $highlightterms = '') {
2424 global $CFG, $USER, $DB, $OUTPUT;
2426 $context = context_course::instance($course->id);
2428 // Rewrite file URLs so that they are correct
2429 $course->summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', NULL);
2431 echo html_writer::start_tag('div', array('class'=>'coursebox clearfix'));
2432 echo html_writer::start_tag('div', array('class'=>'info'));
2433 echo html_writer::start_tag('h3', array('class'=>'name'));
2435 $linkhref = new moodle_url('/course/view.php', array('id'=>$course->id));
2437 $coursename = get_course_display_name_for_list($course);
2438 $linktext = highlight($highlightterms, format_string($coursename));
2439 $linkparams = array('title'=>get_string('entercourse'));
2440 if (empty($course->visible)) {
2441 $linkparams['class'] = 'dimmed';
2443 echo html_writer::link($linkhref, $linktext, $linkparams);
2444 echo html_writer::end_tag('h3');
2446 /// first find all roles that are supposed to be displayed
2447 if (!empty($CFG->coursecontact)) {
2448 $managerroles = explode(',', $CFG->coursecontact);
2451 if (!isset($course->managers)) {
2452 list($sort, $sortparams) = users_order_by_sql('u');
2453 $rusers = get_role_users($managerroles, $context, true,
2454 'ra.id AS raid, u.id, u.username, u.firstname, u.lastname, rn.name AS rolecoursealias,
2455 r.name AS rolename, r.sortorder, r.id AS roleid, r.shortname AS roleshortname',
2456 'r.sortorder ASC, ' . $sort, null, '', '', '', '', $sortparams);
2458 // use the managers array if we have it for perf reasosn
2459 // populate the datastructure like output of get_role_users();
2460 foreach ($course->managers as $manager) {
2461 $user = clone($manager->user);
2462 $user->roleid = $manager->roleid;
2463 $user->rolename = $manager->rolename;
2464 $user->roleshortname = $manager->roleshortname;
2465 $user->rolecoursealias = $manager->rolecoursealias;
2466 $rusers[$user->id] = $user;
2470 $namesarray = array();
2471 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2472 foreach ($rusers as $ra) {
2473 if (isset($namesarray[$ra->id])) {
2474 // only display a user once with the higest sortorder role
2478 $role = new stdClass();
2479 $role->id = $ra->roleid;
2480 $role->name = $ra->rolename;
2481 $role->shortname = $ra->roleshortname;
2482 $role->coursealias = $ra->rolecoursealias;
2483 $rolename = role_get_name($role, $context, ROLENAME_ALIAS);
2485 $fullname = fullname($ra, $canviewfullnames);
2486 $namesarray[$ra->id] = $rolename.': '.
2487 html_writer::link(new moodle_url('/user/view.php', array('id'=>$ra->id, 'course'=>SITEID)), $fullname);
2490 if (!empty($namesarray)) {
2491 echo html_writer::start_tag('ul', array('class'=>'teachers'));
2492 foreach ($namesarray as $name) {
2493 echo html_writer::tag('li', $name);
2495 echo html_writer::end_tag('ul');
2498 echo html_writer::end_tag('div'); // End of info div
2500 echo html_writer::start_tag('div', array('class'=>'summary'));
2501 $options = new stdClass();
2502 $options->noclean = true;
2503 $options->para = false;
2504 $options->overflowdiv = true;
2505 if (!isset($course->summaryformat)) {
2506 $course->summaryformat = FORMAT_MOODLE;
2508 echo highlight($highlightterms, format_text($course->summary, $course->summaryformat, $options, $course->id));
2509 if ($icons = enrol_get_course_info_icons($course)) {
2510 echo html_writer::start_tag('div', array('class'=>'enrolmenticons'));
2511 foreach ($icons as $icon) {
2512 echo $OUTPUT->render($icon);
2514 echo html_writer::end_tag('div'); // End of enrolmenticons div
2516 echo html_writer::end_tag('div'); // End of summary div
2517 echo html_writer::end_tag('div'); // End of coursebox div
2521 * Prints custom user information on the home page.
2522 * Over time this can include all sorts of information
2524 function print_my_moodle() {
2525 global $USER, $CFG, $DB, $OUTPUT;
2527 if (!isloggedin() or isguestuser()) {
2528 print_error('nopermissions', '', '', 'See My Moodle');
2531 $courses = enrol_get_my_courses('summary', 'visible DESC,sortorder ASC');
2533 $rcourses = array();
2534 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
2535 $rcourses = get_my_remotecourses($USER->id);
2536 $rhosts = get_my_remotehosts();
2539 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
2541 if (!empty($courses)) {
2542 echo '<ul class="unlist">';
2543 foreach ($courses as $course) {
2544 if ($course->id == SITEID) {
2548 print_course($course);
2555 if (!empty($rcourses)) {
2556 // at the IDP, we know of all the remote courses
2557 foreach ($rcourses as $course) {
2558 print_remote_course($course, "100%");
2560 } elseif (!empty($rhosts)) {
2561 // non-IDP, we know of all the remote servers, but not courses
2562 foreach ($rhosts as $host) {
2563 print_remote_host($host, "100%");
2569 if ($DB->count_records("course") > (count($courses) + 1) ) { // Some courses not being displayed
2570 echo "<table width=\"100%\"><tr><td align=\"center\">";
2571 print_course_search("", false, "short");
2572 echo "</td><td align=\"center\">";
2573 echo $OUTPUT->single_button("$CFG->wwwroot/course/index.php", get_string("fulllistofcourses"), "get");
2574 echo "</td></tr></table>\n";
2578 if ($DB->count_records("course_categories") > 1) {
2579 echo $OUTPUT->box_start("categorybox");
2580 print_whole_category_list();
2581 echo $OUTPUT->box_end();
2589 function print_course_search($value="", $return=false, $format="plain") {
2595 $id = 'coursesearch';
2601 $strsearchcourses= get_string("searchcourses");
2603 if ($format == 'plain') {
2604 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2605 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2606 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
2607 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" value="'.s($value).'" />';
2608 $output .= '<input type="submit" value="'.get_string('go').'" />';
2609 $output .= '</fieldset></form>';
2610 } else if ($format == 'short') {
2611 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2612 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2613 $output .= '<label for="shortsearchbox">'.$strsearchcourses.': </label>';
2614 $output .= '<input type="text" id="shortsearchbox" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2615 $output .= '<input type="submit" value="'.get_string('go').'" />';
2616 $output .= '</fieldset></form>';
2617 } else if ($format == 'navbar') {
2618 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2619 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2620 $output .= '<label for="navsearchbox">'.$strsearchcourses.': </label>';
2621 $output .= '<input type="text" id="navsearchbox" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2622 $output .= '<input type="submit" value="'.get_string('go').'" />';
2623 $output .= '</fieldset></form>';
2632 function print_remote_course($course, $width="100%") {
2637 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&wantsurl=/course/view.php?id={$course->remoteid}";
2639 echo '<div class="coursebox remotecoursebox clearfix">';
2640 echo '<div class="info">';
2641 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2642 $linkcss.' href="'.$url.'">'
2643 . format_string($course->fullname) .'</a><br />'
2644 . format_string($course->hostname) . ' : '
2645 . format_string($course->cat_name) . ' : '
2646 . format_string($course->shortname). '</div>';
2647 echo '</div><div class="summary">';
2648 $options = new stdClass();
2649 $options->noclean = true;
2650 $options->para = false;
2651 $options->overflowdiv = true;
2652 echo format_text($course->summary, $course->summaryformat, $options);
2657 function print_remote_host($host, $width="100%") {
2662 echo '<div class="coursebox clearfix">';
2663 echo '<div class="info">';
2664 echo '<div class="name">';
2665 echo '<img src="'.$OUTPUT->pix_url('i/mnethost') . '" class="icon" alt="'.get_string('course').'" />';
2666 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2667 . s($host['name']).'</a> - ';
2668 echo $host['count'] . ' ' . get_string('courses');
2675 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2677 function add_course_module($mod) {
2680 $mod->added = time();
2683 $cmid = $DB->insert_record("course_modules", $mod);
2684 rebuild_course_cache($mod->course, true);
2689 * Creates missing course section(s) and rebuilds course cache
2691 * @param int|stdClass $courseorid course id or course object
2692 * @param int|array $sections list of relative section numbers to create
2693 * @return bool if there were any sections created
2695 function course_create_sections_if_missing($courseorid, $sections) {
2697 if (!is_array($sections)) {
2698 $sections = array($sections);
2700 $existing = array_keys(get_fast_modinfo($courseorid)->get_section_info_all());
2701 if (is_object($courseorid)) {
2702 $courseorid = $courseorid->id;
2704 $coursechanged = false;
2705 foreach ($sections as $sectionnum) {
2706 if (!in_array($sectionnum, $existing)) {
2707 $cw = new stdClass();
2708 $cw->course = $courseorid;
2709 $cw->section = $sectionnum;
2711 $cw->summaryformat = FORMAT_HTML;
2713 $id = $DB->insert_record("course_sections", $cw);
2714 $coursechanged = true;
2717 if ($coursechanged) {
2718 rebuild_course_cache($courseorid, true);
2720 return $coursechanged;
2724 * Adds an existing module to the section
2726 * Updates both tables {course_sections} and {course_modules}
2728 * @param int|stdClass $courseorid course id or course object
2729 * @param int $cmid id of the module already existing in course_modules table
2730 * @param int $sectionnum relative number of the section (field course_sections.section)
2731 * If section does not exist it will be created
2732 * @param int|stdClass $beforemod id or object with field id corresponding to the module
2733 * before which the module needs to be included. Null for inserting in the
2734 * end of the section
2735 * @return int The course_sections ID where the module is inserted
2737 function course_add_cm_to_section($courseorid, $cmid, $sectionnum, $beforemod = null) {
2738 global $DB, $COURSE;
2739 if (is_object($beforemod)) {
2740 $beforemod = $beforemod->id;
2742 if (is_object($courseorid)) {
2743 $courseid = $courseorid->id;
2745 $courseid = $courseorid;
2747 course_create_sections_if_missing($courseorid, $sectionnum);
2748 // Do not try to use modinfo here, there is no guarantee it is valid!
2749 $section = $DB->get_record('course_sections', array('course'=>$courseid, 'section'=>$sectionnum), '*', MUST_EXIST);
2750 $modarray = explode(",", trim($section->sequence));
2751 if (empty($section->sequence)) {
2752 $newsequence = "$cmid";
2753 } else if ($beforemod && ($key = array_keys($modarray, $beforemod))) {
2754 $insertarray = array($cmid, $beforemod);
2755 array_splice($modarray, $key[0], 1, $insertarray);
2756 $newsequence = implode(",", $modarray);
2758 $newsequence = "$section->sequence,$cmid";
2760 $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id));
2761 $DB->set_field('course_modules', 'section', $section->id, array('id' => $cmid));
2762 if (is_object($courseorid)) {
2763 rebuild_course_cache($courseorid->id, true);
2765 rebuild_course_cache($courseorid, true);
2767 return $section->id; // Return course_sections ID that was used.
2770 function set_coursemodule_groupmode($id, $groupmode) {
2772 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST);
2773 if ($cm->groupmode != $groupmode) {
2774 $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id));
2775 rebuild_course_cache($cm->course, true);
2777 return ($cm->groupmode != $groupmode);
2780 function set_coursemodule_idnumber($id, $idnumber) {
2782 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST);
2783 if ($cm->idnumber != $idnumber) {
2784 $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id));
2785 rebuild_course_cache($cm->course, true);
2787 return ($cm->idnumber != $idnumber);
2791 * Set the visibility of a module and inherent properties.
2793 * From 2.4 the parameter $prevstateoverrides has been removed, the logic it triggered
2794 * has been moved to {@link set_section_visible()} which was the only place from which
2795 * the parameter was used.
2797 * @param int $id of the module
2798 * @param int $visible state of the module
2799 * @return bool false when the module was not found, true otherwise
2801 function set_coursemodule_visible($id, $visible) {
2803 require_once($CFG->libdir.'/gradelib.php');
2805 // Trigger developer's attention when using the previously removed argument.
2806 if (func_num_args() > 2) {
2807 debugging('Wrong number of arguments passed to set_coursemodule_visible(), $prevstateoverrides
2808 has been removed.', DEBUG_DEVELOPER);
2811 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2814 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
2817 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2818 foreach($events as $event) {
2827 // hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there
2828 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
2830 foreach ($grade_items as $grade_item) {
2831 $grade_item->set_hidden(!$visible);
2835 // Updating visible and visibleold to keep them in sync. Only changing a section visibility will
2836 // affect visibleold to allow for an original visibility restore. See set_section_visible().
2837 $cminfo = new stdClass();
2839 $cminfo->visible = $visible;
2840 $cminfo->visibleold = $visible;
2841 $DB->update_record('course_modules', $cminfo);
2843 rebuild_course_cache($cm->course, true);
2848 * Delete a course module and any associated data at the course level (events)
2849 * Until 1.5 this function simply marked a deleted flag ... now it
2850 * deletes it completely.
2853 function delete_course_module($id) {
2855 require_once($CFG->libdir.'/gradelib.php');
2856 require_once($CFG->dirroot.'/blog/lib.php');
2858 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2861 $modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module));
2862 //delete events from calendar
2863 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2864 foreach($events as $event) {
2865 delete_event($event->id);
2868 //delete grade items, outcome items and grades attached to modules
2869 if ($grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2870 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course))) {
2871 foreach ($grade_items as $grade_item) {
2872 $grade_item->delete('moddelete');
2875 // Delete completion and availability data; it is better to do this even if the
2876 // features are not turned on, in case they were turned on previously (these will be
2877 // very quick on an empty table)
2878 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
2879 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id));
2880 $DB->delete_records('course_modules_avail_fields', array('coursemoduleid' => $cm->id));
2881 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
2882 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
2884 delete_context(CONTEXT_MODULE, $cm->id);
2885 $DB->delete_records('course_modules', array('id'=>$cm->id));
2886 rebuild_course_cache($cm->course, true);
2890 function delete_mod_from_section($modid, $sectionid) {
2893 if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
2895 $modarray = explode(",", $section->sequence);
2897 if ($key = array_keys ($modarray, $modid)) {
2898 array_splice($modarray, $key[0], 1);
2899 $newsequence = implode(",", $modarray);
2900 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
2901 rebuild_course_cache($section->course, true);
2912 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
2914 * @param object $course course object
2915 * @param int $section Section number (not id!!!)
2916 * @param int $move (-1 or 1)
2917 * @return boolean true if section moved successfully
2918 * @todo MDL-33379 remove this function in 2.5
2920 function move_section($course, $section, $move) {
2921 debugging('This function will be removed before 2.5 is released please use move_section_to', DEBUG_DEVELOPER);
2923 /// Moves a whole course section up and down within the course
2930 $sectiondest = $section + $move;
2932 // compartibility with course formats using field 'numsections'
2933 $courseformatoptions = course_get_format($course)->get_format_options();
2934 if (array_key_exists('numsections', $courseformatoptions) &&
2935 $sectiondest > $courseformatoptions['numsections'] or $sectiondest < 1) {
2939 $retval = move_section_to($course, $section, $sectiondest);
2944 * Moves a section within a course, from a position to another.
2945 * Be very careful: $section and $destination refer to section number,
2948 * @param object $course
2949 * @param int $section Section number (not id!!!)
2950 * @param int $destination
2951 * @return boolean Result
2953 function move_section_to($course, $section, $destination) {
2954 /// Moves a whole course section up and down within the course
2957 if (!$destination && $destination != 0) {
2961 // compartibility with course formats using field 'numsections'
2962 $courseformatoptions = course_get_format($course)->get_format_options();
2963 if ((array_key_exists('numsections', $courseformatoptions) &&
2964 ($destination > $courseformatoptions['numsections'])) || ($destination < 1)) {
2968 // Get all sections for this course and re-order them (2 of them should now share the same section number)
2969 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
2970 'section ASC, id ASC', 'id, section')) {
2974 $movedsections = reorder_sections($sections, $section, $destination);
2976 // Update all sections. Do this in 2 steps to avoid breaking database
2977 // uniqueness constraint
2978 $transaction = $DB->start_delegated_transaction();
2979 foreach ($movedsections as $id => $position) {
2980 if ($sections[$id] !== $position) {
2981 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
2984 foreach ($movedsections as $id => $position) {
2985 if ($sections[$id] !== $position) {
2986 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
2990 // If we move the highlighted section itself, then just highlight the destination.
2991 // Adjust the higlighted section location if we move something over it either direction.
2992 if ($section == $course->marker) {
2993 course_set_marker($course->id, $destination);
2994 } elseif ($section > $course->marker && $course->marker >= $destination) {
2995 course_set_marker($course->id, $course->marker+1);
2996 } elseif ($section < $course->marker && $course->marker <= $destination) {
2997 course_set_marker($course->id, $course->marker-1);
3000 $transaction->allow_commit();
3001 rebuild_course_cache($course->id, true);
3006 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
3007 * an original position number and a target position number, rebuilds the array so that the
3008 * move is made without any duplication of section positions.
3009 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
3010 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
3012 * @param array $sections
3013 * @param int $origin_position
3014 * @param int $target_position
3017 function reorder_sections($sections, $origin_position, $target_position) {
3018 if (!is_array($sections)) {
3022 // We can't move section position 0
3023 if ($origin_position < 1) {
3024 echo "We can't move section position 0";
3028 // Locate origin section in sections array
3029 if (!$origin_key = array_search($origin_position, $sections)) {
3030 echo "searched position not in sections array";
3031 return false; // searched position not in sections array
3034 // Extract origin section
3035 $origin_section = $sections[$origin_key];
3036 unset($sections[$origin_key]);
3038 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
3040 $append_array = array();
3041 foreach ($sections as $id => $position) {
3043 $append_array[$id] = $position;
3044 unset($sections[$id]);
3046 if ($position == $target_position) {
3047 if ($target_position < $origin_position) {
3048 $append_array[$id] = $position;
3049 unset($sections[$id]);
3055 // Append moved section
3056 $sections[$origin_key] = $origin_section;
3058 // Append rest of array (if applicable)
3059 if (!empty($append_array)) {
3060 foreach ($append_array as $id => $position) {
3061 $sections[$id] = $position;
3065 // Renumber positions
3067 foreach ($sections as $id => $p) {
3068 $sections[$id] = $position;
3077 * Move the module object $mod to the specified $section
3078 * If $beforemod exists then that is the module
3079 * before which $modid should be inserted
3080 * All parameters are objects
3082 function moveto_module($mod, $section, $beforemod=NULL) {
3085 /// Remove original module from original section
3086 if (! delete_mod_from_section($mod->id, $mod->section)) {
3087 echo $OUTPUT->notification("Could not delete module from existing section");
3090 // if moving to a hidden section then hide module
3091 if (!$section->visible && $mod->visible) {
3092 set_coursemodule_visible($mod->id, 0);
3095 /// Add the module into the new section
3096 course_add_cm_to_section($section->course, $mod->id, $section->section, $beforemod);
3101 * Produces the editing buttons for a module
3103 * @global core_renderer $OUTPUT
3104 * @staticvar type $str
3105 * @param stdClass $mod The module to produce editing buttons for
3106 * @param bool $absolute_ignored (argument ignored) - all links are absolute
3107 * @param bool $moveselect (argument ignored)
3108 * @param int $indent The current indenting
3109 * @param int $section The section to link back to
3110 * @return string XHTML for the editing buttons
3112 function make_editing_buttons(stdClass $mod, $absolute_ignored = true, $moveselect = true, $indent=-1, $section=null) {
3114 if (!($mod instanceof cm_info)) {
3115 $modinfo = get_fast_modinfo($mod->course);
3116 $mod = $modinfo->get_cm($mod->id);
3118 $actions = course_get_cm_edit_actions($mod, $indent, $section);
3120 $courserenderer = $PAGE->get_renderer('core', 'course');
3121 // The space added before the <span> is a ugly hack but required to set the CSS property white-space: nowrap
3122 // and having it to work without attaching the preceding text along with it. Hopefully the refactoring of
3123 // the course page HTML will allow this to be removed.
3124 return ' ' . $courserenderer->course_section_cm_edit_actions($actions);
3128 * Returns the list of all editing actions that current user can perform on the module
3130 * @param cm_info $mod The module to produce editing buttons for
3131 * @param int $indent The current indenting (default -1 means no move left-right actions)
3132 * @param int $sr The section to link back to (used for creating the links)
3133 * @return array array of action_link or pix_icon objects
3135 function course_get_cm_edit_actions(cm_info $mod, $indent = -1, $sr = null) {
3136 global $COURSE, $SITE;
3140 $coursecontext = context_course::instance($mod->course);
3141 $modcontext = context_module::instance($mod->id);
3143 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
3144 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
3146 // no permission to edit anything
3147 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
3151 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
3154 $str = get_strings(array('delete', 'move', 'moveright', 'moveleft',
3155 'update', 'duplicate', 'hide', 'show', 'edittitle'), 'moodle');
3156 $str->assign = get_string('assignroles', 'role');
3157 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
3158 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
3159 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
3160 $str->forcedgroupsnone = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsnone"));
3161 $str->forcedgroupsseparate = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsseparate"));
3162 $str->forcedgroupsvisible = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsvisible"));
3165 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
3168 $baseurl->param('sr', $sr);
3173 if ($mod->modname !== 'label' && $hasmanageactivities &&
3174 (($mod->course == $COURSE->id && course_ajax_enabled($COURSE)) ||
3175 ($mod->course == SITEID && course_ajax_enabled($SITE)))) {
3176 // we will not display link if we are on some other-course page (where we should not see this module anyway)
3177 $actions['title'] = new action_link(
3178 new moodle_url($baseurl, array('update' => $mod->id)),
3179 new pix_icon('t/editstring', $str->edittitle, 'moodle', array('class' => 'iconsmall visibleifjs', 'title' => '')),
3181 array('class' => 'editing_title', 'title' => $str->edittitle)
3186 if ($hasmanageactivities) {
3187 if (right_to_left()) { // Exchange arrows on RTL
3188 $rightarrow = 't/left';
3189 $leftarrow = 't/right';
3191 $rightarrow = 't/right';
3192 $leftarrow = 't/left';
3196 $actions['moveleft'] = new action_link(
3197 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
3198 new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3200 array('class' => 'editing_moveleft', 'title' => $str->moveleft)
3204 $actions['moveright'] = new action_link(
3205 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
3206 new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3208 array('class' => 'editing_moveright', 'title' => $str->moveright)
3214 if ($hasmanageactivities) {
3215 $actions['move'] = new action_link(
3216 new moodle_url($baseurl, array('copy' => $mod->id)),
3217 new pix_icon('t/move', $str->move, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3219 array('class' => 'editing_move', 'title' => $str->move)
3224 if ($hasmanageactivities) {
3225 $actions['update'] = new action_link(
3226 new moodle_url($baseurl, array('update' => $mod->id)),
3227 new pix_icon('t/edit', $str->update, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3229 array('class' => 'editing_update', 'title' => $str->update)
3233 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
3234 // note that restoring on front page is never allowed
3235 if ($mod->course != SITEID && has_all_capabilities($dupecaps, $coursecontext) &&
3236 plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2)) {
3237 $actions['duplicate'] = new action_link(
3238 new moodle_url($baseurl, array('duplicate' => $mod->id)),
3239 new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3241 array('class' => 'editing_duplicate', 'title' => $str->duplicate)
3246 if ($hasmanageactivities) {
3247 $actions['delete'] = new action_link(
3248 new moodle_url($baseurl, array('delete' => $mod->id)),
3249 new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3251 array('class' => 'editing_delete', 'title' => $str->delete)
3256 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
3257 if ($mod->visible) {
3258 $actions['hide'] = new action_link(
3259 new moodle_url($baseurl, array('hide' => $mod->id)),
3260 new pix_icon('t/hide', $str->hide, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3262 array('class' => 'editing_hide', 'title' => $str->hide)
3265 $actions['show'] = new action_link(
3266 new moodle_url($baseurl, array('show' => $mod->id)),
3267 new pix_icon('t/show', $str->show, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3269 array('class' => 'editing_show', 'title' => $str->show)
3275 if ($hasmanageactivities and $mod->groupmode !== false) {
3276 if ($mod->groupmode == SEPARATEGROUPS) {
3277 $groupmode = NOGROUPS;
3278 $grouptitle = $str->groupsseparate;
3279 $forcedgrouptitle = $str->forcedgroupsseparate;
3280 $actionname = 'groupsseparate';
3281 $groupimage = 't/groups';
3282 } else if ($mod->groupmode == VISIBLEGROUPS) {
3283 $groupmode = SEPARATEGROUPS;
3284 $grouptitle = $str->groupsvisible;
3285 $forcedgrouptitle = $str->forcedgroupsvisible;
3286 $actionname = 'groupsvisible';
3287 $groupimage = 't/groupv';
3289 $groupmode = VISIBLEGROUPS;
3290 $grouptitle = $str->groupsnone;
3291 $forcedgrouptitle = $str->forcedgroupsnone;
3292 $actionname = 'groupsnone';
3293 $groupimage = 't/groupn';
3295 if ($mod->groupmodelink) {
3296 $actions[$actionname] = new action_link(
3297 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $groupmode)),
3298 new pix_icon($groupimage, $grouptitle, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3300 array('class' => 'editing_'. $actionname, 'title' => $grouptitle)
3303 $actions[$actionname] = new pix_icon($groupimage, $forcedgrouptitle, 'moodle', array('title' => $forcedgrouptitle, 'class' => 'iconsmall'));
3308 if (has_capability('moodle/role:assign', $modcontext)){
3309 $actions['assign'] = new action_link(
3310 new moodle_url('/admin/roles/assign.php', array('contextid' => $modcontext->id)),
3311 new pix_icon('t/assignroles', $str->assign, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3313 array('class' => 'editing_assign', 'title' => $str->assign)
3321 * given a course object with shortname & fullname, this function will
3322 * truncate the the number of chars allowed and add ... if it was too long
3324 function course_format_name ($course,$max=100) {
3326 $context = context_course::instance($course->id);
3327 $shortname = format_string($course->shortname, true, array('context' => $context));
3328 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
3329 $str = $shortname.': '. $fullname;
3330 if (textlib::strlen($str) <= $max) {
3334 return textlib::substr($str,0,$max-3).'...';
3339 * Is the user allowed to add this type of module to this course?
3340 * @param object $course the course settings. Only $course->id is used.
3341 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
3342 * @return bool whether the current user is allowed to add this type of module to this course.
3344 function course_allowed_module($course, $modname) {
3345 if (is_numeric($modname)) {
3346 throw new coding_exception('Function course_allowed_module no longer
3347 supports numeric module ids. Please update your code to pass the module name.');
3350 $capability = 'mod/' . $modname . ':addinstance';
3351 if (!get_capability_info($capability)) {
3352 // Debug warning that the capability does not exist, but no more than once per page.
3353 static $warned = array();
3354 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
3355 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
3356 debugging('The module ' . $modname . ' does not define the standard capability ' .
3357 $capability , DEBUG_DEVELOPER);
3358 $warned[$modname] = 1;
3361 // If the capability does not exist, the module can always be added.
3365 $coursecontext = context_course::instance($course->id);
3366 return has_capability($capability, $coursecontext);
3370 * Recursively delete category including all subcategories and courses.
3371 * @param stdClass $category
3372 * @param boolean $showfeedback display some notices
3373 * @return array return deleted courses
3375 function category_delete_full($category, $showfeedback=true) {
3377 require_once($CFG->libdir.'/gradelib.php');
3378 require_once($CFG->libdir.'/questionlib.php');
3379 require_once($CFG->dirroot.'/cohort/lib.php');
3381 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3382 foreach ($children as $childcat) {
3383 category_delete_full($childcat, $showfeedback);
3387 $deletedcourses = array();
3388 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC')) {
3389 foreach ($courses as $course) {
3390 if (!delete_course($course, false)) {
3391 throw new moodle_exception('cannotdeletecategorycourse','','',$course->shortname);
3393 $deletedcourses[] = $course;
3397 // move or delete cohorts in this context
3398 cohort_delete_category($category);
3400 // now delete anything that may depend on course category context
3401 grade_course_category_delete($category->id, 0, $showfeedback);
3402 if (!question_delete_course_category($category, 0, $showfeedback)) {
3403 throw new moodle_exception('cannotdeletecategoryquestions','','',$category->name);
3406 // finally delete the category and it's context
3407 $DB->delete_records('course_categories', array('id'=>$category->id));
3408 delete_context(CONTEXT_COURSECAT, $category->id);
3410 events_trigger('course_category_deleted', $category);
3412 return $deletedcourses;
3416 * Delete category, but move contents to another category.
3417 * @param object $ccategory
3418 * @param int $newparentid category id
3419 * @return bool status
3421 function category_delete_move($category, $newparentid, $showfeedback=true) {
3422 global $CFG, $DB, $OUTPUT;
3423 require_once($CFG->libdir.'/gradelib.php');
3424 require_once($CFG->libdir.'/questionlib.php');
3425 require_once($CFG->dirroot.'/cohort/lib.php');
3427 if (!$newparentcat = $DB->get_record('course_categories', array('id'=>$newparentid))) {
3431 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3432 foreach ($children as $childcat) {
3433 move_category($childcat, $newparentcat);
3437 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC', 'id')) {
3438 if (!move_courses(array_keys($courses), $newparentid)) {
3439 if ($showfeedback) {
3440 echo $OUTPUT->notification("Error moving courses");
3444 if ($showfeedback) {
3445 echo $OUTPUT->notification(get_string('coursesmovedout', '', format_string($category->name)), 'notifysuccess');
3449 // move or delete cohorts in this context
3450 cohort_delete_category($category);
3452 // now delete anything that may depend on course category context
3453 grade_course_category_delete($category->id, $newparentid, $showfeedback);
3454 if (!question_delete_course_category($category, $newparentcat, $showfeedback)) {
3455 if ($showfeedback) {
3456 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $category), 'notifysuccess');
3461 // finally delete the category and it's context
3462 $DB->delete_records('course_categories', array('id'=>$category->id));
3463 delete_context(CONTEXT_COURSECAT, $category->id);
3465 events_trigger('course_category_deleted', $category);
3467 if ($showfeedback) {
3468 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', format_string($category->name)), 'notifysuccess');
3474 * Efficiently moves many courses around while maintaining
3475 * sortorder in order.
3477 * @param array $courseids is an array of course ids
3478 * @param int $categoryid