Should be $COURSE not $course
[moodle-linuxchix.git] / course / lib.php
blobf0f198f12ec6790f24e95574cf8e866f4a9b6706
1 <?php // $Id$
2 // Library of useful functions
5 if (defined('COURSE_MAX_LOG_DISPLAY')) { // Being included again - should never happen!!
6 return;
9 define('COURSE_MAX_LOG_DISPLAY', 150); // days
10 define('COURSE_MAX_LOGS_PER_PAGE', 1000); // records
11 define('COURSE_LIVELOG_REFRESH', 60); // Seconds
12 define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds
13 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10); // courses
14 define('COURSE_MAX_COURSES_PER_DROPDOWN',1000); // max courses in log dropdown before switching to optional
15 define('COURSE_MAX_USERS_PER_DROPDOWN',1000); // max users in log dropdown before switching to optional
16 define('FRONTPAGENEWS', 0);
17 define('FRONTPAGECOURSELIST', 1);
18 define('FRONTPAGECATEGORYNAMES', 2);
19 define('FRONTPAGETOPICONLY', 3);
20 define('FRONTPAGECATEGORYCOMBO', 4);
21 define('FRONTPAGECOURSELIMIT', 200); // maximum number of courses displayed on the frontpage
22 define('EXCELROWS', 65535);
23 define('FIRSTUSEDEXCELROW', 3);
25 define('MOD_CLASS_ACTIVITY', 0);
26 define('MOD_CLASS_RESOURCE', 1);
29 function print_recent_selector_form($course, $advancedfilter=0, $selecteduser=0, $selecteddate="lastlogin",
30 $mod="", $modid="activity/All", $modaction="", $selectedgroup="", $selectedsort="default") {
32 global $USER, $CFG;
34 if ($advancedfilter) {
36 // Get all the possible users
37 $users = array();
39 if ($courseusers = get_course_users($course->id, '', '', 'u.id, u.firstname, u.lastname')) {
40 foreach ($courseusers as $courseuser) {
41 $users[$courseuser->id] = fullname($courseuser, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
44 if ($guest = get_guest()) {
45 $users[$guest->id] = fullname($guest);
48 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
49 if ($ccc = get_records("course", "", "", "fullname")) {
50 foreach ($ccc as $cc) {
51 if ($cc->category) {
52 $courses["$cc->id"] = "$cc->fullname";
53 } else {
54 $courses["$cc->id"] = " $cc->fullname (Site)";
58 asort($courses);
61 $activities = array();
63 $selectedactivity = $modid;
65 /// Casting $course->modinfo to string prevents one notice when the field is null
66 if ($modinfo = unserialize((string)$course->modinfo)) {
67 $section = 0;
68 if ($course->format == 'weeks') { // Body
69 $strsection = get_string("week");
70 } else {
71 $strsection = get_string("topic");
74 $activities["activity/All"] = "All activities";
75 $activities["activity/Assignments"] = "All assignments";
76 $activities["activity/Chats"] = "All chats";
77 $activities["activity/Forums"] = "All forums";
78 $activities["activity/Quizzes"] = "All quizzes";
79 $activities["activity/Workshops"] = "All workshops";
81 $activities["section/individual"] = "------------- Individual Activities --------------";
83 foreach ($modinfo as $mod) {
84 if ($mod->mod == "label") {
85 continue;
87 if (!$mod->visible and !has_capability('moodle/course:viewhiddenactivities',get_context_instance(CONTEXT_MODULE, $mod->cm))) {
88 continue;
91 if ($mod->section > 0 and $section <> $mod->section) {
92 $activities["section/$mod->section"] = "-------------- $strsection $mod->section --------------";
94 $section = $mod->section;
95 $mod->name = strip_tags(format_string(urldecode($mod->name),true));
96 if (strlen($mod->name) > 55) {
97 $mod->name = substr($mod->name, 0, 50)."...";
99 if (!$mod->visible) {
100 $mod->name = "(".$mod->name.")";
102 $activities["$mod->cm"] = $mod->name;
104 if ($mod->cm == $modid) {
105 $selectedactivity = "$mod->cm";
110 $strftimedate = get_string("strftimedate");
111 $strftimedaydate = get_string("strftimedaydate");
113 asort($users);
115 // Get all the possible dates
116 // Note that we are keeping track of real (GMT) time and user time
117 // User time is only used in displays - all calcs and passing is GMT
119 $timenow = time(); // GMT
121 // What day is it now for the user, and when is midnight that day (in GMT).
122 $timemidnight = $today = usergetmidnight($timenow);
124 $dates = array();
125 $dates["$USER->lastlogin"] = get_string("lastlogin").", ".userdate($USER->lastlogin, $strftimedate);
126 $dates["$timemidnight"] = get_string("today").", ".userdate($timenow, $strftimedate);
128 if (!$course->startdate or ($course->startdate > $timenow)) {
129 $course->startdate = $course->timecreated;
132 $numdates = 1;
133 while ($timemidnight > $course->startdate and $numdates < 365) {
134 $timemidnight = $timemidnight - 86400;
135 $timenow = $timenow - 86400;
136 $dates["$timemidnight"] = userdate($timenow, $strftimedaydate);
137 $numdates++;
140 if ($selecteddate === "lastlogin") {
141 $selecteddate = $USER->lastlogin;
144 echo '<form action="recent.php" method="get">';
145 echo '<input type="hidden" name="chooserecent" value="1" />';
146 echo "<center>";
147 echo "<table>";
149 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
150 echo "<tr><td><b>" . get_string("courses") . "</b></td><td>";
151 choose_from_menu ($courses, "id", $course->id, "");
152 echo "</td></tr>";
153 } else {
154 echo '<input type="hidden" name="id" value="'.$course->id.'" />';
157 $sortfields = array("default" => get_string("bycourseorder"),"dateasc" => get_string("datemostrecentlast"), "datedesc" => get_string("datemostrecentfirst"));
159 echo "<tr><td><b>" . get_string("participants") . "</b></td><td>";
160 choose_from_menu ($users, "user", $selecteduser, get_string("allparticipants") );
161 echo "</td>";
163 echo '<td align="right"><b>' . get_string("since") . '</b></td><td>';
164 choose_from_menu ($dates, "date", $selecteddate, get_string("alldays"));
165 echo "</td></tr>";
167 echo "<tr><td><b>" . get_string("activities") . "</b></td><td>";
168 choose_from_menu ($activities, "modid", $selectedactivity, "");
169 echo "</td>";
171 echo '<td align="right"><b>' . get_string("sortby") . "</b></td><td>";
172 choose_from_menu ($sortfields, "sortby", $selectedsort, "");
173 echo "</td></tr>";
175 echo '<tr>';
177 $groupmode = groupmode($course);
179 if ($groupmode == VISIBLEGROUPS or ($groupmode and has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id)))) {
180 if ($groups_names = groups_get_groups_names($course->id)) { //TODO:check.
181 echo '<td><b>';
182 if ($groupmode == VISIBLEGROUPS) {
183 print_string('groupsvisible');
184 } else {
185 print_string('groupsseparate');
187 echo ':</b></td><td>';
188 choose_from_menu($groups_names, "selectedgroup", $selectedgroup, get_string("allgroups"), "", "");
189 echo '</td>';
194 echo '<td colspan="2" align="right">';
195 echo '<input type="submit" value="'.get_string('showrecent').'" />';
196 echo "</td></tr>";
198 echo "</table>";
200 $advancedlink = "<a href=\"$CFG->wwwroot/course/recent.php?id=$course->id&amp;advancedfilter=0\">" . get_string("normalfilter") . "</a>";
201 print_heading($advancedlink);
202 echo "</center>";
203 echo "</form>";
205 } else {
207 $day_list = array("1","7","14","21","30");
208 $strsince = get_string("since");
209 $strlastlogin = get_string("lastlogin");
210 $strday = get_string("day");
211 $strdays = get_string("days");
213 $heading = "";
214 foreach ($day_list as $count) {
215 if ($count == "1") {
216 $day = $strday;
217 } else {
218 $day = $strdays;
220 $tmpdate = time() - ($count * 3600 * 24);
221 $heading = $heading .
222 "<a href=\"$CFG->wwwroot/course/recent.php?id=$course->id&amp;date=$tmpdate\"> $count $day</a> | ";
225 $heading = $strsince . ": <a href=\"$CFG->wwwroot/course/recent.php?id=$course->id\">$strlastlogin</a>" . " | " . $heading;
226 print_heading($heading);
228 $advancedlink = "<a href=\"$CFG->wwwroot/course/recent.php?id=$course->id&amp;advancedfilter=1\">" . get_string("advancedfilter") . "</a>";
229 print_heading($advancedlink);
236 function make_log_url($module, $url) {
237 switch ($module) {
238 case 'user':
239 case 'course':
240 case 'file':
241 case 'login':
242 case 'lib':
243 case 'admin':
244 case 'message':
245 case 'calendar':
246 case 'mnet course':
247 return "/course/$url";
248 break;
249 case 'blog':
250 return "/$module/$url";
251 break;
252 case 'upload':
253 return $url;
254 break;
255 case 'library':
256 case '':
257 return '/';
258 break;
259 default:
260 return "/mod/$module/$url";
261 break;
266 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
267 $modname="", $modid=0, $modaction="", $groupid=0) {
269 global $CFG;
271 // It is assumed that $date is the GMT time of midnight for that day,
272 // and so the next 86400 seconds worth of logs are printed.
274 /// Setup for group handling.
276 // TODO: I don't understand group/context/etc. enough to be able to do
277 // something interesting with it here
278 // What is the context of a remote course?
280 /// If the group mode is separate, and this user does not have editing privileges,
281 /// then only the user's group can be viewed.
282 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
283 // $groupid = get_current_group($course->id);
285 /// If this course doesn't have groups, no groupid can be specified.
286 //else if (!$course->groupmode) {
287 // $groupid = 0;
289 $groupid = 0;
291 $joins = array();
293 $qry = "
294 SELECT
295 l.*,
296 u.firstname,
297 u.lastname,
298 u.picture
299 FROM
300 {$CFG->prefix}mnet_log l
301 LEFT JOIN
302 {$CFG->prefix}user u
304 l.userid = u.id
305 WHERE
308 $where .= "l.hostid = '$hostid'";
310 // TODO: Is 1 really a magic number referring to the sitename?
311 if ($course != 1 || $modid != 0) {
312 $where .= " AND\n l.course='$course'";
315 if ($modname) {
316 $where .= " AND\n l.module = '$modname'";
319 if ('site_errors' === $modid) {
320 $where .= " AND\n ( l.action='error' OR l.action='infected' )";
321 } else if ($modid) {
322 //TODO: This assumes that modids are the same across sites... probably
323 //not true
324 $where .= " AND\n l.cmid = '$modid'";
327 if ($modaction) {
328 $firstletter = substr($modaction, 0, 1);
329 if (ctype_alpha($firstletter)) {
330 $where .= " AND\n lower(l.action) LIKE '%" . strtolower($modaction) . "%'";
331 } else if ($firstletter == '-') {
332 $where .= " AND\n lower(l.action) NOT LIKE '%" . strtolower(substr($modaction, 1)) . "%'";
336 if ($user) {
337 $where .= " AND\n l.userid = '$user'";
340 if ($date) {
341 $enddate = $date + 86400;
342 $where .= " AND\n l.time > '$date' AND l.time < '$enddate'";
345 $result = array();
346 $result['totalcount'] = count_records_sql("SELECT COUNT(*) FROM {$CFG->prefix}mnet_log l WHERE $where");
347 if(!empty($result['totalcount'])) {
348 $where .= "\n ORDER BY\n $order";
349 $result['logs'] = get_records_sql($qry.$where, $limitfrom, $limitnum);
350 } else {
351 $result['logs'] = array();
353 return $result;
356 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
357 $modname="", $modid=0, $modaction="", $groupid=0) {
359 // It is assumed that $date is the GMT time of midnight for that day,
360 // and so the next 86400 seconds worth of logs are printed.
362 /// Setup for group handling.
364 /// If the group mode is separate, and this user does not have editing privileges,
365 /// then only the user's group can be viewed.
366 if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
367 $groupid = get_current_group($course->id);
369 /// If this course doesn't have groups, no groupid can be specified.
370 else if (!$course->groupmode) {
371 $groupid = 0;
374 $joins = array();
376 if ($course->id != SITEID || $modid != 0) {
377 $joins[] = "l.course='$course->id'";
380 if ($modname) {
381 $joins[] = "l.module = '$modname'";
384 if ('site_errors' === $modid) {
385 $joins[] = "( l.action='error' OR l.action='infected' )";
386 } else if ($modid) {
387 $joins[] = "l.cmid = '$modid'";
390 if ($modaction) {
391 $firstletter = substr($modaction, 0, 1);
392 if (ctype_alpha($firstletter)) {
393 $joins[] = "lower(l.action) LIKE '%" . strtolower($modaction) . "%'";
394 } else if ($firstletter == '-') {
395 $joins[] = "lower(l.action) NOT LIKE '%" . strtolower(substr($modaction, 1)) . "%'";
399 /// Getting all members of a group.
400 if ($groupid and !$user) {
401 $gusers = groups_get_members($groupid);
402 if (!empty($gusers)) {
403 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
404 } else {
405 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always by false.
408 else if ($user) {
409 $joins[] = "l.userid = '$user'";
412 if ($date) {
413 $enddate = $date + 86400;
414 $joins[] = "l.time > '$date' AND l.time < '$enddate'";
417 $selector = implode(' AND ', $joins);
419 $totalcount = 0; // Initialise
420 $result = array();
421 $result['logs'] = get_logs($selector, $order, $limitfrom, $limitnum, $totalcount);
422 $result['totalcount'] = $totalcount;
423 return $result;
427 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
428 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
430 global $CFG;
432 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
433 $modname, $modid, $modaction, $groupid)) {
434 notify("No logs found!");
435 print_footer($course);
436 exit;
439 $courses = array();
441 if ($course->id == SITEID) {
442 $courses[0] = '';
443 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
444 foreach ($ccc as $cc) {
445 $courses[$cc->id] = $cc->shortname;
448 } else {
449 $courses[$course->id] = $course->shortname;
452 $totalcount = $logs['totalcount'];
453 $count=0;
454 $ldcache = array();
455 $tt = getdate(time());
456 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
458 $strftimedatetime = get_string("strftimedatetime");
460 echo "<div class=\"info\">\n";
461 print_string("displayingrecords", "", $totalcount);
462 echo "</div>\n";
464 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
466 echo '<table class="logtable genearlbox boxaligncenter" summary="">'."\n";
467 // echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\" summary=\"\">\n";
468 echo "<tr>";
469 if ($course->id == SITEID) {
470 echo "<th class=\"c0 header\" scope=\"col\">".get_string('course')."</th>\n";
472 echo "<th class=\"c1 header\" scope=\"col\">".get_string('time')."</th>\n";
473 echo "<th class=\"c2 header\" scope=\"col\">".get_string('ip_address')."</th>\n";
474 echo "<th class=\"c3 header\" scope=\"col\">".get_string('fullname')."</th>\n";
475 echo "<th class=\"c4 header\" scope=\"col\">".get_string('action')."</th>\n";
476 echo "<th class=\"c5 header\" scope=\"col\">".get_string('info')."</th>\n";
477 echo "</tr>\n";
479 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
480 if (empty($logs['logs'])) {
481 $logs['logs'] = array();
484 $row = 1;
485 foreach ($logs['logs'] as $log) {
487 $row = ($row + 1) % 2;
489 if (isset($ldcache[$log->module][$log->action])) {
490 $ld = $ldcache[$log->module][$log->action];
491 } else {
492 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
493 $ldcache[$log->module][$log->action] = $ld;
495 if ($ld && is_numeric($log->info)) {
496 // ugly hack to make sure fullname is shown correctly
497 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
498 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
499 } else {
500 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
504 //Filter log->info
505 $log->info = format_string($log->info);
507 $log->url = strip_tags(urldecode($log->url)); // Some XSS protection
508 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
509 $log->url = str_replace('&', '&amp;', $log->url); /// XHTML compatibility
511 echo '<tr class="r'.$row.'">';
512 if ($course->id == SITEID) {
513 echo "<td class=\"cell c0\">\n";
514 if (empty($log->course)) {
515 echo format_string($log->info)."\n";
516 } else {
517 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course])."</a>\n";
519 echo "</td>\n";
521 echo "<td class=\"cell c1\" align=\"right\">".userdate($log->time, '%a').
522 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
523 echo "<td class=\"cell c2\">\n";
524 link_to_popup_window("/iplookup/index.php?ip=$log->ip&amp;user=$log->userid", 'iplookup',$log->ip, 400, 700);
525 echo "</td>\n";
526 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
527 echo "<td class=\"cell c3\">\n";
528 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}&amp;course={$log->course}\">$fullname</a>\n";
529 echo "</td>\n";
530 echo "<td class=\"cell c4\">\n";
531 link_to_popup_window( make_log_url($log->module,$log->url), 'fromloglive',"$log->module $log->action", 400, 600);
532 echo "</td>\n";;
533 echo "<td class=\"cell c5\">{$log->info}</td>\n";
534 echo "</tr>\n";
536 echo "</table>\n";
538 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
542 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
543 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
545 global $CFG;
547 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
548 $modname, $modid, $modaction, $groupid)) {
549 notify("No logs found!");
550 print_footer($course);
551 exit;
554 if ($course->id == SITEID) {
555 $courses[0] = '';
556 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
557 foreach ($ccc as $cc) {
558 $courses[$cc->id] = $cc->shortname;
563 $totalcount = $logs['totalcount'];
564 $count=0;
565 $ldcache = array();
566 $tt = getdate(time());
567 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
569 $strftimedatetime = get_string("strftimedatetime");
571 echo "<div class=\"info\">\n";
572 print_string("displayingrecords", "", $totalcount);
573 echo "</div>\n";
575 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
577 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
578 echo "<tr>";
579 if ($course->id == SITEID) {
580 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
582 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
583 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
584 echo "<th class=\"c3 header\">".get_string('fullname')."</th>\n";
585 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
586 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
587 echo "</tr>\n";
589 if (empty($logs['logs'])) {
590 echo "</table>\n";
591 return;
594 $row = 1;
595 foreach ($logs['logs'] as $log) {
597 $log->info = $log->coursename;
598 $row = ($row + 1) % 2;
600 if (isset($ldcache[$log->module][$log->action])) {
601 $ld = $ldcache[$log->module][$log->action];
602 } else {
603 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
604 $ldcache[$log->module][$log->action] = $ld;
606 if (0 && $ld && !empty($log->info)) {
607 // ugly hack to make sure fullname is shown correctly
608 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
609 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
610 } else {
611 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
615 //Filter log->info
616 $log->info = format_string($log->info);
618 $log->url = strip_tags(urldecode($log->url)); // Some XSS protection
619 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
620 $log->url = str_replace('&', '&amp;', $log->url); /// XHTML compatibility
622 echo '<tr class="r'.$row.'">';
623 if ($course->id == SITEID) {
624 echo "<td class=\"r$row c0\" >\n";
625 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courses[$log->course]."</a>\n";
626 echo "</td>\n";
628 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time, '%a').
629 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
630 echo "<td class=\"r$row c2\" >\n";
631 link_to_popup_window("/iplookup/index.php?ip=$log->ip&amp;user=$log->userid", 'iplookup',$log->ip, 400, 700);
632 echo "</td>\n";
633 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
634 echo "<td class=\"r$row c3\" >\n";
635 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
636 echo "</td>\n";
637 echo "<td class=\"r$row c4\">\n";
638 echo $log->action .': '.$log->module;
639 echo "</td>\n";;
640 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
641 echo "</tr>\n";
643 echo "</table>\n";
645 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
649 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
650 $modid, $modaction, $groupid) {
652 $text = get_string('course')."\t".get_string('time')."\t".get_string('ip_address')."\t".
653 get_string('fullname')."\t".get_string('action')."\t".get_string('info');
655 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
656 $modname, $modid, $modaction, $groupid)) {
657 return false;
660 $courses = array();
662 if ($course->id == SITEID) {
663 $courses[0] = '';
664 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
665 foreach ($ccc as $cc) {
666 $courses[$cc->id] = $cc->shortname;
669 } else {
670 $courses[$course->id] = $course->shortname;
673 $count=0;
674 $ldcache = array();
675 $tt = getdate(time());
676 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
678 $strftimedatetime = get_string("strftimedatetime");
680 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
681 $filename .= '.txt';
682 header("Content-Type: application/download\n");
683 header("Content-Disposition: attachment; filename=$filename");
684 header("Expires: 0");
685 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
686 header("Pragma: public");
688 echo get_string('savedat').userdate(time(), $strftimedatetime)."\n";
689 echo $text;
691 if (empty($logs['logs'])) {
692 return true;
695 foreach ($logs['logs'] as $log) {
696 if (isset($ldcache[$log->module][$log->action])) {
697 $ld = $ldcache[$log->module][$log->action];
698 } else {
699 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
700 $ldcache[$log->module][$log->action] = $ld;
702 if ($ld && !empty($log->info)) {
703 // ugly hack to make sure fullname is shown correctly
704 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
705 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
706 } else {
707 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
711 //Filter log->info
712 $log->info = format_string($log->info);
714 $log->url = strip_tags(urldecode($log->url)); // Some XSS protection
715 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
716 $log->url = str_replace('&', '&amp;', $log->url); // XHTML compatibility
718 $firstField = $courses[$log->course];
719 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
720 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action, $log->info);
721 $text = implode("\t", $row);
722 echo $text." \n";
724 return true;
728 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
729 $modid, $modaction, $groupid) {
731 global $CFG;
733 require_once("$CFG->libdir/excellib.class.php");
735 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
736 $modname, $modid, $modaction, $groupid)) {
737 return false;
740 $courses = array();
742 if ($course->id == SITEID) {
743 $courses[0] = '';
744 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
745 foreach ($ccc as $cc) {
746 $courses[$cc->id] = $cc->shortname;
749 } else {
750 $courses[$course->id] = $course->shortname;
753 $count=0;
754 $ldcache = array();
755 $tt = getdate(time());
756 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
758 $strftimedatetime = get_string("strftimedatetime");
760 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
761 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
762 $filename .= '.xls';
764 $workbook = new MoodleExcelWorkbook('-');
765 $workbook->send($filename);
767 $worksheet = array();
768 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
769 get_string('fullname'), get_string('action'), get_string('info'));
771 // Creating worksheets
772 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
773 $sheettitle = get_string('excel_sheettitle', 'logs', $wsnumber).$nroPages;
774 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
775 $worksheet[$wsnumber]->set_column(1, 1, 30);
776 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
777 userdate(time(), $strftimedatetime));
778 $col = 0;
779 foreach ($headers as $item) {
780 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
781 $col++;
785 if (empty($logs['logs'])) {
786 $workbook->close();
787 return true;
790 $formatDate =& $workbook->add_format();
791 $formatDate->set_num_format(get_string('log_excel_date_format'));
793 $row = FIRSTUSEDEXCELROW;
794 $wsnumber = 1;
795 $myxls =& $worksheet[$wsnumber];
796 foreach ($logs['logs'] as $log) {
797 if (isset($ldcache[$log->module][$log->action])) {
798 $ld = $ldcache[$log->module][$log->action];
799 } else {
800 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
801 $ldcache[$log->module][$log->action] = $ld;
803 if ($ld && !empty($log->info)) {
804 // ugly hack to make sure fullname is shown correctly
805 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
806 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
807 } else {
808 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
812 // Filter log->info
813 $log->info = format_string($log->info);
814 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
816 if ($nroPages>1) {
817 if ($row > EXCELROWS) {
818 $wsnumber++;
819 $myxls =& $worksheet[$wsnumber];
820 $row = FIRSTUSEDEXCELROW;
824 $myxls->write($row, 0, $courses[$log->course], '');
825 // Excel counts from 1/1/1900
826 $excelTime=25569+$log->time/(3600*24);
827 $myxls->write($row, 1, $excelTime, $formatDate);
828 $myxls->write($row, 2, $log->ip, '');
829 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
830 $myxls->write($row, 3, $fullname, '');
831 $myxls->write($row, 4, $log->module.' '.$log->action, '');
832 $myxls->write($row, 5, $log->info, '');
834 $row++;
837 $workbook->close();
838 return true;
841 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
842 $modid, $modaction, $groupid) {
844 global $CFG;
846 require_once("$CFG->libdir/odslib.class.php");
848 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
849 $modname, $modid, $modaction, $groupid)) {
850 return false;
853 $courses = array();
855 if ($course->id == SITEID) {
856 $courses[0] = '';
857 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
858 foreach ($ccc as $cc) {
859 $courses[$cc->id] = $cc->shortname;
862 } else {
863 $courses[$course->id] = $course->shortname;
866 $count=0;
867 $ldcache = array();
868 $tt = getdate(time());
869 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
871 $strftimedatetime = get_string("strftimedatetime");
873 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
874 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
875 $filename .= '.ods';
877 $workbook = new MoodleODSWorkbook('-');
878 $workbook->send($filename);
880 $worksheet = array();
881 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
882 get_string('fullname'), get_string('action'), get_string('info'));
884 // Creating worksheets
885 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
886 $sheettitle = get_string('excel_sheettitle', 'logs', $wsnumber).$nroPages;
887 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
888 $worksheet[$wsnumber]->set_column(1, 1, 30);
889 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
890 userdate(time(), $strftimedatetime));
891 $col = 0;
892 foreach ($headers as $item) {
893 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
894 $col++;
898 if (empty($logs['logs'])) {
899 $workbook->close();
900 return true;
903 $formatDate =& $workbook->add_format();
904 $formatDate->set_num_format(get_string('log_excel_date_format'));
906 $row = FIRSTUSEDEXCELROW;
907 $wsnumber = 1;
908 $myxls =& $worksheet[$wsnumber];
909 foreach ($logs['logs'] as $log) {
910 if (isset($ldcache[$log->module][$log->action])) {
911 $ld = $ldcache[$log->module][$log->action];
912 } else {
913 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
914 $ldcache[$log->module][$log->action] = $ld;
916 if ($ld && !empty($log->info)) {
917 // ugly hack to make sure fullname is shown correctly
918 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
919 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
920 } else {
921 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
925 // Filter log->info
926 $log->info = format_string($log->info);
927 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
929 if ($nroPages>1) {
930 if ($row > EXCELROWS) {
931 $wsnumber++;
932 $myxls =& $worksheet[$wsnumber];
933 $row = FIRSTUSEDEXCELROW;
937 $myxls->write_string($row, 0, $courses[$log->course]);
938 $myxls->write_date($row, 1, $log->time);
939 $myxls->write_string($row, 2, $log->ip);
940 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
941 $myxls->write_string($row, 3, $fullname);
942 $myxls->write_string($row, 4, $log->module.' '.$log->action);
943 $myxls->write_string($row, 5, $log->info);
945 $row++;
948 $workbook->close();
949 return true;
953 function print_log_graph($course, $userid=0, $type="course.png", $date=0) {
954 global $CFG;
955 if (empty($CFG->gdversion)) {
956 echo "(".get_string("gdneed").")";
957 } else {
958 echo '<img src="'.$CFG->wwwroot.'/course/report/log/graph.php?id='.$course->id.
959 '&amp;user='.$userid.'&amp;type='.$type.'&amp;date='.$date.'" alt="" />';
964 function print_overview($courses) {
966 global $CFG, $USER;
968 $htmlarray = array();
969 if ($modules = get_records('modules')) {
970 foreach ($modules as $mod) {
971 if (file_exists(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php')) {
972 require_once(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php');
973 $fname = $mod->name.'_print_overview';
974 if (function_exists($fname)) {
975 $fname($courses,$htmlarray);
980 foreach ($courses as $course) {
981 print_simple_box_start('center', '100%', '', 5, "coursebox");
982 $linkcss = '';
983 if (empty($course->visible)) {
984 $linkcss = 'class="dimmed"';
986 print_heading('<a title="'. format_string($course->fullname).'" '.$linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'. format_string($course->fullname).'</a>');
987 if (array_key_exists($course->id,$htmlarray)) {
988 foreach ($htmlarray[$course->id] as $modname => $html) {
989 echo $html;
992 print_simple_box_end();
997 function print_recent_activity($course) {
998 // $course is an object
999 // This function trawls through the logs looking for
1000 // anything new since the user's last login
1002 global $CFG, $USER, $SESSION;
1004 $context = get_context_instance(CONTEXT_COURSE, $course->id);
1006 $timestart = time() - COURSE_MAX_RECENT_PERIOD;
1008 if (!has_capability('moodle/legacy:guest', $context, NULL, false)) {
1009 if (!empty($USER->lastcourseaccess[$course->id])) {
1010 if ($USER->lastcourseaccess[$course->id] > $timestart) {
1011 $timestart = $USER->lastcourseaccess[$course->id];
1016 echo '<div class="activitydate">';
1017 echo get_string('activitysince', '', userdate($timestart));
1018 echo '</div>';
1019 echo '<div class="activityhead">';
1021 echo '<a href="'.$CFG->wwwroot.'/course/recent.php?id='.$course->id.'">'.get_string('recentactivityreport').'</a>';
1023 echo "</div>\n";
1026 // Firstly, have there been any new enrolments?
1028 $heading = false;
1029 $content = false;
1031 $users = get_recent_enrolments($course->id, $timestart);
1033 //Accessibility: new users now appear in an <OL> list.
1034 if ($users) {
1035 echo '<div class="newusers">';
1036 if (! $heading) {
1037 print_headline(get_string("newusers").':', 3);
1038 $heading = true;
1039 $content = true;
1041 echo "<ol class=\"list\">\n";
1042 foreach ($users as $user) {
1044 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
1045 echo '<li class="name"><a href="'.$CFG->wwwroot."/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a></li>\n";
1047 echo "</ol>\n</div>\n";
1050 // Next, have there been any modifications to the course structure?
1052 $logs = get_records_select('log', "time > '$timestart' AND course = '$course->id' AND
1053 module = 'course' AND action LIKE '% mod'", "time ASC");
1055 if ($logs) {
1056 foreach ($logs as $key => $log) {
1057 $info = split(' ', $log->info);
1059 if ($info[0] == 'label') { // Labels are special activities
1060 continue;
1063 $modname = get_field($info[0], 'name', 'id', $info[1]);
1064 //Create a temp valid module structure (course,id)
1065 $tempmod->course = $log->course;
1066 $tempmod->id = $info[1];
1067 //Obtain the visible property from the instance
1068 $modvisible = instance_is_visible($info[0],$tempmod);
1070 //Only if the mod is visible
1071 if ($modvisible) {
1072 switch ($log->action) {
1073 case 'add mod':
1074 $stradded = get_string('added', 'moodle', get_string('modulename', $info[0]));
1075 $changelist[$log->info] = array ('operation' => 'add', 'text' => "$stradded:<br /><a href=\"$CFG->wwwroot/course/$log->url\">".format_string($modname,true)."</a>");
1076 break;
1077 case 'update mod':
1078 $strupdated = get_string('updated', 'moodle', get_string('modulename', $info[0]));
1079 if (empty($changelist[$log->info])) {
1080 $changelist[$log->info] = array ('operation' => 'update', 'text' => "$strupdated:<br /><a href=\"$CFG->wwwroot/course/$log->url\">".format_string($modname,true)."</a>");
1082 break;
1083 case 'delete mod':
1084 if (!empty($changelist[$log->info]['operation']) and
1085 $changelist[$log->info]['operation'] == 'add') {
1086 $changelist[$log->info] = NULL;
1087 } else {
1088 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $info[0]));
1089 $changelist[$log->info] = array ('operation' => 'delete', 'text' => $strdeleted);
1091 break;
1097 if (!empty($changelist)) {
1098 foreach ($changelist as $changeinfo => $change) {
1099 if ($change) {
1100 $changes[$changeinfo] = $change;
1103 if (isset($changes)){
1104 if (count($changes) > 0) {
1105 print_headline(get_string('courseupdates').':', 3);
1106 $content = true;
1107 foreach ($changes as $changeinfo => $change) {
1108 echo '<p class="activity">'.$change['text'].'</p>';
1114 // Now display new things from each module
1116 $mods = get_records('modules', 'visible', '1', 'name', 'id, name');
1118 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
1120 foreach ($mods as $mod) { // Each module gets it's own logs and prints them
1121 include_once($CFG->dirroot.'/mod/'.$mod->name.'/lib.php');
1122 $print_recent_activity = $mod->name.'_print_recent_activity';
1123 if (function_exists($print_recent_activity)) {
1125 // NOTE:
1126 // $isteacher (second parameter below) is to be deprecated!
1128 // TODO:
1129 // 1) Make sure that all _print_recent_activity functions are
1130 // not using the $isteacher value.
1131 // 2) Eventually, remove the $isteacher parameter from the
1132 // function calls.
1134 $modcontent = $print_recent_activity($course, $viewfullnames, $timestart);
1135 if ($modcontent) {
1136 $content = true;
1141 if (! $content) {
1142 echo '<p class="message">'.get_string('nothingnew').'</p>';
1147 function get_array_of_activities($courseid) {
1148 // For a given course, returns an array of course activity objects
1149 // Each item in the array contains he following properties:
1150 // cm - course module id
1151 // mod - name of the module (eg forum)
1152 // section - the number of the section (eg week or topic)
1153 // name - the name of the instance
1154 // visible - is the instance visible or not
1155 // extra - contains extra string to include in any link
1157 global $CFG;
1159 $mod = array();
1161 if (!$rawmods = get_course_mods($courseid)) {
1162 return NULL;
1165 if ($sections = get_records("course_sections", "course", $courseid, "section ASC")) {
1166 foreach ($sections as $section) {
1167 if (!empty($section->sequence)) {
1168 $sequence = explode(",", $section->sequence);
1169 foreach ($sequence as $seq) {
1170 if (empty($rawmods[$seq])) {
1171 continue;
1173 $mod[$seq]->cm = $rawmods[$seq]->id;
1174 $mod[$seq]->mod = $rawmods[$seq]->modname;
1175 $mod[$seq]->section = $section->section;
1176 $mod[$seq]->name = urlencode(get_field($rawmods[$seq]->modname, "name", "id", $rawmods[$seq]->instance));
1177 $mod[$seq]->visible = $rawmods[$seq]->visible;
1178 $mod[$seq]->extra = "";
1180 $modname = $mod[$seq]->mod;
1181 $functionname = $modname."_get_coursemodule_info";
1183 include_once("$CFG->dirroot/mod/$modname/lib.php");
1185 if (function_exists($functionname)) {
1186 if ($info = $functionname($rawmods[$seq])) {
1187 if (!empty($info->extra)) {
1188 $mod[$seq]->extra = $info->extra;
1190 if (!empty($info->icon)) {
1191 $mod[$seq]->icon = $info->icon;
1199 return $mod;
1205 function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
1206 // Returns a number of useful structures for course displays
1208 $mods = NULL; // course modules indexed by id
1209 $modnames = NULL; // all course module names (except resource!)
1210 $modnamesplural= NULL; // all course module names (plural form)
1211 $modnamesused = NULL; // course module names used
1213 if ($allmods = get_records("modules")) {
1214 foreach ($allmods as $mod) {
1215 if ($mod->visible) {
1216 $modnames[$mod->name] = get_string("modulename", "$mod->name");
1217 $modnamesplural[$mod->name] = get_string("modulenameplural", "$mod->name");
1220 asort($modnames);
1221 } else {
1222 error("No modules are installed!");
1225 if ($rawmods = get_course_mods($courseid)) {
1226 foreach($rawmods as $mod) { // Index the mods
1227 if (empty($modnames[$mod->modname])) {
1228 continue;
1230 $mods[$mod->id] = $mod;
1231 $mods[$mod->id]->modfullname = $modnames[$mod->modname];
1232 if ($mod->visible or has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_COURSE, $courseid))) {
1233 $modnamesused[$mod->modname] = $modnames[$mod->modname];
1236 if ($modnamesused) {
1237 asort($modnamesused);
1243 function get_all_sections($courseid) {
1245 return get_records("course_sections", "course", "$courseid", "section",
1246 "section, id, course, summary, sequence, visible");
1249 function course_set_display($courseid, $display=0) {
1250 global $USER;
1252 if ($display == "all" or empty($display)) {
1253 $display = 0;
1256 if (empty($USER->id) or $USER->username == 'guest') {
1257 //do not store settings in db for guests
1258 } else if (record_exists("course_display", "userid", $USER->id, "course", $courseid)) {
1259 set_field("course_display", "display", $display, "userid", $USER->id, "course", $courseid);
1260 } else {
1261 $record->userid = $USER->id;
1262 $record->course = $courseid;
1263 $record->display = $display;
1264 if (!insert_record("course_display", $record)) {
1265 notify("Could not save your course display!");
1269 return $USER->display[$courseid] = $display; // Note: = not ==
1272 function set_section_visible($courseid, $sectionnumber, $visibility) {
1273 /// For a given course section, markes it visible or hidden,
1274 /// and does the same for every activity in that section
1276 if ($section = get_record("course_sections", "course", $courseid, "section", $sectionnumber)) {
1277 set_field("course_sections", "visible", "$visibility", "id", $section->id);
1278 if (!empty($section->sequence)) {
1279 $modules = explode(",", $section->sequence);
1280 foreach ($modules as $moduleid) {
1281 set_coursemodule_visible($moduleid, $visibility, true);
1284 rebuild_course_cache($courseid);
1289 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%") {
1290 /// Prints a section full of activity modules
1291 global $CFG, $USER;
1293 static $groupbuttons;
1294 static $groupbuttonslink;
1295 static $isteacher;
1296 static $isediting;
1297 static $ismoving;
1298 static $strmovehere;
1299 static $strmovefull;
1300 static $strunreadpostsone;
1302 static $untracked;
1303 static $usetracking;
1305 $labelformatoptions = New stdClass;
1307 if (!isset($isteacher)) {
1308 $groupbuttons = ($course->groupmode or (!$course->groupmodeforce));
1309 $groupbuttonslink = (!$course->groupmodeforce);
1310 $isediting = isediting($course->id);
1311 $ismoving = $isediting && ismoving($course->id);
1312 if ($ismoving) {
1313 $strmovehere = get_string("movehere");
1314 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1316 include_once($CFG->dirroot.'/mod/forum/lib.php');
1317 if ($usetracking = forum_tp_can_track_forums()) {
1318 $strunreadpostsone = get_string('unreadpostsone', 'forum');
1319 $untracked = forum_tp_get_untracked_forums($USER->id, $course->id);
1322 $labelformatoptions->noclean = true;
1324 /// Casting $course->modinfo to string prevents one notice when the field is null
1325 $modinfo = unserialize((string)$course->modinfo);
1327 //Acccessibility: replace table with list <ul>, but don't output empty list.
1328 if (!empty($section->sequence)) {
1330 // Fix bug #5027, don't want style=\"width:$width\".
1331 echo "<ul class=\"section\">\n";
1332 $sectionmods = explode(",", $section->sequence);
1334 foreach ($sectionmods as $modnumber) {
1335 if (empty($mods[$modnumber])) {
1336 continue;
1338 $mod = $mods[$modnumber];
1340 if (($mod->visible or has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_COURSE, $course->id))) &&
1341 (!$ismoving || $mod->id != $USER->activitycopy)) {
1342 echo '<li class="activity '.$mod->modname.'" id="module-'.$modnumber.'">'; // Unique ID
1343 if ($ismoving) {
1344 echo '<a title="'.$strmovefull.'"'.
1345 ' href="'.$CFG->wwwroot.'/course/mod.php?moveto='.$mod->id.'&amp;sesskey='.$USER->sesskey.'">'.
1346 '<img class="movetarget" src="'.$CFG->pixpath.'/movehere.gif" '.
1347 ' alt="'.$strmovehere.'" /></a><br />
1350 $instancename = urldecode($modinfo[$modnumber]->name);
1351 $instancename = format_string($instancename, true, $course->id);
1353 if (!empty($modinfo[$modnumber]->extra)) {
1354 $extra = urldecode($modinfo[$modnumber]->extra);
1355 } else {
1356 $extra = "";
1359 if (!empty($modinfo[$modnumber]->icon)) {
1360 $icon = "$CFG->pixpath/".urldecode($modinfo[$modnumber]->icon);
1361 } else {
1362 $icon = "$CFG->modpixpath/$mod->modname/icon.gif";
1365 if ($mod->indent) {
1366 print_spacer(12, 20 * $mod->indent, false);
1369 if ($mod->modname == "label") {
1370 if (!$mod->visible) {
1371 echo "<span class=\"dimmed_text\">";
1373 echo format_text($extra, FORMAT_HTML, $labelformatoptions);
1374 if (!$mod->visible) {
1375 echo "</span>";
1378 } else { // Normal activity
1380 if (!empty($USER->screenreader)) {
1381 $typestring = '('.get_string('modulename',$mod->modname).') ';
1382 } else {
1383 $typestring = '';
1386 $linkcss = $mod->visible ? "" : " class=\"dimmed\" ";
1387 echo '<img src="'.$icon.'"'.
1388 ' class="activityicon" alt="'.$mod->modfullname.'" />'.
1389 ' <a title="'.$mod->modfullname.'" '.$linkcss.' '.$extra.
1390 ' href="'.$CFG->wwwroot.'/mod/'.$mod->modname.'/view.php?id='.$mod->id.'">'.
1391 $typestring.$instancename.'</a>';
1393 if ($usetracking && $mod->modname == 'forum') {
1394 $groupmode = groupmode($course, $mod);
1395 $groupid = ($groupmode == SEPARATEGROUPS && !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) ?
1396 get_current_group($course->id) : false;
1398 if (forum_tp_can_track_forums() && !isset($untracked[$mod->instance])) {
1399 $unread = forum_tp_count_forum_unread_posts($USER->id, $mod->instance, $groupid);
1400 if ($unread) {
1401 echo '<span class="unread"> <a href="'.$CFG->wwwroot.'/mod/forum/view.php?id='.$mod->id.'">';
1402 if ($unread == 1) {
1403 echo $strunreadpostsone;
1404 } else {
1405 print_string('unreadpostsnumber', 'forum', $unread);
1407 echo '</a> </span>';
1412 if ($isediting) {
1413 // TODO: we must define this as mod property!
1414 if ($groupbuttons and $mod->modname != 'label' and $mod->modname != 'resource' and $mod->modname != 'glossary') {
1415 if (! $mod->groupmodelink = $groupbuttonslink) {
1416 $mod->groupmode = $course->groupmode;
1419 } else {
1420 $mod->groupmode = false;
1422 echo '&nbsp;&nbsp;';
1423 echo make_editing_buttons($mod, $absolute, true, $mod->indent, $section->section);
1425 echo "</li>\n";
1428 } elseif ($ismoving) {
1429 echo "<ul class=\"section\">\n";
1431 if ($ismoving) {
1432 echo '<li><a title="'.$strmovefull.'"'.
1433 ' href="'.$CFG->wwwroot.'/course/mod.php?movetosection='.$section->id.'&amp;sesskey='.$USER->sesskey.'">'.
1434 '<img class="movetarget" src="'.$CFG->pixpath.'/movehere.gif" '.
1435 ' alt="'.$strmovehere.'" /></a></li>
1438 if (!empty($section->sequence) || $ismoving) {
1439 echo "</ul><!--class='section'-->\n\n";
1444 * Prints the menus to add activities and resources.
1446 function print_section_add_menus($course, $section, $modnames, $vertical=false, $return=false) {
1447 global $CFG;
1449 // check to see if user can add menus
1450 if (!has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $course->id))) {
1451 return false;
1454 static $resources = false;
1455 static $activities = false;
1457 if ($resources === false) {
1458 $resources = array();
1459 $activities = array();
1461 foreach($modnames as $modname=>$modnamestr) {
1462 if (!course_allowed_module($course, $modname)) {
1463 continue;
1466 require_once("$CFG->dirroot/mod/$modname/lib.php");
1467 $gettypesfunc = $modname.'_get_types';
1468 if (function_exists($gettypesfunc)) {
1469 $types = $gettypesfunc();
1470 foreach($types as $type) {
1471 if ($type->modclass == MOD_CLASS_RESOURCE) {
1472 $resources[$type->type] = $type->typestr;
1473 } else {
1474 $activities[$type->type] = $type->typestr;
1477 } else {
1478 // all mods without type are considered activity
1479 $activities[$modname] = $modnamestr;
1484 $straddactivity = get_string('addactivity');
1485 $straddresource = get_string('addresource');
1487 $output = '<div class="section_add_menus">';
1489 if (!$vertical) {
1490 $output .= '<div class="horizontal">';
1493 if (!empty($resources)) {
1494 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&amp;section=$section&amp;sesskey=".sesskey()."&amp;add=",
1495 $resources, "ressection$section", "", $straddresource, 'resource/types', $straddresource, true);
1498 if (!empty($activities)) {
1499 $output .= ' ';
1500 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&amp;section=$section&amp;sesskey=".sesskey()."&amp;add=",
1501 $activities, "section$section", "", $straddactivity, 'mods', $straddactivity, true);
1504 if (!$vertical) {
1505 $output .= '</div>';
1508 $output .= '</div>';
1510 if ($return) {
1511 return $output;
1512 } else {
1513 echo $output;
1517 function rebuild_course_cache($courseid=0) {
1518 // Rebuilds the cached list of course activities stored in the database
1519 // If a courseid is not specified, then all are rebuilt
1521 if ($courseid) {
1522 $select = "id = '$courseid'";
1523 } else {
1524 $select = "";
1527 if ($courses = get_records_select("course", $select,'','id,fullname')) {
1528 foreach ($courses as $course) {
1529 $modinfo = serialize(get_array_of_activities($course->id));
1530 if (!set_field("course", "modinfo", $modinfo, "id", $course->id)) {
1531 notify("Could not cache module information for course '" . format_string($course->fullname) . "'!");
1539 function make_categories_list(&$list, &$parents, $category=NULL, $path="") {
1540 /// Given an empty array, this function recursively travels the
1541 /// categories, building up a nice list for display. It also makes
1542 /// an array that list all the parents for each category.
1544 // initialize the arrays if needed
1545 if (!is_array($list)) {
1546 $list = array();
1548 if (!is_array($parents)) {
1549 $parents = array();
1552 if ($category) {
1553 if ($path) {
1554 $path = $path.' / '.format_string($category->name);
1555 } else {
1556 $path = format_string($category->name);
1558 $list[$category->id] = $path;
1559 } else {
1560 $category->id = 0;
1563 if ($categories = get_categories($category->id)) { // Print all the children recursively
1564 foreach ($categories as $cat) {
1565 if (!empty($category->id)) {
1566 if (isset($parents[$category->id])) {
1567 $parents[$cat->id] = $parents[$category->id];
1569 $parents[$cat->id][] = $category->id;
1571 make_categories_list($list, $parents, $cat, $path);
1577 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $files = true) {
1578 /// Recursive function to print out all the categories in a nice format
1579 /// with or without courses included
1580 global $CFG;
1582 if (isset($CFG->max_category_depth) && ($depth >= $CFG->max_category_depth)) {
1583 return;
1586 if (!$displaylist) {
1587 make_categories_list($displaylist, $parentslist);
1590 if ($category) {
1591 if ($category->visible or has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
1592 print_category_info($category, $depth, $files);
1593 } else {
1594 return; // Don't bother printing children of invisible categories
1597 } else {
1598 $category->id = "0";
1601 if ($categories = get_categories($category->id)) { // Print all the children recursively
1602 $countcats = count($categories);
1603 $count = 0;
1604 $first = true;
1605 $last = false;
1606 foreach ($categories as $cat) {
1607 $count++;
1608 if ($count == $countcats) {
1609 $last = true;
1611 $up = $first ? false : true;
1612 $down = $last ? false : true;
1613 $first = false;
1615 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1, $files);
1620 // this function will return $options array for choose_from_menu, with whitespace to denote nesting.
1622 function make_categories_options() {
1623 make_categories_list($cats,$parents);
1624 foreach ($cats as $key => $value) {
1625 if (array_key_exists($key,$parents)) {
1626 if ($indent = count($parents[$key])) {
1627 for ($i = 0; $i < $indent; $i++) {
1628 $cats[$key] = '&nbsp;'.$cats[$key];
1633 return $cats;
1636 function print_category_info($category, $depth, $files = false) {
1637 /// Prints the category info in indented fashion
1638 /// This function is only used by print_whole_category_list() above
1640 global $CFG;
1641 static $strallowguests, $strrequireskey, $strsummary;
1643 if (empty($strsummary)) {
1644 $strallowguests = get_string('allowguests');
1645 $strrequireskey = get_string('requireskey');
1646 $strsummary = get_string('summary');
1649 $catlinkcss = $category->visible ? '' : ' class="dimmed" ';
1651 $coursecount = count_records('course') <= FRONTPAGECOURSELIMIT;
1652 if ($files and $coursecount) {
1653 $catimage = '<img src="'.$CFG->pixpath.'/i/course.gif" alt="" />';
1654 } else {
1655 $catimage = "&nbsp;";
1658 echo "\n\n".'<table class="categorylist">';
1660 if ($files and $coursecount) {
1661 $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');
1663 echo '<tr>';
1665 if ($depth) {
1666 $indent = $depth*30;
1667 $rows = count($courses) + 1;
1668 echo '<td rowspan="'.$rows.'" valign="top" width="'.$indent.'">';
1669 print_spacer(10, $indent);
1670 echo '</td>';
1673 echo '<td valign="top" class="category image">'.$catimage.'</td>';
1674 echo '<td valign="top" class="category name">';
1675 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot.'/course/category.php?id='.$category->id.'">'. format_string($category->name).'</a>';
1676 echo '</td>';
1677 echo '<td class="category info">&nbsp;</td>';
1678 echo '</tr>';
1680 if ($courses && !(isset($CFG->max_category_depth)&&($depth>=$CFG->max_category_depth-1))) {
1681 foreach ($courses as $course) {
1682 $linkcss = $course->visible ? '' : ' class="dimmed" ';
1683 echo '<tr><td valign="top">&nbsp;';
1684 echo '</td><td valign="top" class="course name">';
1685 echo '<a '.$linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'. format_string($course->fullname).'</a>';
1686 echo '</td><td align="right" valign="top" class="course info">';
1687 if ($course->guest ) {
1688 echo '<a title="'.$strallowguests.'" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">';
1689 echo '<img alt="'.$strallowguests.'" src="'.$CFG->pixpath.'/i/guest.gif" /></a>';
1690 } else {
1691 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath.'/spacer.gif" />';
1693 if ($course->password) {
1694 echo '<a title="'.$strrequireskey.'" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">';
1695 echo '<img alt="'.$strrequireskey.'" src="'.$CFG->pixpath.'/i/key.gif" /></a>';
1696 } else {
1697 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath.'/spacer.gif" />';
1699 if ($course->summary) {
1700 link_to_popup_window ('/course/info.php?id='.$course->id, 'courseinfo',
1701 '<img alt="'.$strsummary.'" src="'.$CFG->pixpath.'/i/info.gif" />',
1702 400, 500, $strsummary);
1703 } else {
1704 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath.'/spacer.gif" />';
1706 echo '</td></tr>';
1709 } else {
1711 echo '<tr>';
1713 if ($depth) {
1714 $indent = $depth*20;
1715 echo '<td valign="top" width="'.$indent.'">';
1716 print_spacer(10, $indent);
1717 echo '</td>';
1720 echo '<td valign="top" class="category name">';
1721 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot.'/course/category.php?id='.$category->id.'">'. format_string($category->name).'</a>';
1722 echo '</td>';
1723 echo '<td valign="top" class="category number">';
1724 if ($category->coursecount) {
1725 echo $category->coursecount;
1727 echo '</td></tr>';
1729 echo '</table>';
1733 function print_courses($category, $hidesitecourse = false) {
1734 /// Category is 0 (for all courses) or an object
1736 global $CFG;
1738 if (empty($category)) {
1739 $categories = get_categories(0); // Parent = 0 ie top-level categories only
1740 if ($categories != null and count($categories) == 1) {
1741 $category = array_shift($categories);
1742 $courses = get_courses($category->id, 'c.sortorder ASC', 'c.id,c.category,c.sortorder,c.visible,c.fullname,c.shortname,c.password,c.summary,c.teacher,c.cost,c.currency,c.enrol,c.guest');
1743 } else {
1744 $courses = get_courses('all', 'c.sortorder ASC', 'c.id,c.category,c.sortorder,c.visible,c.fullname,c.shortname,c.password,c.summary,c.teacher,c.cost,c.currency,c.enrol,c.guest');
1746 unset($categories);
1747 } else {
1748 $categories = get_categories($category->id); // sub categories
1749 $courses = get_courses($category->id, 'c.sortorder ASC', 'c.id,c.category,c.sortorder,c.visible,c.fullname,c.shortname,c.password,c.summary,c.teacher,c.cost,c.currency,c.enrol,c.guest');
1752 if ($courses) {
1753 foreach ($courses as $course) {
1754 if ($hidesitecourse and ($course->id == SITEID)) {
1755 continue;
1757 print_course($course);
1759 } else {
1760 print_heading(get_string("nocoursesyet"));
1761 $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
1762 if (has_capability('moodle/course:create', $context)) {
1763 $options = array();
1764 $options['category'] = $category->id;
1765 echo '<div class="addcoursebutton">';
1766 print_single_button($CFG->wwwroot.'/course/edit.php', $options, get_string("addnewcourse"));
1767 echo '</div>';
1776 function print_course($course) {
1778 global $CFG, $USER;
1780 $context = get_context_instance(CONTEXT_COURSE, $course->id);
1782 $linkcss = $course->visible ? '' : ' class="dimmed" ';
1784 echo '<div class="coursebox">';
1785 echo '<div class="info">';
1786 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
1787 $linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.
1788 format_string($course->fullname).'</a></div>';
1790 /// first find all roles that are supposed to be displayed
1791 if ($managerroles = get_config('', 'coursemanager')) {
1792 $coursemanagerroles = split(',', $managerroles);
1793 $roles = get_records_select( 'role', '', 'sortorder' );
1794 foreach ($roles as $role) {
1795 if (in_array( $role->id, $coursemanagerroles )) {
1796 if ($users = get_role_users($role->id, $context, true, '', 'u.lastname ASC', true)) {
1797 foreach ($users as $teacher) {
1798 $fullname = fullname($teacher, has_capability('moodle/site:viewfullnames', $context));
1799 $namesarray[] = role_get_name($role, $context).': <a href="'.$CFG->wwwroot.'/user/view.php?id='.
1800 $teacher->id.'&amp;course='.SITEID.'">'.$fullname.'</a>';
1806 if (!empty($namesarray)) {
1807 echo "<ul class=\"teachers\">\n<li>";
1808 echo implode('</li><li>', $namesarray);
1809 echo "</li></ul>";
1813 require_once("$CFG->dirroot/enrol/enrol.class.php");
1814 $enrol = enrolment_factory::factory($course->enrol);
1815 echo $enrol->get_access_icons($course);
1817 echo '</div><div class="summary">';
1818 $options = NULL;
1819 $options->noclean = true;
1820 $options->para = false;
1821 echo format_text($course->summary, FORMAT_MOODLE, $options, $course->id);
1822 echo '</div>';
1823 echo '</div>';
1824 echo '<div class="clearer"></div>';
1828 function print_my_moodle() {
1829 /// Prints custom user information on the home page.
1830 /// Over time this can include all sorts of information
1832 global $USER, $CFG;
1834 if (empty($USER->id)) {
1835 error("It shouldn't be possible to see My Moodle without being logged in.");
1838 $courses = get_my_courses($USER->id);
1839 $rhosts = array();
1840 $rcourses = array();
1841 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
1842 $rcourses = get_my_remotecourses($USER->id);
1843 $rhosts = get_my_remotehosts();
1846 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
1848 if (!empty($courses)) {
1849 foreach ($courses as $course) {
1850 if ($course->id == SITEID) {
1851 continue;
1853 print_course($course, "100%");
1857 // MNET
1858 if (!empty($rcourses)) {
1859 // at the IDP, we know of all the remote courses
1860 foreach ($rcourses as $course) {
1861 print_remote_course($course, "100%");
1863 } elseif (!empty($rhosts)) {
1864 // non-IDP, we know of all the remote servers, but not courses
1865 foreach ($rhosts as $host) {
1866 print_remote_host($host, "100%");
1869 unset($course);
1870 unset($host);
1872 if (count_records("course") > (count($courses) + 1) ) { // Some courses not being displayed
1873 echo "<table width=\"100%\"><tr><td align=\"center\">";
1874 print_course_search("", false, "short");
1875 echo "</td><td align=\"center\">";
1876 print_single_button("$CFG->wwwroot/course/index.php", NULL, get_string("fulllistofcourses"), "get");
1877 echo "</td></tr></table>\n";
1880 } else {
1881 if (count_records("course_categories") > 1) {
1882 print_simple_box_start("center", "100%", "#FFFFFF", 5, "categorybox");
1883 print_whole_category_list();
1884 print_simple_box_end();
1885 } else {
1886 print_courses(0);
1892 function print_course_search($value="", $return=false, $format="plain") {
1894 global $CFG;
1895 static $count = 0;
1897 $count++;
1899 $id = 'coursesearch';
1901 if ($count > 1) {
1902 $id .= $count;
1905 $strsearchcourses= get_string("searchcourses");
1907 if ($format == 'plain') {
1908 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
1909 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
1910 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
1911 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
1912 $output .= '<input type="submit" value="'.get_string('go').'" />';
1913 $output .= '</fieldset></form>';
1914 } else if ($format == 'short') {
1915 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
1916 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
1917 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
1918 $output .= '<input type="text" id="coursesearchbox" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
1919 $output .= '<input type="submit" value="'.get_string('go').'" />';
1920 $output .= '</fieldset></form>';
1921 } else if ($format == 'navbar') {
1922 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
1923 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
1924 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
1925 $output .= '<input type="text" id="coursesearchbox" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
1926 $output .= '<input type="submit" value="'.get_string('go').'" />';
1927 $output .= '</fieldset></form>';
1930 if ($return) {
1931 return $output;
1933 echo $output;
1936 function print_remote_course($course, $width="100%") {
1938 global $CFG, $USER;
1940 $linkcss = '';
1942 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&amp;wantsurl=/course/view.php?id={$course->remoteid}";
1944 echo '<div class="coursebox remotecoursebox">';
1945 echo '<div class="info">';
1946 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
1947 $linkcss.' href="'.$url.'">'
1948 . format_string($course->fullname) .'</a><br />'
1949 . format_string($course->hostname) . ' : '
1950 . format_string($course->cat_name) . ' : '
1951 . format_string($course->shortname). '</div>';
1952 echo '</div><div class="summary">';
1953 $options = NULL;
1954 $options->noclean = true;
1955 $options->para = false;
1956 echo format_text($course->summary, FORMAT_MOODLE, $options);
1957 echo '</div>';
1958 echo '</div>';
1959 echo '<div class="clearer"></div>';
1962 function print_remote_host($host, $width="100%") {
1964 global $CFG, $USER;
1966 $linkcss = '';
1968 echo '<div class="coursebox">';
1969 echo '<div class="info">';
1970 echo '<div class="name">';
1971 echo '<img src="'.$CFG->pixpath.'/i/mnethost.gif" class="icon" alt="'.get_string('course').'" />';
1972 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
1973 . s($host['name']).'</a> - ';
1974 echo $host['count'] . ' ' . get_string('courses');
1975 echo '</div>';
1976 echo '</div>';
1977 echo '</div>';
1978 echo '<div class="clearer"></div>';
1982 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
1984 function add_course_module($mod) {
1986 $mod->added = time();
1987 unset($mod->id);
1989 return insert_record("course_modules", $mod);
1992 function add_mod_to_section($mod, $beforemod=NULL) {
1993 /// Given a full mod object with section and course already defined
1994 /// If $before is specified, then this is an existing ID which we
1995 /// will insert the new module before
1997 /// Returns the course_sections ID where the mod is inserted
1999 if ($section = get_record("course_sections", "course", "$mod->course", "section", "$mod->section")) {
2001 $section->sequence = trim($section->sequence);
2003 if (empty($section->sequence)) {
2004 $newsequence = "$mod->coursemodule";
2006 } else if ($beforemod) {
2007 $modarray = explode(",", $section->sequence);
2009 if ($key = array_keys ($modarray, $beforemod->id)) {
2010 $insertarray = array($mod->id, $beforemod->id);
2011 array_splice($modarray, $key[0], 1, $insertarray);
2012 $newsequence = implode(",", $modarray);
2014 } else { // Just tack it on the end anyway
2015 $newsequence = "$section->sequence,$mod->coursemodule";
2018 } else {
2019 $newsequence = "$section->sequence,$mod->coursemodule";
2022 if (set_field("course_sections", "sequence", $newsequence, "id", $section->id)) {
2023 return $section->id; // Return course_sections ID that was used.
2024 } else {
2025 return 0;
2028 } else { // Insert a new record
2029 $section->course = $mod->course;
2030 $section->section = $mod->section;
2031 $section->summary = "";
2032 $section->sequence = $mod->coursemodule;
2033 return insert_record("course_sections", $section);
2037 function set_coursemodule_groupmode($id, $groupmode) {
2038 return set_field("course_modules", "groupmode", $groupmode, "id", $id);
2041 function set_coursemodule_idnumber($id, $idnumber) {
2042 return set_field("course_modules", "idnumber", $idnumber, "id", $id);
2045 * $prevstateoverrides = true will set the visibility of the course module
2046 * to what is defined in visibleold. This enables us to remember the current
2047 * visibility when making a whole section hidden, so that when we toggle
2048 * that section back to visible, we are able to return the visibility of
2049 * the course module back to what it was originally.
2051 function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
2052 if (!$cm = get_record('course_modules', 'id', $id)) {
2053 return false;
2055 if (!$modulename = get_field('modules', 'name', 'id', $cm->module)) {
2056 return false;
2058 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
2059 foreach($events as $event) {
2060 if ($visible) {
2061 show_event($event);
2062 } else {
2063 hide_event($event);
2067 if ($prevstateoverrides) {
2068 if ($visible == '0') {
2069 // Remember the current visible state so we can toggle this back.
2070 set_field('course_modules', 'visibleold', $cm->visible, 'id', $id);
2071 } else {
2072 // Get the previous saved visible states.
2073 return set_field('course_modules', 'visible', $cm->visibleold, 'id', $id);
2076 return set_field("course_modules", "visible", $visible, "id", $id);
2080 * Delete a course module and any associated data at the course level (events)
2081 * Until 1.5 this function simply marked a deleted flag ... now it
2082 * deletes it completely.
2085 function delete_course_module($id) {
2086 global $CFG;
2087 require_once($CFG->libdir.'/gradelib.php');
2089 if (!$cm = get_record('course_modules', 'id', $id)) {
2090 return true;
2092 $modulename = get_field('modules', 'name', 'id', $cm->module);
2093 //delete events from calendar
2094 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
2095 foreach($events as $event) {
2096 delete_event($event->id);
2099 //delete grade items, outcome items and grades attached to modules
2100 if ($grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2101 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course))) {
2102 foreach ($grade_items as $grade_item) {
2103 $grade_item->delete('moddelete');
2107 return delete_records('course_modules', 'id', $cm->id);
2110 function delete_mod_from_section($mod, $section) {
2112 if ($section = get_record("course_sections", "id", "$section") ) {
2114 $modarray = explode(",", $section->sequence);
2116 if ($key = array_keys ($modarray, $mod)) {
2117 array_splice($modarray, $key[0], 1);
2118 $newsequence = implode(",", $modarray);
2119 return set_field("course_sections", "sequence", $newsequence, "id", $section->id);
2120 } else {
2121 return false;
2125 return false;
2128 function move_section($course, $section, $move) {
2129 /// Moves a whole course section up and down within the course
2130 global $USER;
2132 if (!$move) {
2133 return true;
2136 $sectiondest = $section + $move;
2138 if ($sectiondest > $course->numsections or $sectiondest < 1) {
2139 return false;
2142 if (!$sectionrecord = get_record("course_sections", "course", $course->id, "section", $section)) {
2143 return false;
2146 if (!$sectiondestrecord = get_record("course_sections", "course", $course->id, "section", $sectiondest)) {
2147 return false;
2150 if (!set_field("course_sections", "section", $sectiondest, "id", $sectionrecord->id)) {
2151 return false;
2153 if (!set_field("course_sections", "section", $section, "id", $sectiondestrecord->id)) {
2154 return false;
2156 // if the focus is on the section that is being moved, then move the focus along
2157 if (isset($USER->display[$course->id]) and ($USER->display[$course->id] == $section)) {
2158 course_set_display($course->id, $sectiondest);
2161 // Check for duplicates and fix order if needed.
2162 // There is a very rare case that some sections in the same course have the same section id.
2163 $sections = get_records_select('course_sections', "course = $course->id", 'section ASC');
2164 $n = 0;
2165 foreach ($sections as $section) {
2166 if ($section->section != $n) {
2167 if (!set_field('course_sections', 'section', $n, 'id', $section->id)) {
2168 return false;
2171 $n++;
2173 return true;
2177 function moveto_module($mod, $section, $beforemod=NULL) {
2178 /// All parameters are objects
2179 /// Move the module object $mod to the specified $section
2180 /// If $beforemod exists then that is the module
2181 /// before which $modid should be inserted
2183 /// Remove original module from original section
2185 if (! delete_mod_from_section($mod->id, $mod->section)) {
2186 notify("Could not delete module from existing section");
2189 /// Update module itself if necessary
2191 if ($mod->section != $section->id) {
2192 $mod->section = $section->id;
2193 if (!update_record("course_modules", $mod)) {
2194 return false;
2196 // if moving to a hidden section then hide module
2197 if (!$section->visible) {
2198 set_coursemodule_visible($mod->id, 0);
2202 /// Add the module into the new section
2204 $mod->course = $section->course;
2205 $mod->section = $section->section; // need relative reference
2206 $mod->coursemodule = $mod->id;
2208 if (! add_mod_to_section($mod, $beforemod)) {
2209 return false;
2212 return true;
2216 function make_editing_buttons($mod, $absolute=false, $moveselect=true, $indent=-1, $section=-1) {
2217 global $CFG, $USER;
2219 static $str;
2220 static $sesskey;
2222 $modcontext = get_context_instance(CONTEXT_MODULE, $mod->id);
2223 // no permission to edit
2224 if (!has_capability('moodle/course:manageactivities', $modcontext)) {
2225 return false;
2228 if (!isset($str)) {
2229 $str->delete = get_string("delete");
2230 $str->move = get_string("move");
2231 $str->moveup = get_string("moveup");
2232 $str->movedown = get_string("movedown");
2233 $str->moveright = get_string("moveright");
2234 $str->moveleft = get_string("moveleft");
2235 $str->update = get_string("update");
2236 $str->duplicate = get_string("duplicate");
2237 $str->hide = get_string("hide");
2238 $str->show = get_string("show");
2239 $str->clicktochange = get_string("clicktochange");
2240 $str->forcedmode = get_string("forcedmode");
2241 $str->groupsnone = get_string("groupsnone");
2242 $str->groupsseparate = get_string("groupsseparate");
2243 $str->groupsvisible = get_string("groupsvisible");
2244 $sesskey = sesskey();
2247 if ($section >= 0) {
2248 $section = '&amp;sr='.$section; // Section return
2249 } else {
2250 $section = '';
2253 if ($absolute) {
2254 $path = $CFG->wwwroot.'/course';
2255 } else {
2256 $path = '.';
2259 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
2260 if ($mod->visible) {
2261 $hideshow = '<a class="editing_hide" title="'.$str->hide.'" href="'.$path.'/mod.php?hide='.$mod->id.
2262 '&amp;sesskey='.$sesskey.$section.'"><img'.
2263 ' src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" '.
2264 ' alt="'.$str->hide.'" /></a>'."\n";
2265 } else {
2266 $hideshow = '<a class="editing_show" title="'.$str->show.'" href="'.$path.'/mod.php?show='.$mod->id.
2267 '&amp;sesskey='.$sesskey.$section.'"><img'.
2268 ' src="'.$CFG->pixpath.'/t/show.gif" class="iconsmall" '.
2269 ' alt="'.$str->show.'" /></a>'."\n";
2272 if ($mod->groupmode !== false) {
2273 if ($mod->groupmode == SEPARATEGROUPS) {
2274 $grouptitle = $str->groupsseparate;
2275 $groupclass = 'editing_groupsseparate';
2276 $groupimage = $CFG->pixpath.'/t/groups.gif';
2277 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=0&amp;sesskey='.$sesskey;
2278 } else if ($mod->groupmode == VISIBLEGROUPS) {
2279 $grouptitle = $str->groupsvisible;
2280 $groupclass = 'editing_groupsvisible';
2281 $groupimage = $CFG->pixpath.'/t/groupv.gif';
2282 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=1&amp;sesskey='.$sesskey;
2283 } else {
2284 $grouptitle = $str->groupsnone;
2285 $groupclass = 'editing_groupsnone';
2286 $groupimage = $CFG->pixpath.'/t/groupn.gif';
2287 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=2&amp;sesskey='.$sesskey;
2289 if ($mod->groupmodelink) {
2290 $groupmode = '<a class="'.$groupclass.'" title="'.$grouptitle.' ('.$str->clicktochange.')" href="'.$grouplink.'">'.
2291 '<img src="'.$groupimage.'" class="iconsmall" '.
2292 'alt="'.$grouptitle.'" /></a>';
2293 } else {
2294 $groupmode = '<img title="'.$grouptitle.' ('.$str->forcedmode.')" '.
2295 ' src="'.$groupimage.'" class="iconsmall" '.
2296 'alt="'.$grouptitle.'" />';
2298 } else {
2299 $groupmode = "";
2302 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $mod->course))) {
2303 if ($moveselect) {
2304 $move = '<a class="editing_move" title="'.$str->move.'" href="'.$path.'/mod.php?copy='.$mod->id.
2305 '&amp;sesskey='.$sesskey.$section.'"><img'.
2306 ' src="'.$CFG->pixpath.'/t/move.gif" class="iconsmall" '.
2307 ' alt="'.$str->move.'" /></a>'."\n";
2308 } else {
2309 $move = '<a class="editing_moveup" title="'.$str->moveup.'" href="'.$path.'/mod.php?id='.$mod->id.
2310 '&amp;move=-1&amp;sesskey='.$sesskey.$section.'"><img'.
2311 ' src="'.$CFG->pixpath.'/t/up.gif" class="iconsmall" '.
2312 ' alt="'.$str->moveup.'" /></a>'."\n".
2313 '<a class="editing_movedown" title="'.$str->movedown.'" href="'.$path.'/mod.php?id='.$mod->id.
2314 '&amp;move=1&amp;sesskey='.$sesskey.$section.'"><img'.
2315 ' src="'.$CFG->pixpath.'/t/down.gif" class="iconsmall" '.
2316 ' alt="'.$str->movedown.'" /></a>'."\n";
2318 } else {
2319 $move = '';
2322 $leftright = '';
2323 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $mod->course))) {
2325 if (right_to_left()) { // Exchange arrows on RTL
2326 $rightarrow = 'left.gif';
2327 $leftarrow = 'right.gif';
2328 } else {
2329 $rightarrow = 'right.gif';
2330 $leftarrow = 'left.gif';
2333 if ($indent > 0) {
2334 $leftright .= '<a class="editing_moveleft" title="'.$str->moveleft.'" href="'.$path.'/mod.php?id='.$mod->id.
2335 '&amp;indent=-1&amp;sesskey='.$sesskey.$section.'"><img'.
2336 ' src="'.$CFG->pixpath.'/t/'.$leftarrow.'" class="iconsmall" '.
2337 ' alt="'.$str->moveleft.'" /></a>'."\n";
2339 if ($indent >= 0) {
2340 $leftright .= '<a class="editing_moveright" title="'.$str->moveright.'" href="'.$path.'/mod.php?id='.$mod->id.
2341 '&amp;indent=1&amp;sesskey='.$sesskey.$section.'"><img'.
2342 ' src="'.$CFG->pixpath.'/t/'.$rightarrow.'" class="iconsmall" '.
2343 ' alt="'.$str->moveright.'" /></a>'."\n";
2347 return '<span class="commands">'."\n".$leftright.$move.
2348 '<a class="editing_update" title="'.$str->update.'" href="'.$path.'/mod.php?update='.$mod->id.
2349 '&amp;sesskey='.$sesskey.$section.'"><img'.
2350 ' src="'.$CFG->pixpath.'/t/edit.gif" class="iconsmall" '.
2351 ' alt="'.$str->update.'" /></a>'."\n".
2352 '<a class="editing_delete" title="'.$str->delete.'" href="'.$path.'/mod.php?delete='.$mod->id.
2353 '&amp;sesskey='.$sesskey.$section.'"><img'.
2354 ' src="'.$CFG->pixpath.'/t/delete.gif" class="iconsmall" '.
2355 ' alt="'.$str->delete.'" /></a>'."\n".$hideshow.$groupmode."\n".'</span>';
2359 * given a course object with shortname & fullname, this function will
2360 * truncate the the number of chars allowed and add ... if it was too long
2362 function course_format_name ($course,$max=100) {
2364 $str = $course->shortname.': '. $course->fullname;
2365 if (strlen($str) <= $max) {
2366 return $str;
2368 else {
2369 return substr($str,0,$max-3).'...';
2374 * This function will return true if the given course is a child course at all
2376 function course_in_meta ($course) {
2377 return record_exists("course_meta","child_course",$course->id);
2382 * Print standard form elements on module setup forms in mod/.../mod.html
2384 function print_standard_coursemodule_settings($form) {
2385 if (! $course = get_record('course', 'id', $form->course)) {
2386 error("This course doesn't exist");
2388 print_groupmode_setting($form, $course);
2389 print_visible_setting($form, $course);
2393 * Print groupmode form element on module setup forms in mod/.../mod.html
2395 function print_groupmode_setting($form, $course=NULL) {
2397 if (empty($course)) {
2398 if (! $course = get_record('course', 'id', $form->course)) {
2399 error("This course doesn't exist");
2402 if ($form->coursemodule) {
2403 if (! $cm = get_record('course_modules', 'id', $form->coursemodule)) {
2404 error("This course module doesn't exist");
2406 } else {
2407 $cm = null;
2409 $groupmode = groupmode($course, $cm);
2410 if ($course->groupmode or (!$course->groupmodeforce)) {
2411 echo '<tr valign="top">';
2412 echo '<td align="right"><b>'.get_string('groupmode').':</b></td>';
2413 echo '<td align="left">';
2414 unset($choices);
2415 $choices[NOGROUPS] = get_string('groupsnone');
2416 $choices[SEPARATEGROUPS] = get_string('groupsseparate');
2417 $choices[VISIBLEGROUPS] = get_string('groupsvisible');
2418 choose_from_menu($choices, 'groupmode', $groupmode, '', '', 0, false, $course->groupmodeforce);
2419 helpbutton('groupmode', get_string('groupmode'));
2420 echo '</td></tr>';
2425 * Print visibility setting form element on module setup forms in mod/.../mod.html
2427 function print_visible_setting($form, $course=NULL) {
2428 if (empty($course)) {
2429 if (! $course = get_record('course', 'id', $form->course)) {
2430 error("This course doesn't exist");
2433 if ($form->coursemodule) {
2434 $visible = get_field('course_modules', 'visible', 'id', $form->coursemodule);
2435 } else {
2436 $visible = true;
2439 if ($form->mode == 'add') { // in this case $form->section is the section number, not the id
2440 $hiddensection = !get_field('course_sections', 'visible', 'section', $form->section, 'course', $form->course);
2441 } else {
2442 $hiddensection = !get_field('course_sections', 'visible', 'id', $form->section);
2444 if ($hiddensection) {
2445 $visible = false;
2448 echo '<tr valign="top">';
2449 echo '<td align="right"><b>'.get_string('visible', '').':</b></td>';
2450 echo '<td align="left">';
2451 unset($choices);
2452 $choices[1] = get_string('show');
2453 $choices[0] = get_string('hide');
2454 choose_from_menu($choices, 'visible', $visible, '', '', 0, false, $hiddensection);
2455 echo '</td></tr>';
2458 function update_restricted_mods($course,$mods) {
2459 delete_records("course_allowed_modules","course",$course->id);
2460 if (empty($course->restrictmodules)) {
2461 return;
2463 else {
2464 foreach ($mods as $mod) {
2465 if ($mod == 0)
2466 continue; // this is the 'allow none' option
2467 $am->course = $course->id;
2468 $am->module = $mod;
2469 insert_record("course_allowed_modules",$am);
2475 * This function will take an int (module id) or a string (module name)
2476 * and return true or false, whether it's allowed in the given course (object)
2477 * $mod is not allowed to be an object, as the field for the module id is inconsistent
2478 * depending on where in the code it's called from (sometimes $mod->id, sometimes $mod->module)
2481 function course_allowed_module($course,$mod) {
2482 if (empty($course->restrictmodules)) {
2483 return true;
2486 // i am not sure this capability is correct
2487 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
2488 return true;
2490 if (is_numeric($mod)) {
2491 $modid = $mod;
2492 } else if (is_string($mod)) {
2493 if ($mod = get_field("modules","id","name",$mod))
2494 $modid = $mod;
2496 if (empty($modid)) {
2497 return false;
2499 return (record_exists("course_allowed_modules","course",$course->id,"module",$modid));
2502 /***
2503 *** Efficiently moves many courses around while maintaining
2504 *** sortorder in order.
2506 *** $courseids is an array of course ids
2510 function move_courses ($courseids, $categoryid) {
2512 global $CFG;
2514 if (!empty($courseids)) {
2516 $courseids = array_reverse($courseids);
2518 foreach ($courseids as $courseid) {
2520 if (! $course = get_record("course", "id", $courseid)) {
2521 notify("Error finding course $courseid");
2522 } else {
2523 // figure out a sortorder that we can use in the destination category
2524 $sortorder = get_field_sql('SELECT MIN(sortorder)-1 AS min
2525 FROM ' . $CFG->prefix . 'course WHERE category=' . $categoryid);
2526 if ($sortorder === false) {
2527 // the category is empty
2528 // rather than let the db default to 0
2529 // set it to > 100 and avoid extra work in fix_coursesortorder()
2530 $sortorder = 200;
2531 } else if ($sortorder < 10) {
2532 fix_course_sortorder($categoryid);
2535 $course->category = $categoryid;
2536 $course->sortorder = $sortorder;
2537 $course->fullname = addslashes($course->fullname);
2538 $course->shortname = addslashes($course->shortname);
2539 $course->summary = addslashes($course->summary);
2540 $course->password = addslashes($course->password);
2541 $course->teacher = addslashes($course->teacher);
2542 $course->teachers = addslashes($course->teachers);
2543 $course->student = addslashes($course->student);
2544 $course->students = addslashes($course->students);
2546 if (!update_record('course', $course)) {
2547 notify("An error occurred - course not moved!");
2549 // parents changed (course category)
2550 // rebuild this context and all children
2551 rebuild_context_rel(get_context_instance(CONTEXT_COURSE, $course->id));
2554 fix_course_sortorder();
2556 return true;
2560 * @param string $format Course format ID e.g. 'weeks'
2561 * @return Name that the course format prefers for sections
2563 function get_section_name($format) {
2564 $sectionname = get_string("name$format","format_$format");
2565 if($sectionname == "[[name$format]]") {
2566 $sectionname = get_string("name$format");
2568 return $sectionname;
2572 * Can the current user delete this course?
2573 * @param int $courseid
2574 * @return boolean
2576 * Exception here to fix MDL-7796.
2578 * FIXME
2579 * Course creators who can manage activities in the course
2580 * shoule be allowed to delete the course. We do it this
2581 * way because we need a quick fix to bring the functionality
2582 * in line with what we had pre-roles. We can't give the
2583 * default course creator role moodle/course:delete at
2584 * CONTEXT_SYSTEM level because this will allow them to
2585 * delete any course in the site. So we hard code this here
2586 * for now.
2588 * @author vyshane AT gmail.com
2590 function can_delete_course($courseid) {
2592 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2594 return ( has_capability('moodle/course:delete', $context)
2595 || (has_capability('moodle/legacy:coursecreator', $context)
2596 && has_capability('moodle/course:manageactivities', $context)) );
2601 * Create a course and either return a $course object or false
2603 * @param object $data - all the data needed for an entry in the 'course' table
2605 function create_course($data) {
2606 global $CFG, $USER;
2608 // preprocess allowed mods
2609 $allowedmods = empty($data->allowedmods) ? array() : $data->allowedmods;
2610 unset($data->allowedmods);
2611 if (!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
2612 if ($CFG->restrictmodulesfor == 'all') {
2613 $data->restrictmodules = 1;
2614 } else {
2615 $data->restrictmodules = 0;
2619 $data->timecreated = time();
2621 // place at beginning of category
2622 fix_course_sortorder();
2623 $data->sortorder = get_field_sql("SELECT min(sortorder)-1 FROM {$CFG->prefix}course WHERE category=$data->category");
2624 if (empty($data->sortorder)) {
2625 $data->sortorder = 100;
2628 if ($newcourseid = insert_record('course', $data)) { // Set up new course
2630 $course = get_record('course', 'id', $newcourseid);
2632 // Setup the blocks
2633 $page = page_create_object(PAGE_COURSE_VIEW, $course->id);
2634 blocks_repopulate_page($page); // Return value not checked because you can always edit later
2636 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
2637 update_restricted_mods($course, $allowedmods);
2640 $section = new object();
2641 $section->course = $course->id; // Create a default section.
2642 $section->section = 0;
2643 $section->id = insert_record('course_sections', $section);
2645 fix_course_sortorder();
2647 add_to_log(SITEID, 'course', 'new', 'view.php?id='.$course->id, $data->fullname.' (ID '.$course->id.')');
2649 return $course;
2652 return false; // error
2657 * Update a course and return true or false
2659 * @param object $data - all the data needed for an entry in the 'course' table
2661 function update_course($data) {
2662 global $USER, $CFG;
2664 // preprocess allowed mods
2665 $allowedmods = empty($data->allowedmods) ? array() : $data->allowedmods;
2666 unset($data->allowedmods);
2667 if (!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
2668 unset($data->restrictmodules);
2671 $oldcourse = get_record('course', 'id', $data->id); // should not fail, already tested above
2672 if (!has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $oldcourse->category))
2673 or !has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $data->category))) {
2674 // can not move to new category, keep the old one
2675 unset($data->category);
2678 // Update with the new data
2679 if (update_record('course', $data)) {
2681 $course = get_record('course', 'id', $data->id);
2683 add_to_log($course->id, "course", "update", "edit.php?id=$course->id", $course->id);
2685 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
2686 update_restricted_mods($course, $allowedmods);
2689 fix_course_sortorder();
2691 // Test for and remove blocks which aren't appropriate anymore
2692 $page = page_create_object(PAGE_COURSE_VIEW, $course->id);
2693 blocks_remove_inappropriate($page);
2695 // put custom role names into db
2696 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2698 foreach ($data as $dname => $dvalue) {
2700 // is this the right param?
2701 $dvalue = clean_param($dvalue, PARAM_NOTAGS);
2703 if (!strstr($dname, 'role_')) {
2704 continue;
2707 $dt = explode('_', $dname);
2708 $roleid = $dt[1];
2709 // make up our mind whether we want to delete, update or insert
2711 if (empty($dvalue)) {
2713 delete_records('role_names', 'contextid', $context->id, 'roleid', $roleid);
2715 } else if ($t = get_record('role_names', 'contextid', $context->id, 'roleid', $roleid)) {
2717 $t->text = $dvalue;
2718 update_record('role_names', $t);
2720 } else {
2722 $t->contextid = $context->id;
2723 $t->roleid = $roleid;
2724 $t->text = $dvalue;
2725 insert_record('role_names', $t);
2730 return true;
2734 return false;