3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * Library of useful functions
21 * @copyright 1999 Martin Dougiamas http://dougiamas.com
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') || die;
29 require_once($CFG->libdir.'/completionlib.php');
30 require_once($CFG->libdir.'/filelib.php');
31 require_once($CFG->dirroot.'/course/dnduploadlib.php');
32 require_once($CFG->dirroot.'/course/format/lib.php');
34 define('COURSE_MAX_LOGS_PER_PAGE', 1000); // records
35 define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds
38 * Number of courses to display when summaries are included.
40 * @deprecated since 2.4, use $CFG->courseswithsummarieslimit instead.
42 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10);
44 define('COURSE_MAX_COURSES_PER_DROPDOWN',1000); // max courses in log dropdown before switching to optional
45 define('COURSE_MAX_USERS_PER_DROPDOWN',1000); // max users in log dropdown before switching to optional
46 define('FRONTPAGENEWS', '0');
47 define('FRONTPAGECOURSELIST', '1');
48 define('FRONTPAGECATEGORYNAMES', '2');
49 define('FRONTPAGETOPICONLY', '3');
50 define('FRONTPAGECATEGORYCOMBO', '4');
51 define('FRONTPAGECOURSELIMIT', 200); // maximum number of courses displayed on the frontpage
52 define('EXCELROWS', 65535);
53 define('FIRSTUSEDEXCELROW', 3);
55 define('MOD_CLASS_ACTIVITY', 0);
56 define('MOD_CLASS_RESOURCE', 1);
58 function make_log_url($module, $url) {
61 if (strpos($url, 'report/') === 0) {
62 // there is only one report type, course reports are deprecated
72 if (strpos($url, '../') === 0) {
73 $url = ltrim($url, '.');
75 $url = "/course/$url";
80 $url = "/$module/$url";
93 $url = "/message/$url";
105 $url = "/mod/$module/$url";
109 //now let's sanitise urls - there might be some ugly nasties:-(
110 $parts = explode('?', $url);
111 $script = array_shift($parts);
112 if (strpos($script, 'http') === 0) {
113 $script = clean_param($script, PARAM_URL);
115 $script = clean_param($script, PARAM_PATH);
120 $query = implode('', $parts);
121 $query = str_replace('&', '&', $query); // both & and & are stored in db :-|
122 $parts = explode('&', $query);
123 $eq = urlencode('=');
124 foreach ($parts as $key=>$part) {
125 $part = urlencode(urldecode($part));
126 $part = str_replace($eq, '=', $part);
127 $parts[$key] = $part;
129 $query = '?'.implode('&', $parts);
132 return $script.$query;
136 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
137 $modname="", $modid=0, $modaction="", $groupid=0) {
140 // It is assumed that $date is the GMT time of midnight for that day,
141 // and so the next 86400 seconds worth of logs are printed.
143 /// Setup for group handling.
145 // TODO: I don't understand group/context/etc. enough to be able to do
146 // something interesting with it here
147 // What is the context of a remote course?
149 /// If the group mode is separate, and this user does not have editing privileges,
150 /// then only the user's group can be viewed.
151 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
152 // $groupid = get_current_group($course->id);
154 /// If this course doesn't have groups, no groupid can be specified.
155 //else if (!$course->groupmode) {
164 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
166 LEFT JOIN {user} u ON l.userid = u.id
170 $where .= "l.hostid = :hostid";
171 $params['hostid'] = $hostid;
173 // TODO: Is 1 really a magic number referring to the sitename?
174 if ($course != SITEID || $modid != 0) {
175 $where .= " AND l.course=:courseid";
176 $params['courseid'] = $course;
180 $where .= " AND l.module = :modname";
181 $params['modname'] = $modname;
184 if ('site_errors' === $modid) {
185 $where .= " AND ( l.action='error' OR l.action='infected' )";
187 //TODO: This assumes that modids are the same across sites... probably
189 $where .= " AND l.cmid = :modid";
190 $params['modid'] = $modid;
194 $firstletter = substr($modaction, 0, 1);
195 if ($firstletter == '-') {
196 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
197 $params['modaction'] = '%'.substr($modaction, 1).'%';
199 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
200 $params['modaction'] = '%'.$modaction.'%';
205 $where .= " AND l.userid = :user";
206 $params['user'] = $user;
210 $enddate = $date + 86400;
211 $where .= " AND l.time > :date AND l.time < :enddate";
212 $params['date'] = $date;
213 $params['enddate'] = $enddate;
217 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
218 if(!empty($result['totalcount'])) {
219 $where .= " ORDER BY $order";
220 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
222 $result['logs'] = array();
227 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
228 $modname="", $modid=0, $modaction="", $groupid=0) {
229 global $DB, $SESSION, $USER;
230 // It is assumed that $date is the GMT time of midnight for that day,
231 // and so the next 86400 seconds worth of logs are printed.
233 /// Setup for group handling.
235 /// If the group mode is separate, and this user does not have editing privileges,
236 /// then only the user's group can be viewed.
237 if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
238 if (isset($SESSION->currentgroup[$course->id])) {
239 $groupid = $SESSION->currentgroup[$course->id];
241 $groupid = groups_get_all_groups($course->id, $USER->id);
242 if (is_array($groupid)) {
243 $groupid = array_shift(array_keys($groupid));
244 $SESSION->currentgroup[$course->id] = $groupid;
250 /// If this course doesn't have groups, no groupid can be specified.
251 else if (!$course->groupmode) {
258 if ($course->id != SITEID || $modid != 0) {
259 $joins[] = "l.course = :courseid";
260 $params['courseid'] = $course->id;
264 $joins[] = "l.module = :modname";
265 $params['modname'] = $modname;
268 if ('site_errors' === $modid) {
269 $joins[] = "( l.action='error' OR l.action='infected' )";
271 $joins[] = "l.cmid = :modid";
272 $params['modid'] = $modid;
276 $firstletter = substr($modaction, 0, 1);
277 if ($firstletter == '-') {
278 $joins[] = $DB->sql_like('l.action', ':modaction', false, true, true);
279 $params['modaction'] = '%'.substr($modaction, 1).'%';
281 $joins[] = $DB->sql_like('l.action', ':modaction', false);
282 $params['modaction'] = '%'.$modaction.'%';
287 /// Getting all members of a group.
288 if ($groupid and !$user) {
289 if ($gusers = groups_get_members($groupid)) {
290 $gusers = array_keys($gusers);
291 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
293 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
297 $joins[] = "l.userid = :userid";
298 $params['userid'] = $user;
302 $enddate = $date + 86400;
303 $joins[] = "l.time > :date AND l.time < :enddate";
304 $params['date'] = $date;
305 $params['enddate'] = $enddate;
308 $selector = implode(' AND ', $joins);
310 $totalcount = 0; // Initialise
312 $result['logs'] = get_logs($selector, $params, $order, $limitfrom, $limitnum, $totalcount);
313 $result['totalcount'] = $totalcount;
318 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
319 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
321 global $CFG, $DB, $OUTPUT;
323 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
324 $modname, $modid, $modaction, $groupid)) {
325 echo $OUTPUT->notification("No logs found!");
326 echo $OUTPUT->footer();
332 if ($course->id == SITEID) {
334 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
335 foreach ($ccc as $cc) {
336 $courses[$cc->id] = $cc->shortname;
340 $courses[$course->id] = $course->shortname;
343 $totalcount = $logs['totalcount'];
346 $tt = getdate(time());
347 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
349 $strftimedatetime = get_string("strftimedatetime");
351 echo "<div class=\"info\">\n";
352 print_string("displayingrecords", "", $totalcount);
355 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
357 $table = new html_table();
358 $table->classes = array('logtable','generalbox');
359 $table->align = array('right', 'left', 'left');
360 $table->head = array(
362 get_string('ip_address'),
363 get_string('fullnameuser'),
364 get_string('action'),
367 $table->data = array();
369 if ($course->id == SITEID) {
370 array_unshift($table->align, 'left');
371 array_unshift($table->head, get_string('course'));
374 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
375 if (empty($logs['logs'])) {
376 $logs['logs'] = array();
379 foreach ($logs['logs'] as $log) {
381 if (isset($ldcache[$log->module][$log->action])) {
382 $ld = $ldcache[$log->module][$log->action];
384 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
385 $ldcache[$log->module][$log->action] = $ld;
387 if ($ld && is_numeric($log->info)) {
388 // ugly hack to make sure fullname is shown correctly
389 if ($ld->mtable == 'user' && $ld->field == $DB->sql_concat('firstname', "' '" , 'lastname')) {
390 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
392 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
397 $log->info = format_string($log->info);
399 // If $log->url has been trimmed short by the db size restriction
400 // code in add_to_log, keep a note so we don't add a link to a broken url
401 $brokenurl=(textlib::strlen($log->url)==100 && textlib::substr($log->url,97)=='...');
404 if ($course->id == SITEID) {
405 if (empty($log->course)) {
406 $row[] = get_string('site');
408 $row[] = "<a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course])."</a>";
412 $row[] = userdate($log->time, '%a').' '.userdate($log->time, $strftimedatetime);
414 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
415 $row[] = $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 440, 'width' => 700)));
417 $row[] = html_writer::link(new moodle_url("/user/view.php?id={$log->userid}&course={$log->course}"), fullname($log, has_capability('moodle/site:viewfullnames', context_course::instance($course->id))));
419 $displayaction="$log->module $log->action";
421 $row[] = $displayaction;
423 $link = make_log_url($log->module,$log->url);
424 $row[] = $OUTPUT->action_link($link, $displayaction, new popup_action('click', $link, 'fromloglive'), array('height' => 440, 'width' => 700));
427 $table->data[] = $row;
430 echo html_writer::table($table);
431 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
435 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
436 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
438 global $CFG, $DB, $OUTPUT;
440 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
441 $modname, $modid, $modaction, $groupid)) {
442 echo $OUTPUT->notification("No logs found!");
443 echo $OUTPUT->footer();
447 if ($course->id == SITEID) {
449 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
450 foreach ($ccc as $cc) {
451 $courses[$cc->id] = $cc->shortname;
456 $totalcount = $logs['totalcount'];
459 $tt = getdate(time());
460 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
462 $strftimedatetime = get_string("strftimedatetime");
464 echo "<div class=\"info\">\n";
465 print_string("displayingrecords", "", $totalcount);
468 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
470 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
472 if ($course->id == SITEID) {
473 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
475 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
476 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
477 echo "<th class=\"c3 header\">".get_string('fullnameuser')."</th>\n";
478 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
479 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
482 if (empty($logs['logs'])) {
488 foreach ($logs['logs'] as $log) {
490 $log->info = $log->coursename;
491 $row = ($row + 1) % 2;
493 if (isset($ldcache[$log->module][$log->action])) {
494 $ld = $ldcache[$log->module][$log->action];
496 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
497 $ldcache[$log->module][$log->action] = $ld;
499 if (0 && $ld && !empty($log->info)) {
500 // ugly hack to make sure fullname is shown correctly
501 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
502 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
504 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
509 $log->info = format_string($log->info);
511 echo '<tr class="r'.$row.'">';
512 if ($course->id == SITEID) {
513 $courseshortname = format_string($courses[$log->course], true, array('context' => context_course::instance(SITEID)));
514 echo "<td class=\"r$row c0\" >\n";
515 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courseshortname."</a>\n";
518 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time, '%a').
519 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
520 echo "<td class=\"r$row c2\" >\n";
521 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
522 echo $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 400, 'width' => 700)));
524 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', context_course::instance($course->id)));
525 echo "<td class=\"r$row c3\" >\n";
526 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
528 echo "<td class=\"r$row c4\">\n";
529 echo $log->action .': '.$log->module;
531 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
536 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
540 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
541 $modid, $modaction, $groupid) {
544 require_once($CFG->libdir . '/csvlib.class.php');
546 $csvexporter = new csv_export_writer('tab');
549 $header[] = get_string('course');
550 $header[] = get_string('time');
551 $header[] = get_string('ip_address');
552 $header[] = get_string('fullnameuser');
553 $header[] = get_string('action');
554 $header[] = get_string('info');
556 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
557 $modname, $modid, $modaction, $groupid)) {
563 if ($course->id == SITEID) {
565 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
566 foreach ($ccc as $cc) {
567 $courses[$cc->id] = $cc->shortname;
571 $courses[$course->id] = $course->shortname;
576 $tt = getdate(time());
577 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
579 $strftimedatetime = get_string("strftimedatetime");
581 $csvexporter->set_filename('logs', '.txt');
582 $title = array(get_string('savedat').userdate(time(), $strftimedatetime));
583 $csvexporter->add_data($title);
584 $csvexporter->add_data($header);
586 if (empty($logs['logs'])) {
590 foreach ($logs['logs'] as $log) {
591 if (isset($ldcache[$log->module][$log->action])) {
592 $ld = $ldcache[$log->module][$log->action];
594 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
595 $ldcache[$log->module][$log->action] = $ld;
597 if ($ld && !empty($log->info)) {
598 // ugly hack to make sure fullname is shown correctly
599 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
600 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
602 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
607 $log->info = format_string($log->info);
608 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
610 $coursecontext = context_course::instance($course->id);
611 $firstField = format_string($courses[$log->course], true, array('context' => $coursecontext));
612 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
613 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
614 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action.' ('.$actionurl.')', $log->info);
615 $csvexporter->add_data($row);
617 $csvexporter->download_file();
622 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
623 $modid, $modaction, $groupid) {
627 require_once("$CFG->libdir/excellib.class.php");
629 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
630 $modname, $modid, $modaction, $groupid)) {
636 if ($course->id == SITEID) {
638 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
639 foreach ($ccc as $cc) {
640 $courses[$cc->id] = $cc->shortname;
644 $courses[$course->id] = $course->shortname;
649 $tt = getdate(time());
650 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
652 $strftimedatetime = get_string("strftimedatetime");
654 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
655 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
658 $workbook = new MoodleExcelWorkbook('-');
659 $workbook->send($filename);
661 $worksheet = array();
662 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
663 get_string('fullnameuser'), get_string('action'), get_string('info'));
665 // Creating worksheets
666 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
667 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
668 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
669 $worksheet[$wsnumber]->set_column(1, 1, 30);
670 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
671 userdate(time(), $strftimedatetime));
673 foreach ($headers as $item) {
674 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
679 if (empty($logs['logs'])) {
684 $formatDate =& $workbook->add_format();
685 $formatDate->set_num_format(get_string('log_excel_date_format'));
687 $row = FIRSTUSEDEXCELROW;
689 $myxls =& $worksheet[$wsnumber];
690 foreach ($logs['logs'] as $log) {
691 if (isset($ldcache[$log->module][$log->action])) {
692 $ld = $ldcache[$log->module][$log->action];
694 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
695 $ldcache[$log->module][$log->action] = $ld;
697 if ($ld && !empty($log->info)) {
698 // ugly hack to make sure fullname is shown correctly
699 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
700 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
702 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
707 $log->info = format_string($log->info);
708 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
711 if ($row > EXCELROWS) {
713 $myxls =& $worksheet[$wsnumber];
714 $row = FIRSTUSEDEXCELROW;
718 $coursecontext = context_course::instance($course->id);
720 $myxls->write($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)), '');
721 $myxls->write_date($row, 1, $log->time, $formatDate); // write_date() does conversion/timezone support. MDL-14934
722 $myxls->write($row, 2, $log->ip, '');
723 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
724 $myxls->write($row, 3, $fullname, '');
725 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
726 $myxls->write($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')', '');
727 $myxls->write($row, 5, $log->info, '');
736 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
737 $modid, $modaction, $groupid) {
741 require_once("$CFG->libdir/odslib.class.php");
743 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
744 $modname, $modid, $modaction, $groupid)) {
750 if ($course->id == SITEID) {
752 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
753 foreach ($ccc as $cc) {
754 $courses[$cc->id] = $cc->shortname;
758 $courses[$course->id] = $course->shortname;
763 $tt = getdate(time());
764 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
766 $strftimedatetime = get_string("strftimedatetime");
768 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
769 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
772 $workbook = new MoodleODSWorkbook('-');
773 $workbook->send($filename);
775 $worksheet = array();
776 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
777 get_string('fullnameuser'), get_string('action'), get_string('info'));
779 // Creating worksheets
780 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
781 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
782 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
783 $worksheet[$wsnumber]->set_column(1, 1, 30);
784 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
785 userdate(time(), $strftimedatetime));
787 foreach ($headers as $item) {
788 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
793 if (empty($logs['logs'])) {
798 $formatDate =& $workbook->add_format();
799 $formatDate->set_num_format(get_string('log_excel_date_format'));
801 $row = FIRSTUSEDEXCELROW;
803 $myxls =& $worksheet[$wsnumber];
804 foreach ($logs['logs'] as $log) {
805 if (isset($ldcache[$log->module][$log->action])) {
806 $ld = $ldcache[$log->module][$log->action];
808 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
809 $ldcache[$log->module][$log->action] = $ld;
811 if ($ld && !empty($log->info)) {
812 // ugly hack to make sure fullname is shown correctly
813 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
814 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
816 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
821 $log->info = format_string($log->info);
822 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
825 if ($row > EXCELROWS) {
827 $myxls =& $worksheet[$wsnumber];
828 $row = FIRSTUSEDEXCELROW;
832 $coursecontext = context_course::instance($course->id);
834 $myxls->write_string($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)));
835 $myxls->write_date($row, 1, $log->time);
836 $myxls->write_string($row, 2, $log->ip);
837 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
838 $myxls->write_string($row, 3, $fullname);
839 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
840 $myxls->write_string($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')');
841 $myxls->write_string($row, 5, $log->info);
851 function print_overview($courses, array $remote_courses=array()) {
852 global $CFG, $USER, $DB, $OUTPUT;
854 $htmlarray = array();
855 if ($modules = $DB->get_records('modules')) {
856 foreach ($modules as $mod) {
857 if (file_exists(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php')) {
858 include_once(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php');
859 $fname = $mod->name.'_print_overview';
860 if (function_exists($fname)) {
861 $fname($courses,$htmlarray);
866 foreach ($courses as $course) {
867 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
868 echo $OUTPUT->box_start('coursebox');
869 $attributes = array('title' => s($fullname));
870 if (empty($course->visible)) {
871 $attributes['class'] = 'dimmed';
873 echo $OUTPUT->heading(html_writer::link(
874 new moodle_url('/course/view.php', array('id' => $course->id)), $fullname, $attributes), 3);
875 if (array_key_exists($course->id,$htmlarray)) {
876 foreach ($htmlarray[$course->id] as $modname => $html) {
880 echo $OUTPUT->box_end();
883 if (!empty($remote_courses)) {
884 echo $OUTPUT->heading(get_string('remotecourses', 'mnet'));
886 foreach ($remote_courses as $course) {
887 echo $OUTPUT->box_start('coursebox');
888 $attributes = array('title' => s($course->fullname));
889 echo $OUTPUT->heading(html_writer::link(
890 new moodle_url('/auth/mnet/jump.php', array('hostid' => $course->hostid, 'wantsurl' => '/course/view.php?id='.$course->remoteid)),
891 format_string($course->shortname),
892 $attributes) . ' (' . format_string($course->hostname) . ')', 3);
893 echo $OUTPUT->box_end();
899 * This function trawls through the logs looking for
900 * anything new since the user's last login
902 function print_recent_activity($course) {
903 // $course is an object
904 global $CFG, $USER, $SESSION, $DB, $OUTPUT;
906 $context = context_course::instance($course->id);
908 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
910 $timestart = round(time() - COURSE_MAX_RECENT_PERIOD, -2); // better db caching for guests - 100 seconds
912 if (!isguestuser()) {
913 if (!empty($USER->lastcourseaccess[$course->id])) {
914 if ($USER->lastcourseaccess[$course->id] > $timestart) {
915 $timestart = $USER->lastcourseaccess[$course->id];
920 echo '<div class="activitydate">';
921 echo get_string('activitysince', '', userdate($timestart));
923 echo '<div class="activityhead">';
925 echo '<a href="'.$CFG->wwwroot.'/course/recent.php?id='.$course->id.'">'.get_string('recentactivityreport').'</a>';
931 /// Firstly, have there been any new enrolments?
933 $users = get_recent_enrolments($course->id, $timestart);
935 //Accessibility: new users now appear in an <OL> list.
937 echo '<div class="newusers">';
938 echo $OUTPUT->heading(get_string("newusers").':', 3);
940 echo "<ol class=\"list\">\n";
941 foreach ($users as $user) {
942 $fullname = fullname($user, $viewfullnames);
943 echo '<li class="name"><a href="'."$CFG->wwwroot/user/view.php?id=$user->id&course=$course->id\">$fullname</a></li>\n";
945 echo "</ol>\n</div>\n";
948 /// Next, have there been any modifications to the course structure?
950 $modinfo = get_fast_modinfo($course);
952 $changelist = array();
954 $logs = $DB->get_records_select('log', "time > ? AND course = ? AND
955 module = 'course' AND
956 (action = 'add mod' OR action = 'update mod' OR action = 'delete mod')",
957 array($timestart, $course->id), "id ASC");
960 $actions = array('add mod', 'update mod', 'delete mod');
961 $newgones = array(); // added and later deleted items
962 foreach ($logs as $key => $log) {
963 if (!in_array($log->action, $actions)) {
966 $info = explode(' ', $log->info);
968 // note: in most cases I replaced hardcoding of label with use of
969 // $cm->has_view() but it was not possible to do this here because
970 // we don't necessarily have the $cm for it
971 if ($info[0] == 'label') { // Labels are ignored in recent activity
975 if (count($info) != 2) {
976 debugging("Incorrect log entry info: id = ".$log->id, DEBUG_DEVELOPER);
981 $instanceid = $info[1];
983 if ($log->action == 'delete mod') {
984 // unfortunately we do not know if the mod was visible
985 if (!array_key_exists($log->info, $newgones)) {
986 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $modname));
987 $changelist[$log->info] = array ('operation' => 'delete', 'text' => $strdeleted);
990 if (!isset($modinfo->instances[$modname][$instanceid])) {
991 if ($log->action == 'add mod') {
992 // do not display added and later deleted activities
993 $newgones[$log->info] = true;
997 $cm = $modinfo->instances[$modname][$instanceid];
998 if (!$cm->uservisible) {
1002 if ($log->action == 'add mod') {
1003 $stradded = get_string('added', 'moodle', get_string('modulename', $modname));
1004 $changelist[$log->info] = array('operation' => 'add', 'text' => "$stradded:<br /><a href=\"$CFG->wwwroot/mod/$cm->modname/view.php?id={$cm->id}\">".format_string($cm->name, true)."</a>");
1006 } else if ($log->action == 'update mod' and empty($changelist[$log->info])) {
1007 $strupdated = get_string('updated', 'moodle', get_string('modulename', $modname));
1008 $changelist[$log->info] = array('operation' => 'update', 'text' => "$strupdated:<br /><a href=\"$CFG->wwwroot/mod/$cm->modname/view.php?id={$cm->id}\">".format_string($cm->name, true)."</a>");
1014 if (!empty($changelist)) {
1015 echo $OUTPUT->heading(get_string("courseupdates").':', 3);
1017 foreach ($changelist as $changeinfo => $change) {
1018 echo '<p class="activity">'.$change['text'].'</p>';
1022 /// Now display new things from each module
1024 $usedmodules = array();
1025 foreach($modinfo->cms as $cm) {
1026 if (isset($usedmodules[$cm->modname])) {
1029 if (!$cm->uservisible) {
1032 $usedmodules[$cm->modname] = $cm->modname;
1035 foreach ($usedmodules as $modname) { // Each module gets it's own logs and prints them
1036 if (file_exists($CFG->dirroot.'/mod/'.$modname.'/lib.php')) {
1037 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
1038 $print_recent_activity = $modname.'_print_recent_activity';
1039 if (function_exists($print_recent_activity)) {
1040 // NOTE: original $isteacher (second parameter below) was replaced with $viewfullnames!
1041 $content = $print_recent_activity($course, $viewfullnames, $timestart) || $content;
1044 debugging("Missing lib.php in lib/{$modname} - please reinstall files or uninstall the module");
1049 echo '<p class="message">'.get_string('nothingnew').'</p>';
1054 * For a given course, returns an array of course activity objects
1055 * Each item in the array contains he following properties:
1057 function get_array_of_activities($courseid) {
1058 // cm - course module id
1059 // mod - name of the module (eg forum)
1060 // section - the number of the section (eg week or topic)
1061 // name - the name of the instance
1062 // visible - is the instance visible or not
1063 // groupingid - grouping id
1064 // groupmembersonly - is this instance visible to group members only
1065 // extra - contains extra string to include in any link
1067 if(!empty($CFG->enableavailability)) {
1068 require_once($CFG->libdir.'/conditionlib.php');
1071 $course = $DB->get_record('course', array('id'=>$courseid));
1073 if (empty($course)) {
1074 throw new moodle_exception('courseidnotfound');
1079 $rawmods = get_course_mods($courseid);
1080 if (empty($rawmods)) {
1081 return $mod; // always return array
1084 if ($sections = $DB->get_records("course_sections", array("course"=>$courseid), "section ASC")) {
1085 foreach ($sections as $section) {
1086 if (!empty($section->sequence)) {
1087 $sequence = explode(",", $section->sequence);
1088 foreach ($sequence as $seq) {
1089 if (empty($rawmods[$seq])) {
1092 $mod[$seq] = new stdClass();
1093 $mod[$seq]->id = $rawmods[$seq]->instance;
1094 $mod[$seq]->cm = $rawmods[$seq]->id;
1095 $mod[$seq]->mod = $rawmods[$seq]->modname;
1097 // Oh dear. Inconsistent names left here for backward compatibility.
1098 $mod[$seq]->section = $section->section;
1099 $mod[$seq]->sectionid = $rawmods[$seq]->section;
1101 $mod[$seq]->module = $rawmods[$seq]->module;
1102 $mod[$seq]->added = $rawmods[$seq]->added;
1103 $mod[$seq]->score = $rawmods[$seq]->score;
1104 $mod[$seq]->idnumber = $rawmods[$seq]->idnumber;
1105 $mod[$seq]->visible = $rawmods[$seq]->visible;
1106 $mod[$seq]->visibleold = $rawmods[$seq]->visibleold;
1107 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
1108 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
1109 $mod[$seq]->groupmembersonly = $rawmods[$seq]->groupmembersonly;
1110 $mod[$seq]->indent = $rawmods[$seq]->indent;
1111 $mod[$seq]->completion = $rawmods[$seq]->completion;
1112 $mod[$seq]->extra = "";
1113 $mod[$seq]->completiongradeitemnumber =
1114 $rawmods[$seq]->completiongradeitemnumber;
1115 $mod[$seq]->completionview = $rawmods[$seq]->completionview;
1116 $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected;
1117 $mod[$seq]->availablefrom = $rawmods[$seq]->availablefrom;
1118 $mod[$seq]->availableuntil = $rawmods[$seq]->availableuntil;
1119 $mod[$seq]->showavailability = $rawmods[$seq]->showavailability;
1120 $mod[$seq]->showdescription = $rawmods[$seq]->showdescription;
1121 if (!empty($CFG->enableavailability)) {
1122 condition_info::fill_availability_conditions($rawmods[$seq]);
1123 $mod[$seq]->conditionscompletion = $rawmods[$seq]->conditionscompletion;
1124 $mod[$seq]->conditionsgrade = $rawmods[$seq]->conditionsgrade;
1125 $mod[$seq]->conditionsfield = $rawmods[$seq]->conditionsfield;
1128 $modname = $mod[$seq]->mod;
1129 $functionname = $modname."_get_coursemodule_info";
1131 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
1135 include_once("$CFG->dirroot/mod/$modname/lib.php");
1137 if ($hasfunction = function_exists($functionname)) {
1138 if ($info = $functionname($rawmods[$seq])) {
1139 if (!empty($info->icon)) {
1140 $mod[$seq]->icon = $info->icon;
1142 if (!empty($info->iconcomponent)) {
1143 $mod[$seq]->iconcomponent = $info->iconcomponent;
1145 if (!empty($info->name)) {
1146 $mod[$seq]->name = $info->name;
1148 if ($info instanceof cached_cm_info) {
1149 // When using cached_cm_info you can include three new fields
1150 // that aren't available for legacy code
1151 if (!empty($info->content)) {
1152 $mod[$seq]->content = $info->content;
1154 if (!empty($info->extraclasses)) {
1155 $mod[$seq]->extraclasses = $info->extraclasses;
1157 if (!empty($info->iconurl)) {
1158 $mod[$seq]->iconurl = $info->iconurl;
1160 if (!empty($info->onclick)) {
1161 $mod[$seq]->onclick = $info->onclick;
1163 if (!empty($info->customdata)) {
1164 $mod[$seq]->customdata = $info->customdata;
1167 // When using a stdclass, the (horrible) deprecated ->extra field
1168 // is available for BC
1169 if (!empty($info->extra)) {
1170 $mod[$seq]->extra = $info->extra;
1175 // When there is no modname_get_coursemodule_info function,
1176 // but showdescriptions is enabled, then we use the 'intro'
1177 // and 'introformat' fields in the module table
1178 if (!$hasfunction && $rawmods[$seq]->showdescription) {
1179 if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
1180 array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
1181 // Set content from intro and introformat. Filters are disabled
1182 // because we filter it with format_text at display time
1183 $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
1184 $modvalues, $rawmods[$seq]->id, false);
1186 // To save making another query just below, put name in here
1187 $mod[$seq]->name = $modvalues->name;
1190 if (!isset($mod[$seq]->name)) {
1191 $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
1194 // Minimise the database size by unsetting default options when they are
1195 // 'empty'. This list corresponds to code in the cm_info constructor.
1196 foreach (array('idnumber', 'groupmode', 'groupingid', 'groupmembersonly',
1197 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
1198 'icon', 'iconcomponent', 'customdata', 'showavailability', 'availablefrom',
1199 'availableuntil', 'conditionscompletion', 'conditionsgrade',
1200 'completionview', 'completionexpected', 'score', 'showdescription')
1202 if (property_exists($mod[$seq], $property) &&
1203 empty($mod[$seq]->{$property})) {
1204 unset($mod[$seq]->{$property});
1207 // Special case: this value is usually set to null, but may be 0
1208 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
1209 is_null($mod[$seq]->completiongradeitemnumber)) {
1210 unset($mod[$seq]->completiongradeitemnumber);
1220 * Returns the localised human-readable names of all used modules
1222 * @param bool $plural if true returns the plural forms of the names
1223 * @return array where key is the module name (component name without 'mod_') and
1224 * the value is the human-readable string. Array sorted alphabetically by value
1226 function get_module_types_names($plural = false) {
1227 static $modnames = null;
1229 if ($modnames === null) {
1230 $modnames = array(0 => array(), 1 => array());
1231 if ($allmods = $DB->get_records("modules")) {
1232 foreach ($allmods as $mod) {
1233 if (file_exists("$CFG->dirroot/mod/$mod->name/lib.php") && $mod->visible) {
1234 $modnames[0][$mod->name] = get_string("modulename", "$mod->name");
1235 $modnames[1][$mod->name] = get_string("modulenameplural", "$mod->name");
1238 collatorlib::asort($modnames[0]);
1239 collatorlib::asort($modnames[1]);
1242 return $modnames[(int)$plural];
1246 * Set highlighted section. Only one section can be highlighted at the time.
1248 * @param int $courseid course id
1249 * @param int $marker highlight section with this number, 0 means remove higlightin
1252 function course_set_marker($courseid, $marker) {
1254 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
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 * This data is also used in other areas of the code.
1311 * @param cm_info $cm Course-module data (must come from get_fast_modinfo)
1312 * @param object $course Moodle course object
1313 * @return array An array with the following values in this order:
1314 * $content (optional extra content for after link),
1315 * $instancename (text of link)
1317 function get_print_section_cm_text(cm_info $cm, $course) {
1320 // Get content from modinfo if specified. Content displays either
1321 // in addition to the standard link (below), or replaces it if
1322 // the link is turned off by setting ->url to null.
1323 if (($content = $cm->get_content()) !== '') {
1324 // Improve filter performance by preloading filter setttings for all
1325 // activities on the course (this does nothing if called multiple
1327 filter_preload_activities($cm->get_modinfo());
1329 // Get module context
1330 $modulecontext = context_module::instance($cm->id);
1331 $labelformatoptions = new stdClass();
1332 $labelformatoptions->noclean = true;
1333 $labelformatoptions->overflowdiv = true;
1334 $labelformatoptions->context = $modulecontext;
1335 $content = format_text($content, FORMAT_HTML, $labelformatoptions);
1340 // Get course context
1341 $coursecontext = context_course::instance($course->id);
1342 $stringoptions = new stdClass;
1343 $stringoptions->context = $coursecontext;
1344 $instancename = format_string($cm->name, true, $stringoptions);
1345 return array($content, $instancename);
1349 * Prints a section full of activity modules
1351 * @param stdClass $course The course
1352 * @param stdClass|section_info $section The section object containing properties id and section
1353 * @param array $mods (argument not used)
1354 * @param array $modnamesused (argument not used)
1355 * @param bool $absolute All links are absolute
1356 * @param string $width Width of the container
1357 * @param bool $hidecompletion Hide completion status
1358 * @param int $sectionreturn The section to return to
1361 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%", $hidecompletion=false, $sectionreturn=null) {
1362 global $CFG, $USER, $DB, $PAGE, $OUTPUT;
1364 static $initialised;
1366 static $groupbuttons;
1367 static $groupbuttonslink;
1370 static $strmovehere;
1371 static $strmovefull;
1372 static $strunreadpostsone;
1374 if (!isset($initialised)) {
1375 $groupbuttons = ($course->groupmode or (!$course->groupmodeforce));
1376 $groupbuttonslink = (!$course->groupmodeforce);
1377 $isediting = $PAGE->user_is_editing();
1378 $ismoving = $isediting && ismoving($course->id);
1380 $strmovehere = get_string("movehere");
1381 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1383 $initialised = true;
1386 $modinfo = get_fast_modinfo($course);
1387 $completioninfo = new completion_info($course);
1389 //Accessibility: replace table with list <ul>, but don't output empty list.
1390 if (!empty($modinfo->sections[$section->section])) {
1392 // Fix bug #5027, don't want style=\"width:$width\".
1393 echo "<ul class=\"section img-text\">\n";
1395 foreach ($modinfo->sections[$section->section] as $modnumber) {
1396 $mod = $modinfo->cms[$modnumber];
1398 if ($ismoving and $mod->id == $USER->activitycopy) {
1399 // do not display moving mod
1403 // We can continue (because it will not be displayed at all)
1405 // 1) The activity is not visible to users
1407 // 2a) The 'showavailability' option is not set (if that is set,
1408 // we need to display the activity so we can show
1409 // availability info)
1411 // 2b) The 'availableinfo' is empty, i.e. the activity was
1412 // hidden in a way that leaves no info, such as using the
1414 if (!$mod->uservisible &&
1415 (empty($mod->showavailability) ||
1416 empty($mod->availableinfo))) {
1417 // visibility shortcut
1421 // In some cases the activity is visible to user, but it is
1422 // dimmed. This is done if viewhiddenactivities is true and if:
1423 // 1. the activity is not visible, or
1424 // 2. the activity has dates set which do not include current, or
1425 // 3. the activity has any other conditions set (regardless of whether
1426 // current user meets them)
1427 $modcontext = context_module::instance($mod->id);
1428 $canviewhidden = has_capability('moodle/course:viewhiddenactivities', $modcontext);
1429 $accessiblebutdim = false;
1430 if ($canviewhidden) {
1431 $accessiblebutdim = !$mod->visible;
1432 if (!empty($CFG->enableavailability)) {
1433 $accessiblebutdim = $accessiblebutdim ||
1434 $mod->availablefrom > time() ||
1435 ($mod->availableuntil && $mod->availableuntil < time()) ||
1436 count($mod->conditionsgrade) > 0 ||
1437 count($mod->conditionscompletion) > 0;
1441 $liclasses = array();
1442 $liclasses[] = 'activity';
1443 $liclasses[] = $mod->modname;
1444 $liclasses[] = 'modtype_'.$mod->modname;
1445 $extraclasses = $mod->get_extra_classes();
1446 if ($extraclasses) {
1447 $liclasses = array_merge($liclasses, explode(' ', $extraclasses));
1449 echo html_writer::start_tag('li', array('class'=>join(' ', $liclasses), 'id'=>'module-'.$modnumber));
1451 echo '<a title="'.$strmovefull.'"'.
1452 ' href="'.$CFG->wwwroot.'/course/mod.php?moveto='.$mod->id.'&sesskey='.sesskey().'">'.
1453 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1454 ' alt="'.$strmovehere.'" /></a><br />
1458 $classes = array('mod-indent');
1459 if (!empty($mod->indent)) {
1460 $classes[] = 'mod-indent-'.$mod->indent;
1461 if ($mod->indent > 15) {
1462 $classes[] = 'mod-indent-huge';
1465 echo html_writer::start_tag('div', array('class'=>join(' ', $classes)));
1467 // Get data about this course-module
1468 list($content, $instancename) =
1469 get_print_section_cm_text($modinfo->cms[$modnumber], $course);
1471 //Accessibility: for files get description via icon, this is very ugly hack!
1473 $altname = $mod->modfullname;
1474 // Avoid unnecessary duplication: if e.g. a forum name already
1475 // includes the word forum (or Forum, etc) then it is unhelpful
1476 // to include that in the accessible description that is added.
1477 if (false !== strpos(textlib::strtolower($instancename),
1478 textlib::strtolower($altname))) {
1481 // File type after name, for alphabetic lists (screen reader).
1483 $altname = get_accesshide(' '.$altname);
1486 // We may be displaying this just in order to show information
1487 // about visibility, without the actual link
1489 if ($mod->uservisible) {
1490 // Nope - in this case the link is fully working for user
1493 if ($accessiblebutdim) {
1494 $linkclasses .= ' dimmed conditionalhidden';
1495 $textclasses .= ' dimmed_text conditionalhidden';
1496 $accesstext = '<span class="accesshide">'.
1497 get_string('hiddenfromstudents').': </span>';
1502 $linkcss = 'class="activityinstance ' . trim($linkclasses) . '" ';
1504 $linkcss = 'class="activityinstance"';
1507 $textcss = 'class="' . trim($textclasses) . '" ';
1512 // Get on-click attribute value if specified
1513 $onclick = $mod->get_on_click();
1515 $onclick = ' onclick="' . $onclick . '"';
1518 if ($url = $mod->get_url()) {
1519 // Display link itself
1520 echo '<a ' . $linkcss . $mod->extra . $onclick .
1521 ' href="' . $url . '"><img src="' . $mod->get_icon_url() .
1522 '" class="iconlarge activityicon" alt="' . $mod->modfullname . '" />' .
1523 $accesstext . '<span class="instancename">' .
1524 $instancename . $altname . '</span></a>';
1526 // If specified, display extra content after link
1528 $contentpart = '<div class="' . trim('contentafterlink' . $textclasses) .
1529 '">' . $content . '</div>';
1532 // No link, so display only content
1533 $contentpart = '<div ' . $textcss . $mod->extra . '>' .
1534 $accesstext . $content . '</div>';
1537 if (!empty($mod->groupingid) && has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
1538 $groupings = groups_get_all_groupings($course->id);
1539 echo " <span class=\"groupinglabel\">(".format_string($groupings[$mod->groupingid]->name).')</span>';
1542 $textclasses = $extraclasses;
1543 $textclasses .= ' dimmed_text';
1545 $textcss = 'class="' . trim($textclasses) . '" ';
1549 $accesstext = '<span class="accesshide">' .
1550 get_string('notavailableyet', 'condition') .
1553 if ($url = $mod->get_url()) {
1554 // Display greyed-out text of link
1555 echo '<div ' . $textcss . $mod->extra .
1556 ' >' . '<img src="' . $mod->get_icon_url() .
1557 '" class="activityicon" alt="" /> <span>'. $instancename . $altname .
1560 // Do not display content after link when it is greyed out like this.
1562 // No link, so display only content (also greyed)
1563 $contentpart = '<div ' . $textcss . $mod->extra . '>' .
1564 $accesstext . $content . '</div>';
1568 // Module can put text after the link (e.g. forum unread)
1569 echo $mod->get_after_link();
1571 // If there is content but NO link (eg label), then display the
1572 // content here (BEFORE any icons). In this case cons must be
1573 // displayed after the content so that it makes more sense visually
1574 // and for accessibility reasons, e.g. if you have a one-line label
1575 // it should work similarly (at least in terms of ordering) to an
1582 if ($groupbuttons and plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
1583 if (! $mod->groupmodelink = $groupbuttonslink) {
1584 $mod->groupmode = $course->groupmode;
1588 $mod->groupmode = false;
1590 echo make_editing_buttons($mod, $absolute, true, $mod->indent, $sectionreturn);
1591 echo $mod->get_after_edit_icons();
1595 $completion = $hidecompletion
1596 ? COMPLETION_TRACKING_NONE
1597 : $completioninfo->is_enabled($mod);
1598 if ($completion!=COMPLETION_TRACKING_NONE && isloggedin() &&
1599 !isguestuser() && $mod->uservisible) {
1600 $completiondata = $completioninfo->get_data($mod,true);
1601 $completionicon = '';
1603 switch ($completion) {
1604 case COMPLETION_TRACKING_MANUAL :
1605 $completionicon = 'manual-enabled'; break;
1606 case COMPLETION_TRACKING_AUTOMATIC :
1607 $completionicon = 'auto-enabled'; break;
1610 } else if ($completion==COMPLETION_TRACKING_MANUAL) {
1611 switch($completiondata->completionstate) {
1612 case COMPLETION_INCOMPLETE:
1613 $completionicon = 'manual-n'; break;
1614 case COMPLETION_COMPLETE:
1615 $completionicon = 'manual-y'; break;
1617 } else { // Automatic
1618 switch($completiondata->completionstate) {
1619 case COMPLETION_INCOMPLETE:
1620 $completionicon = 'auto-n'; break;
1621 case COMPLETION_COMPLETE:
1622 $completionicon = 'auto-y'; break;
1623 case COMPLETION_COMPLETE_PASS:
1624 $completionicon = 'auto-pass'; break;
1625 case COMPLETION_COMPLETE_FAIL:
1626 $completionicon = 'auto-fail'; break;
1629 if ($completionicon) {
1630 $imgsrc = $OUTPUT->pix_url('i/completion-'.$completionicon);
1631 $formattedname = format_string($mod->name, true, array('context' => $modcontext));
1632 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $formattedname);
1633 if ($completion == COMPLETION_TRACKING_MANUAL && !$isediting) {
1634 $imgtitle = get_string('completion-title-' . $completionicon, 'completion', $formattedname);
1636 $completiondata->completionstate==COMPLETION_COMPLETE
1637 ? COMPLETION_INCOMPLETE
1638 : COMPLETION_COMPLETE;
1639 // In manual mode the icon is a toggle form...
1641 // If this completion state is used by the
1642 // conditional activities system, we need to turn
1644 if (!empty($CFG->enableavailability) &&
1645 condition_info::completion_value_used_as_condition($course, $mod)) {
1646 $extraclass = ' preventjs';
1651 <form class='togglecompletion$extraclass' method='post' action='".$CFG->wwwroot."/course/togglecompletion.php'><div>
1652 <input type='hidden' name='id' value='{$mod->id}' />
1653 <input type='hidden' name='modulename' value='".s($mod->name)."' />
1654 <input type='hidden' name='sesskey' value='".sesskey()."' />
1655 <input type='hidden' name='completionstate' value='$newstate' />
1656 <input type='image' src='$imgsrc' alt='$imgalt' title='$imgtitle' />
1659 // In auto mode, or when editing, the icon is just an image
1660 echo "<span class='autocompletion'>";
1661 echo "<img src='$imgsrc' alt='$imgalt' title='$imgalt' /></span>";
1666 // If there is content AND a link, then display the content here
1667 // (AFTER any icons). Otherwise it was displayed before
1672 // Show availability information (for someone who isn't allowed to
1673 // see the activity itself, or for staff)
1674 if (!$mod->uservisible) {
1675 echo '<div class="availabilityinfo">'.$mod->availableinfo.'</div>';
1676 } else if ($canviewhidden && !empty($CFG->enableavailability)) {
1677 $visibilityclass = '';
1678 if (!$mod->visible) {
1679 $visibilityclass = 'accesshide';
1681 $ci = new condition_info($mod);
1682 $fullinfo = $ci->get_full_information();
1684 echo '<div class="availabilityinfo '.$visibilityclass.'">'.get_string($mod->showavailability
1685 ? 'userrestriction_visible'
1686 : 'userrestriction_hidden','condition',
1687 $fullinfo).'</div>';
1691 echo html_writer::end_tag('div');
1692 echo html_writer::end_tag('li')."\n";
1695 } elseif ($ismoving) {
1696 echo "<ul class=\"section\">\n";
1700 echo '<li><a title="'.$strmovefull.'"'.
1701 ' href="'.$CFG->wwwroot.'/course/mod.php?movetosection='.$section->id.'&sesskey='.sesskey().'">'.
1702 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1703 ' alt="'.$strmovehere.'" /></a></li>
1706 if (!empty($modinfo->sections[$section->section]) || $ismoving) {
1707 echo "</ul><!--class='section'-->\n\n";
1712 * Prints the menus to add activities and resources.
1714 * @param stdClass $course The course
1715 * @param int $section relative section number (field course_sections.section)
1716 * @param null|array $modnames An array containing the list of modules and their names
1717 * if omitted will be taken from get_module_types_names()
1718 * @param bool $vertical Vertical orientation
1719 * @param bool $return Return the menus or send them to output
1720 * @param int $sectionreturn The section to link back to
1721 * @return void|string depending on $return
1723 function print_section_add_menus($course, $section, $modnames = null, $vertical=false, $return=false, $sectionreturn=null) {
1724 global $CFG, $OUTPUT;
1726 if ($modnames === null) {
1727 $modnames = get_module_types_names();
1730 // check to see if user can add menus and there are modules to add
1731 if (!has_capability('moodle/course:manageactivities', context_course::instance($course->id))
1732 || empty($modnames)) {
1740 // Retrieve all modules with associated metadata
1741 $modules = get_module_metadata($course, $modnames, $sectionreturn);
1743 // We'll sort resources and activities into two lists
1744 $resources = array();
1745 $activities = array();
1747 // We need to add the section section to the link for each module
1748 $sectionlink = '§ion=' . $section . '&sr=' . $sectionreturn;
1750 foreach ($modules as $module) {
1751 if (isset($module->types)) {
1752 // This module has a subtype
1753 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1754 $subtypes = array();
1755 foreach ($module->types as $subtype) {
1756 $subtypes[$subtype->link . $sectionlink] = $subtype->title;
1759 // Sort module subtypes into the list
1760 if (!empty($module->title)) {
1761 // This grouping has a name
1762 if ($module->archetype == MOD_CLASS_RESOURCE) {
1763 $resources[] = array($module->title=>$subtypes);
1765 $activities[] = array($module->title=>$subtypes);
1768 // This grouping does not have a name
1769 if ($module->archetype == MOD_CLASS_RESOURCE) {
1770 $resources = array_merge($resources, $subtypes);
1772 $activities = array_merge($activities, $subtypes);
1776 // This module has no subtypes
1777 if ($module->archetype == MOD_ARCHETYPE_RESOURCE) {
1778 $resources[$module->link . $sectionlink] = $module->title;
1779 } else if ($module->archetype === MOD_ARCHETYPE_SYSTEM) {
1780 // System modules cannot be added by user, do not add to dropdown
1782 $activities[$module->link . $sectionlink] = $module->title;
1787 $straddactivity = get_string('addactivity');
1788 $straddresource = get_string('addresource');
1789 $sectionname = get_section_name($course, $section);
1790 $strresourcelabel = get_string('addresourcetosection', null, $sectionname);
1791 $stractivitylabel = get_string('addactivitytosection', null, $sectionname);
1793 $output = html_writer::start_tag('div', array('class' => 'section_add_menus', 'id' => 'add_menus-section-' . $section));
1796 $output .= html_writer::start_tag('div', array('class' => 'horizontal'));
1799 if (!empty($resources)) {
1800 $select = new url_select($resources, '', array(''=>$straddresource), "ressection$section");
1801 $select->set_help_icon('resources');
1802 $select->set_label($strresourcelabel, array('class' => 'accesshide'));
1803 $output .= $OUTPUT->render($select);
1806 if (!empty($activities)) {
1807 $select = new url_select($activities, '', array(''=>$straddactivity), "section$section");
1808 $select->set_help_icon('activities');
1809 $select->set_label($stractivitylabel, array('class' => 'accesshide'));
1810 $output .= $OUTPUT->render($select);
1814 $output .= html_writer::end_tag('div');
1817 $output .= html_writer::end_tag('div');
1819 if (course_ajax_enabled($course)) {
1820 $straddeither = get_string('addresourceoractivity');
1821 // The module chooser link
1822 $modchooser = html_writer::start_tag('div', array('class' => 'mdl-right'));
1823 $modchooser.= html_writer::start_tag('div', array('class' => 'section-modchooser'));
1824 $icon = $OUTPUT->pix_icon('t/add', $straddeither);
1825 $span = html_writer::tag('span', $straddeither, array('class' => 'section-modchooser-text'));
1826 $modchooser .= html_writer::tag('span', $icon . $span, array('class' => 'section-modchooser-link'));
1827 $modchooser.= html_writer::end_tag('div');
1828 $modchooser.= html_writer::end_tag('div');
1830 // Wrap the normal output in a noscript div
1831 $usemodchooser = get_user_preferences('usemodchooser', $CFG->modchooserdefault);
1832 if ($usemodchooser) {
1833 $output = html_writer::tag('div', $output, array('class' => 'hiddenifjs addresourcedropdown'));
1834 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'visibleifjs addresourcemodchooser'));
1836 // If the module chooser is disabled, we need to ensure that the dropdowns are shown even if javascript is disabled
1837 $output = html_writer::tag('div', $output, array('class' => 'show addresourcedropdown'));
1838 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'hide addresourcemodchooser'));
1840 $output = $modchooser . $output;
1851 * Retrieve all metadata for the requested modules
1853 * @param object $course The Course
1854 * @param array $modnames An array containing the list of modules and their
1856 * @param int $sectionreturn The section to return to
1857 * @return array A list of stdClass objects containing metadata about each
1860 function get_module_metadata($course, $modnames, $sectionreturn = null) {
1861 global $CFG, $OUTPUT;
1863 // get_module_metadata will be called once per section on the page and courses may show
1864 // different modules to one another
1865 static $modlist = array();
1866 if (!isset($modlist[$course->id])) {
1867 $modlist[$course->id] = array();
1871 $urlbase = "/course/mod.php?id=$course->id&sesskey=".sesskey().'&sr='.$sectionreturn.'&add=';
1872 foreach($modnames as $modname => $modnamestr) {
1873 if (!course_allowed_module($course, $modname)) {
1876 if (isset($modlist[$modname])) {
1877 // This module is already cached
1878 $return[$modname] = $modlist[$course->id][$modname];
1882 // Include the module lib
1883 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1884 if (!file_exists($libfile)) {
1887 include_once($libfile);
1889 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1890 $gettypesfunc = $modname.'_get_types';
1891 if (function_exists($gettypesfunc)) {
1892 if ($types = $gettypesfunc()) {
1893 $group = new stdClass();
1894 $group->name = $modname;
1895 $group->icon = $OUTPUT->pix_icon('icon', '', $modname, array('class' => 'icon'));
1896 foreach($types as $type) {
1897 if ($type->typestr === '--') {
1900 if (strpos($type->typestr, '--') === 0) {
1901 $group->title = str_replace('--', '', $type->typestr);
1904 // Set the Sub Type metadata
1905 $subtype = new stdClass();
1906 $subtype->title = $type->typestr;
1907 $subtype->type = str_replace('&', '&', $type->type);
1908 $subtype->name = preg_replace('/.*type=/', '', $subtype->type);
1909 $subtype->archetype = $type->modclass;
1911 // The group archetype should match the subtype archetypes and all subtypes
1912 // should have the same archetype
1913 $group->archetype = $subtype->archetype;
1915 if (get_string_manager()->string_exists('help' . $subtype->name, $modname)) {
1916 $subtype->help = get_string('help' . $subtype->name, $modname);
1918 $subtype->link = $urlbase . $subtype->type;
1919 $group->types[] = $subtype;
1921 $modlist[$course->id][$modname] = $group;
1924 $module = new stdClass();
1925 $module->title = get_string('modulename', $modname);
1926 $module->name = $modname;
1927 $module->link = $urlbase . $modname;
1928 $module->icon = $OUTPUT->pix_icon('icon', '', $module->name, array('class' => 'icon'));
1929 $sm = get_string_manager();
1930 if ($sm->string_exists('modulename_help', $modname)) {
1931 $module->help = get_string('modulename_help', $modname);
1932 if ($sm->string_exists('modulename_link', $modname)) { // Link to further info in Moodle docs
1933 $link = get_string('modulename_link', $modname);
1934 $linktext = get_string('morehelp');
1935 $module->help .= html_writer::tag('div', $OUTPUT->doc_link($link, $linktext, true), array('class' => 'helpdoclink'));
1938 $module->archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1939 $modlist[$course->id][$modname] = $module;
1941 $return[$modname] = $modlist[$course->id][$modname];
1948 * Return the course category context for the category with id $categoryid, except
1949 * that if $categoryid is 0, return the system context.
1951 * @param integer $categoryid a category id or 0.
1952 * @return object the corresponding context
1954 function get_category_or_system_context($categoryid) {
1956 return context_coursecat::instance($categoryid, IGNORE_MISSING);
1958 return context_system::instance();
1963 * Gets the child categories of a given courses category. Uses a static cache
1964 * to make repeat calls efficient.
1966 * @param int $parentid the id of a course category.
1967 * @return array all the child course categories.
1969 function get_child_categories($parentid) {
1970 static $allcategories = null;
1972 // only fill in this variable the first time
1973 if (null == $allcategories) {
1974 $allcategories = array();
1976 $categories = get_categories();
1977 foreach ($categories as $category) {
1978 if (empty($allcategories[$category->parent])) {
1979 $allcategories[$category->parent] = array();
1981 $allcategories[$category->parent][] = $category;
1985 if (empty($allcategories[$parentid])) {
1988 return $allcategories[$parentid];
1993 * This function recursively travels the categories, building up a nice list
1994 * for display. It also makes an array that list all the parents for each
1997 * For example, if you have a tree of categories like:
1998 * Miscellaneous (id = 1)
1999 * Subcategory (id = 2)
2000 * Sub-subcategory (id = 4)
2001 * Other category (id = 3)
2002 * Then after calling this function you will have
2003 * $list = array(1 => 'Miscellaneous', 2 => 'Miscellaneous / Subcategory',
2004 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
2005 * 3 => 'Other category');
2006 * $parents = array(2 => array(1), 4 => array(1, 2));
2008 * If you specify $requiredcapability, then only categories where the current
2009 * user has that capability will be added to $list, although all categories
2010 * will still be added to $parents, and if you only have $requiredcapability
2011 * in a child category, not the parent, then the child catgegory will still be
2014 * If you specify the option $excluded, then that category, and all its children,
2015 * are omitted from the tree. This is useful when you are doing something like
2016 * moving categories, where you do not want to allow people to move a category
2017 * to be the child of itself.
2019 * @param array $list For output, accumulates an array categoryid => full category path name
2020 * @param array $parents For output, accumulates an array categoryid => list of parent category ids.
2021 * @param string/array $requiredcapability if given, only categories where the current
2022 * user has this capability will be added to $list. Can also be an array of capabilities,
2023 * in which case they are all required.
2024 * @param integer $excludeid Omit this category and its children from the lists built.
2025 * @param object $category Build the tree starting at this category - otherwise starts at the top level.
2026 * @param string $path For internal use, as part of recursive calls.
2028 function make_categories_list(&$list, &$parents, $requiredcapability = '',
2029 $excludeid = 0, $category = NULL, $path = "") {
2031 // initialize the arrays if needed
2032 if (!is_array($list)) {
2035 if (!is_array($parents)) {
2039 if (empty($category)) {
2040 // Start at the top level.
2041 $category = new stdClass;
2044 // This is the excluded category, don't include it.
2045 if ($excludeid > 0 && $excludeid == $category->id) {
2049 $context = context_coursecat::instance($category->id);
2050 $categoryname = format_string($category->name, true, array('context' => $context));
2054 $path = $path.' / '.$categoryname;
2056 $path = $categoryname;
2059 // Add this category to $list, if the permissions check out.
2060 if (empty($requiredcapability)) {
2061 $list[$category->id] = $path;
2064 $requiredcapability = (array)$requiredcapability;
2065 if (has_all_capabilities($requiredcapability, $context)) {
2066 $list[$category->id] = $path;
2071 // Add all the children recursively, while updating the parents array.
2072 if ($categories = get_child_categories($category->id)) {
2073 foreach ($categories as $cat) {
2074 if (!empty($category->id)) {
2075 if (isset($parents[$category->id])) {
2076 $parents[$cat->id] = $parents[$category->id];
2078 $parents[$cat->id][] = $category->id;
2080 make_categories_list($list, $parents, $requiredcapability, $excludeid, $cat, $path);
2086 * This function generates a structured array of courses and categories.
2088 * The depth of categories is limited by $CFG->maxcategorydepth however there
2089 * is no limit on the number of courses!
2091 * Suitable for use with the course renderers course_category_tree method:
2092 * $renderer = $PAGE->get_renderer('core','course');
2093 * echo $renderer->course_category_tree(get_course_category_tree());
2095 * @global moodle_database $DB
2099 function get_course_category_tree($id = 0, $depth = 0) {
2101 $viewhiddencats = has_capability('moodle/category:viewhiddencategories', context_system::instance());
2102 $categories = get_child_categories($id);
2103 $categoryids = array();
2104 foreach ($categories as $key => &$category) {
2105 if (!$category->visible && !$viewhiddencats) {
2106 unset($categories[$key]);
2109 $categoryids[$category->id] = $category;
2110 if (empty($CFG->maxcategorydepth) || $depth <= $CFG->maxcategorydepth) {
2111 list($category->categories, $subcategories) = get_course_category_tree($category->id, $depth+1);
2112 foreach ($subcategories as $subid=>$subcat) {
2113 $categoryids[$subid] = $subcat;
2115 $category->courses = array();
2120 // This is a recursive call so return the required array
2121 return array($categories, $categoryids);
2124 if (empty($categoryids)) {
2125 // No categories available (probably all hidden).
2129 // The depth is 0 this function has just been called so we can finish it off
2131 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
2132 list($catsql, $catparams) = $DB->get_in_or_equal(array_keys($categoryids));
2134 c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary,c.category
2138 WHERE c.category $catsql ORDER BY c.sortorder ASC";
2139 if ($courses = $DB->get_records_sql($sql, $catparams)) {
2140 // loop throught them
2141 foreach ($courses as $course) {
2142 if ($course->id == SITEID) {
2145 context_instance_preload($course);
2146 if (!empty($course->visible) || has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
2147 $categoryids[$course->category]->courses[$course->id] = $course;
2155 * Recursive function to print out all the categories in a nice format
2156 * with or without courses included
2158 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true) {
2161 // maxcategorydepth == 0 meant no limit
2162 if (!empty($CFG->maxcategorydepth) && $depth >= $CFG->maxcategorydepth) {
2166 if (!$displaylist) {
2167 make_categories_list($displaylist, $parentslist);
2171 if ($category->visible or has_capability('moodle/category:viewhiddencategories', context_system::instance())) {
2172 print_category_info($category, $depth, $showcourses);
2174 return; // Don't bother printing children of invisible categories
2178 $category = new stdClass();
2179 $category->id = "0";
2182 if ($categories = get_child_categories($category->id)) { // Print all the children recursively
2183 $countcats = count($categories);
2187 foreach ($categories as $cat) {
2189 if ($count == $countcats) {
2192 $up = $first ? false : true;
2193 $down = $last ? false : true;
2196 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1, $showcourses);
2202 * This function will return $options array for html_writer::select(), with whitespace to denote nesting.
2204 function make_categories_options() {
2205 make_categories_list($cats,$parents);
2206 foreach ($cats as $key => $value) {
2207 if (array_key_exists($key,$parents)) {
2208 if ($indent = count($parents[$key])) {
2209 for ($i = 0; $i < $indent; $i++) {
2210 $cats[$key] = ' '.$cats[$key];
2219 * Prints the category info in indented fashion
2220 * This function is only used by print_whole_category_list() above
2222 function print_category_info($category, $depth=0, $showcourses = false) {
2223 global $CFG, $DB, $OUTPUT;
2225 $strsummary = get_string('summary');
2228 if (!$category->visible) {
2229 $catlinkcss = array('class'=>'dimmed');
2231 static $coursecount = null;
2232 if (null === $coursecount) {
2233 // only need to check this once
2234 $coursecount = $DB->count_records('course') <= FRONTPAGECOURSELIMIT;
2237 if ($showcourses and $coursecount) {
2238 $catimage = '<img src="'.$OUTPUT->pix_url('i/course') . '" alt="" />';
2240 $catimage = " ";
2243 $courses = get_courses($category->id, 'c.sortorder ASC', 'c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary');
2244 $context = context_coursecat::instance($category->id);
2245 $fullname = format_string($category->name, true, array('context' => $context));
2247 if ($showcourses and $coursecount) {
2248 echo '<div class="categorylist clearfix">';
2250 $cat .= html_writer::tag('div', $catimage, array('class'=>'image'));
2251 $catlink = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
2252 $cat .= html_writer::tag('div', $catlink, array('class'=>'name'));
2256 for ($i=0; $i< $depth; $i++) {
2257 $html = html_writer::tag('div', $html . $cat, array('class'=>'indentation'));
2263 echo html_writer::tag('div', $html, array('class'=>'category'));
2264 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
2266 // does the depth exceed maxcategorydepth
2267 // maxcategorydepth == 0 or unset meant no limit
2268 $limit = !(isset($CFG->maxcategorydepth) && ($depth >= $CFG->maxcategorydepth-1));
2269 if ($courses && ($limit || $CFG->maxcategorydepth == 0)) {
2270 foreach ($courses as $course) {
2272 if (!$course->visible) {
2273 $linkcss = array('class'=>'dimmed');
2276 $coursename = get_course_display_name_for_list($course);
2277 $courselink = html_writer::link(new moodle_url('/course/view.php', array('id'=>$course->id)), format_string($coursename), $linkcss);
2281 if ($icons = enrol_get_course_info_icons($course)) {
2282 foreach ($icons as $pix_icon) {
2283 $courseicon = $OUTPUT->render($pix_icon).' ';
2287 $coursecontent = html_writer::tag('div', $courseicon.$courselink, array('class'=>'name'));
2289 if ($course->summary) {
2290 $link = new moodle_url('/course/info.php?id='.$course->id);
2291 $actionlink = $OUTPUT->action_link($link, '<img alt="'.$strsummary.'" src="'.$OUTPUT->pix_url('i/info') . '" />',
2292 new popup_action('click', $link, 'courseinfo', array('height' => 400, 'width' => 500)),
2293 array('title'=>$strsummary));
2295 $coursecontent .= html_writer::tag('div', $actionlink, array('class'=>'info'));
2299 for ($i=0; $i <= $depth; $i++) {
2300 $html = html_writer::tag('div', $html . $coursecontent , array('class'=>'indentation'));
2301 $coursecontent = '';
2303 echo html_writer::tag('div', $html, array('class'=>'course clearfloat'));
2308 echo '<div class="categorylist">';
2310 $cat = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
2311 if (count($courses) > 0) {
2312 $cat .= html_writer::tag('span', ' ('.count($courses).')', array('title'=>get_string('numberofcourses'), 'class'=>'numberofcourse'));
2316 for ($i=0; $i< $depth; $i++) {
2317 $html = html_writer::tag('div', $html .$cat, array('class'=>'indentation'));
2324 echo html_writer::tag('div', $html, array('class'=>'category'));
2325 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
2331 * Print the buttons relating to course requests.
2333 * @param object $systemcontext the system context.
2335 function print_course_request_buttons($systemcontext) {
2336 global $CFG, $DB, $OUTPUT;
2337 if (empty($CFG->enablecourserequests)) {
2340 if (!has_capability('moodle/course:create', $systemcontext) && has_capability('moodle/course:request', $systemcontext)) {
2341 /// Print a button to request a new course
2342 echo $OUTPUT->single_button('request.php', get_string('requestcourse'), 'get');
2344 /// Print a button to manage pending requests
2345 if (has_capability('moodle/site:approvecourse', $systemcontext)) {
2346 $disabled = !$DB->record_exists('course_request', array());
2347 echo $OUTPUT->single_button('pending.php', get_string('coursespending'), 'get', array('disabled'=>$disabled));
2352 * Does the user have permission to edit things in this category?
2354 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2355 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
2357 function can_edit_in_category($categoryid = 0) {
2358 $context = get_category_or_system_context($categoryid);
2359 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
2363 * Prints the turn editing on/off button on course/index.php or course/category.php.
2365 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2366 * @return string HTML of the editing button, or empty string, if this user is not allowed
2369 function update_category_button($categoryid = 0) {
2370 global $CFG, $PAGE, $OUTPUT;
2372 // Check permissions.
2373 if (!can_edit_in_category($categoryid)) {
2377 // Work out the appropriate action.
2378 if ($PAGE->user_is_editing()) {
2379 $label = get_string('turneditingoff');
2382 $label = get_string('turneditingon');
2386 // Generate the button HTML.
2387 $options = array('categoryedit' => $edit, 'sesskey' => sesskey());
2389 $options['id'] = $categoryid;
2390 $page = 'category.php';
2392 $page = 'index.php';
2394 return $OUTPUT->single_button(new moodle_url('/course/' . $page, $options), $label, 'get');
2398 * Category is 0 (for all courses) or an object
2400 function print_courses($category) {
2401 global $CFG, $OUTPUT;
2403 if (!is_object($category) && $category==0) {
2404 $categories = get_child_categories(0); // Parent = 0 ie top-level categories only
2405 if (is_array($categories) && count($categories) == 1) {
2406 $category = array_shift($categories);
2407 $courses = get_courses_wmanagers($category->id,
2409 array('summary','summaryformat'));
2411 $courses = get_courses_wmanagers('all',
2413 array('summary','summaryformat'));
2417 $courses = get_courses_wmanagers($category->id,
2419 array('summary','summaryformat'));
2423 echo html_writer::start_tag('ul', array('class'=>'unlist'));
2424 foreach ($courses as $course) {
2425 $coursecontext = context_course::instance($course->id);
2426 if ($course->visible == 1 || has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2427 echo html_writer::start_tag('li');
2428 print_course($course);
2429 echo html_writer::end_tag('li');
2432 echo html_writer::end_tag('ul');
2434 echo $OUTPUT->heading(get_string("nocoursesyet"));
2435 $context = context_system::instance();
2436 if (has_capability('moodle/course:create', $context)) {
2438 if (!empty($category->id)) {
2439 $options['category'] = $category->id;
2441 $options['category'] = $CFG->defaultrequestcategory;
2443 echo html_writer::start_tag('div', array('class'=>'addcoursebutton'));
2444 echo $OUTPUT->single_button(new moodle_url('/course/edit.php', $options), get_string("addnewcourse"));
2445 echo html_writer::end_tag('div');
2451 * Print a description of a course, suitable for browsing in a list.
2453 * @param object $course the course object.
2454 * @param string $highlightterms (optional) some search terms that should be highlighted in the display.
2456 function print_course($course, $highlightterms = '') {
2457 global $CFG, $USER, $DB, $OUTPUT;
2459 $context = context_course::instance($course->id);
2461 // Rewrite file URLs so that they are correct
2462 $course->summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', NULL);
2464 echo html_writer::start_tag('div', array('class'=>'coursebox clearfix'));
2465 echo html_writer::start_tag('div', array('class'=>'info'));
2466 echo html_writer::start_tag('h3', array('class'=>'name'));
2468 $linkhref = new moodle_url('/course/view.php', array('id'=>$course->id));
2470 $coursename = get_course_display_name_for_list($course);
2471 $linktext = highlight($highlightterms, format_string($coursename));
2472 $linkparams = array('title'=>get_string('entercourse'));
2473 if (empty($course->visible)) {
2474 $linkparams['class'] = 'dimmed';
2476 echo html_writer::link($linkhref, $linktext, $linkparams);
2477 echo html_writer::end_tag('h3');
2479 /// first find all roles that are supposed to be displayed
2480 if (!empty($CFG->coursecontact)) {
2481 $managerroles = explode(',', $CFG->coursecontact);
2484 if (!isset($course->managers)) {
2485 list($sort, $sortparams) = users_order_by_sql('u');
2486 $rusers = get_role_users($managerroles, $context, true,
2487 'ra.id AS raid, u.id, u.username, u.firstname, u.lastname, rn.name AS rolecoursealias,
2488 r.name AS rolename, r.sortorder, r.id AS roleid, r.shortname AS roleshortname',
2489 'r.sortorder ASC, ' . $sort, null, '', '', '', '', $sortparams);
2491 // use the managers array if we have it for perf reasosn
2492 // populate the datastructure like output of get_role_users();
2493 foreach ($course->managers as $manager) {
2494 $user = clone($manager->user);
2495 $user->roleid = $manager->roleid;
2496 $user->rolename = $manager->rolename;
2497 $user->roleshortname = $manager->roleshortname;
2498 $user->rolecoursealias = $manager->rolecoursealias;
2499 $rusers[$user->id] = $user;
2503 $namesarray = array();
2504 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2505 foreach ($rusers as $ra) {
2506 if (isset($namesarray[$ra->id])) {
2507 // only display a user once with the higest sortorder role
2511 $role = new stdClass();
2512 $role->id = $ra->roleid;
2513 $role->name = $ra->rolename;
2514 $role->shortname = $ra->roleshortname;
2515 $role->coursealias = $ra->rolecoursealias;
2516 $rolename = role_get_name($role, $context, ROLENAME_ALIAS);
2518 $fullname = fullname($ra, $canviewfullnames);
2519 $namesarray[$ra->id] = $rolename.': '.
2520 html_writer::link(new moodle_url('/user/view.php', array('id'=>$ra->id, 'course'=>SITEID)), $fullname);
2523 if (!empty($namesarray)) {
2524 echo html_writer::start_tag('ul', array('class'=>'teachers'));
2525 foreach ($namesarray as $name) {
2526 echo html_writer::tag('li', $name);
2528 echo html_writer::end_tag('ul');
2531 echo html_writer::end_tag('div'); // End of info div
2533 echo html_writer::start_tag('div', array('class'=>'summary'));
2534 $options = new stdClass();
2535 $options->noclean = true;
2536 $options->para = false;
2537 $options->overflowdiv = true;
2538 if (!isset($course->summaryformat)) {
2539 $course->summaryformat = FORMAT_MOODLE;
2541 echo highlight($highlightterms, format_text($course->summary, $course->summaryformat, $options, $course->id));
2542 if ($icons = enrol_get_course_info_icons($course)) {
2543 echo html_writer::start_tag('div', array('class'=>'enrolmenticons'));
2544 foreach ($icons as $icon) {
2545 echo $OUTPUT->render($icon);
2547 echo html_writer::end_tag('div'); // End of enrolmenticons div
2549 echo html_writer::end_tag('div'); // End of summary div
2550 echo html_writer::end_tag('div'); // End of coursebox div
2554 * Prints custom user information on the home page.
2555 * Over time this can include all sorts of information
2557 function print_my_moodle() {
2558 global $USER, $CFG, $DB, $OUTPUT;
2560 if (!isloggedin() or isguestuser()) {
2561 print_error('nopermissions', '', '', 'See My Moodle');
2564 $courses = enrol_get_my_courses('summary', 'visible DESC,sortorder ASC');
2566 $rcourses = array();
2567 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
2568 $rcourses = get_my_remotecourses($USER->id);
2569 $rhosts = get_my_remotehosts();
2572 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
2574 if (!empty($courses)) {
2575 echo '<ul class="unlist">';
2576 foreach ($courses as $course) {
2577 if ($course->id == SITEID) {
2581 print_course($course);
2588 if (!empty($rcourses)) {
2589 // at the IDP, we know of all the remote courses
2590 foreach ($rcourses as $course) {
2591 print_remote_course($course, "100%");
2593 } elseif (!empty($rhosts)) {
2594 // non-IDP, we know of all the remote servers, but not courses
2595 foreach ($rhosts as $host) {
2596 print_remote_host($host, "100%");
2602 if ($DB->count_records("course") > (count($courses) + 1) ) { // Some courses not being displayed
2603 echo "<table width=\"100%\"><tr><td align=\"center\">";
2604 print_course_search("", false, "short");
2605 echo "</td><td align=\"center\">";
2606 echo $OUTPUT->single_button("$CFG->wwwroot/course/index.php", get_string("fulllistofcourses"), "get");
2607 echo "</td></tr></table>\n";
2611 if ($DB->count_records("course_categories") > 1) {
2612 echo $OUTPUT->box_start("categorybox");
2613 print_whole_category_list();
2614 echo $OUTPUT->box_end();
2622 function print_course_search($value="", $return=false, $format="plain") {
2628 $id = 'coursesearch';
2634 $strsearchcourses= get_string("searchcourses");
2636 if ($format == 'plain') {
2637 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2638 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2639 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
2640 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" value="'.s($value).'" />';
2641 $output .= '<input type="submit" value="'.get_string('go').'" />';
2642 $output .= '</fieldset></form>';
2643 } else if ($format == 'short') {
2644 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2645 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2646 $output .= '<label for="shortsearchbox">'.$strsearchcourses.': </label>';
2647 $output .= '<input type="text" id="shortsearchbox" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2648 $output .= '<input type="submit" value="'.get_string('go').'" />';
2649 $output .= '</fieldset></form>';
2650 } else if ($format == 'navbar') {
2651 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2652 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2653 $output .= '<label for="navsearchbox">'.$strsearchcourses.': </label>';
2654 $output .= '<input type="text" id="navsearchbox" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2655 $output .= '<input type="submit" value="'.get_string('go').'" />';
2656 $output .= '</fieldset></form>';
2665 function print_remote_course($course, $width="100%") {
2670 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&wantsurl=/course/view.php?id={$course->remoteid}";
2672 echo '<div class="coursebox remotecoursebox clearfix">';
2673 echo '<div class="info">';
2674 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2675 $linkcss.' href="'.$url.'">'
2676 . format_string($course->fullname) .'</a><br />'
2677 . format_string($course->hostname) . ' : '
2678 . format_string($course->cat_name) . ' : '
2679 . format_string($course->shortname). '</div>';
2680 echo '</div><div class="summary">';
2681 $options = new stdClass();
2682 $options->noclean = true;
2683 $options->para = false;
2684 $options->overflowdiv = true;
2685 echo format_text($course->summary, $course->summaryformat, $options);
2690 function print_remote_host($host, $width="100%") {
2695 echo '<div class="coursebox clearfix">';
2696 echo '<div class="info">';
2697 echo '<div class="name">';
2698 echo '<img src="'.$OUTPUT->pix_url('i/mnethost') . '" class="icon" alt="'.get_string('course').'" />';
2699 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2700 . s($host['name']).'</a> - ';
2701 echo $host['count'] . ' ' . get_string('courses');
2708 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2710 function add_course_module($mod) {
2713 $mod->added = time();
2716 $cmid = $DB->insert_record("course_modules", $mod);
2717 rebuild_course_cache($mod->course, true);
2722 * Creates missing course section(s) and rebuilds course cache
2724 * @param int|stdClass $courseorid course id or course object
2725 * @param int|array $sections list of relative section numbers to create
2726 * @return bool if there were any sections created
2728 function course_create_sections_if_missing($courseorid, $sections) {
2730 if (!is_array($sections)) {
2731 $sections = array($sections);
2733 $existing = array_keys(get_fast_modinfo($courseorid)->get_section_info_all());
2734 if (is_object($courseorid)) {
2735 $courseorid = $courseorid->id;
2737 $coursechanged = false;
2738 foreach ($sections as $sectionnum) {
2739 if (!in_array($sectionnum, $existing)) {
2740 $cw = new stdClass();
2741 $cw->course = $courseorid;
2742 $cw->section = $sectionnum;
2744 $cw->summaryformat = FORMAT_HTML;
2746 $id = $DB->insert_record("course_sections", $cw);
2747 $coursechanged = true;
2750 if ($coursechanged) {
2751 rebuild_course_cache($courseorid, true);
2753 return $coursechanged;
2757 * Adds an existing module to the section
2759 * Updates both tables {course_sections} and {course_modules}
2761 * @param int|stdClass $courseorid course id or course object
2762 * @param int $modid id of the module already existing in course_modules table
2763 * @param int $sectionnum relative number of the section (field course_sections.section)
2764 * If section does not exist it will be created
2765 * @param int|stdClass $beforemod id or object with field id corresponding to the module
2766 * before which the module needs to be included. Null for inserting in the
2767 * end of the section
2768 * @return int The course_sections ID where the module is inserted
2770 function course_add_cm_to_section($courseorid, $modid, $sectionnum, $beforemod = null) {
2771 global $DB, $COURSE;
2772 if (is_object($beforemod)) {
2773 $beforemod = $beforemod->id;
2775 course_create_sections_if_missing($courseorid, $sectionnum);
2776 $section = get_fast_modinfo($courseorid)->get_section_info($sectionnum);
2777 $modarray = explode(",", trim($section->sequence));
2778 if (empty($section->sequence)) {
2779 $newsequence = "$modid";
2780 } else if ($beforemod && ($key = array_keys($modarray, $beforemod))) {
2781 $insertarray = array($modid, $beforemod);
2782 array_splice($modarray, $key[0], 1, $insertarray);
2783 $newsequence = implode(",", $modarray);
2785 $newsequence = "$section->sequence,$modid";
2787 $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id));
2788 $DB->set_field('course_modules', 'section', $section->id, array('id' => $modid));
2789 if (is_object($courseorid)) {
2790 rebuild_course_cache($courseorid->id, true);
2792 rebuild_course_cache($courseorid, true);
2794 return $section->id; // Return course_sections ID that was used.
2797 function set_coursemodule_groupmode($id, $groupmode) {
2799 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST);
2800 if ($cm->groupmode != $groupmode) {
2801 $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id));
2802 rebuild_course_cache($cm->course, true);
2804 return ($cm->groupmode != $groupmode);
2807 function set_coursemodule_idnumber($id, $idnumber) {
2809 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST);
2810 if ($cm->idnumber != $idnumber) {
2811 $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id));
2812 rebuild_course_cache($cm->course, true);
2814 return ($cm->idnumber != $idnumber);
2818 * Set the visibility of a module and inherent properties.
2820 * From 2.4 the parameter $prevstateoverrides has been removed, the logic it triggered
2821 * has been moved to {@link set_section_visible()} which was the only place from which
2822 * the parameter was used.
2824 * @param int $id of the module
2825 * @param int $visible state of the module
2826 * @return bool false when the module was not found, true otherwise
2828 function set_coursemodule_visible($id, $visible) {
2830 require_once($CFG->libdir.'/gradelib.php');
2832 // Trigger developer's attention when using the previously removed argument.
2833 if (func_num_args() > 2) {
2834 debugging('Wrong number of arguments passed to set_coursemodule_visible(), $prevstateoverrides
2835 has been removed.', DEBUG_DEVELOPER);
2838 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2841 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
2844 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2845 foreach($events as $event) {
2854 // hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there
2855 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
2857 foreach ($grade_items as $grade_item) {
2858 $grade_item->set_hidden(!$visible);
2862 // Updating visible and visibleold to keep them in sync. Only changing a section visibility will
2863 // affect visibleold to allow for an original visibility restore. See set_section_visible().
2864 $cminfo = new stdClass();
2866 $cminfo->visible = $visible;
2867 $cminfo->visibleold = $visible;
2868 $DB->update_record('course_modules', $cminfo);
2870 rebuild_course_cache($cm->course, true);
2875 * Delete a course module and any associated data at the course level (events)
2876 * Until 1.5 this function simply marked a deleted flag ... now it
2877 * deletes it completely.
2880 function delete_course_module($id) {
2882 require_once($CFG->libdir.'/gradelib.php');
2883 require_once($CFG->dirroot.'/blog/lib.php');
2885 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2888 $modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module));
2889 //delete events from calendar
2890 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2891 foreach($events as $event) {
2892 delete_event($event->id);
2895 //delete grade items, outcome items and grades attached to modules
2896 if ($grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2897 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course))) {
2898 foreach ($grade_items as $grade_item) {
2899 $grade_item->delete('moddelete');
2902 // Delete completion and availability data; it is better to do this even if the
2903 // features are not turned on, in case they were turned on previously (these will be
2904 // very quick on an empty table)
2905 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
2906 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id));
2907 $DB->delete_records('course_modules_avail_fields', array('coursemoduleid' => $cm->id));
2908 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
2909 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
2911 delete_context(CONTEXT_MODULE, $cm->id);
2912 $DB->delete_records('course_modules', array('id'=>$cm->id));
2913 rebuild_course_cache($cm->course, true);
2917 function delete_mod_from_section($modid, $sectionid) {
2920 if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
2922 $modarray = explode(",", $section->sequence);
2924 if ($key = array_keys ($modarray, $modid)) {
2925 array_splice($modarray, $key[0], 1);
2926 $newsequence = implode(",", $modarray);
2927 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
2928 rebuild_course_cache($section->course, true);
2939 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
2941 * @param object $course course object
2942 * @param int $section Section number (not id!!!)
2943 * @param int $move (-1 or 1)
2944 * @return boolean true if section moved successfully
2945 * @todo MDL-33379 remove this function in 2.5
2947 function move_section($course, $section, $move) {
2948 debugging('This function will be removed before 2.5 is released please use move_section_to', DEBUG_DEVELOPER);
2950 /// Moves a whole course section up and down within the course
2957 $sectiondest = $section + $move;
2959 // compartibility with course formats using field 'numsections'
2960 $courseformatoptions = course_get_format($course)->get_format_options();
2961 if (array_key_exists('numsections', $courseformatoptions) &&
2962 $sectiondest > $courseformatoptions['numsections'] or $sectiondest < 1) {
2966 $retval = move_section_to($course, $section, $sectiondest);
2971 * Moves a section within a course, from a position to another.
2972 * Be very careful: $section and $destination refer to section number,
2975 * @param object $course
2976 * @param int $section Section number (not id!!!)
2977 * @param int $destination
2978 * @return boolean Result
2980 function move_section_to($course, $section, $destination) {
2981 /// Moves a whole course section up and down within the course
2984 if (!$destination && $destination != 0) {
2988 // compartibility with course formats using field 'numsections'
2989 $courseformatoptions = course_get_format($course)->get_format_options();
2990 if ((array_key_exists('numsections', $courseformatoptions) &&
2991 ($destination > $courseformatoptions['numsections'])) || ($destination < 1)) {
2995 // Get all sections for this course and re-order them (2 of them should now share the same section number)
2996 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
2997 'section ASC, id ASC', 'id, section')) {
3001 $movedsections = reorder_sections($sections, $section, $destination);
3003 // Update all sections. Do this in 2 steps to avoid breaking database
3004 // uniqueness constraint
3005 $transaction = $DB->start_delegated_transaction();
3006 foreach ($movedsections as $id => $position) {
3007 if ($sections[$id] !== $position) {
3008 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
3011 foreach ($movedsections as $id => $position) {
3012 if ($sections[$id] !== $position) {
3013 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
3017 // If we move the highlighted section itself, then just highlight the destination.
3018 // Adjust the higlighted section location if we move something over it either direction.
3019 if ($section == $course->marker) {
3020 course_set_marker($course->id, $destination);
3021 } elseif ($section > $course->marker && $course->marker >= $destination) {
3022 course_set_marker($course->id, $course->marker+1);
3023 } elseif ($section < $course->marker && $course->marker <= $destination) {
3024 course_set_marker($course->id, $course->marker-1);
3027 $transaction->allow_commit();
3028 rebuild_course_cache($course->id, true);
3033 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
3034 * an original position number and a target position number, rebuilds the array so that the
3035 * move is made without any duplication of section positions.
3036 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
3037 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
3039 * @param array $sections
3040 * @param int $origin_position
3041 * @param int $target_position
3044 function reorder_sections($sections, $origin_position, $target_position) {
3045 if (!is_array($sections)) {
3049 // We can't move section position 0
3050 if ($origin_position < 1) {
3051 echo "We can't move section position 0";
3055 // Locate origin section in sections array
3056 if (!$origin_key = array_search($origin_position, $sections)) {
3057 echo "searched position not in sections array";
3058 return false; // searched position not in sections array
3061 // Extract origin section
3062 $origin_section = $sections[$origin_key];
3063 unset($sections[$origin_key]);
3065 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
3067 $append_array = array();
3068 foreach ($sections as $id => $position) {
3070 $append_array[$id] = $position;
3071 unset($sections[$id]);
3073 if ($position == $target_position) {
3074 if ($target_position < $origin_position) {
3075 $append_array[$id] = $position;
3076 unset($sections[$id]);
3082 // Append moved section
3083 $sections[$origin_key] = $origin_section;
3085 // Append rest of array (if applicable)
3086 if (!empty($append_array)) {
3087 foreach ($append_array as $id => $position) {
3088 $sections[$id] = $position;
3092 // Renumber positions
3094 foreach ($sections as $id => $p) {
3095 $sections[$id] = $position;
3104 * Move the module object $mod to the specified $section
3105 * If $beforemod exists then that is the module
3106 * before which $modid should be inserted
3107 * All parameters are objects
3109 function moveto_module($mod, $section, $beforemod=NULL) {
3112 /// Remove original module from original section
3113 if (! delete_mod_from_section($mod->id, $mod->section)) {
3114 echo $OUTPUT->notification("Could not delete module from existing section");
3117 // if moving to a hidden section then hide module
3118 if (!$section->visible && $mod->visible) {
3119 set_coursemodule_visible($mod->id, 0);
3122 /// Add the module into the new section
3123 course_add_cm_to_section($section->course, $mod->id, $section->section, $beforemod);
3128 * Produces the editing buttons for a module
3130 * @global core_renderer $OUTPUT
3131 * @staticvar type $str
3132 * @param stdClass $mod The module to produce editing buttons for
3133 * @param bool $absolute_ignored ignored - all links are absolute
3134 * @param bool $moveselect If true a move seleciton process is used (default true)
3135 * @param int $indent The current indenting
3136 * @param int $section The section to link back to
3137 * @return string XHTML for the editing buttons
3139 function make_editing_buttons(stdClass $mod, $absolute_ignored = true, $moveselect = true, $indent=-1, $section=null) {
3140 global $CFG, $OUTPUT, $COURSE;
3144 $coursecontext = context_course::instance($mod->course);
3145 $modcontext = context_module::instance($mod->id);
3147 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
3148 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
3150 // no permission to edit anything
3151 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
3155 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
3158 $str = new stdClass;
3159 $str->assign = get_string("assignroles", 'role');
3160 $str->delete = get_string("delete");
3161 $str->move = get_string("move");
3162 $str->moveup = get_string("moveup");
3163 $str->movedown = get_string("movedown");
3164 $str->moveright = get_string("moveright");
3165 $str->moveleft = get_string("moveleft");
3166 $str->update = get_string("update");
3167 $str->duplicate = get_string("duplicate");
3168 $str->hide = get_string("hide");
3169 $str->show = get_string("show");
3170 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
3171 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
3172 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
3173 $str->forcedgroupsnone = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsnone"));
3174 $str->forcedgroupsseparate = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsseparate"));
3175 $str->forcedgroupsvisible = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsvisible"));
3176 $str->edittitle = get_string('edittitle', 'moodle');
3179 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
3181 if ($section !== null) {
3182 $baseurl->param('sr', $section);
3187 if ($mod->modname !== 'label' && $hasmanageactivities && course_ajax_enabled($COURSE)) {
3188 $actions[] = new action_link(
3189 new moodle_url($baseurl, array('update' => $mod->id)),
3190 new pix_icon('t/editstring', $str->edittitle, 'moodle', array('class' => 'iconsmall visibleifjs', 'title' => '')),
3192 array('class' => 'editing_title', 'title' => $str->edittitle)
3197 if ($hasmanageactivities) {
3198 if (right_to_left()) { // Exchange arrows on RTL
3199 $rightarrow = 't/left';
3200 $leftarrow = 't/right';
3202 $rightarrow = 't/right';
3203 $leftarrow = 't/left';
3207 $actions[] = new action_link(
3208 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
3209 new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3211 array('class' => 'editing_moveleft', 'title' => $str->moveleft)
3215 $actions[] = new action_link(
3216 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
3217 new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3219 array('class' => 'editing_moveright', 'title' => $str->moveright)
3225 if ($hasmanageactivities) {
3227 $actions[] = new action_link(
3228 new moodle_url($baseurl, array('copy' => $mod->id)),
3229 new pix_icon('t/move', $str->move, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3231 array('class' => 'editing_move', 'title' => $str->move)
3234 $actions[] = new action_link(
3235 new moodle_url($baseurl, array('id' => $mod->id, 'move' => '-1')),
3236 new pix_icon('t/up', $str->moveup, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3238 array('class' => 'editing_moveup', 'title' => $str->moveup)
3240 $actions[] = new action_link(
3241 new moodle_url($baseurl, array('id' => $mod->id, 'move' => '1')),
3242 new pix_icon('t/down', $str->movedown, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3244 array('class' => 'editing_movedown', 'title' => $str->movedown)
3250 if ($hasmanageactivities) {
3251 $actions[] = new action_link(
3252 new moodle_url($baseurl, array('update' => $mod->id)),
3253 new pix_icon('t/edit', $str->update, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3255 array('class' => 'editing_update', 'title' => $str->update)
3259 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
3260 if (has_all_capabilities($dupecaps, $coursecontext) && plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2)) {
3261 $actions[] = new action_link(
3262 new moodle_url($baseurl, array('duplicate' => $mod->id)),
3263 new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3265 array('class' => 'editing_duplicate', 'title' => $str->duplicate)
3270 if ($hasmanageactivities) {
3271 $actions[] = new action_link(
3272 new moodle_url($baseurl, array('delete' => $mod->id)),
3273 new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3275 array('class' => 'editing_delete', 'title' => $str->delete)
3280 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
3281 if ($mod->visible) {
3282 $actions[] = new action_link(
3283 new moodle_url($baseurl, array('hide' => $mod->id)),
3284 new pix_icon('t/hide', $str->hide, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3286 array('class' => 'editing_hide', 'title' => $str->hide)
3289 $actions[] = new action_link(
3290 new moodle_url($baseurl, array('show' => $mod->id)),
3291 new pix_icon('t/show', $str->show, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3293 array('class' => 'editing_show', 'title' => $str->show)
3299 if ($hasmanageactivities and $mod->groupmode !== false) {
3300 if ($mod->groupmode == SEPARATEGROUPS) {
3302 $grouptitle = $str->groupsseparate;
3303 $forcedgrouptitle = $str->forcedgroupsseparate;
3304 $groupclass = 'editing_groupsseparate';
3305 $groupimage = 't/groups';
3306 } else if ($mod->groupmode == VISIBLEGROUPS) {
3308 $grouptitle = $str->groupsvisible;
3309 $forcedgrouptitle = $str->forcedgroupsvisible;
3310 $groupclass = 'editing_groupsvisible';
3311 $groupimage = 't/groupv';
3314 $grouptitle = $str->groupsnone;
3315 $forcedgrouptitle = $str->forcedgroupsnone;
3316 $groupclass = 'editing_groupsnone';
3317 $groupimage = 't/groupn';
3319 if ($mod->groupmodelink) {
3320 $actions[] = new action_link(
3321 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $groupmode)),
3322 new pix_icon($groupimage, $grouptitle, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3324 array('class' => $groupclass, 'title' => $grouptitle)
3327 $actions[] = new pix_icon($groupimage, $forcedgrouptitle, 'moodle', array('title' => $forcedgrouptitle, 'class' => 'iconsmall'));
3332 if (has_capability('moodle/role:assign', $modcontext)){
3333 $actions[] = new action_link(
3334 new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $modcontext->id)),
3335 new pix_icon('t/assignroles', $str->assign, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3337 array('class' => 'editing_assign', 'title' => $str->assign)
3341 $output = html_writer::start_tag('span', array('class' => 'commands'));
3342 foreach ($actions as $action) {
3343 if ($action instanceof renderable) {
3344 $output .= $OUTPUT->render($action);
3349 $output .= html_writer::end_tag('span');
3354 * given a course object with shortname & fullname, this function will
3355 * truncate the the number of chars allowed and add ... if it was too long
3357 function course_format_name ($course,$max=100) {
3359 $context = context_course::instance($course->id);
3360 $shortname = format_string($course->shortname, true, array('context' => $context));
3361 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
3362 $str = $shortname.': '. $fullname;
3363 if (textlib::strlen($str) <= $max) {
3367 return textlib::substr($str,0,$max-3).'...';
3372 * Is the user allowed to add this type of module to this course?
3373 * @param object $course the course settings. Only $course->id is used.
3374 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
3375 * @return bool whether the current user is allowed to add this type of module to this course.
3377 function course_allowed_module($course, $modname) {
3378 if (is_numeric($modname)) {
3379 throw new coding_exception('Function course_allowed_module no longer
3380 supports numeric module ids. Please update your code to pass the module name.');
3383 $capability = 'mod/' . $modname . ':addinstance';
3384 if (!get_capability_info($capability)) {
3385 // Debug warning that the capability does not exist, but no more than once per page.
3386 static $warned = array();
3387 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
3388 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
3389 debugging('The module ' . $modname . ' does not define the standard capability ' .
3390 $capability , DEBUG_DEVELOPER);
3391 $warned[$modname] = 1;
3394 // If the capability does not exist, the module can always be added.
3398 $coursecontext = context_course::instance($course->id);
3399 return has_capability($capability, $coursecontext);
3403 * Recursively delete category including all subcategories and courses.
3404 * @param stdClass $category
3405 * @param boolean $showfeedback display some notices
3406 * @return array return deleted courses
3408 function category_delete_full($category, $showfeedback=true) {
3410 require_once($CFG->libdir.'/gradelib.php');
3411 require_once($CFG->libdir.'/questionlib.php');
3412 require_once($CFG->dirroot.'/cohort/lib.php');
3414 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3415 foreach ($children as $childcat) {
3416 category_delete_full($childcat, $showfeedback);
3420 $deletedcourses = array();
3421 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC')) {
3422 foreach ($courses as $course) {
3423 if (!delete_course($course, false)) {
3424 throw new moodle_exception('cannotdeletecategorycourse','','',$course->shortname);
3426 $deletedcourses[] = $course;
3430 // move or delete cohorts in this context
3431 cohort_delete_category($category);
3433 // now delete anything that may depend on course category context
3434 grade_course_category_delete($category->id, 0, $showfeedback);
3435 if (!question_delete_course_category($category, 0, $showfeedback)) {
3436 throw new moodle_exception('cannotdeletecategoryquestions','','',$category->name);
3439 // finally delete the category and it's context
3440 $DB->delete_records('course_categories', array('id'=>$category->id));
3441 delete_context(CONTEXT_COURSECAT, $category->id);
3443 events_trigger('course_category_deleted', $category);
3445 return $deletedcourses;
3449 * Delete category, but move contents to another category.
3450 * @param object $ccategory
3451 * @param int $newparentid category id
3452 * @return bool status
3454 function category_delete_move($category, $newparentid, $showfeedback=true) {
3455 global $CFG, $DB, $OUTPUT;
3456 require_once($CFG->libdir.'/gradelib.php');
3457 require_once($CFG->libdir.'/questionlib.php');
3458 require_once($CFG->dirroot.'/cohort/lib.php');
3460 if (!$newparentcat = $DB->get_record('course_categories', array('id'=>$newparentid))) {
3464 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3465 foreach ($children as $childcat) {
3466 move_category($childcat, $newparentcat);
3470 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC', 'id')) {
3471 if (!move_courses(array_keys($courses), $newparentid)) {
3472 if ($showfeedback) {
3473 echo $OUTPUT->notification("Error moving courses");
3477 if ($showfeedback) {
3478 echo $OUTPUT->notification(get_string('coursesmovedout', '', format_string($category->name)), 'notifysuccess');
3482 // move or delete cohorts in this context
3483 cohort_delete_category($category);