Fix a possible race condition in the PaintWeb DML code.
[moodle/mihaisucan.git] / course / lib.php
blob74ed3164bff3794a0912530e65fa87cd58904c32
1 <?php // $Id$
2 // Library of useful functions
5 define('COURSE_MAX_LOG_DISPLAY', 150); // days
6 define('COURSE_MAX_LOGS_PER_PAGE', 1000); // records
7 define('COURSE_LIVELOG_REFRESH', 60); // Seconds
8 define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds
9 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10); // courses
10 define('COURSE_MAX_COURSES_PER_DROPDOWN',1000); // max courses in log dropdown before switching to optional
11 define('COURSE_MAX_USERS_PER_DROPDOWN',1000); // max users in log dropdown before switching to optional
12 define('FRONTPAGENEWS', '0');
13 define('FRONTPAGECOURSELIST', '1');
14 define('FRONTPAGECATEGORYNAMES', '2');
15 define('FRONTPAGETOPICONLY', '3');
16 define('FRONTPAGECATEGORYCOMBO', '4');
17 if (!defined('FRONTPAGECOURSELIMIT')) {
18 define('FRONTPAGECOURSELIMIT', 200); // maximum number of courses displayed on the frontpage
20 define('EXCELROWS', 65535);
21 define('FIRSTUSEDEXCELROW', 3);
23 define('MOD_CLASS_ACTIVITY', 0);
24 define('MOD_CLASS_RESOURCE', 1);
26 if (!defined('MAX_MODINFO_CACHE_SIZE')) {
27 define('MAX_MODINFO_CACHE_SIZE', 10);
30 function make_log_url($module, $url) {
31 switch ($module) {
32 case 'course':
33 case 'file':
34 case 'login':
35 case 'lib':
36 case 'admin':
37 case 'calendar':
38 case 'mnet course':
39 if (strpos($url, '../') === 0) {
40 $url = ltrim($url, '.');
41 } else {
42 $url = "/course/$url";
44 break;
45 case 'user':
46 case 'blog':
47 $url = "/$module/$url";
48 break;
49 case 'upload':
50 $url = $url;
51 break;
52 case 'library':
53 case '':
54 $url = '/';
55 break;
56 case 'message':
57 $url = "/message/$url";
58 break;
59 case 'notes':
60 $url = "/notes/$url";
61 break;
62 case 'tag':
63 $url = "/tag/$url";
64 break;
65 case 'role':
66 $url = '/'.$url;
67 break;
68 default:
69 $url = "/mod/$module/$url";
70 break;
73 //now let's sanitise urls - there might be some ugly nasties:-(
74 $parts = explode('?', $url);
75 $script = array_shift($parts);
76 if (strpos($script, 'http') === 0) {
77 $script = clean_param($script, PARAM_URL);
78 } else {
79 $script = clean_param($script, PARAM_PATH);
82 $query = '';
83 if ($parts) {
84 $query = implode('', $parts);
85 $query = str_replace('&amp;', '&', $query); // both & and &amp; are stored in db :-|
86 $parts = explode('&', $query);
87 $eq = urlencode('=');
88 foreach ($parts as $key=>$part) {
89 $part = urlencode(urldecode($part));
90 $part = str_replace($eq, '=', $part);
91 $parts[$key] = $part;
93 $query = '?'.implode('&amp;', $parts);
96 return $script.$query;
100 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
101 $modname="", $modid=0, $modaction="", $groupid=0) {
103 global $CFG;
105 // It is assumed that $date is the GMT time of midnight for that day,
106 // and so the next 86400 seconds worth of logs are printed.
108 /// Setup for group handling.
110 // TODO: I don't understand group/context/etc. enough to be able to do
111 // something interesting with it here
112 // What is the context of a remote course?
114 /// If the group mode is separate, and this user does not have editing privileges,
115 /// then only the user's group can be viewed.
116 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
117 // $groupid = get_current_group($course->id);
119 /// If this course doesn't have groups, no groupid can be specified.
120 //else if (!$course->groupmode) {
121 // $groupid = 0;
123 $groupid = 0;
125 $joins = array();
127 $qry = "
128 SELECT
129 l.*,
130 u.firstname,
131 u.lastname,
132 u.picture
133 FROM
134 {$CFG->prefix}mnet_log l
135 LEFT JOIN
136 {$CFG->prefix}user u
138 l.userid = u.id
139 WHERE
142 $where .= "l.hostid = '$hostid'";
144 // TODO: Is 1 really a magic number referring to the sitename?
145 if ($course != 1 || $modid != 0) {
146 $where .= " AND\n l.course='$course'";
149 if ($modname) {
150 $where .= " AND\n l.module = '$modname'";
153 if ('site_errors' === $modid) {
154 $where .= " AND\n ( l.action='error' OR l.action='infected' )";
155 } else if ($modid) {
156 //TODO: This assumes that modids are the same across sites... probably
157 //not true
158 $where .= " AND\n l.cmid = '$modid'";
161 if ($modaction) {
162 $firstletter = substr($modaction, 0, 1);
163 if (preg_match('/[[:alpha:]]/', $firstletter)) {
164 $where .= " AND\n lower(l.action) LIKE '%" . strtolower($modaction) . "%'";
165 } else if ($firstletter == '-') {
166 $where .= " AND\n lower(l.action) NOT LIKE '%" . strtolower(substr($modaction, 1)) . "%'";
170 if ($user) {
171 $where .= " AND\n l.userid = '$user'";
174 if ($date) {
175 $enddate = $date + 86400;
176 $where .= " AND\n l.time > '$date' AND l.time < '$enddate'";
179 $result = array();
180 $result['totalcount'] = count_records_sql("SELECT COUNT(*) FROM {$CFG->prefix}mnet_log l WHERE $where");
181 if(!empty($result['totalcount'])) {
182 $where .= "\n ORDER BY\n $order";
183 $result['logs'] = get_records_sql($qry.$where, $limitfrom, $limitnum);
184 } else {
185 $result['logs'] = array();
187 return $result;
190 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
191 $modname="", $modid=0, $modaction="", $groupid=0) {
193 // It is assumed that $date is the GMT time of midnight for that day,
194 // and so the next 86400 seconds worth of logs are printed.
196 /// Setup for group handling.
198 /// If the group mode is separate, and this user does not have editing privileges,
199 /// then only the user's group can be viewed.
200 if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
201 $groupid = get_current_group($course->id);
203 /// If this course doesn't have groups, no groupid can be specified.
204 else if (!$course->groupmode) {
205 $groupid = 0;
208 $joins = array();
210 if ($course->id != SITEID || $modid != 0) {
211 $joins[] = "l.course='$course->id'";
214 if ($modname) {
215 $joins[] = "l.module = '$modname'";
218 if ('site_errors' === $modid) {
219 $joins[] = "( l.action='error' OR l.action='infected' )";
220 } else if ($modid) {
221 $joins[] = "l.cmid = '$modid'";
224 if ($modaction) {
225 $firstletter = substr($modaction, 0, 1);
226 if (preg_match('/[[:alpha:]]/', $firstletter)) {
227 $joins[] = "lower(l.action) LIKE '%" . strtolower($modaction) . "%'";
228 } else if ($firstletter == '-') {
229 $joins[] = "lower(l.action) NOT LIKE '%" . strtolower(substr($modaction, 1)) . "%'";
234 /// Getting all members of a group.
235 if ($groupid and !$user) {
236 if ($gusers = groups_get_members($groupid)) {
237 $gusers = array_keys($gusers);
238 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
239 } else {
240 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
243 else if ($user) {
244 $joins[] = "l.userid = '$user'";
247 if ($date) {
248 $enddate = $date + 86400;
249 $joins[] = "l.time > '$date' AND l.time < '$enddate'";
252 $selector = implode(' AND ', $joins);
254 $totalcount = 0; // Initialise
255 $result = array();
256 $result['logs'] = get_logs($selector, $order, $limitfrom, $limitnum, $totalcount);
257 $result['totalcount'] = $totalcount;
258 return $result;
262 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
263 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
265 global $CFG;
267 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
268 $modname, $modid, $modaction, $groupid)) {
269 notify("No logs found!");
270 print_footer($course);
271 exit;
274 $courses = array();
276 if ($course->id == SITEID) {
277 $courses[0] = '';
278 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
279 foreach ($ccc as $cc) {
280 $courses[$cc->id] = $cc->shortname;
283 } else {
284 $courses[$course->id] = $course->shortname;
287 $totalcount = $logs['totalcount'];
288 $count=0;
289 $ldcache = array();
290 $tt = getdate(time());
291 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
293 $strftimedatetime = get_string("strftimedatetime");
295 echo "<div class=\"info\">\n";
296 print_string("displayingrecords", "", $totalcount);
297 echo "</div>\n";
299 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
301 echo '<table class="logtable generalbox boxaligncenter" summary="">'."\n";
302 // echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\" summary=\"\">\n";
303 echo "<tr>";
304 if ($course->id == SITEID) {
305 echo "<th class=\"c0 header\" scope=\"col\">".get_string('course')."</th>\n";
307 echo "<th class=\"c1 header\" scope=\"col\">".get_string('time')."</th>\n";
308 echo "<th class=\"c2 header\" scope=\"col\">".get_string('ip_address')."</th>\n";
309 echo "<th class=\"c3 header\" scope=\"col\">".get_string('fullname')."</th>\n";
310 echo "<th class=\"c4 header\" scope=\"col\">".get_string('action')."</th>\n";
311 echo "<th class=\"c5 header\" scope=\"col\">".get_string('info')."</th>\n";
312 echo "</tr>\n";
314 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
315 if (empty($logs['logs'])) {
316 $logs['logs'] = array();
319 $row = 1;
320 foreach ($logs['logs'] as $log) {
322 $row = ($row + 1) % 2;
324 if (isset($ldcache[$log->module][$log->action])) {
325 $ld = $ldcache[$log->module][$log->action];
326 } else {
327 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
328 $ldcache[$log->module][$log->action] = $ld;
330 if ($ld && is_numeric($log->info)) {
331 // ugly hack to make sure fullname is shown correctly
332 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
333 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
334 } else {
335 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
339 //Filter log->info
340 $log->info = format_string($log->info);
342 // If $log->url has been trimmed short by the db size restriction
343 // code in add_to_log, keep a note so we don't add a link to a broken url
344 $tl=textlib_get_instance();
345 $brokenurl=($tl->strlen($log->url)==100 && $tl->substr($log->url,97)=='...');
347 echo '<tr class="r'.$row.'">';
348 if ($course->id == SITEID) {
349 echo "<td class=\"cell c0\">\n";
350 if (empty($log->course)) {
351 echo get_string('site') . "\n";
352 } else {
353 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course])."</a>\n";
355 echo "</td>\n";
357 echo "<td class=\"cell c1\" align=\"right\">".userdate($log->time, '%a').
358 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
359 echo "<td class=\"cell c2\">\n";
360 link_to_popup_window("/iplookup/index.php?ip=$log->ip&amp;user=$log->userid", 'iplookup',$log->ip, 440, 700);
361 echo "</td>\n";
362 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
363 echo "<td class=\"cell c3\">\n";
364 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}&amp;course={$log->course}\">$fullname</a>\n";
365 echo "</td>\n";
366 echo "<td class=\"cell c4\">\n";
367 $displayaction="$log->module $log->action";
368 if($brokenurl) {
369 echo $displayaction;
370 } else {
371 link_to_popup_window( make_log_url($log->module,$log->url), 'fromloglive',$displayaction, 440, 700);
373 echo "</td>\n";;
374 echo "<td class=\"cell c5\">{$log->info}</td>\n";
375 echo "</tr>\n";
377 echo "</table>\n";
379 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
383 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
384 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
386 global $CFG;
388 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
389 $modname, $modid, $modaction, $groupid)) {
390 notify("No logs found!");
391 print_footer($course);
392 exit;
395 if ($course->id == SITEID) {
396 $courses[0] = '';
397 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
398 foreach ($ccc as $cc) {
399 $courses[$cc->id] = $cc->shortname;
404 $totalcount = $logs['totalcount'];
405 $count=0;
406 $ldcache = array();
407 $tt = getdate(time());
408 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
410 $strftimedatetime = get_string("strftimedatetime");
412 echo "<div class=\"info\">\n";
413 print_string("displayingrecords", "", $totalcount);
414 echo "</div>\n";
416 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
418 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
419 echo "<tr>";
420 if ($course->id == SITEID) {
421 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
423 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
424 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
425 echo "<th class=\"c3 header\">".get_string('fullname')."</th>\n";
426 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
427 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
428 echo "</tr>\n";
430 if (empty($logs['logs'])) {
431 echo "</table>\n";
432 return;
435 $row = 1;
436 foreach ($logs['logs'] as $log) {
438 $log->info = $log->coursename;
439 $row = ($row + 1) % 2;
441 if (isset($ldcache[$log->module][$log->action])) {
442 $ld = $ldcache[$log->module][$log->action];
443 } else {
444 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
445 $ldcache[$log->module][$log->action] = $ld;
447 if (0 && $ld && !empty($log->info)) {
448 // ugly hack to make sure fullname is shown correctly
449 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
450 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
451 } else {
452 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
456 //Filter log->info
457 $log->info = format_string($log->info);
459 echo '<tr class="r'.$row.'">';
460 if ($course->id == SITEID) {
461 echo "<td class=\"r$row c0\" >\n";
462 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courses[$log->course]."</a>\n";
463 echo "</td>\n";
465 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time, '%a').
466 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
467 echo "<td class=\"r$row c2\" >\n";
468 link_to_popup_window("/iplookup/index.php?ip=$log->ip&amp;user=$log->userid", 'iplookup',$log->ip, 400, 700);
469 echo "</td>\n";
470 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
471 echo "<td class=\"r$row c3\" >\n";
472 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
473 echo "</td>\n";
474 echo "<td class=\"r$row c4\">\n";
475 echo $log->action .': '.$log->module;
476 echo "</td>\n";;
477 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
478 echo "</tr>\n";
480 echo "</table>\n";
482 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
486 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
487 $modid, $modaction, $groupid) {
489 $text = get_string('course')."\t".get_string('time')."\t".get_string('ip_address')."\t".
490 get_string('fullname')."\t".get_string('action')."\t".get_string('info');
492 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
493 $modname, $modid, $modaction, $groupid)) {
494 return false;
497 $courses = array();
499 if ($course->id == SITEID) {
500 $courses[0] = '';
501 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
502 foreach ($ccc as $cc) {
503 $courses[$cc->id] = $cc->shortname;
506 } else {
507 $courses[$course->id] = $course->shortname;
510 $count=0;
511 $ldcache = array();
512 $tt = getdate(time());
513 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
515 $strftimedatetime = get_string("strftimedatetime");
517 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
518 $filename .= '.txt';
519 header("Content-Type: application/download\n");
520 header("Content-Disposition: attachment; filename=$filename");
521 header("Expires: 0");
522 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
523 header("Pragma: public");
525 echo get_string('savedat').userdate(time(), $strftimedatetime)."\n";
526 echo $text;
528 if (empty($logs['logs'])) {
529 return true;
532 foreach ($logs['logs'] as $log) {
533 if (isset($ldcache[$log->module][$log->action])) {
534 $ld = $ldcache[$log->module][$log->action];
535 } else {
536 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
537 $ldcache[$log->module][$log->action] = $ld;
539 if ($ld && !empty($log->info)) {
540 // ugly hack to make sure fullname is shown correctly
541 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
542 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
543 } else {
544 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
548 //Filter log->info
549 $log->info = format_string($log->info);
550 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
552 $firstField = $courses[$log->course];
553 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
554 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action, $log->info);
555 $text = implode("\t", $row);
556 echo $text." \n";
558 return true;
562 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
563 $modid, $modaction, $groupid) {
565 global $CFG;
567 require_once("$CFG->libdir/excellib.class.php");
569 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
570 $modname, $modid, $modaction, $groupid)) {
571 return false;
574 $courses = array();
576 if ($course->id == SITEID) {
577 $courses[0] = '';
578 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
579 foreach ($ccc as $cc) {
580 $courses[$cc->id] = $cc->shortname;
583 } else {
584 $courses[$course->id] = $course->shortname;
587 $count=0;
588 $ldcache = array();
589 $tt = getdate(time());
590 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
592 $strftimedatetime = get_string("strftimedatetime");
594 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
595 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
596 $filename .= '.xls';
598 $workbook = new MoodleExcelWorkbook('-');
599 $workbook->send($filename);
601 $worksheet = array();
602 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
603 get_string('fullname'), get_string('action'), get_string('info'));
605 // Creating worksheets
606 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
607 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
608 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
609 $worksheet[$wsnumber]->set_column(1, 1, 30);
610 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
611 userdate(time(), $strftimedatetime));
612 $col = 0;
613 foreach ($headers as $item) {
614 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
615 $col++;
619 if (empty($logs['logs'])) {
620 $workbook->close();
621 return true;
624 $formatDate =& $workbook->add_format();
625 $formatDate->set_num_format(get_string('log_excel_date_format'));
627 $row = FIRSTUSEDEXCELROW;
628 $wsnumber = 1;
629 $myxls =& $worksheet[$wsnumber];
630 foreach ($logs['logs'] as $log) {
631 if (isset($ldcache[$log->module][$log->action])) {
632 $ld = $ldcache[$log->module][$log->action];
633 } else {
634 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
635 $ldcache[$log->module][$log->action] = $ld;
637 if ($ld && !empty($log->info)) {
638 // ugly hack to make sure fullname is shown correctly
639 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
640 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
641 } else {
642 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
646 // Filter log->info
647 $log->info = format_string($log->info);
648 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
650 if ($nroPages>1) {
651 if ($row > EXCELROWS) {
652 $wsnumber++;
653 $myxls =& $worksheet[$wsnumber];
654 $row = FIRSTUSEDEXCELROW;
658 $myxls->write($row, 0, $courses[$log->course], '');
659 // Excel counts from 1/1/1900
660 $excelTime=25569+$log->time/(3600*24);
661 $myxls->write($row, 1, $excelTime, $formatDate);
662 $myxls->write($row, 2, $log->ip, '');
663 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
664 $myxls->write($row, 3, $fullname, '');
665 $myxls->write($row, 4, $log->module.' '.$log->action, '');
666 $myxls->write($row, 5, $log->info, '');
668 $row++;
671 $workbook->close();
672 return true;
675 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
676 $modid, $modaction, $groupid) {
678 global $CFG;
680 require_once("$CFG->libdir/odslib.class.php");
682 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
683 $modname, $modid, $modaction, $groupid)) {
684 return false;
687 $courses = array();
689 if ($course->id == SITEID) {
690 $courses[0] = '';
691 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
692 foreach ($ccc as $cc) {
693 $courses[$cc->id] = $cc->shortname;
696 } else {
697 $courses[$course->id] = $course->shortname;
700 $count=0;
701 $ldcache = array();
702 $tt = getdate(time());
703 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
705 $strftimedatetime = get_string("strftimedatetime");
707 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
708 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
709 $filename .= '.ods';
711 $workbook = new MoodleODSWorkbook('-');
712 $workbook->send($filename);
714 $worksheet = array();
715 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
716 get_string('fullname'), get_string('action'), get_string('info'));
718 // Creating worksheets
719 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
720 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
721 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
722 $worksheet[$wsnumber]->set_column(1, 1, 30);
723 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
724 userdate(time(), $strftimedatetime));
725 $col = 0;
726 foreach ($headers as $item) {
727 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
728 $col++;
732 if (empty($logs['logs'])) {
733 $workbook->close();
734 return true;
737 $formatDate =& $workbook->add_format();
738 $formatDate->set_num_format(get_string('log_excel_date_format'));
740 $row = FIRSTUSEDEXCELROW;
741 $wsnumber = 1;
742 $myxls =& $worksheet[$wsnumber];
743 foreach ($logs['logs'] as $log) {
744 if (isset($ldcache[$log->module][$log->action])) {
745 $ld = $ldcache[$log->module][$log->action];
746 } else {
747 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
748 $ldcache[$log->module][$log->action] = $ld;
750 if ($ld && !empty($log->info)) {
751 // ugly hack to make sure fullname is shown correctly
752 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
753 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
754 } else {
755 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
759 // Filter log->info
760 $log->info = format_string($log->info);
761 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
763 if ($nroPages>1) {
764 if ($row > EXCELROWS) {
765 $wsnumber++;
766 $myxls =& $worksheet[$wsnumber];
767 $row = FIRSTUSEDEXCELROW;
771 $myxls->write_string($row, 0, $courses[$log->course]);
772 $myxls->write_date($row, 1, $log->time);
773 $myxls->write_string($row, 2, $log->ip);
774 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
775 $myxls->write_string($row, 3, $fullname);
776 $myxls->write_string($row, 4, $log->module.' '.$log->action);
777 $myxls->write_string($row, 5, $log->info);
779 $row++;
782 $workbook->close();
783 return true;
787 function print_log_graph($course, $userid=0, $type="course.png", $date=0) {
788 global $CFG, $USER;
789 if (empty($CFG->gdversion)) {
790 echo "(".get_string("gdneed").")";
791 } else {
792 // MDL-10818, do not display broken graph when user has no permission to view graph
793 if (has_capability('coursereport/log:view', get_context_instance(CONTEXT_COURSE, $course->id)) ||
794 ($course->showreports and $USER->id == $userid)) {
795 echo '<img src="'.$CFG->wwwroot.'/course/report/log/graph.php?id='.$course->id.
796 '&amp;user='.$userid.'&amp;type='.$type.'&amp;date='.$date.'" alt="" />';
802 function print_overview($courses) {
804 global $CFG, $USER;
806 $htmlarray = array();
807 if ($modules = get_records('modules')) {
808 foreach ($modules as $mod) {
809 if (file_exists(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php')) {
810 include_once(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php');
811 $fname = $mod->name.'_print_overview';
812 if (function_exists($fname)) {
813 $fname($courses,$htmlarray);
818 foreach ($courses as $course) {
819 print_simple_box_start('center', '100%', '', 5, "coursebox");
820 $linkcss = '';
821 if (empty($course->visible)) {
822 $linkcss = 'class="dimmed"';
824 print_heading('<a title="'. format_string($course->fullname).'" '.$linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'. format_string($course->fullname).'</a>');
825 if (array_key_exists($course->id,$htmlarray)) {
826 foreach ($htmlarray[$course->id] as $modname => $html) {
827 echo $html;
830 print_simple_box_end();
835 function print_recent_activity($course) {
836 // $course is an object
837 // This function trawls through the logs looking for
838 // anything new since the user's last login
840 global $CFG, $USER, $SESSION;
842 $context = get_context_instance(CONTEXT_COURSE, $course->id);
844 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
846 $timestart = round(time() - COURSE_MAX_RECENT_PERIOD, -2); // better db caching for guests - 100 seconds
848 if (!has_capability('moodle/legacy:guest', $context, NULL, false)) {
849 if (!empty($USER->lastcourseaccess[$course->id])) {
850 if ($USER->lastcourseaccess[$course->id] > $timestart) {
851 $timestart = $USER->lastcourseaccess[$course->id];
856 echo '<div class="activitydate">';
857 echo get_string('activitysince', '', userdate($timestart));
858 echo '</div>';
859 echo '<div class="activityhead">';
861 echo '<a href="'.$CFG->wwwroot.'/course/recent.php?id='.$course->id.'">'.get_string('recentactivityreport').'</a>';
863 echo "</div>\n";
865 $content = false;
867 /// Firstly, have there been any new enrolments?
869 $users = get_recent_enrolments($course->id, $timestart);
871 //Accessibility: new users now appear in an <OL> list.
872 if ($users) {
873 echo '<div class="newusers">';
874 print_headline(get_string("newusers").':', 3);
875 $content = true;
876 echo "<ol class=\"list\">\n";
877 foreach ($users as $user) {
878 $fullname = fullname($user, $viewfullnames);
879 echo '<li class="name"><a href="'."$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a></li>\n";
881 echo "</ol>\n</div>\n";
884 /// Next, have there been any modifications to the course structure?
886 $modinfo =& get_fast_modinfo($course);
888 $changelist = array();
890 $logs = get_records_select('log', "time > $timestart AND course = $course->id AND
891 module = 'course' AND
892 (action = 'add mod' OR action = 'update mod' OR action = 'delete mod')",
893 "id ASC");
895 if ($logs) {
896 $actions = array('add mod', 'update mod', 'delete mod');
897 $newgones = array(); // added and later deleted items
898 foreach ($logs as $key => $log) {
899 if (!in_array($log->action, $actions)) {
900 continue;
902 $info = split(' ', $log->info);
904 if ($info[0] == 'label') { // Labels are ignored in recent activity
905 continue;
908 if (count($info) != 2) {
909 debugging("Incorrect log entry info: id = ".$log->id, DEBUG_DEVELOPER);
910 continue;
913 $modname = $info[0];
914 $instanceid = $info[1];
916 if ($log->action == 'delete mod') {
917 // unfortunately we do not know if the mod was visible
918 if (!array_key_exists($log->info, $newgones)) {
919 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $modname));
920 $changelist[$log->info] = array ('operation' => 'delete', 'text' => $strdeleted);
922 } else {
923 if (!isset($modinfo->instances[$modname][$instanceid])) {
924 if ($log->action == 'add mod') {
925 // do not display added and later deleted activities
926 $newgones[$log->info] = true;
928 continue;
930 $cm = $modinfo->instances[$modname][$instanceid];
931 if (!$cm->uservisible) {
932 continue;
935 if ($log->action == 'add mod') {
936 $stradded = get_string('added', 'moodle', get_string('modulename', $modname));
937 $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>");
939 } else if ($log->action == 'update mod' and empty($changelist[$log->info])) {
940 $strupdated = get_string('updated', 'moodle', get_string('modulename', $modname));
941 $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>");
947 if (!empty($changelist)) {
948 print_headline(get_string('courseupdates').':', 3);
949 $content = true;
950 foreach ($changelist as $changeinfo => $change) {
951 echo '<p class="activity">'.$change['text'].'</p>';
955 /// Now display new things from each module
957 $usedmodules = array();
958 foreach($modinfo->cms as $cm) {
959 if (isset($usedmodules[$cm->modname])) {
960 continue;
962 if (!$cm->uservisible) {
963 continue;
965 $usedmodules[$cm->modname] = $cm->modname;
968 foreach ($usedmodules as $modname) { // Each module gets it's own logs and prints them
969 if (file_exists($CFG->dirroot.'/mod/'.$modname.'/lib.php')) {
970 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
971 $print_recent_activity = $modname.'_print_recent_activity';
972 if (function_exists($print_recent_activity)) {
973 // NOTE: original $isteacher (second parameter below) was replaced with $viewfullnames!
974 $content = $print_recent_activity($course, $viewfullnames, $timestart) || $content;
976 } else {
977 debugging("Missing lib.php in lib/{$modname} - please reinstall files or uninstall the module");
981 if (! $content) {
982 echo '<p class="message">'.get_string('nothingnew').'</p>';
987 function get_array_of_activities($courseid) {
988 // For a given course, returns an array of course activity objects
989 // Each item in the array contains he following properties:
990 // cm - course module id
991 // mod - name of the module (eg forum)
992 // section - the number of the section (eg week or topic)
993 // name - the name of the instance
994 // visible - is the instance visible or not
995 // groupingid - grouping id
996 // groupmembersonly - is this instance visible to group members only
997 // extra - contains extra string to include in any link
999 global $CFG;
1001 $mod = array();
1003 if (!$rawmods = get_course_mods($courseid)) {
1004 return $mod; // always return array
1007 if ($sections = get_records("course_sections", "course", $courseid, "section ASC")) {
1008 foreach ($sections as $section) {
1009 if (!empty($section->sequence)) {
1010 $sequence = explode(",", $section->sequence);
1011 foreach ($sequence as $seq) {
1012 if (empty($rawmods[$seq])) {
1013 continue;
1015 $mod[$seq]->id = $rawmods[$seq]->instance;
1016 $mod[$seq]->cm = $rawmods[$seq]->id;
1017 $mod[$seq]->mod = $rawmods[$seq]->modname;
1018 $mod[$seq]->section = $section->section;
1019 $mod[$seq]->visible = $rawmods[$seq]->visible;
1020 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
1021 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
1022 $mod[$seq]->groupmembersonly = $rawmods[$seq]->groupmembersonly;
1023 $mod[$seq]->extra = "";
1025 $modname = $mod[$seq]->mod;
1026 $functionname = $modname."_get_coursemodule_info";
1028 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
1029 continue;
1032 include_once("$CFG->dirroot/mod/$modname/lib.php");
1034 if (function_exists($functionname)) {
1035 if ($info = $functionname($rawmods[$seq])) {
1036 if (!empty($info->extra)) {
1037 $mod[$seq]->extra = $info->extra;
1039 if (!empty($info->icon)) {
1040 $mod[$seq]->icon = $info->icon;
1042 if (!empty($info->name)) {
1043 $mod[$seq]->name = urlencode($info->name);
1047 if (!isset($mod[$seq]->name)) {
1048 $mod[$seq]->name = urlencode(get_field($rawmods[$seq]->modname, "name", "id", $rawmods[$seq]->instance));
1054 return $mod;
1059 * Returns reference to full info about modules in course (including visibility).
1060 * Cached and as fast as possible (0 or 1 db query).
1061 * @param $course object or 'reset' string to reset caches, modinfo may be updated in db
1062 * @return mixed courseinfo object or nothing if resetting
1064 function &get_fast_modinfo(&$course, $userid=0) {
1065 global $CFG, $USER;
1067 static $cache = array();
1069 if ($course === 'reset') {
1070 $cache = array();
1071 $nothing = null;
1072 return $nothing; // we must return some reference
1075 if (empty($userid)) {
1076 $userid = $USER->id;
1079 if (array_key_exists($course->id, $cache) and $cache[$course->id]->userid == $userid) {
1080 return $cache[$course->id];
1083 if (empty($course->modinfo)) {
1084 // no modinfo yet - load it
1085 rebuild_course_cache($course->id);
1086 $course->modinfo = get_field('course', 'modinfo', 'id', $course->id);
1089 $modinfo = new object();
1090 $modinfo->courseid = $course->id;
1091 $modinfo->userid = $userid;
1092 $modinfo->sections = array();
1093 $modinfo->cms = array();
1094 $modinfo->instances = array();
1095 $modinfo->groups = null; // loaded only when really needed - the only one db query
1097 $info = unserialize($course->modinfo);
1098 if (!is_array($info)) {
1099 // hmm, something is wrong - lets try to fix it
1100 rebuild_course_cache($course->id);
1101 $course->modinfo = get_field('course', 'modinfo', 'id', $course->id);
1102 $info = unserialize($course->modinfo);
1103 if (!is_array($info)) {
1104 return $modinfo;
1108 if ($info) {
1109 // detect if upgrade required
1110 $first = reset($info);
1111 if (!isset($first->id)) {
1112 rebuild_course_cache($course->id);
1113 $course->modinfo = get_field('course', 'modinfo', 'id', $course->id);
1114 $info = unserialize($course->modinfo);
1115 if (!is_array($info)) {
1116 return $modinfo;
1121 $modlurals = array();
1123 // If we haven't already preloaded contexts for the course, do it now
1124 preload_course_contexts($course->id);
1126 foreach ($info as $mod) {
1127 if (empty($mod->name)) {
1128 // something is wrong here
1129 continue;
1131 // reconstruct minimalistic $cm
1132 $cm = new object();
1133 $cm->id = $mod->cm;
1134 $cm->instance = $mod->id;
1135 $cm->course = $course->id;
1136 $cm->modname = $mod->mod;
1137 $cm->name = urldecode($mod->name);
1138 $cm->visible = $mod->visible;
1139 $cm->sectionnum = $mod->section;
1140 $cm->groupmode = $mod->groupmode;
1141 $cm->groupingid = $mod->groupingid;
1142 $cm->groupmembersonly = $mod->groupmembersonly;
1143 $cm->extra = isset($mod->extra) ? urldecode($mod->extra) : '';
1144 $cm->icon = isset($mod->icon) ? $mod->icon : '';
1145 $cm->uservisible = true;
1147 // preload long names plurals and also check module is installed properly
1148 if (!isset($modlurals[$cm->modname])) {
1149 if (!file_exists("$CFG->dirroot/mod/$cm->modname/lib.php")) {
1150 continue;
1152 $modlurals[$cm->modname] = get_string('modulenameplural', $cm->modname);
1154 $cm->modplural = $modlurals[$cm->modname];
1156 $modcontext = get_context_instance(CONTEXT_MODULE,$cm->id);
1158 if (!$cm->visible and !has_capability('moodle/course:viewhiddenactivities',
1159 $modcontext, $userid)) {
1160 $cm->uservisible = false;
1162 } else if (!empty($CFG->enablegroupings) and !empty($cm->groupmembersonly)
1163 and !has_capability('moodle/site:accessallgroups', $modcontext, $userid)) {
1164 if (is_null($modinfo->groups)) {
1165 $modinfo->groups = groups_get_user_groups($course->id, $userid);
1167 if (empty($modinfo->groups[$cm->groupingid])) {
1168 $cm->uservisible = false;
1172 if (!isset($modinfo->instances[$cm->modname])) {
1173 $modinfo->instances[$cm->modname] = array();
1175 $modinfo->instances[$cm->modname][$cm->instance] =& $cm;
1176 $modinfo->cms[$cm->id] =& $cm;
1178 // reconstruct sections
1179 if (!isset($modinfo->sections[$cm->sectionnum])) {
1180 $modinfo->sections[$cm->sectionnum] = array();
1182 $modinfo->sections[$cm->sectionnum][] = $cm->id;
1184 unset($cm);
1187 unset($cache[$course->id]); // prevent potential reference problems when switching users
1188 $cache[$course->id] = $modinfo;
1190 // Ensure cache does not use too much RAM
1191 if (count($cache) > MAX_MODINFO_CACHE_SIZE) {
1192 reset($cache);
1193 $key = key($cache);
1194 unset($cache[$key]);
1197 return $cache[$course->id];
1201 function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
1202 // Returns a number of useful structures for course displays
1204 $mods = array(); // course modules indexed by id
1205 $modnames = array(); // all course module names (except resource!)
1206 $modnamesplural= array(); // all course module names (plural form)
1207 $modnamesused = array(); // course module names used
1209 if ($allmods = get_records("modules")) {
1210 foreach ($allmods as $mod) {
1211 if ($mod->visible) {
1212 $modnames[$mod->name] = get_string("modulename", "$mod->name");
1213 $modnamesplural[$mod->name] = get_string("modulenameplural", "$mod->name");
1216 asort($modnames, SORT_LOCALE_STRING);
1217 } else {
1218 error("No modules are installed!");
1221 if ($rawmods = get_course_mods($courseid)) {
1222 foreach($rawmods as $mod) { // Index the mods
1223 if (empty($modnames[$mod->modname])) {
1224 continue;
1226 $mods[$mod->id] = $mod;
1227 $mods[$mod->id]->modfullname = $modnames[$mod->modname];
1228 if (!$mod->visible and !has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_COURSE, $courseid))) {
1229 continue;
1231 // Check groupings
1232 if (!groups_course_module_visible($mod)) {
1233 continue;
1235 $modnamesused[$mod->modname] = $modnames[$mod->modname];
1237 if ($modnamesused) {
1238 asort($modnamesused, SORT_LOCALE_STRING);
1244 function get_all_sections($courseid) {
1246 return get_records("course_sections", "course", "$courseid", "section",
1247 "section, id, course, summary, sequence, visible");
1250 function course_set_display($courseid, $display=0) {
1251 global $USER;
1253 if ($display == "all" or empty($display)) {
1254 $display = 0;
1257 if (empty($USER->id) or $USER->username == 'guest') {
1258 //do not store settings in db for guests
1259 } else if (record_exists("course_display", "userid", $USER->id, "course", $courseid)) {
1260 set_field("course_display", "display", $display, "userid", $USER->id, "course", $courseid);
1261 } else {
1262 $record = new object();
1263 $record->userid = $USER->id;
1264 $record->course = $courseid;
1265 $record->display = $display;
1266 if (!insert_record("course_display", $record)) {
1267 notify("Could not save your course display!");
1271 return $USER->display[$courseid] = $display; // Note: = not ==
1274 function set_section_visible($courseid, $sectionnumber, $visibility) {
1275 /// For a given course section, markes it visible or hidden,
1276 /// and does the same for every activity in that section
1278 if ($section = get_record("course_sections", "course", $courseid, "section", $sectionnumber)) {
1279 set_field("course_sections", "visible", "$visibility", "id", $section->id);
1280 if (!empty($section->sequence)) {
1281 $modules = explode(",", $section->sequence);
1282 foreach ($modules as $moduleid) {
1283 set_coursemodule_visible($moduleid, $visibility, true);
1286 rebuild_course_cache($courseid);
1291 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%") {
1292 /// Prints a section full of activity modules
1293 global $CFG, $USER;
1295 static $initialised;
1297 static $groupbuttons;
1298 static $groupbuttonslink;
1299 static $isediting;
1300 static $ismoving;
1301 static $strmovehere;
1302 static $strmovefull;
1303 static $strunreadpostsone;
1304 static $usetracking;
1305 static $groupings;
1308 if (!isset($initialised)) {
1309 $groupbuttons = ($course->groupmode or (!$course->groupmodeforce));
1310 $groupbuttonslink = (!$course->groupmodeforce);
1311 $isediting = isediting($course->id);
1312 $ismoving = $isediting && ismoving($course->id);
1313 if ($ismoving) {
1314 $strmovehere = get_string("movehere");
1315 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1317 include_once($CFG->dirroot.'/mod/forum/lib.php');
1318 if ($usetracking = forum_tp_can_track_forums()) {
1319 $strunreadpostsone = get_string('unreadpostsone', 'forum');
1321 $initialised = true;
1324 $labelformatoptions = new object();
1325 $labelformatoptions->noclean = true;
1327 /// Casting $course->modinfo to string prevents one notice when the field is null
1328 $modinfo = get_fast_modinfo($course);
1331 //Acccessibility: replace table with list <ul>, but don't output empty list.
1332 if (!empty($section->sequence)) {
1334 // Fix bug #5027, don't want style=\"width:$width\".
1335 echo "<ul class=\"section img-text\">\n";
1336 $sectionmods = explode(",", $section->sequence);
1338 foreach ($sectionmods as $modnumber) {
1339 if (empty($mods[$modnumber])) {
1340 continue;
1343 $mod = $mods[$modnumber];
1345 if ($ismoving and $mod->id == $USER->activitycopy) {
1346 // do not display moving mod
1347 continue;
1350 if (isset($modinfo->cms[$modnumber])) {
1351 if (!$modinfo->cms[$modnumber]->uservisible) {
1352 // visibility shortcut
1353 continue;
1355 } else {
1356 if (!file_exists("$CFG->dirroot/mod/$mod->modname/lib.php")) {
1357 // module not installed
1358 continue;
1360 if (!coursemodule_visible_for_user($mod)) {
1361 // full visibility check
1362 continue;
1366 echo '<li class="activity '.$mod->modname.'" id="module-'.$modnumber.'">'; // Unique ID
1367 if ($ismoving) {
1368 echo '<a title="'.$strmovefull.'"'.
1369 ' href="'.$CFG->wwwroot.'/course/mod.php?moveto='.$mod->id.'&amp;sesskey='.$USER->sesskey.'">'.
1370 '<img class="movetarget" src="'.$CFG->pixpath.'/movehere.gif" '.
1371 ' alt="'.$strmovehere.'" /></a><br />
1375 if ($mod->indent) {
1376 print_spacer(12, 20 * $mod->indent, false);
1379 $extra = '';
1380 if (!empty($modinfo->cms[$modnumber]->extra)) {
1381 $extra = $modinfo->cms[$modnumber]->extra;
1384 if ($mod->modname == "label") {
1385 echo "<span class=\"";
1386 if (!$mod->visible) {
1387 echo 'dimmed_text';
1388 } else {
1389 echo 'label';
1391 echo '">';
1392 echo format_text($extra, FORMAT_HTML, $labelformatoptions);
1393 echo "</span>";
1394 if (!empty($CFG->enablegroupings) && !empty($mod->groupingid) && has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
1395 if (!isset($groupings)) {
1396 $groupings = groups_get_all_groupings($course->id);
1398 echo " <span class=\"groupinglabel\">(".format_string($groupings[$mod->groupingid]->name).')</span>';
1401 } else { // Normal activity
1402 $instancename = format_string($modinfo->cms[$modnumber]->name, true, $course->id);
1404 if (!empty($modinfo->cms[$modnumber]->icon)) {
1405 $icon = "$CFG->pixpath/".$modinfo->cms[$modnumber]->icon;
1406 } else {
1407 $icon = "$CFG->modpixpath/$mod->modname/icon.gif";
1410 //Accessibility: for files get description via icon.
1411 $altname = '';
1412 if ('resource'==$mod->modname) {
1413 if (!empty($modinfo->cms[$modnumber]->icon)) {
1414 $possaltname = $modinfo->cms[$modnumber]->icon;
1416 $mimetype = mimeinfo_from_icon('type', $possaltname);
1417 $altname = get_mimetype_description($mimetype);
1418 } else {
1419 $altname = $mod->modfullname;
1421 } else {
1422 $altname = $mod->modfullname;
1424 // Avoid unnecessary duplication.
1425 if (false!==stripos($instancename, $altname)) {
1426 $altname = '';
1428 // File type after name, for alphabetic lists (screen reader).
1429 if ($altname) {
1430 $altname = get_accesshide(' '.$altname);
1433 $linkcss = $mod->visible ? "" : " class=\"dimmed\" ";
1434 echo '<a '.$linkcss.' '.$extra. // Title unnecessary!
1435 ' href="'.$CFG->wwwroot.'/mod/'.$mod->modname.'/view.php?id='.$mod->id.'">'.
1436 '<img src="'.$icon.'" class="activityicon" alt="" /> <span>'.
1437 $instancename.$altname.'</span></a>';
1439 if (!empty($CFG->enablegroupings) && !empty($mod->groupingid) && has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
1440 if (!isset($groupings)) {
1441 $groupings = groups_get_all_groupings($course->id);
1443 echo " <span class=\"groupinglabel\">(".format_string($groupings[$mod->groupingid]->name).')</span>';
1446 if ($usetracking && $mod->modname == 'forum') {
1447 if ($unread = forum_tp_count_forum_unread_posts($mod, $course)) {
1448 echo '<span class="unread"> <a href="'.$CFG->wwwroot.'/mod/forum/view.php?id='.$mod->id.'">';
1449 if ($unread == 1) {
1450 echo $strunreadpostsone;
1451 } else {
1452 print_string('unreadpostsnumber', 'forum', $unread);
1454 echo '</a></span>';
1458 if ($isediting) {
1459 // TODO: we must define this as mod property!
1460 if ($groupbuttons and $mod->modname != 'label' and $mod->modname != 'resource' and $mod->modname != 'glossary') {
1461 if (! $mod->groupmodelink = $groupbuttonslink) {
1462 $mod->groupmode = $course->groupmode;
1465 } else {
1466 $mod->groupmode = false;
1468 echo '&nbsp;&nbsp;';
1469 echo make_editing_buttons($mod, $absolute, true, $mod->indent, $section->section);
1471 echo "</li>\n";
1474 } elseif ($ismoving) {
1475 echo "<ul class=\"section\">\n";
1478 if ($ismoving) {
1479 echo '<li><a title="'.$strmovefull.'"'.
1480 ' href="'.$CFG->wwwroot.'/course/mod.php?movetosection='.$section->id.'&amp;sesskey='.$USER->sesskey.'">'.
1481 '<img class="movetarget" src="'.$CFG->pixpath.'/movehere.gif" '.
1482 ' alt="'.$strmovehere.'" /></a></li>
1485 if (!empty($section->sequence) || $ismoving) {
1486 echo "</ul><!--class='section'-->\n\n";
1491 * Prints the menus to add activities and resources.
1493 function print_section_add_menus($course, $section, $modnames, $vertical=false, $return=false) {
1494 global $CFG;
1496 // check to see if user can add menus
1497 if (!has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $course->id))) {
1498 return false;
1501 static $resources = false;
1502 static $activities = false;
1504 if ($resources === false) {
1505 $resources = array();
1506 $activities = array();
1508 foreach($modnames as $modname=>$modnamestr) {
1509 if (!course_allowed_module($course, $modname)) {
1510 continue;
1513 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1514 if (!file_exists($libfile)) {
1515 continue;
1517 include_once($libfile);
1518 $gettypesfunc = $modname.'_get_types';
1519 if (function_exists($gettypesfunc)) {
1520 $types = $gettypesfunc();
1521 foreach($types as $type) {
1522 if (!isset($type->modclass) or !isset($type->typestr)) {
1523 debugging('Incorrect activity type in '.$modname);
1524 continue;
1526 if ($type->modclass == MOD_CLASS_RESOURCE) {
1527 $resources[$type->type] = $type->typestr;
1528 } else {
1529 $activities[$type->type] = $type->typestr;
1532 } else {
1533 // all mods without type are considered activity
1534 $activities[$modname] = $modnamestr;
1539 $straddactivity = get_string('addactivity');
1540 $straddresource = get_string('addresource');
1542 $output = '<div class="section_add_menus">';
1544 if (!$vertical) {
1545 $output .= '<div class="horizontal">';
1548 if (!empty($resources)) {
1549 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&amp;section=$section&amp;sesskey=".sesskey()."&amp;add=",
1550 $resources, "ressection$section", "", $straddresource, 'resource/types', $straddresource, true);
1553 if (!empty($activities)) {
1554 $output .= ' ';
1555 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&amp;section=$section&amp;sesskey=".sesskey()."&amp;add=",
1556 $activities, "section$section", "", $straddactivity, 'mods', $straddactivity, true);
1559 if (!$vertical) {
1560 $output .= '</div>';
1563 $output .= '</div>';
1565 if ($return) {
1566 return $output;
1567 } else {
1568 echo $output;
1573 * Return the course category context for the category with id $categoryid, except
1574 * that if $categoryid is 0, return the system context.
1576 * @param integer $categoryid a category id or 0.
1577 * @return object the corresponding context
1579 function get_category_or_system_context($categoryid) {
1580 if ($categoryid) {
1581 return get_context_instance(CONTEXT_COURSECAT, $categoryid);
1582 } else {
1583 return get_context_instance(CONTEXT_SYSTEM);
1588 * Rebuilds the cached list of course activities stored in the database
1589 * @param int $courseid - id of course to rebuil, empty means all
1590 * @param boolean $clearonly - only clear the modinfo fields, gets rebuild automatically on the fly
1592 function rebuild_course_cache($courseid=0, $clearonly=false) {
1593 global $COURSE;
1595 if ($clearonly) {
1596 $courseselect = empty($courseid) ? "" : "id = $courseid";
1597 set_field_select('course', 'modinfo', null, $courseselect);
1598 // update cached global COURSE too ;-)
1599 if ($courseid == $COURSE->id) {
1600 $COURSE->modinfo = null;
1602 // reset the fast modinfo cache
1603 $reset = 'reset';
1604 get_fast_modinfo($reset);
1605 return;
1608 if ($courseid) {
1609 $select = "id = '$courseid'";
1610 } else {
1611 $select = "";
1612 @set_time_limit(0); // this could take a while! MDL-10954
1615 if ($rs = get_recordset_select("course", $select,'','id,fullname')) {
1616 while($course = rs_fetch_next_record($rs)) {
1617 $modinfo = serialize(get_array_of_activities($course->id));
1618 if (!set_field("course", "modinfo", $modinfo, "id", $course->id)) {
1619 notify("Could not cache module information for course '" . format_string($course->fullname) . "'!");
1621 // update cached global COURSE too ;-)
1622 if ($course->id == $COURSE->id) {
1623 $COURSE->modinfo = $modinfo;
1626 rs_close($rs);
1628 // reset the fast modinfo cache
1629 $reset = 'reset';
1630 get_fast_modinfo($reset);
1634 * Gets the child categories of a given coures category. Uses a static cache
1635 * to make repeat calls efficient.
1637 * @param unknown_type $parentid the id of a course category.
1638 * @return array all the child course categories.
1640 function get_child_categories($parentid) {
1641 static $allcategories = null;
1643 // only fill in this variable the first time
1644 if (null == $allcategories) {
1645 $allcategories = array();
1647 $categories = get_categories();
1648 foreach ($categories as $category) {
1649 if (empty($allcategories[$category->parent])) {
1650 $allcategories[$category->parent] = array();
1652 $allcategories[$category->parent][] = $category;
1656 if (empty($allcategories[$parentid])) {
1657 return array();
1658 } else {
1659 return $allcategories[$parentid];
1664 * This function recursively travels the categories, building up a nice list
1665 * for display. It also makes an array that list all the parents for each
1666 * category.
1668 * For example, if you have a tree of categories like:
1669 * Miscellaneous (id = 1)
1670 * Subcategory (id = 2)
1671 * Sub-subcategory (id = 4)
1672 * Other category (id = 3)
1673 * Then after calling this function you will have
1674 * $list = array(1 => 'Miscellaneous', 2 => 'Miscellaneous / Subcategory',
1675 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
1676 * 3 => 'Other category');
1677 * $parents = array(2 => array(1), 4 => array(1, 2));
1679 * If you specify $requiredcapability, then only categories where the current
1680 * user has that capability will be added to $list, although all categories
1681 * will still be added to $parents, and if you only have $requiredcapability
1682 * in a child category, not the parent, then the child catgegory will still be
1683 * included.
1685 * If you specify the option $excluded, then that category, and all its children,
1686 * are omitted from the tree. This is useful when you are doing something like
1687 * moving categories, where you do not want to allow people to move a category
1688 * to be the child of itself.
1690 * @param array $list For output, accumulates an array categoryid => full category path name
1691 * @param array $parents For output, accumulates an array categoryid => list of parent category ids.
1692 * @param string/array $requiredcapability if given, only categories where the current
1693 * user has this capability will be added to $list. Can also be an array of capabilities,
1694 * in which case they are all required.
1695 * @param integer $excludeid Omit this category and its children from the lists built.
1696 * @param object $category Build the tree starting at this category - otherwise starts at the top level.
1697 * @param string $path For internal use, as part of recursive calls.
1699 function make_categories_list(&$list, &$parents, $requiredcapability = '',
1700 $excludeid = 0, $category = NULL, $path = "") {
1702 // initialize the arrays if needed
1703 if (!is_array($list)) {
1704 $list = array();
1706 if (!is_array($parents)) {
1707 $parents = array();
1710 if (empty($category)) {
1711 // Start at the top level.
1712 $category = new stdClass;
1713 $category->id = 0;
1714 } else {
1715 // This is the excluded category, don't include it.
1716 if ($excludeid > 0 && $excludeid == $category->id) {
1717 return;
1720 // Update $path.
1721 if ($path) {
1722 $path = $path.' / '.format_string($category->name);
1723 } else {
1724 $path = format_string($category->name);
1727 // Add this category to $list, if the permissions check out.
1728 if (empty($requiredcapability)) {
1729 $list[$category->id] = $path;
1731 } else {
1732 ensure_context_subobj_present($category, CONTEXT_COURSECAT);
1733 $requiredcapability = (array)$requiredcapability;
1734 if (has_all_capabilities($requiredcapability, $category->context)) {
1735 $list[$category->id] = $path;
1740 // Add all the children recursively, while updating the parents array.
1741 if ($categories = get_child_categories($category->id)) {
1742 foreach ($categories as $cat) {
1743 if (!empty($category->id)) {
1744 if (isset($parents[$category->id])) {
1745 $parents[$cat->id] = $parents[$category->id];
1747 $parents[$cat->id][] = $category->id;
1749 make_categories_list($list, $parents, $requiredcapability, $excludeid, $cat, $path);
1754 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true) {
1755 /// Recursive function to print out all the categories in a nice format
1756 /// with or without courses included
1757 global $CFG;
1759 // maxcategorydepth == 0 meant no limit
1760 if (!empty($CFG->maxcategorydepth) && $depth >= $CFG->maxcategorydepth) {
1761 return;
1764 if (!$displaylist) {
1765 make_categories_list($displaylist, $parentslist);
1768 if ($category) {
1769 if ($category->visible or has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_SYSTEM))) {
1770 print_category_info($category, $depth, $showcourses);
1771 } else {
1772 return; // Don't bother printing children of invisible categories
1775 } else {
1776 $category->id = "0";
1779 if ($categories = get_child_categories($category->id)) { // Print all the children recursively
1780 $countcats = count($categories);
1781 $count = 0;
1782 $first = true;
1783 $last = false;
1784 foreach ($categories as $cat) {
1785 $count++;
1786 if ($count == $countcats) {
1787 $last = true;
1789 $up = $first ? false : true;
1790 $down = $last ? false : true;
1791 $first = false;
1793 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1, $showcourses);
1798 // this function will return $options array for choose_from_menu, with whitespace to denote nesting.
1800 function make_categories_options() {
1801 make_categories_list($cats,$parents);
1802 foreach ($cats as $key => $value) {
1803 if (array_key_exists($key,$parents)) {
1804 if ($indent = count($parents[$key])) {
1805 for ($i = 0; $i < $indent; $i++) {
1806 $cats[$key] = '&nbsp;'.$cats[$key];
1811 return $cats;
1814 function print_category_info($category, $depth, $showcourses = false) {
1815 /// Prints the category info in indented fashion
1816 /// This function is only used by print_whole_category_list() above
1818 global $CFG;
1819 static $strallowguests, $strrequireskey, $strsummary;
1821 if (empty($strsummary)) {
1822 $strallowguests = get_string('allowguests');
1823 $strrequireskey = get_string('requireskey');
1824 $strsummary = get_string('summary');
1827 $catlinkcss = $category->visible ? '' : ' class="dimmed" ';
1829 static $coursecount = null;
1830 if (null === $coursecount) {
1831 // only need to check this once
1832 $coursecount = count_records('course') <= FRONTPAGECOURSELIMIT;
1835 if ($showcourses and $coursecount) {
1836 $catimage = '<img src="'.$CFG->pixpath.'/i/course.gif" alt="" />';
1837 } else {
1838 $catimage = "&nbsp;";
1841 echo "\n\n".'<table class="categorylist">';
1843 $courses = get_courses($category->id, 'c.sortorder ASC', 'c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.password,c.summary,c.guest,c.cost,c.currency');
1844 if ($showcourses and $coursecount) {
1846 echo '<tr>';
1848 if ($depth) {
1849 $indent = $depth*30;
1850 $rows = count($courses) + 1;
1851 echo '<td class="category indentation" rowspan="'.$rows.'" valign="top">';
1852 print_spacer(10, $indent);
1853 echo '</td>';
1856 echo '<td valign="top" class="category image">'.$catimage.'</td>';
1857 echo '<td valign="top" class="category name">';
1858 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot.'/course/category.php?id='.$category->id.'">'. format_string($category->name).'</a>';
1859 echo '</td>';
1860 echo '<td class="category info">&nbsp;</td>';
1861 echo '</tr>';
1863 // does the depth exceed maxcategorydepth
1864 // maxcategorydepth == 0 or unset meant no limit
1866 $limit = !(isset($CFG->maxcategorydepth) && ($depth >= $CFG->maxcategorydepth-1));
1868 if ($courses && ($limit || $CFG->maxcategorydepth == 0)) {
1869 foreach ($courses as $course) {
1870 $linkcss = $course->visible ? '' : ' class="dimmed" ';
1871 echo '<tr><td valign="top">&nbsp;';
1872 echo '</td><td valign="top" class="course name">';
1873 echo '<a '.$linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'. format_string($course->fullname).'</a>';
1874 echo '</td><td align="right" valign="top" class="course info">';
1875 if ($course->guest ) {
1876 echo '<a title="'.$strallowguests.'" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">';
1877 echo '<img alt="'.$strallowguests.'" src="'.$CFG->pixpath.'/i/guest.gif" /></a>';
1878 } else {
1879 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath.'/spacer.gif" />';
1881 if ($course->password) {
1882 echo '<a title="'.$strrequireskey.'" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">';
1883 echo '<img alt="'.$strrequireskey.'" src="'.$CFG->pixpath.'/i/key.gif" /></a>';
1884 } else {
1885 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath.'/spacer.gif" />';
1887 if ($course->summary) {
1888 link_to_popup_window ('/course/info.php?id='.$course->id, 'courseinfo',
1889 '<img alt="'.$strsummary.'" src="'.$CFG->pixpath.'/i/info.gif" />',
1890 400, 500, $strsummary);
1891 } else {
1892 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath.'/spacer.gif" />';
1894 echo '</td></tr>';
1897 } else {
1899 echo '<tr>';
1901 if ($depth) {
1902 $indent = $depth*20;
1903 echo '<td class="category indentation" valign="top">';
1904 print_spacer(10, $indent);
1905 echo '</td>';
1908 echo '<td valign="top" class="category name">';
1909 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot.'/course/category.php?id='.$category->id.'">'. format_string($category->name).'</a>';
1910 echo '</td>';
1911 echo '<td valign="top" class="category number">';
1912 if (count($courses)) {
1913 echo count($courses);
1915 echo '</td></tr>';
1917 echo '</table>';
1921 * Print the buttons relating to course requests.
1923 * @param object $systemcontext the system context.
1925 function print_course_request_buttons($systemcontext) {
1926 global $CFG;
1927 if (empty($CFG->enablecourserequests)) {
1928 return;
1930 if (isloggedin() && !isguestuser() && !has_capability('moodle/course:create', $systemcontext) && has_capability('moodle/course:request', $systemcontext)) {
1931 /// Print a button to request a new course
1932 print_single_button('request.php', NULL, get_string('requestcourse'), 'get');
1934 /// Print a button to manage pending requests
1935 if (has_capability('moodle/site:approvecourse', $systemcontext)) {
1936 print_single_button('pending.php', NULL, get_string('coursespending'), 'get', '_self', false, '', !record_exists('course_request'));
1941 * Prints the turn editing on/off button on course/index.php or course/category.php.
1943 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
1944 * @return string HTML of the editing button, or empty string, if this user is not allowed
1945 * to see it.
1947 function update_category_button($categoryid = 0) {
1948 global $CFG, $USER;
1950 // Check permissions.
1951 $context = get_category_or_system_context($categoryid);
1952 if (!has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context)) {
1953 return '';
1956 // Work out the appropriate action.
1957 if (!empty($USER->categoryediting)) {
1958 $label = get_string('turneditingoff');
1959 $edit = 'off';
1960 } else {
1961 $label = get_string('turneditingon');
1962 $edit = 'on';
1965 // Generate the button HTML.
1966 $options = array('categoryedit' => $edit, 'sesskey' => sesskey());
1967 if ($categoryid) {
1968 $options['id'] = $categoryid;
1969 $page = 'category.php';
1970 } else {
1971 $page = 'index.php';
1973 return print_single_button($CFG->wwwroot . '/course/' . $page, $options,
1974 $label, 'get', '', true);
1977 function print_courses($category) {
1978 /// Category is 0 (for all courses) or an object
1980 global $CFG;
1982 if (!is_object($category) && $category==0) {
1983 $categories = get_child_categories(0); // Parent = 0 ie top-level categories only
1984 if (is_array($categories) && count($categories) == 1) {
1985 $category = array_shift($categories);
1986 $courses = get_courses_wmanagers($category->id,
1987 'c.sortorder ASC',
1988 array('password','summary','currency'));
1989 } else {
1990 $courses = get_courses_wmanagers('all',
1991 'c.sortorder ASC',
1992 array('password','summary','currency'));
1994 unset($categories);
1995 } else {
1996 $courses = get_courses_wmanagers($category->id,
1997 'c.sortorder ASC',
1998 array('password','summary','currency'));
2001 if ($courses) {
2002 echo '<ul class="unlist">';
2003 foreach ($courses as $course) {
2004 if ($course->visible == 1
2005 || has_capability('moodle/course:viewhiddencourses',$course->context)) {
2006 echo '<li>';
2007 print_course($course);
2008 echo "</li>\n";
2011 echo "</ul>\n";
2012 } else {
2013 print_heading(get_string("nocoursesyet"));
2014 $context = get_context_instance(CONTEXT_SYSTEM);
2015 if (has_capability('moodle/course:create', $context)) {
2016 $options = array();
2017 $options['category'] = $category->id;
2018 echo '<div class="addcoursebutton">';
2019 print_single_button($CFG->wwwroot.'/course/edit.php', $options, get_string("addnewcourse"));
2020 echo '</div>';
2026 * Print a description of a course, suitable for browsing in a list.
2028 * @param object $course the course object.
2029 * @param string $highlightterms (optional) some search terms that should be highlighted in the display.
2031 function print_course($course, $highlightterms = '') {
2033 global $CFG, $USER;
2035 if (isset($course->context)) {
2036 $context = $course->context;
2037 } else {
2038 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2041 $linkcss = $course->visible ? '' : ' class="dimmed" ';
2043 echo '<div class="coursebox clearfix">';
2044 echo '<div class="info">';
2045 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2046 $linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.
2047 highlight($highlightterms, format_string($course->fullname)).'</a></div>';
2049 /// first find all roles that are supposed to be displayed
2051 if (!empty($CFG->coursemanager)) {
2052 $managerroles = split(',', $CFG->coursemanager);
2053 $canseehidden = has_capability('moodle/role:viewhiddenassigns', $context);
2054 $namesarray = array();
2055 if (isset($course->managers)) {
2056 if (count($course->managers)) {
2057 $rusers = $course->managers;
2058 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2060 /// Rename some of the role names if needed
2061 if (isset($context)) {
2062 $aliasnames = get_records('role_names', 'contextid', $context->id,'','roleid,contextid,name');
2065 // keep a note of users displayed to eliminate duplicates
2066 $usersshown = array();
2067 foreach ($rusers as $ra) {
2069 // if we've already displayed user don't again
2070 if (in_array($ra->user->id,$usersshown)) {
2071 continue;
2073 $usersshown[] = $ra->user->id;
2075 if ($ra->hidden == 0 || $canseehidden) {
2076 $fullname = fullname($ra->user, $canviewfullnames);
2077 if ($ra->hidden == 1) {
2078 $status = " <img src=\"{$CFG->pixpath}/t/show.gif\" title=\"".get_string('userhashiddenassignments', 'role')."\" alt=\"".get_string('hiddenassign')."\" class=\"hide-show-image\"/>";
2079 } else {
2080 $status = '';
2083 if (isset($aliasnames[$ra->roleid])) {
2084 $ra->rolename = $aliasnames[$ra->roleid]->name;
2087 $namesarray[] = format_string($ra->rolename)
2088 . ': <a href="'.$CFG->wwwroot.'/user/view.php?id='.$ra->user->id.'&amp;course='.SITEID.'">'
2089 . $fullname . '</a>' . $status;
2093 } else {
2094 $rusers = get_role_users($managerroles, $context,
2095 true, '', 'r.sortorder ASC, u.lastname ASC', $canseehidden);
2096 if (is_array($rusers) && count($rusers)) {
2097 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2099 /// Rename some of the role names if needed
2100 if (isset($context)) {
2101 $aliasnames = get_records('role_names', 'contextid', $context->id,'','roleid,contextid,name');
2104 foreach ($rusers as $teacher) {
2105 $fullname = fullname($teacher, $canviewfullnames);
2107 /// Apply role names
2108 if (isset($aliasnames[$teacher->roleid])) {
2109 $teacher->rolename = $aliasnames[$teacher->roleid]->name;
2112 $namesarray[] = format_string($teacher->rolename)
2113 . ': <a href="'.$CFG->wwwroot.'/user/view.php?id='.$teacher->id.'&amp;course='.SITEID.'">'
2114 . $fullname . '</a>';
2119 if (!empty($namesarray)) {
2120 echo "<ul class=\"teachers\">\n<li>";
2121 echo implode('</li><li>', $namesarray);
2122 echo "</li></ul>";
2126 require_once("$CFG->dirroot/enrol/enrol.class.php");
2127 $enrol = enrolment_factory::factory($course->enrol);
2128 echo $enrol->get_access_icons($course);
2130 echo '</div><div class="summary">';
2131 $options = NULL;
2132 $options->noclean = true;
2133 $options->para = false;
2134 echo highlight($highlightterms, format_text($course->summary, FORMAT_MOODLE, $options, $course->id));
2135 echo '</div>';
2136 echo '</div>';
2139 function print_my_moodle() {
2140 /// Prints custom user information on the home page.
2141 /// Over time this can include all sorts of information
2143 global $USER, $CFG;
2145 if (empty($USER->id)) {
2146 error("It shouldn't be possible to see My Moodle without being logged in.");
2149 $courses = get_my_courses($USER->id, 'visible DESC,sortorder ASC', array('summary'));
2150 $rhosts = array();
2151 $rcourses = array();
2152 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
2153 $rcourses = get_my_remotecourses($USER->id);
2154 $rhosts = get_my_remotehosts();
2157 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
2159 if (!empty($courses)) {
2160 echo '<ul class="unlist">';
2161 foreach ($courses as $course) {
2162 if ($course->id == SITEID) {
2163 continue;
2165 echo '<li>';
2166 print_course($course);
2167 echo "</li>\n";
2169 echo "</ul>\n";
2172 // MNET
2173 if (!empty($rcourses)) {
2174 // at the IDP, we know of all the remote courses
2175 foreach ($rcourses as $course) {
2176 print_remote_course($course, "100%");
2178 } elseif (!empty($rhosts)) {
2179 // non-IDP, we know of all the remote servers, but not courses
2180 foreach ($rhosts as $host) {
2181 print_remote_host($host, "100%");
2184 unset($course);
2185 unset($host);
2187 if (count_records("course") > (count($courses) + 1) ) { // Some courses not being displayed
2188 echo "<table width=\"100%\"><tr><td align=\"center\">";
2189 print_course_search("", false, "short");
2190 echo "</td><td align=\"center\">";
2191 print_single_button("$CFG->wwwroot/course/index.php", NULL, get_string("fulllistofcourses"), "get");
2192 echo "</td></tr></table>\n";
2195 } else {
2196 if (count_records("course_categories") > 1) {
2197 print_simple_box_start("center", "100%", "#FFFFFF", 5, "categorybox");
2198 print_whole_category_list();
2199 print_simple_box_end();
2200 } else {
2201 print_courses(0);
2207 function print_course_search($value="", $return=false, $format="plain") {
2209 global $CFG;
2210 static $count = 0;
2212 $count++;
2214 $id = 'coursesearch';
2216 if ($count > 1) {
2217 $id .= $count;
2220 $strsearchcourses= get_string("searchcourses");
2222 if ($format == 'plain') {
2223 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2224 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2225 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
2226 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" value="'.s($value, true).'" />';
2227 $output .= '<input type="submit" value="'.get_string('go').'" />';
2228 $output .= '</fieldset></form>';
2229 } else if ($format == 'short') {
2230 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2231 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2232 $output .= '<label for="shortsearchbox">'.$strsearchcourses.': </label>';
2233 $output .= '<input type="text" id="shortsearchbox" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
2234 $output .= '<input type="submit" value="'.get_string('go').'" />';
2235 $output .= '</fieldset></form>';
2236 } else if ($format == 'navbar') {
2237 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2238 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2239 $output .= '<label for="navsearchbox">'.$strsearchcourses.': </label>';
2240 $output .= '<input type="text" id="navsearchbox" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
2241 $output .= '<input type="submit" value="'.get_string('go').'" />';
2242 $output .= '</fieldset></form>';
2245 if ($return) {
2246 return $output;
2248 echo $output;
2251 function print_remote_course($course, $width="100%") {
2253 global $CFG, $USER;
2255 $linkcss = '';
2257 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&amp;wantsurl=/course/view.php?id={$course->remoteid}";
2259 echo '<div class="coursebox remotecoursebox clearfix">';
2260 echo '<div class="info">';
2261 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2262 $linkcss.' href="'.$url.'">'
2263 . format_string($course->fullname) .'</a><br />'
2264 . format_string($course->hostname) . ' : '
2265 . format_string($course->cat_name) . ' : '
2266 . format_string($course->shortname). '</div>';
2267 echo '</div><div class="summary">';
2268 $options = NULL;
2269 $options->noclean = true;
2270 $options->para = false;
2271 echo format_text($course->summary, FORMAT_MOODLE, $options);
2272 echo '</div>';
2273 echo '</div>';
2276 function print_remote_host($host, $width="100%") {
2278 global $CFG, $USER;
2280 $linkcss = '';
2282 echo '<div class="coursebox clearfix">';
2283 echo '<div class="info">';
2284 echo '<div class="name">';
2285 echo '<img src="'.$CFG->pixpath.'/i/mnethost.gif" class="icon" alt="'.get_string('course').'" />';
2286 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2287 . s($host['name']).'</a> - ';
2288 echo $host['count'] . ' ' . get_string('courses');
2289 echo '</div>';
2290 echo '</div>';
2291 echo '</div>';
2295 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2297 function add_course_module($mod) {
2299 $mod->added = time();
2300 unset($mod->id);
2302 return insert_record("course_modules", $mod);
2306 * Returns course section - creates new if does not exist yet.
2307 * @param int $relative section number
2308 * @param int $courseid
2309 * @return object $course_section object
2311 function get_course_section($section, $courseid) {
2312 if ($cw = get_record("course_sections", "section", $section, "course", $courseid)) {
2313 return $cw;
2315 $cw = new object();
2316 $cw->course = $courseid;
2317 $cw->section = $section;
2318 $cw->summary = "";
2319 $cw->sequence = "";
2320 $id = insert_record("course_sections", $cw);
2321 return get_record("course_sections", "id", $id);
2324 * Given a full mod object with section and course already defined, adds this module to that section.
2326 * @param object $mod
2327 * @param int $beforemod An existing ID which we will insert the new module before
2328 * @return int The course_sections ID where the mod is inserted
2330 function add_mod_to_section($mod, $beforemod=NULL) {
2332 if ($section = get_record("course_sections", "course", "$mod->course", "section", "$mod->section")) {
2334 $section->sequence = trim($section->sequence);
2336 if (empty($section->sequence)) {
2337 $newsequence = "$mod->coursemodule";
2339 } else if ($beforemod) {
2340 $modarray = explode(",", $section->sequence);
2342 if ($key = array_keys ($modarray, $beforemod->id)) {
2343 $insertarray = array($mod->id, $beforemod->id);
2344 array_splice($modarray, $key[0], 1, $insertarray);
2345 $newsequence = implode(",", $modarray);
2347 } else { // Just tack it on the end anyway
2348 $newsequence = "$section->sequence,$mod->coursemodule";
2351 } else {
2352 $newsequence = "$section->sequence,$mod->coursemodule";
2355 if (set_field("course_sections", "sequence", $newsequence, "id", $section->id)) {
2356 return $section->id; // Return course_sections ID that was used.
2357 } else {
2358 return 0;
2361 } else { // Insert a new record
2362 $section->course = $mod->course;
2363 $section->section = $mod->section;
2364 $section->summary = "";
2365 $section->sequence = $mod->coursemodule;
2366 return insert_record("course_sections", $section);
2370 function set_coursemodule_groupmode($id, $groupmode) {
2371 return set_field("course_modules", "groupmode", $groupmode, "id", $id);
2374 function set_coursemodule_groupingid($id, $groupingid) {
2375 return set_field("course_modules", "groupingid", $groupingid, "id", $id);
2378 function set_coursemodule_groupmembersonly($id, $groupmembersonly) {
2379 return set_field("course_modules", "groupmembersonly", $groupmembersonly, "id", $id);
2382 function set_coursemodule_idnumber($id, $idnumber) {
2383 return set_field("course_modules", "idnumber", $idnumber, "id", $id);
2386 * $prevstateoverrides = true will set the visibility of the course module
2387 * to what is defined in visibleold. This enables us to remember the current
2388 * visibility when making a whole section hidden, so that when we toggle
2389 * that section back to visible, we are able to return the visibility of
2390 * the course module back to what it was originally.
2392 function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
2393 if (!$cm = get_record('course_modules', 'id', $id)) {
2394 return false;
2396 if (!$modulename = get_field('modules', 'name', 'id', $cm->module)) {
2397 return false;
2399 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
2400 foreach($events as $event) {
2401 if ($visible) {
2402 show_event($event);
2403 } else {
2404 hide_event($event);
2408 if ($prevstateoverrides) {
2409 if ($visible == '0') {
2410 // Remember the current visible state so we can toggle this back.
2411 set_field('course_modules', 'visibleold', $cm->visible, 'id', $id);
2412 } else {
2413 // Get the previous saved visible states.
2414 return set_field('course_modules', 'visible', $cm->visibleold, 'id', $id);
2417 return set_field("course_modules", "visible", $visible, "id", $id);
2421 * Delete a course module and any associated data at the course level (events)
2422 * Until 1.5 this function simply marked a deleted flag ... now it
2423 * deletes it completely.
2426 function delete_course_module($id) {
2427 global $CFG;
2428 require_once($CFG->libdir.'/gradelib.php');
2430 if (!$cm = get_record('course_modules', 'id', $id)) {
2431 return true;
2433 $modulename = get_field('modules', 'name', 'id', $cm->module);
2434 //delete events from calendar
2435 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
2436 foreach($events as $event) {
2437 delete_event($event->id);
2440 //delete grade items, outcome items and grades attached to modules
2441 if ($grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2442 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course))) {
2443 foreach ($grade_items as $grade_item) {
2444 $grade_item->delete('moddelete');
2448 delete_context(CONTEXT_MODULE, $cm->id);
2449 return delete_records('course_modules', 'id', $cm->id);
2452 function delete_mod_from_section($mod, $section) {
2454 if ($section = get_record("course_sections", "id", "$section") ) {
2456 $modarray = explode(",", $section->sequence);
2458 if ($key = array_keys ($modarray, $mod)) {
2459 array_splice($modarray, $key[0], 1);
2460 $newsequence = implode(",", $modarray);
2461 return set_field("course_sections", "sequence", $newsequence, "id", $section->id);
2462 } else {
2463 return false;
2467 return false;
2471 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
2473 * @param object $course
2474 * @param int $section
2475 * @param int $move (-1 or 1)
2477 function move_section($course, $section, $move) {
2478 /// Moves a whole course section up and down within the course
2479 global $USER;
2481 if (!$move) {
2482 return true;
2485 $sectiondest = $section + $move;
2487 if ($sectiondest > $course->numsections or $sectiondest < 1) {
2488 return false;
2491 if (!$sectionrecord = get_record("course_sections", "course", $course->id, "section", $section)) {
2492 return false;
2495 if (!$sectiondestrecord = get_record("course_sections", "course", $course->id, "section", $sectiondest)) {
2496 return false;
2500 $count = abs($sectiondest - $section);
2501 $direction = ($sectiondest - $section) / $count;
2503 for ($i = 0, $ref = $section + $direction; $i < $count; ++$i, $ref += $direction) {
2504 if (!set_field("course_sections", "section", $ref - $direction, 'course', $course->id, 'section', $ref)) {
2505 return false;
2509 if (!set_field("course_sections", "section", $sectiondest, "id", $sectionrecord->id)) {
2510 return false;
2513 // if the focus is on the section that is being moved, then move the focus along
2514 if (isset($USER->display[$course->id]) and ($USER->display[$course->id] == $section)) {
2515 course_set_display($course->id, $sectiondest);
2518 // Check for duplicates and fix order if needed.
2519 // There is a very rare case that some sections in the same course have the same section id.
2520 $sections = get_records_select('course_sections', "course = $course->id", 'section ASC');
2521 $n = 0;
2522 foreach ($sections as $section) {
2523 if ($section->section != $n) {
2524 if (!set_field('course_sections', 'section', $n, 'id', $section->id)) {
2525 return false;
2528 $n++;
2530 return true;
2534 * Moves a section within a course, from a position to another.
2535 * Be very careful: $section and $destination refer to section number,
2536 * not id!.
2538 * @param object $course
2539 * @param int $section Section number (not id!!!)
2540 * @param int $destination
2541 * @return boolean Result
2543 function move_section_to($course, $section, $destination) {
2544 /// Moves a whole course section up and down within the course
2545 global $USER;
2547 if (!$destination && $destination != 0) {
2548 return true;
2551 if ($destination > $course->numsections) {
2552 return false;
2555 // Get all sections for this course and re-order them (2 of them should now share the same section number)
2556 if (!$sections = get_records_menu('course_sections', 'course',$course->id, 'section ASC, id ASC', 'id, section')) {
2557 return false;
2560 $sections = reorder_sections($sections, $section, $destination);
2562 // Update all sections
2563 foreach ($sections as $id => $position) {
2564 set_field('course_sections', 'section', $position, 'id', $id);
2567 // if the focus is on the section that is being moved, then move the focus along
2568 if (isset($USER->display[$course->id]) and ($USER->display[$course->id] == $section)) {
2569 course_set_display($course->id, $destination);
2571 return true;
2575 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
2576 * an original position number and a target position number, rebuilds the array so that the
2577 * move is made without any duplication of section positions.
2578 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
2579 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
2581 * @param array $sections
2582 * @param int $origin_position
2583 * @param int $target_position
2584 * @return array
2586 function reorder_sections($sections, $origin_position, $target_position) {
2587 if (!is_array($sections)) {
2588 return false;
2591 // We can't move section position 0
2592 if ($origin_position < 1) {
2593 echo "We can't move section position 0";
2594 return false;
2597 // Locate origin section in sections array
2598 if (!$origin_key = array_search($origin_position, $sections)) {
2599 echo "searched position not in sections array";
2600 return false; // searched position not in sections array
2603 // Extract origin section
2604 $origin_section = $sections[$origin_key];
2605 unset($sections[$origin_key]);
2607 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
2608 $found = false;
2609 $append_array = array();
2610 foreach ($sections as $id => $position) {
2611 if ($found) {
2612 $append_array[$id] = $position;
2613 unset($sections[$id]);
2615 if ($position == $target_position) {
2616 $found = true;
2620 // Append moved section
2621 $sections[$origin_key] = $origin_section;
2623 // Append rest of array (if applicable)
2624 if (!empty($append_array)) {
2625 foreach ($append_array as $id => $position) {
2626 $sections[$id] = $position;
2630 // Renumber positions
2631 $position = 0;
2632 foreach ($sections as $id => $p) {
2633 $sections[$id] = $position;
2634 $position++;
2637 return $sections;
2641 function moveto_module($mod, $section, $beforemod=NULL) {
2642 /// All parameters are objects
2643 /// Move the module object $mod to the specified $section
2644 /// If $beforemod exists then that is the module
2645 /// before which $modid should be inserted
2647 /// Remove original module from original section
2649 if (! delete_mod_from_section($mod->id, $mod->section)) {
2650 notify("Could not delete module from existing section");
2653 /// Update module itself if necessary
2655 if ($mod->section != $section->id) {
2656 $mod->section = $section->id;
2657 if (!update_record("course_modules", $mod)) {
2658 return false;
2660 // if moving to a hidden section then hide module
2661 if (!$section->visible) {
2662 set_coursemodule_visible($mod->id, 0);
2666 /// Add the module into the new section
2668 $mod->course = $section->course;
2669 $mod->section = $section->section; // need relative reference
2670 $mod->coursemodule = $mod->id;
2672 if (! add_mod_to_section($mod, $beforemod)) {
2673 return false;
2676 return true;
2680 function make_editing_buttons($mod, $absolute=false, $moveselect=true, $indent=-1, $section=-1) {
2681 global $CFG, $USER;
2683 static $str;
2684 static $sesskey;
2686 $modcontext = get_context_instance(CONTEXT_MODULE, $mod->id);
2687 // no permission to edit
2688 if (!has_capability('moodle/course:manageactivities', $modcontext)) {
2689 return false;
2692 if (!isset($str)) {
2693 $str->delete = get_string("delete");
2694 $str->move = get_string("move");
2695 $str->moveup = get_string("moveup");
2696 $str->movedown = get_string("movedown");
2697 $str->moveright = get_string("moveright");
2698 $str->moveleft = get_string("moveleft");
2699 $str->update = get_string("update");
2700 $str->duplicate = get_string("duplicate");
2701 $str->hide = get_string("hide");
2702 $str->show = get_string("show");
2703 $str->clicktochange = get_string("clicktochange");
2704 $str->forcedmode = get_string("forcedmode");
2705 $str->groupsnone = get_string("groupsnone");
2706 $str->groupsseparate = get_string("groupsseparate");
2707 $str->groupsvisible = get_string("groupsvisible");
2708 $sesskey = sesskey();
2711 if ($section >= 0) {
2712 $section = '&amp;sr='.$section; // Section return
2713 } else {
2714 $section = '';
2717 if ($absolute) {
2718 $path = $CFG->wwwroot.'/course';
2719 } else {
2720 $path = '.';
2723 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
2724 if ($mod->visible) {
2725 $hideshow = '<a class="editing_hide" title="'.$str->hide.'" href="'.$path.'/mod.php?hide='.$mod->id.
2726 '&amp;sesskey='.$sesskey.$section.'"><img'.
2727 ' src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" '.
2728 ' alt="'.$str->hide.'" /></a>'."\n";
2729 } else {
2730 $hideshow = '<a class="editing_show" title="'.$str->show.'" href="'.$path.'/mod.php?show='.$mod->id.
2731 '&amp;sesskey='.$sesskey.$section.'"><img'.
2732 ' src="'.$CFG->pixpath.'/t/show.gif" class="iconsmall" '.
2733 ' alt="'.$str->show.'" /></a>'."\n";
2735 } else {
2736 $hideshow = '';
2739 if ($mod->groupmode !== false) {
2740 if ($mod->groupmode == SEPARATEGROUPS) {
2741 $grouptitle = $str->groupsseparate;
2742 $groupclass = 'editing_groupsseparate';
2743 $groupimage = $CFG->pixpath.'/t/groups.gif';
2744 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=0&amp;sesskey='.$sesskey;
2745 } else if ($mod->groupmode == VISIBLEGROUPS) {
2746 $grouptitle = $str->groupsvisible;
2747 $groupclass = 'editing_groupsvisible';
2748 $groupimage = $CFG->pixpath.'/t/groupv.gif';
2749 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=1&amp;sesskey='.$sesskey;
2750 } else {
2751 $grouptitle = $str->groupsnone;
2752 $groupclass = 'editing_groupsnone';
2753 $groupimage = $CFG->pixpath.'/t/groupn.gif';
2754 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=2&amp;sesskey='.$sesskey;
2756 if ($mod->groupmodelink) {
2757 $groupmode = '<a class="'.$groupclass.'" title="'.$grouptitle.' ('.$str->clicktochange.')" href="'.$grouplink.'">'.
2758 '<img src="'.$groupimage.'" class="iconsmall" '.
2759 'alt="'.$grouptitle.'" /></a>';
2760 } else {
2761 $groupmode = '<img title="'.$grouptitle.' ('.$str->forcedmode.')" '.
2762 ' src="'.$groupimage.'" class="iconsmall" '.
2763 'alt="'.$grouptitle.'" />';
2765 } else {
2766 $groupmode = "";
2769 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $mod->course))) {
2770 if ($moveselect) {
2771 $move = '<a class="editing_move" title="'.$str->move.'" href="'.$path.'/mod.php?copy='.$mod->id.
2772 '&amp;sesskey='.$sesskey.$section.'"><img'.
2773 ' src="'.$CFG->pixpath.'/t/move.gif" class="iconsmall" '.
2774 ' alt="'.$str->move.'" /></a>'."\n";
2775 } else {
2776 $move = '<a class="editing_moveup" title="'.$str->moveup.'" href="'.$path.'/mod.php?id='.$mod->id.
2777 '&amp;move=-1&amp;sesskey='.$sesskey.$section.'"><img'.
2778 ' src="'.$CFG->pixpath.'/t/up.gif" class="iconsmall" '.
2779 ' alt="'.$str->moveup.'" /></a>'."\n".
2780 '<a class="editing_movedown" title="'.$str->movedown.'" href="'.$path.'/mod.php?id='.$mod->id.
2781 '&amp;move=1&amp;sesskey='.$sesskey.$section.'"><img'.
2782 ' src="'.$CFG->pixpath.'/t/down.gif" class="iconsmall" '.
2783 ' alt="'.$str->movedown.'" /></a>'."\n";
2785 } else {
2786 $move = '';
2789 $leftright = '';
2790 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $mod->course))) {
2792 if (right_to_left()) { // Exchange arrows on RTL
2793 $rightarrow = 'left.gif';
2794 $leftarrow = 'right.gif';
2795 } else {
2796 $rightarrow = 'right.gif';
2797 $leftarrow = 'left.gif';
2800 if ($indent > 0) {
2801 $leftright .= '<a class="editing_moveleft" title="'.$str->moveleft.'" href="'.$path.'/mod.php?id='.$mod->id.
2802 '&amp;indent=-1&amp;sesskey='.$sesskey.$section.'"><img'.
2803 ' src="'.$CFG->pixpath.'/t/'.$leftarrow.'" class="iconsmall" '.
2804 ' alt="'.$str->moveleft.'" /></a>'."\n";
2806 if ($indent >= 0) {
2807 $leftright .= '<a class="editing_moveright" title="'.$str->moveright.'" href="'.$path.'/mod.php?id='.$mod->id.
2808 '&amp;indent=1&amp;sesskey='.$sesskey.$section.'"><img'.
2809 ' src="'.$CFG->pixpath.'/t/'.$rightarrow.'" class="iconsmall" '.
2810 ' alt="'.$str->moveright.'" /></a>'."\n";
2814 return '<span class="commands">'."\n".$leftright.$move.
2815 '<a class="editing_update" title="'.$str->update.'" href="'.$path.'/mod.php?update='.$mod->id.
2816 '&amp;sesskey='.$sesskey.$section.'"><img'.
2817 ' src="'.$CFG->pixpath.'/t/edit.gif" class="iconsmall" '.
2818 ' alt="'.$str->update.'" /></a>'."\n".
2819 '<a class="editing_delete" title="'.$str->delete.'" href="'.$path.'/mod.php?delete='.$mod->id.
2820 '&amp;sesskey='.$sesskey.$section.'"><img'.
2821 ' src="'.$CFG->pixpath.'/t/delete.gif" class="iconsmall" '.
2822 ' alt="'.$str->delete.'" /></a>'."\n".$hideshow.$groupmode."\n".'</span>';
2826 * given a course object with shortname & fullname, this function will
2827 * truncate the the number of chars allowed and add ... if it was too long
2829 function course_format_name ($course,$max=100) {
2831 $str = $course->shortname.': '. $course->fullname;
2832 if (strlen($str) <= $max) {
2833 return $str;
2835 else {
2836 return substr($str,0,$max-3).'...';
2841 * This function will return true if the given course is a child course at all
2843 function course_in_meta ($course) {
2844 return record_exists("course_meta","child_course",$course->id);
2849 * Print standard form elements on module setup forms in mod/.../mod.html
2851 function print_standard_coursemodule_settings($form, $features=null) {
2852 if (! $course = get_record('course', 'id', $form->course)) {
2853 error("This course doesn't exist");
2855 print_groupmode_setting($form, $course);
2856 if (!empty($features->groupings)) {
2857 print_grouping_settings($form, $course);
2859 print_visible_setting($form, $course);
2863 * Print groupmode form element on module setup forms in mod/.../mod.html
2865 function print_groupmode_setting($form, $course=NULL) {
2867 if (empty($course)) {
2868 if (! $course = get_record('course', 'id', $form->course)) {
2869 error("This course doesn't exist");
2872 if ($form->coursemodule) {
2873 if (! $cm = get_record('course_modules', 'id', $form->coursemodule)) {
2874 error("This course module doesn't exist");
2876 $groupmode = groups_get_activity_groupmode($cm);
2877 } else {
2878 $cm = null;
2879 $groupmode = groups_get_course_groupmode($course);
2881 if ($course->groupmode or (!$course->groupmodeforce)) {
2882 echo '<tr valign="top">';
2883 echo '<td align="right"><b>'.get_string('groupmode').':</b></td>';
2884 echo '<td align="left">';
2885 $choices = array();
2886 $choices[NOGROUPS] = get_string('groupsnone');
2887 $choices[SEPARATEGROUPS] = get_string('groupsseparate');
2888 $choices[VISIBLEGROUPS] = get_string('groupsvisible');
2889 choose_from_menu($choices, 'groupmode', $groupmode, '', '', 0, false, $course->groupmodeforce);
2890 helpbutton('groupmode', get_string('groupmode'));
2891 echo '</td></tr>';
2896 * Print groupmode form element on module setup forms in mod/.../mod.html
2898 function print_grouping_settings($form, $course=NULL) {
2900 if (empty($course)) {
2901 if (! $course = get_record('course', 'id', $form->course)) {
2902 error("This course doesn't exist");
2905 if ($form->coursemodule) {
2906 if (! $cm = get_record('course_modules', 'id', $form->coursemodule)) {
2907 error("This course module doesn't exist");
2909 } else {
2910 $cm = null;
2913 $groupings = get_records_menu('groupings', 'courseid', $course->id, 'name', 'id, name');
2914 if (!empty($groupings)) {
2915 echo '<tr valign="top">';
2916 echo '<td align="right"><b>'.get_string('grouping', 'group').':</b></td>';
2917 echo '<td align="left">';
2919 $groupings;
2920 $groupingid = isset($cm->groupingid) ? $cm->groupingid : 0;
2922 choose_from_menu($groupings, 'groupingid', $groupingid, get_string('none'), '', 0, false);
2923 echo '</td></tr>';
2925 $checked = empty($cm->groupmembersonly) ? '':'checked="checked"';
2926 echo '<tr valign="top">';
2927 echo '<td align="right"><b>'.get_string('groupmembersonly', 'group').':</b></td>';
2928 echo '<td align="left">';
2929 echo "<input type=\"checkbox\" name=\"groupmembersonly\" value=\"1\" $checked />";
2930 echo '</td></tr>';
2936 * Print visibility setting form element on module setup forms in mod/.../mod.html
2938 function print_visible_setting($form, $course=NULL) {
2939 if (empty($course)) {
2940 if (! $course = get_record('course', 'id', $form->course)) {
2941 error("This course doesn't exist");
2944 if ($form->coursemodule) {
2945 $visible = get_field('course_modules', 'visible', 'id', $form->coursemodule);
2946 } else {
2947 $visible = true;
2950 if ($form->mode == 'add') { // in this case $form->section is the section number, not the id
2951 $hiddensection = !get_field('course_sections', 'visible', 'section', $form->section, 'course', $form->course);
2952 } else {
2953 $hiddensection = !get_field('course_sections', 'visible', 'id', $form->section);
2955 if ($hiddensection) {
2956 $visible = false;
2959 echo '<tr valign="top">';
2960 echo '<td align="right"><b>'.get_string('visible', '').':</b></td>';
2961 echo '<td align="left">';
2962 $choices = array(1 => get_string('show'), 0 => get_string('hide'));
2963 choose_from_menu($choices, 'visible', $visible, '', '', 0, false, $hiddensection);
2964 echo '</td></tr>';
2967 function update_restricted_mods($course,$mods) {
2969 /// Delete all the current restricted list
2970 delete_records('course_allowed_modules','course',$course->id);
2972 if (empty($course->restrictmodules)) {
2973 return; // We're done
2976 /// Insert the new list of restricted mods
2977 foreach ($mods as $mod) {
2978 if ($mod == 0) {
2979 continue; // this is the 'allow none' option
2981 $am = new object();
2982 $am->course = $course->id;
2983 $am->module = $mod;
2984 insert_record('course_allowed_modules',$am);
2989 * This function will take an int (module id) or a string (module name)
2990 * and return true or false, whether it's allowed in the given course (object)
2991 * $mod is not allowed to be an object, as the field for the module id is inconsistent
2992 * depending on where in the code it's called from (sometimes $mod->id, sometimes $mod->module)
2995 function course_allowed_module($course,$mod) {
2997 if (empty($course->restrictmodules)) {
2998 return true;
3001 // Admins and admin-like people who can edit everything can also add anything.
3002 // This is a bit wierd, really. I debated taking it out but it's enshrined in help for the setting.
3003 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM))) {
3004 return true;
3007 if (is_numeric($mod)) {
3008 $modid = $mod;
3009 } else if (is_string($mod)) {
3010 $modid = get_field('modules','id','name',$mod);
3012 if (empty($modid)) {
3013 return false;
3016 return (record_exists('course_allowed_modules','course',$course->id,'module',$modid));
3020 * Recursively delete category including all subcategories and courses.
3021 * @param object $ccategory
3022 * @return bool status
3024 function category_delete_full($category, $showfeedback=true) {
3025 global $CFG;
3026 require_once($CFG->libdir.'/gradelib.php');
3027 require_once($CFG->libdir.'/questionlib.php');
3029 if ($children = get_records('course_categories', 'parent', $category->id, 'sortorder ASC')) {
3030 foreach ($children as $childcat) {
3031 if (!category_delete_full($childcat, $showfeedback)) {
3032 notify("Error deleting category $childcat->name");
3033 return false;
3038 if ($courses = get_records('course', 'category', $category->id, 'sortorder ASC')) {
3039 foreach ($courses as $course) {
3040 if (!delete_course($course->id, false)) {
3041 notify("Error deleting course $course->shortname");
3042 return false;
3044 notify(get_string('coursedeleted', '', $course->shortname), 'notifysuccess');
3048 // now delete anything that may depend on course category context
3049 grade_course_category_delete($category->id, 0, $showfeedback);
3050 if (!question_delete_course_category($category, 0, $showfeedback)) {
3051 notify(get_string('errordeletingquestionsfromcategory', 'question', $category), 'notifysuccess');
3052 return false;
3055 // finally delete the category and it's context
3056 delete_records('course_categories', 'id', $category->id);
3057 delete_context(CONTEXT_COURSECAT, $category->id);
3059 events_trigger('course_category_deleted', $category);
3061 notify(get_string('coursecategorydeleted', '', format_string($category->name)), 'notifysuccess');
3063 return true;
3067 * Delete category, but move contents to another category.
3068 * @param object $ccategory
3069 * @param int $newparentid category id
3070 * @return bool status
3072 function category_delete_move($category, $newparentid, $showfeedback=true) {
3073 global $CFG;
3074 require_once($CFG->libdir.'/gradelib.php');
3075 require_once($CFG->libdir.'/questionlib.php');
3077 if (!$newparentcat = get_record('course_categories', 'id', $newparentid)) {
3078 return false;
3081 if ($children = get_records('course_categories', 'parent', $category->id, 'sortorder ASC')) {
3082 foreach ($children as $childcat) {
3083 if (!move_category($childcat, $newparentcat)) {
3084 notify("Error moving category $childcat->name");
3085 return false;
3090 if ($courses = get_records('course', 'category', $category->id, 'sortorder ASC', 'id')) {
3091 if (!move_courses(array_keys($courses), $newparentid)) {
3092 notify("Error moving courses");
3093 return false;
3095 notify(get_string('coursesmovedout', '', format_string($category->name)), 'notifysuccess');
3098 // now delete anything that may depend on course category context
3099 grade_course_category_delete($category->id, $newparentid, $showfeedback);
3100 if (!question_delete_course_category($category, $newparentcat, $showfeedback)) {
3101 notify(get_string('errordeletingquestionsfromcategory', 'question', $category), 'notifysuccess');
3102 return false;
3105 // finally delete the category and it's context
3106 delete_records('course_categories', 'id', $category->id);
3107 delete_context(CONTEXT_COURSECAT, $category->id);
3109 events_trigger('course_category_deleted', $category);
3111 notify(get_string('coursecategorydeleted', '', format_string($category->name)), 'notifysuccess');
3113 return true;
3116 /***
3117 *** Efficiently moves many courses around while maintaining
3118 *** sortorder in order.
3120 *** $courseids is an array of course ids
3124 function move_courses ($courseids, $categoryid) {
3126 global $CFG;
3128 if (!empty($courseids)) {
3130 $courseids = array_reverse($courseids);
3132 foreach ($courseids as $courseid) {
3134 if (! $course = get_record("course", "id", $courseid)) {
3135 notify("Error finding course $courseid");
3136 } else {
3137 // figure out a sortorder that we can use in the destination category
3138 $sortorder = get_field_sql('SELECT MIN(sortorder)-1 AS min
3139 FROM ' . $CFG->prefix . 'course WHERE category=' . $categoryid);
3140 if (is_null($sortorder) || $sortorder === false) {
3141 // the category is empty
3142 // rather than let the db default to 0
3143 // set it to > 100 and avoid extra work in fix_coursesortorder()
3144 $sortorder = 200;
3145 } else if ($sortorder < 10) {
3146 fix_course_sortorder($categoryid);
3149 $course->category = $categoryid;
3150 $course->sortorder = $sortorder;
3152 if (!update_record('course', addslashes_recursive($course))) {
3153 notify("An error occurred - course not moved!");
3156 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3157 $newparent = get_context_instance(CONTEXT_COURSECAT, $course->category);
3158 context_moved($context, $newparent);
3161 fix_course_sortorder();
3163 return true;
3166 /***
3167 *** Efficiently moves a category - NOTE that this can have
3168 *** a huge impact access-control-wise...
3172 function move_category ($category, $newparentcat) {
3174 global $CFG;
3176 $context = get_context_instance(CONTEXT_COURSECAT, $category->id);
3178 if (empty($newparentcat->id)) {
3179 if (!set_field('course_categories', 'parent', 0, 'id', $category->id)) {
3180 return false;
3182 $newparent = get_context_instance(CONTEXT_SYSTEM);
3183 } else {
3184 if (!set_field('course_categories', 'parent', $newparentcat->id, 'id', $category->id)) {
3185 return false;
3187 $newparent = get_context_instance(CONTEXT_COURSECAT, $newparentcat->id);
3190 context_moved($context, $newparent);
3192 // The most effective thing would be to find the common parent,
3193 // until then, do it sitewide...
3194 fix_course_sortorder();
3197 return true;
3201 * @param string $format Course format ID e.g. 'weeks'
3202 * @return Name that the course format prefers for sections
3204 function get_section_name($format) {
3205 $sectionname = get_string("name$format","format_$format");
3206 if($sectionname == "[[name$format]]") {
3207 $sectionname = get_string("name$format");
3209 return $sectionname;
3213 * Can the current user delete this course?
3214 * Course creators have exception,
3215 * 1 day after the creation they can sill delete the course.
3216 * @param int $courseid
3217 * @return boolean
3219 function can_delete_course($courseid) {
3220 global $USER;
3222 $context = get_context_instance(CONTEXT_COURSE, $courseid);
3224 if (has_capability('moodle/course:delete', $context)) {
3225 return true;
3228 // hack: now try to find out if creator created this course recently (1 day)
3229 if (!has_capability('moodle/course:create', $context)) {
3230 return false;
3233 $since = time() - 60*60*24;
3235 $select = "module = 'course' AND action = 'new' AND userid = $USER->id AND url='view.php?id=$courseid' AND time > $since";
3237 return record_exists_select('log', $select);
3241 * Save the Your name for 'Some role' strings.
3243 * @param integer $courseid the id of this course.
3244 * @param array $data the data that came from the course settings form.
3246 function save_local_role_names($courseid, $data) {
3247 $context = get_context_instance(CONTEXT_COURSE, $courseid);
3249 foreach ($data as $fieldname => $value) {
3250 if (!strstr($fieldname, 'role_')) {
3251 continue;
3253 list($ignored, $roleid) = explode('_', $fieldname);
3255 // make up our mind whether we want to delete, update or insert
3256 if (!$value) {
3257 delete_records('role_names', 'contextid', $context->id, 'roleid', $roleid);
3259 } else if ($rolename = get_record('role_names', 'contextid', $context->id, 'roleid', $roleid)) {
3260 $rolename->name = $value;
3261 update_record('role_names', $rolename);
3263 } else {
3264 $rolename = new stdClass;
3265 $rolename->contextid = $context->id;
3266 $rolename->roleid = $roleid;
3267 $rolename->name = $value;
3268 insert_record('role_names', $rolename, false);
3274 * Create a course and either return a $course object or false
3276 * @param object $data - all the data needed for an entry in the 'course' table
3278 function create_course($data) {
3279 global $CFG, $USER;
3281 // preprocess allowed mods
3282 $allowedmods = empty($data->allowedmods) ? array() : $data->allowedmods;
3283 unset($data->allowedmods);
3284 if ($CFG->restrictmodulesfor == 'all') {
3285 $data->restrictmodules = 1;
3287 // if the user is not an admin, get the default allowed modules because
3288 // there are no modules passed by the form
3289 if(!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
3290 if(!$allowedmods && $CFG->defaultallowedmodules) {
3291 $allowedmods = explode(',', $CFG->defaultallowedmodules);
3294 } else {
3295 $data->restrictmodules = 0;
3298 $data->timecreated = time();
3300 // place at beginning of category
3301 fix_course_sortorder();
3302 $data->sortorder = get_field_sql("SELECT min(sortorder)-1 FROM {$CFG->prefix}course WHERE category=$data->category");
3303 if (empty($data->sortorder)) {
3304 $data->sortorder = 100;
3307 if ($newcourseid = insert_record('course', $data)) { // Set up new course
3309 $course = get_record('course', 'id', $newcourseid);
3311 // Setup the blocks
3312 $page = page_create_object(PAGE_COURSE_VIEW, $course->id);
3313 blocks_repopulate_page($page); // Return value not checked because you can always edit later
3315 update_restricted_mods($course, $allowedmods);
3317 $section = new object();
3318 $section->course = $course->id; // Create a default section.
3319 $section->section = 0;
3320 $section->id = insert_record('course_sections', $section);
3322 fix_course_sortorder();
3324 add_to_log(SITEID, 'course', 'new', 'view.php?id='.$course->id, $data->fullname.' (ID '.$course->id.')');
3326 // Save any custom role names.
3327 save_local_role_names($course->id, $data);
3329 // Trigger events
3330 events_trigger('course_created', $course);
3332 return $course;
3335 return false; // error
3339 * Update a course and return true or false
3341 * @param object $data - all the data needed for an entry in the 'course' table
3343 function update_course($data) {
3344 global $USER, $CFG;
3346 // Preprocess allowed mods
3347 $allowedmods = empty($data->allowedmods) ? array() : $data->allowedmods;
3348 unset($data->allowedmods);
3350 // Normal teachers can't change setting
3351 if (!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
3352 unset($data->restrictmodules);
3355 $movecat = false;
3356 $oldcourse = get_record('course', 'id', $data->id); // should not fail, already tested above
3357 if (!has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $oldcourse->category))
3358 or !has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $data->category))) {
3359 // can not move to new category, keep the old one
3360 unset($data->category);
3361 } elseif ($oldcourse->category != $data->category) {
3362 $movecat = true;
3365 // Update with the new data
3366 if (update_record('course', $data)) {
3368 $course = get_record('course', 'id', $data->id);
3370 add_to_log($course->id, "course", "update", "edit.php?id=$course->id", $course->id);
3372 // "Admins" can change allowed mods for a course
3373 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
3374 update_restricted_mods($course, $allowedmods);
3377 if ($movecat) {
3378 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3379 $newparent = get_context_instance(CONTEXT_COURSECAT, $course->category);
3380 context_moved($context, $newparent);
3383 fix_course_sortorder();
3385 // Test for and remove blocks which aren't appropriate anymore
3386 $page = page_create_object(PAGE_COURSE_VIEW, $course->id);
3387 blocks_remove_inappropriate($page);
3389 // Save any custom role names.
3390 save_local_role_names($course->id, $data);
3392 // Trigger events
3393 events_trigger('course_updated', $course);
3395 return true;
3399 return false;