MDL-10902:
[moodle-linuxchix.git] / course / lib.php
blobc8e5989b833ee599109f6ffd64a2bec680903b29
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 = groups_get_all_groups($course->id)) {
181 $group_names = array();
182 foreach($groups as $group) {
183 $group_names[$group->id] = format_string($group->name);
185 echo '<td><b>';
186 if ($groupmode == VISIBLEGROUPS) {
187 print_string('groupsvisible');
188 } else {
189 print_string('groupsseparate');
191 echo ':</b></td><td>';
192 choose_from_menu($group_names, "selectedgroup", $selectedgroup, get_string("allgroups"), "", "");
193 echo '</td>';
198 echo '<td colspan="2" align="right">';
199 echo '<input type="submit" value="'.get_string('showrecent').'" />';
200 echo "</td></tr>";
202 echo "</table>";
204 $advancedlink = "<a href=\"$CFG->wwwroot/course/recent.php?id=$course->id&amp;advancedfilter=0\">" . get_string("normalfilter") . "</a>";
205 print_heading($advancedlink);
206 echo "</center>";
207 echo "</form>";
209 } else {
211 $day_list = array("1","7","14","21","30");
212 $strsince = get_string("since");
213 $strlastlogin = get_string("lastlogin");
214 $strday = get_string("day");
215 $strdays = get_string("days");
217 $heading = "";
218 foreach ($day_list as $count) {
219 if ($count == "1") {
220 $day = $strday;
221 } else {
222 $day = $strdays;
224 $tmpdate = time() - ($count * 3600 * 24);
225 $heading = $heading .
226 "<a href=\"$CFG->wwwroot/course/recent.php?id=$course->id&amp;date=$tmpdate\"> $count $day</a> | ";
229 $heading = $strsince . ": <a href=\"$CFG->wwwroot/course/recent.php?id=$course->id\">$strlastlogin</a>" . " | " . $heading;
230 print_heading($heading);
232 $advancedlink = "<a href=\"$CFG->wwwroot/course/recent.php?id=$course->id&amp;advancedfilter=1\">" . get_string("advancedfilter") . "</a>";
233 print_heading($advancedlink);
240 function make_log_url($module, $url) {
241 switch ($module) {
242 case 'user':
243 case 'course':
244 case 'file':
245 case 'login':
246 case 'lib':
247 case 'admin':
248 case 'message':
249 case 'calendar':
250 case 'mnet course':
251 return "/course/$url";
252 break;
253 case 'blog':
254 return "/$module/$url";
255 break;
256 case 'upload':
257 return $url;
258 break;
259 case 'library':
260 case '':
261 return '/';
262 break;
263 default:
264 return "/mod/$module/$url";
265 break;
270 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
271 $modname="", $modid=0, $modaction="", $groupid=0) {
273 global $CFG;
275 // It is assumed that $date is the GMT time of midnight for that day,
276 // and so the next 86400 seconds worth of logs are printed.
278 /// Setup for group handling.
280 // TODO: I don't understand group/context/etc. enough to be able to do
281 // something interesting with it here
282 // What is the context of a remote course?
284 /// If the group mode is separate, and this user does not have editing privileges,
285 /// then only the user's group can be viewed.
286 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
287 // $groupid = get_current_group($course->id);
289 /// If this course doesn't have groups, no groupid can be specified.
290 //else if (!$course->groupmode) {
291 // $groupid = 0;
293 $groupid = 0;
295 $joins = array();
297 $qry = "
298 SELECT
299 l.*,
300 u.firstname,
301 u.lastname,
302 u.picture
303 FROM
304 {$CFG->prefix}mnet_log l
305 LEFT JOIN
306 {$CFG->prefix}user u
308 l.userid = u.id
309 WHERE
312 $where .= "l.hostid = '$hostid'";
314 // TODO: Is 1 really a magic number referring to the sitename?
315 if ($course != 1 || $modid != 0) {
316 $where .= " AND\n l.course='$course'";
319 if ($modname) {
320 $where .= " AND\n l.module = '$modname'";
323 if ('site_errors' === $modid) {
324 $where .= " AND\n ( l.action='error' OR l.action='infected' )";
325 } else if ($modid) {
326 //TODO: This assumes that modids are the same across sites... probably
327 //not true
328 $where .= " AND\n l.cmid = '$modid'";
331 if ($modaction) {
332 $firstletter = substr($modaction, 0, 1);
333 if (ctype_alpha($firstletter)) {
334 $where .= " AND\n lower(l.action) LIKE '%" . strtolower($modaction) . "%'";
335 } else if ($firstletter == '-') {
336 $where .= " AND\n lower(l.action) NOT LIKE '%" . strtolower(substr($modaction, 1)) . "%'";
340 if ($user) {
341 $where .= " AND\n l.userid = '$user'";
344 if ($date) {
345 $enddate = $date + 86400;
346 $where .= " AND\n l.time > '$date' AND l.time < '$enddate'";
349 $result = array();
350 $result['totalcount'] = count_records_sql("SELECT COUNT(*) FROM {$CFG->prefix}mnet_log l WHERE $where");
351 if(!empty($result['totalcount'])) {
352 $where .= "\n ORDER BY\n $order";
353 $result['logs'] = get_records_sql($qry.$where, $limitfrom, $limitnum);
354 } else {
355 $result['logs'] = array();
357 return $result;
360 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
361 $modname="", $modid=0, $modaction="", $groupid=0) {
363 // It is assumed that $date is the GMT time of midnight for that day,
364 // and so the next 86400 seconds worth of logs are printed.
366 /// Setup for group handling.
368 /// If the group mode is separate, and this user does not have editing privileges,
369 /// then only the user's group can be viewed.
370 if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
371 $groupid = get_current_group($course->id);
373 /// If this course doesn't have groups, no groupid can be specified.
374 else if (!$course->groupmode) {
375 $groupid = 0;
378 $joins = array();
380 if ($course->id != SITEID || $modid != 0) {
381 $joins[] = "l.course='$course->id'";
384 if ($modname) {
385 $joins[] = "l.module = '$modname'";
388 if ('site_errors' === $modid) {
389 $joins[] = "( l.action='error' OR l.action='infected' )";
390 } else if ($modid) {
391 $joins[] = "l.cmid = '$modid'";
394 if ($modaction) {
395 $firstletter = substr($modaction, 0, 1);
396 if (ctype_alpha($firstletter)) {
397 $joins[] = "lower(l.action) LIKE '%" . strtolower($modaction) . "%'";
398 } else if ($firstletter == '-') {
399 $joins[] = "lower(l.action) NOT LIKE '%" . strtolower(substr($modaction, 1)) . "%'";
403 /// Getting all members of a group.
404 if ($groupid and !$user) {
405 if ($gusers = groups_get_members($groupid)) {
406 $gusers = array_keys($gusers);
407 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
408 } else {
409 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always by false.
412 else if ($user) {
413 $joins[] = "l.userid = '$user'";
416 if ($date) {
417 $enddate = $date + 86400;
418 $joins[] = "l.time > '$date' AND l.time < '$enddate'";
421 $selector = implode(' AND ', $joins);
423 $totalcount = 0; // Initialise
424 $result = array();
425 $result['logs'] = get_logs($selector, $order, $limitfrom, $limitnum, $totalcount);
426 $result['totalcount'] = $totalcount;
427 return $result;
431 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
432 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
434 global $CFG;
436 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
437 $modname, $modid, $modaction, $groupid)) {
438 notify("No logs found!");
439 print_footer($course);
440 exit;
443 $courses = array();
445 if ($course->id == SITEID) {
446 $courses[0] = '';
447 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
448 foreach ($ccc as $cc) {
449 $courses[$cc->id] = $cc->shortname;
452 } else {
453 $courses[$course->id] = $course->shortname;
456 $totalcount = $logs['totalcount'];
457 $count=0;
458 $ldcache = array();
459 $tt = getdate(time());
460 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
462 $strftimedatetime = get_string("strftimedatetime");
464 echo "<div class=\"info\">\n";
465 print_string("displayingrecords", "", $totalcount);
466 echo "</div>\n";
468 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
470 echo '<table class="logtable genearlbox boxaligncenter" summary="">'."\n";
471 // echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\" summary=\"\">\n";
472 echo "<tr>";
473 if ($course->id == SITEID) {
474 echo "<th class=\"c0 header\" scope=\"col\">".get_string('course')."</th>\n";
476 echo "<th class=\"c1 header\" scope=\"col\">".get_string('time')."</th>\n";
477 echo "<th class=\"c2 header\" scope=\"col\">".get_string('ip_address')."</th>\n";
478 echo "<th class=\"c3 header\" scope=\"col\">".get_string('fullname')."</th>\n";
479 echo "<th class=\"c4 header\" scope=\"col\">".get_string('action')."</th>\n";
480 echo "<th class=\"c5 header\" scope=\"col\">".get_string('info')."</th>\n";
481 echo "</tr>\n";
483 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
484 if (empty($logs['logs'])) {
485 $logs['logs'] = array();
488 $row = 1;
489 foreach ($logs['logs'] as $log) {
491 $row = ($row + 1) % 2;
493 if (isset($ldcache[$log->module][$log->action])) {
494 $ld = $ldcache[$log->module][$log->action];
495 } else {
496 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
497 $ldcache[$log->module][$log->action] = $ld;
499 if ($ld && is_numeric($log->info)) {
500 // ugly hack to make sure fullname is shown correctly
501 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
502 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
503 } else {
504 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
508 //Filter log->info
509 $log->info = format_string($log->info);
511 $log->url = strip_tags(urldecode($log->url)); // Some XSS protection
512 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
513 $log->url = str_replace('&', '&amp;', $log->url); /// XHTML compatibility
515 echo '<tr class="r'.$row.'">';
516 if ($course->id == SITEID) {
517 echo "<td class=\"cell c0\">\n";
518 if (empty($log->course)) {
519 echo format_string($log->info)."\n";
520 } else {
521 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course])."</a>\n";
523 echo "</td>\n";
525 echo "<td class=\"cell c1\" align=\"right\">".userdate($log->time, '%a').
526 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
527 echo "<td class=\"cell c2\">\n";
528 link_to_popup_window("/iplookup/index.php?ip=$log->ip&amp;user=$log->userid", 'iplookup',$log->ip, 400, 700);
529 echo "</td>\n";
530 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
531 echo "<td class=\"cell c3\">\n";
532 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}&amp;course={$log->course}\">$fullname</a>\n";
533 echo "</td>\n";
534 echo "<td class=\"cell c4\">\n";
535 link_to_popup_window( make_log_url($log->module,$log->url), 'fromloglive',"$log->module $log->action", 400, 600);
536 echo "</td>\n";;
537 echo "<td class=\"cell c5\">{$log->info}</td>\n";
538 echo "</tr>\n";
540 echo "</table>\n";
542 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
546 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
547 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
549 global $CFG;
551 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
552 $modname, $modid, $modaction, $groupid)) {
553 notify("No logs found!");
554 print_footer($course);
555 exit;
558 if ($course->id == SITEID) {
559 $courses[0] = '';
560 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
561 foreach ($ccc as $cc) {
562 $courses[$cc->id] = $cc->shortname;
567 $totalcount = $logs['totalcount'];
568 $count=0;
569 $ldcache = array();
570 $tt = getdate(time());
571 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
573 $strftimedatetime = get_string("strftimedatetime");
575 echo "<div class=\"info\">\n";
576 print_string("displayingrecords", "", $totalcount);
577 echo "</div>\n";
579 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
581 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
582 echo "<tr>";
583 if ($course->id == SITEID) {
584 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
586 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
587 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
588 echo "<th class=\"c3 header\">".get_string('fullname')."</th>\n";
589 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
590 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
591 echo "</tr>\n";
593 if (empty($logs['logs'])) {
594 echo "</table>\n";
595 return;
598 $row = 1;
599 foreach ($logs['logs'] as $log) {
601 $log->info = $log->coursename;
602 $row = ($row + 1) % 2;
604 if (isset($ldcache[$log->module][$log->action])) {
605 $ld = $ldcache[$log->module][$log->action];
606 } else {
607 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
608 $ldcache[$log->module][$log->action] = $ld;
610 if (0 && $ld && !empty($log->info)) {
611 // ugly hack to make sure fullname is shown correctly
612 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
613 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
614 } else {
615 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
619 //Filter log->info
620 $log->info = format_string($log->info);
622 $log->url = strip_tags(urldecode($log->url)); // Some XSS protection
623 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
624 $log->url = str_replace('&', '&amp;', $log->url); /// XHTML compatibility
626 echo '<tr class="r'.$row.'">';
627 if ($course->id == SITEID) {
628 echo "<td class=\"r$row c0\" >\n";
629 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courses[$log->course]."</a>\n";
630 echo "</td>\n";
632 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time, '%a').
633 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
634 echo "<td class=\"r$row c2\" >\n";
635 link_to_popup_window("/iplookup/index.php?ip=$log->ip&amp;user=$log->userid", 'iplookup',$log->ip, 400, 700);
636 echo "</td>\n";
637 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
638 echo "<td class=\"r$row c3\" >\n";
639 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
640 echo "</td>\n";
641 echo "<td class=\"r$row c4\">\n";
642 echo $log->action .': '.$log->module;
643 echo "</td>\n";;
644 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
645 echo "</tr>\n";
647 echo "</table>\n";
649 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
653 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
654 $modid, $modaction, $groupid) {
656 $text = get_string('course')."\t".get_string('time')."\t".get_string('ip_address')."\t".
657 get_string('fullname')."\t".get_string('action')."\t".get_string('info');
659 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
660 $modname, $modid, $modaction, $groupid)) {
661 return false;
664 $courses = array();
666 if ($course->id == SITEID) {
667 $courses[0] = '';
668 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
669 foreach ($ccc as $cc) {
670 $courses[$cc->id] = $cc->shortname;
673 } else {
674 $courses[$course->id] = $course->shortname;
677 $count=0;
678 $ldcache = array();
679 $tt = getdate(time());
680 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
682 $strftimedatetime = get_string("strftimedatetime");
684 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
685 $filename .= '.txt';
686 header("Content-Type: application/download\n");
687 header("Content-Disposition: attachment; filename=$filename");
688 header("Expires: 0");
689 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
690 header("Pragma: public");
692 echo get_string('savedat').userdate(time(), $strftimedatetime)."\n";
693 echo $text;
695 if (empty($logs['logs'])) {
696 return true;
699 foreach ($logs['logs'] as $log) {
700 if (isset($ldcache[$log->module][$log->action])) {
701 $ld = $ldcache[$log->module][$log->action];
702 } else {
703 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
704 $ldcache[$log->module][$log->action] = $ld;
706 if ($ld && !empty($log->info)) {
707 // ugly hack to make sure fullname is shown correctly
708 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
709 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
710 } else {
711 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
715 //Filter log->info
716 $log->info = format_string($log->info);
718 $log->url = strip_tags(urldecode($log->url)); // Some XSS protection
719 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
720 $log->url = str_replace('&', '&amp;', $log->url); // XHTML compatibility
722 $firstField = $courses[$log->course];
723 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
724 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action, $log->info);
725 $text = implode("\t", $row);
726 echo $text." \n";
728 return true;
732 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
733 $modid, $modaction, $groupid) {
735 global $CFG;
737 require_once("$CFG->libdir/excellib.class.php");
739 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
740 $modname, $modid, $modaction, $groupid)) {
741 return false;
744 $courses = array();
746 if ($course->id == SITEID) {
747 $courses[0] = '';
748 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
749 foreach ($ccc as $cc) {
750 $courses[$cc->id] = $cc->shortname;
753 } else {
754 $courses[$course->id] = $course->shortname;
757 $count=0;
758 $ldcache = array();
759 $tt = getdate(time());
760 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
762 $strftimedatetime = get_string("strftimedatetime");
764 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
765 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
766 $filename .= '.xls';
768 $workbook = new MoodleExcelWorkbook('-');
769 $workbook->send($filename);
771 $worksheet = array();
772 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
773 get_string('fullname'), get_string('action'), get_string('info'));
775 // Creating worksheets
776 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
777 $sheettitle = get_string('excel_sheettitle', 'logs', $wsnumber).$nroPages;
778 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
779 $worksheet[$wsnumber]->set_column(1, 1, 30);
780 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
781 userdate(time(), $strftimedatetime));
782 $col = 0;
783 foreach ($headers as $item) {
784 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
785 $col++;
789 if (empty($logs['logs'])) {
790 $workbook->close();
791 return true;
794 $formatDate =& $workbook->add_format();
795 $formatDate->set_num_format(get_string('log_excel_date_format'));
797 $row = FIRSTUSEDEXCELROW;
798 $wsnumber = 1;
799 $myxls =& $worksheet[$wsnumber];
800 foreach ($logs['logs'] as $log) {
801 if (isset($ldcache[$log->module][$log->action])) {
802 $ld = $ldcache[$log->module][$log->action];
803 } else {
804 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
805 $ldcache[$log->module][$log->action] = $ld;
807 if ($ld && !empty($log->info)) {
808 // ugly hack to make sure fullname is shown correctly
809 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
810 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
811 } else {
812 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
816 // Filter log->info
817 $log->info = format_string($log->info);
818 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
820 if ($nroPages>1) {
821 if ($row > EXCELROWS) {
822 $wsnumber++;
823 $myxls =& $worksheet[$wsnumber];
824 $row = FIRSTUSEDEXCELROW;
828 $myxls->write($row, 0, $courses[$log->course], '');
829 // Excel counts from 1/1/1900
830 $excelTime=25569+$log->time/(3600*24);
831 $myxls->write($row, 1, $excelTime, $formatDate);
832 $myxls->write($row, 2, $log->ip, '');
833 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
834 $myxls->write($row, 3, $fullname, '');
835 $myxls->write($row, 4, $log->module.' '.$log->action, '');
836 $myxls->write($row, 5, $log->info, '');
838 $row++;
841 $workbook->close();
842 return true;
845 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
846 $modid, $modaction, $groupid) {
848 global $CFG;
850 require_once("$CFG->libdir/odslib.class.php");
852 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
853 $modname, $modid, $modaction, $groupid)) {
854 return false;
857 $courses = array();
859 if ($course->id == SITEID) {
860 $courses[0] = '';
861 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
862 foreach ($ccc as $cc) {
863 $courses[$cc->id] = $cc->shortname;
866 } else {
867 $courses[$course->id] = $course->shortname;
870 $count=0;
871 $ldcache = array();
872 $tt = getdate(time());
873 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
875 $strftimedatetime = get_string("strftimedatetime");
877 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
878 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
879 $filename .= '.ods';
881 $workbook = new MoodleODSWorkbook('-');
882 $workbook->send($filename);
884 $worksheet = array();
885 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
886 get_string('fullname'), get_string('action'), get_string('info'));
888 // Creating worksheets
889 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
890 $sheettitle = get_string('excel_sheettitle', 'logs', $wsnumber).$nroPages;
891 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
892 $worksheet[$wsnumber]->set_column(1, 1, 30);
893 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
894 userdate(time(), $strftimedatetime));
895 $col = 0;
896 foreach ($headers as $item) {
897 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
898 $col++;
902 if (empty($logs['logs'])) {
903 $workbook->close();
904 return true;
907 $formatDate =& $workbook->add_format();
908 $formatDate->set_num_format(get_string('log_excel_date_format'));
910 $row = FIRSTUSEDEXCELROW;
911 $wsnumber = 1;
912 $myxls =& $worksheet[$wsnumber];
913 foreach ($logs['logs'] as $log) {
914 if (isset($ldcache[$log->module][$log->action])) {
915 $ld = $ldcache[$log->module][$log->action];
916 } else {
917 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
918 $ldcache[$log->module][$log->action] = $ld;
920 if ($ld && !empty($log->info)) {
921 // ugly hack to make sure fullname is shown correctly
922 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
923 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
924 } else {
925 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
929 // Filter log->info
930 $log->info = format_string($log->info);
931 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
933 if ($nroPages>1) {
934 if ($row > EXCELROWS) {
935 $wsnumber++;
936 $myxls =& $worksheet[$wsnumber];
937 $row = FIRSTUSEDEXCELROW;
941 $myxls->write_string($row, 0, $courses[$log->course]);
942 $myxls->write_date($row, 1, $log->time);
943 $myxls->write_string($row, 2, $log->ip);
944 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
945 $myxls->write_string($row, 3, $fullname);
946 $myxls->write_string($row, 4, $log->module.' '.$log->action);
947 $myxls->write_string($row, 5, $log->info);
949 $row++;
952 $workbook->close();
953 return true;
957 function print_log_graph($course, $userid=0, $type="course.png", $date=0) {
958 global $CFG;
959 if (empty($CFG->gdversion)) {
960 echo "(".get_string("gdneed").")";
961 } else {
962 echo '<img src="'.$CFG->wwwroot.'/course/report/log/graph.php?id='.$course->id.
963 '&amp;user='.$userid.'&amp;type='.$type.'&amp;date='.$date.'" alt="" />';
968 function print_overview($courses) {
970 global $CFG, $USER;
972 $htmlarray = array();
973 if ($modules = get_records('modules')) {
974 foreach ($modules as $mod) {
975 if (file_exists(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php')) {
976 require_once(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php');
977 $fname = $mod->name.'_print_overview';
978 if (function_exists($fname)) {
979 $fname($courses,$htmlarray);
984 foreach ($courses as $course) {
985 print_simple_box_start('center', '100%', '', 5, "coursebox");
986 $linkcss = '';
987 if (empty($course->visible)) {
988 $linkcss = 'class="dimmed"';
990 print_heading('<a title="'. format_string($course->fullname).'" '.$linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'. format_string($course->fullname).'</a>');
991 if (array_key_exists($course->id,$htmlarray)) {
992 foreach ($htmlarray[$course->id] as $modname => $html) {
993 echo $html;
996 print_simple_box_end();
1001 function print_recent_activity($course) {
1002 // $course is an object
1003 // This function trawls through the logs looking for
1004 // anything new since the user's last login
1006 global $CFG, $USER, $SESSION;
1008 $context = get_context_instance(CONTEXT_COURSE, $course->id);
1010 $timestart = time() - COURSE_MAX_RECENT_PERIOD;
1012 if (!has_capability('moodle/legacy:guest', $context, NULL, false)) {
1013 if (!empty($USER->lastcourseaccess[$course->id])) {
1014 if ($USER->lastcourseaccess[$course->id] > $timestart) {
1015 $timestart = $USER->lastcourseaccess[$course->id];
1020 echo '<div class="activitydate">';
1021 echo get_string('activitysince', '', userdate($timestart));
1022 echo '</div>';
1023 echo '<div class="activityhead">';
1025 echo '<a href="'.$CFG->wwwroot.'/course/recent.php?id='.$course->id.'">'.get_string('recentactivityreport').'</a>';
1027 echo "</div>\n";
1030 // Firstly, have there been any new enrolments?
1032 $heading = false;
1033 $content = false;
1035 $users = get_recent_enrolments($course->id, $timestart);
1037 //Accessibility: new users now appear in an <OL> list.
1038 if ($users) {
1039 echo '<div class="newusers">';
1040 if (! $heading) {
1041 print_headline(get_string("newusers").':', 3);
1042 $heading = true;
1043 $content = true;
1045 echo "<ol class=\"list\">\n";
1046 foreach ($users as $user) {
1048 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
1049 echo '<li class="name"><a href="'.$CFG->wwwroot."/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a></li>\n";
1051 echo "</ol>\n</div>\n";
1054 // Next, have there been any modifications to the course structure?
1056 $logs = get_records_select('log', "time > '$timestart' AND course = '$course->id' AND
1057 module = 'course' AND action LIKE '% mod'", "time ASC");
1059 if ($logs) {
1060 foreach ($logs as $key => $log) {
1061 $info = split(' ', $log->info);
1063 if ($info[0] == 'label') { // Labels are special activities
1064 continue;
1067 $modname = get_field($info[0], 'name', 'id', $info[1]);
1068 //Create a temp valid module structure (course,id)
1069 $tempmod->course = $log->course;
1070 $tempmod->id = $info[1];
1071 //Obtain the visible property from the instance
1072 $modvisible = instance_is_visible($info[0],$tempmod);
1074 //Only if the mod is visible
1075 if ($modvisible) {
1076 switch ($log->action) {
1077 case 'add mod':
1078 $stradded = get_string('added', 'moodle', get_string('modulename', $info[0]));
1079 $changelist[$log->info] = array ('operation' => 'add', 'text' => "$stradded:<br /><a href=\"$CFG->wwwroot/course/$log->url\">".format_string($modname,true)."</a>");
1080 break;
1081 case 'update mod':
1082 $strupdated = get_string('updated', 'moodle', get_string('modulename', $info[0]));
1083 if (empty($changelist[$log->info])) {
1084 $changelist[$log->info] = array ('operation' => 'update', 'text' => "$strupdated:<br /><a href=\"$CFG->wwwroot/course/$log->url\">".format_string($modname,true)."</a>");
1086 break;
1087 case 'delete mod':
1088 if (!empty($changelist[$log->info]['operation']) and
1089 $changelist[$log->info]['operation'] == 'add') {
1090 $changelist[$log->info] = NULL;
1091 } else {
1092 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $info[0]));
1093 $changelist[$log->info] = array ('operation' => 'delete', 'text' => $strdeleted);
1095 break;
1101 if (!empty($changelist)) {
1102 foreach ($changelist as $changeinfo => $change) {
1103 if ($change) {
1104 $changes[$changeinfo] = $change;
1107 if (isset($changes)){
1108 if (count($changes) > 0) {
1109 print_headline(get_string('courseupdates').':', 3);
1110 $content = true;
1111 foreach ($changes as $changeinfo => $change) {
1112 echo '<p class="activity">'.$change['text'].'</p>';
1118 // Now display new things from each module
1120 $mods = get_records('modules', 'visible', '1', 'name', 'id, name');
1122 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
1124 foreach ($mods as $mod) { // Each module gets it's own logs and prints them
1125 include_once($CFG->dirroot.'/mod/'.$mod->name.'/lib.php');
1126 $print_recent_activity = $mod->name.'_print_recent_activity';
1127 if (function_exists($print_recent_activity)) {
1129 // NOTE:
1130 // $isteacher (second parameter below) is to be deprecated!
1132 // TODO:
1133 // 1) Make sure that all _print_recent_activity functions are
1134 // not using the $isteacher value.
1135 // 2) Eventually, remove the $isteacher parameter from the
1136 // function calls.
1138 $modcontent = $print_recent_activity($course, $viewfullnames, $timestart);
1139 if ($modcontent) {
1140 $content = true;
1145 if (! $content) {
1146 echo '<p class="message">'.get_string('nothingnew').'</p>';
1151 function get_array_of_activities($courseid) {
1152 // For a given course, returns an array of course activity objects
1153 // Each item in the array contains he following properties:
1154 // cm - course module id
1155 // mod - name of the module (eg forum)
1156 // section - the number of the section (eg week or topic)
1157 // name - the name of the instance
1158 // visible - is the instance visible or not
1159 // extra - contains extra string to include in any link
1161 global $CFG;
1163 $mod = array();
1165 if (!$rawmods = get_course_mods($courseid)) {
1166 return NULL;
1169 if ($sections = get_records("course_sections", "course", $courseid, "section ASC")) {
1170 foreach ($sections as $section) {
1171 if (!empty($section->sequence)) {
1172 $sequence = explode(",", $section->sequence);
1173 foreach ($sequence as $seq) {
1174 if (empty($rawmods[$seq])) {
1175 continue;
1177 $mod[$seq]->cm = $rawmods[$seq]->id;
1178 $mod[$seq]->mod = $rawmods[$seq]->modname;
1179 $mod[$seq]->section = $section->section;
1180 $mod[$seq]->name = urlencode(get_field($rawmods[$seq]->modname, "name", "id", $rawmods[$seq]->instance));
1181 $mod[$seq]->visible = $rawmods[$seq]->visible;
1182 $mod[$seq]->extra = "";
1184 $modname = $mod[$seq]->mod;
1185 $functionname = $modname."_get_coursemodule_info";
1187 include_once("$CFG->dirroot/mod/$modname/lib.php");
1189 if (function_exists($functionname)) {
1190 if ($info = $functionname($rawmods[$seq])) {
1191 if (!empty($info->extra)) {
1192 $mod[$seq]->extra = $info->extra;
1194 if (!empty($info->icon)) {
1195 $mod[$seq]->icon = $info->icon;
1203 return $mod;
1209 function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
1210 // Returns a number of useful structures for course displays
1212 $mods = NULL; // course modules indexed by id
1213 $modnames = NULL; // all course module names (except resource!)
1214 $modnamesplural= NULL; // all course module names (plural form)
1215 $modnamesused = NULL; // course module names used
1217 if ($allmods = get_records("modules")) {
1218 foreach ($allmods as $mod) {
1219 if ($mod->visible) {
1220 $modnames[$mod->name] = get_string("modulename", "$mod->name");
1221 $modnamesplural[$mod->name] = get_string("modulenameplural", "$mod->name");
1224 asort($modnames);
1225 } else {
1226 error("No modules are installed!");
1229 if ($rawmods = get_course_mods($courseid)) {
1230 foreach($rawmods as $mod) { // Index the mods
1231 if (empty($modnames[$mod->modname])) {
1232 continue;
1234 $mods[$mod->id] = $mod;
1235 $mods[$mod->id]->modfullname = $modnames[$mod->modname];
1236 if ($mod->visible or has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_COURSE, $courseid))) {
1237 $modnamesused[$mod->modname] = $modnames[$mod->modname];
1240 if ($modnamesused) {
1241 asort($modnamesused);
1247 function get_all_sections($courseid) {
1249 return get_records("course_sections", "course", "$courseid", "section",
1250 "section, id, course, summary, sequence, visible");
1253 function course_set_display($courseid, $display=0) {
1254 global $USER;
1256 if ($display == "all" or empty($display)) {
1257 $display = 0;
1260 if (empty($USER->id) or $USER->username == 'guest') {
1261 //do not store settings in db for guests
1262 } else if (record_exists("course_display", "userid", $USER->id, "course", $courseid)) {
1263 set_field("course_display", "display", $display, "userid", $USER->id, "course", $courseid);
1264 } else {
1265 $record->userid = $USER->id;
1266 $record->course = $courseid;
1267 $record->display = $display;
1268 if (!insert_record("course_display", $record)) {
1269 notify("Could not save your course display!");
1273 return $USER->display[$courseid] = $display; // Note: = not ==
1276 function set_section_visible($courseid, $sectionnumber, $visibility) {
1277 /// For a given course section, markes it visible or hidden,
1278 /// and does the same for every activity in that section
1280 if ($section = get_record("course_sections", "course", $courseid, "section", $sectionnumber)) {
1281 set_field("course_sections", "visible", "$visibility", "id", $section->id);
1282 if (!empty($section->sequence)) {
1283 $modules = explode(",", $section->sequence);
1284 foreach ($modules as $moduleid) {
1285 set_coursemodule_visible($moduleid, $visibility, true);
1288 rebuild_course_cache($courseid);
1293 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%") {
1294 /// Prints a section full of activity modules
1295 global $CFG, $USER;
1297 static $groupbuttons;
1298 static $groupbuttonslink;
1299 static $isteacher;
1300 static $isediting;
1301 static $ismoving;
1302 static $strmovehere;
1303 static $strmovefull;
1304 static $strunreadpostsone;
1306 static $untracked;
1307 static $usetracking;
1309 $labelformatoptions = New stdClass;
1311 if (!isset($isteacher)) {
1312 $groupbuttons = ($course->groupmode or (!$course->groupmodeforce));
1313 $groupbuttonslink = (!$course->groupmodeforce);
1314 $isediting = isediting($course->id);
1315 $ismoving = $isediting && ismoving($course->id);
1316 if ($ismoving) {
1317 $strmovehere = get_string("movehere");
1318 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1320 include_once($CFG->dirroot.'/mod/forum/lib.php');
1321 if ($usetracking = forum_tp_can_track_forums()) {
1322 $strunreadpostsone = get_string('unreadpostsone', 'forum');
1323 $untracked = forum_tp_get_untracked_forums($USER->id, $course->id);
1326 $labelformatoptions->noclean = true;
1328 /// Casting $course->modinfo to string prevents one notice when the field is null
1329 $modinfo = unserialize((string)$course->modinfo);
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\">\n";
1336 $sectionmods = explode(",", $section->sequence);
1338 foreach ($sectionmods as $modnumber) {
1339 if (empty($mods[$modnumber])) {
1340 continue;
1342 $mod = $mods[$modnumber];
1344 if (($mod->visible or has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_COURSE, $course->id))) &&
1345 (!$ismoving || $mod->id != $USER->activitycopy)) {
1346 echo '<li class="activity '.$mod->modname.'" id="module-'.$modnumber.'">'; // Unique ID
1347 if ($ismoving) {
1348 echo '<a title="'.$strmovefull.'"'.
1349 ' href="'.$CFG->wwwroot.'/course/mod.php?moveto='.$mod->id.'&amp;sesskey='.$USER->sesskey.'">'.
1350 '<img class="movetarget" src="'.$CFG->pixpath.'/movehere.gif" '.
1351 ' alt="'.$strmovehere.'" /></a><br />
1354 $instancename = urldecode($modinfo[$modnumber]->name);
1355 $instancename = format_string($instancename, true, $course->id);
1357 if (!empty($modinfo[$modnumber]->extra)) {
1358 $extra = urldecode($modinfo[$modnumber]->extra);
1359 } else {
1360 $extra = "";
1363 if (!empty($modinfo[$modnumber]->icon)) {
1364 $icon = "$CFG->pixpath/".urldecode($modinfo[$modnumber]->icon);
1365 } else {
1366 $icon = "$CFG->modpixpath/$mod->modname/icon.gif";
1369 if ($mod->indent) {
1370 print_spacer(12, 20 * $mod->indent, false);
1373 if ($mod->modname == "label") {
1374 if (!$mod->visible) {
1375 echo "<span class=\"dimmed_text\">";
1377 echo format_text($extra, FORMAT_HTML, $labelformatoptions);
1378 if (!$mod->visible) {
1379 echo "</span>";
1382 } else { // Normal activity
1384 if (!empty($USER->screenreader)) {
1385 $typestring = '('.get_string('modulename',$mod->modname).') ';
1386 } else {
1387 $typestring = '';
1390 $linkcss = $mod->visible ? "" : " class=\"dimmed\" ";
1391 echo '<img src="'.$icon.'"'.
1392 ' class="activityicon" alt="'.$mod->modfullname.'" />'.
1393 ' <a title="'.$mod->modfullname.'" '.$linkcss.' '.$extra.
1394 ' href="'.$CFG->wwwroot.'/mod/'.$mod->modname.'/view.php?id='.$mod->id.'">'.
1395 $typestring.$instancename.'</a>';
1397 if ($usetracking && $mod->modname == 'forum') {
1398 $groupmode = groupmode($course, $mod);
1399 $groupid = ($groupmode == SEPARATEGROUPS && !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) ?
1400 get_current_group($course->id) : false;
1402 if (forum_tp_can_track_forums() && !isset($untracked[$mod->instance])) {
1403 $unread = forum_tp_count_forum_unread_posts($USER->id, $mod->instance, $groupid);
1404 if ($unread) {
1405 echo '<span class="unread"> <a href="'.$CFG->wwwroot.'/mod/forum/view.php?id='.$mod->id.'">';
1406 if ($unread == 1) {
1407 echo $strunreadpostsone;
1408 } else {
1409 print_string('unreadpostsnumber', 'forum', $unread);
1411 echo '</a> </span>';
1416 if ($isediting) {
1417 // TODO: we must define this as mod property!
1418 if ($groupbuttons and $mod->modname != 'label' and $mod->modname != 'resource' and $mod->modname != 'glossary') {
1419 if (! $mod->groupmodelink = $groupbuttonslink) {
1420 $mod->groupmode = $course->groupmode;
1423 } else {
1424 $mod->groupmode = false;
1426 echo '&nbsp;&nbsp;';
1427 echo make_editing_buttons($mod, $absolute, true, $mod->indent, $section->section);
1429 echo "</li>\n";
1432 } elseif ($ismoving) {
1433 echo "<ul class=\"section\">\n";
1435 if ($ismoving) {
1436 echo '<li><a title="'.$strmovefull.'"'.
1437 ' href="'.$CFG->wwwroot.'/course/mod.php?movetosection='.$section->id.'&amp;sesskey='.$USER->sesskey.'">'.
1438 '<img class="movetarget" src="'.$CFG->pixpath.'/movehere.gif" '.
1439 ' alt="'.$strmovehere.'" /></a></li>
1442 if (!empty($section->sequence) || $ismoving) {
1443 echo "</ul><!--class='section'-->\n\n";
1448 * Prints the menus to add activities and resources.
1450 function print_section_add_menus($course, $section, $modnames, $vertical=false, $return=false) {
1451 global $CFG;
1453 // check to see if user can add menus
1454 if (!has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $course->id))) {
1455 return false;
1458 static $resources = false;
1459 static $activities = false;
1461 if ($resources === false) {
1462 $resources = array();
1463 $activities = array();
1465 foreach($modnames as $modname=>$modnamestr) {
1466 if (!course_allowed_module($course, $modname)) {
1467 continue;
1470 require_once("$CFG->dirroot/mod/$modname/lib.php");
1471 $gettypesfunc = $modname.'_get_types';
1472 if (function_exists($gettypesfunc)) {
1473 $types = $gettypesfunc();
1474 foreach($types as $type) {
1475 if ($type->modclass == MOD_CLASS_RESOURCE) {
1476 $resources[$type->type] = $type->typestr;
1477 } else {
1478 $activities[$type->type] = $type->typestr;
1481 } else {
1482 // all mods without type are considered activity
1483 $activities[$modname] = $modnamestr;
1488 $straddactivity = get_string('addactivity');
1489 $straddresource = get_string('addresource');
1491 $output = '<div class="section_add_menus">';
1493 if (!$vertical) {
1494 $output .= '<div class="horizontal">';
1497 if (!empty($resources)) {
1498 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&amp;section=$section&amp;sesskey=".sesskey()."&amp;add=",
1499 $resources, "ressection$section", "", $straddresource, 'resource/types', $straddresource, true);
1502 if (!empty($activities)) {
1503 $output .= ' ';
1504 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&amp;section=$section&amp;sesskey=".sesskey()."&amp;add=",
1505 $activities, "section$section", "", $straddactivity, 'mods', $straddactivity, true);
1508 if (!$vertical) {
1509 $output .= '</div>';
1512 $output .= '</div>';
1514 if ($return) {
1515 return $output;
1516 } else {
1517 echo $output;
1521 function rebuild_course_cache($courseid=0) {
1522 // Rebuilds the cached list of course activities stored in the database
1523 // If a courseid is not specified, then all are rebuilt
1525 if ($courseid) {
1526 $select = "id = '$courseid'";
1527 } else {
1528 $select = "";
1531 if ($courses = get_records_select("course", $select,'','id,fullname')) {
1532 foreach ($courses as $course) {
1533 $modinfo = serialize(get_array_of_activities($course->id));
1534 if (!set_field("course", "modinfo", $modinfo, "id", $course->id)) {
1535 notify("Could not cache module information for course '" . format_string($course->fullname) . "'!");
1543 function make_categories_list(&$list, &$parents, $category=NULL, $path="") {
1544 /// Given an empty array, this function recursively travels the
1545 /// categories, building up a nice list for display. It also makes
1546 /// an array that list all the parents for each category.
1548 // initialize the arrays if needed
1549 if (!is_array($list)) {
1550 $list = array();
1552 if (!is_array($parents)) {
1553 $parents = array();
1556 if ($category) {
1557 if ($path) {
1558 $path = $path.' / '.format_string($category->name);
1559 } else {
1560 $path = format_string($category->name);
1562 $list[$category->id] = $path;
1563 } else {
1564 $category->id = 0;
1567 if ($categories = get_categories($category->id)) { // Print all the children recursively
1568 foreach ($categories as $cat) {
1569 if (!empty($category->id)) {
1570 if (isset($parents[$category->id])) {
1571 $parents[$cat->id] = $parents[$category->id];
1573 $parents[$cat->id][] = $category->id;
1575 make_categories_list($list, $parents, $cat, $path);
1581 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $files = true) {
1582 /// Recursive function to print out all the categories in a nice format
1583 /// with or without courses included
1584 global $CFG;
1586 if (isset($CFG->max_category_depth) && ($depth >= $CFG->max_category_depth)) {
1587 return;
1590 if (!$displaylist) {
1591 make_categories_list($displaylist, $parentslist);
1594 if ($category) {
1595 if ($category->visible or has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
1596 print_category_info($category, $depth, $files);
1597 } else {
1598 return; // Don't bother printing children of invisible categories
1601 } else {
1602 $category->id = "0";
1605 if ($categories = get_categories($category->id)) { // Print all the children recursively
1606 $countcats = count($categories);
1607 $count = 0;
1608 $first = true;
1609 $last = false;
1610 foreach ($categories as $cat) {
1611 $count++;
1612 if ($count == $countcats) {
1613 $last = true;
1615 $up = $first ? false : true;
1616 $down = $last ? false : true;
1617 $first = false;
1619 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1, $files);
1624 // this function will return $options array for choose_from_menu, with whitespace to denote nesting.
1626 function make_categories_options() {
1627 make_categories_list($cats,$parents);
1628 foreach ($cats as $key => $value) {
1629 if (array_key_exists($key,$parents)) {
1630 if ($indent = count($parents[$key])) {
1631 for ($i = 0; $i < $indent; $i++) {
1632 $cats[$key] = '&nbsp;'.$cats[$key];
1637 return $cats;
1640 function print_category_info($category, $depth, $files = false) {
1641 /// Prints the category info in indented fashion
1642 /// This function is only used by print_whole_category_list() above
1644 global $CFG;
1645 static $strallowguests, $strrequireskey, $strsummary;
1647 if (empty($strsummary)) {
1648 $strallowguests = get_string('allowguests');
1649 $strrequireskey = get_string('requireskey');
1650 $strsummary = get_string('summary');
1653 $catlinkcss = $category->visible ? '' : ' class="dimmed" ';
1655 $coursecount = count_records('course') <= FRONTPAGECOURSELIMIT;
1656 if ($files and $coursecount) {
1657 $catimage = '<img src="'.$CFG->pixpath.'/i/course.gif" alt="" />';
1658 } else {
1659 $catimage = "&nbsp;";
1662 echo "\n\n".'<table class="categorylist">';
1664 if ($files and $coursecount) {
1665 $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');
1667 echo '<tr>';
1669 if ($depth) {
1670 $indent = $depth*30;
1671 $rows = count($courses) + 1;
1672 echo '<td rowspan="'.$rows.'" valign="top" width="'.$indent.'">';
1673 print_spacer(10, $indent);
1674 echo '</td>';
1677 echo '<td valign="top" class="category image">'.$catimage.'</td>';
1678 echo '<td valign="top" class="category name">';
1679 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot.'/course/category.php?id='.$category->id.'">'. format_string($category->name).'</a>';
1680 echo '</td>';
1681 echo '<td class="category info">&nbsp;</td>';
1682 echo '</tr>';
1684 if ($courses && !(isset($CFG->max_category_depth)&&($depth>=$CFG->max_category_depth-1))) {
1685 foreach ($courses as $course) {
1686 $linkcss = $course->visible ? '' : ' class="dimmed" ';
1687 echo '<tr><td valign="top">&nbsp;';
1688 echo '</td><td valign="top" class="course name">';
1689 echo '<a '.$linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'. format_string($course->fullname).'</a>';
1690 echo '</td><td align="right" valign="top" class="course info">';
1691 if ($course->guest ) {
1692 echo '<a title="'.$strallowguests.'" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">';
1693 echo '<img alt="'.$strallowguests.'" src="'.$CFG->pixpath.'/i/guest.gif" /></a>';
1694 } else {
1695 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath.'/spacer.gif" />';
1697 if ($course->password) {
1698 echo '<a title="'.$strrequireskey.'" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">';
1699 echo '<img alt="'.$strrequireskey.'" src="'.$CFG->pixpath.'/i/key.gif" /></a>';
1700 } else {
1701 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath.'/spacer.gif" />';
1703 if ($course->summary) {
1704 link_to_popup_window ('/course/info.php?id='.$course->id, 'courseinfo',
1705 '<img alt="'.$strsummary.'" src="'.$CFG->pixpath.'/i/info.gif" />',
1706 400, 500, $strsummary);
1707 } else {
1708 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath.'/spacer.gif" />';
1710 echo '</td></tr>';
1713 } else {
1715 echo '<tr>';
1717 if ($depth) {
1718 $indent = $depth*20;
1719 echo '<td valign="top" width="'.$indent.'">';
1720 print_spacer(10, $indent);
1721 echo '</td>';
1724 echo '<td valign="top" class="category name">';
1725 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot.'/course/category.php?id='.$category->id.'">'. format_string($category->name).'</a>';
1726 echo '</td>';
1727 echo '<td valign="top" class="category number">';
1728 if ($category->coursecount) {
1729 echo $category->coursecount;
1731 echo '</td></tr>';
1733 echo '</table>';
1737 function print_courses($category, $hidesitecourse = false) {
1738 /// Category is 0 (for all courses) or an object
1740 global $CFG;
1742 if (empty($category)) {
1743 $categories = get_categories(0); // Parent = 0 ie top-level categories only
1744 if ($categories != null and count($categories) == 1) {
1745 $category = array_shift($categories);
1746 $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');
1747 } else {
1748 $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');
1750 unset($categories);
1751 } else {
1752 $categories = get_categories($category->id); // sub categories
1753 $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');
1756 if ($courses) {
1757 foreach ($courses as $course) {
1758 if ($hidesitecourse and ($course->id == SITEID)) {
1759 continue;
1761 print_course($course);
1763 } else {
1764 print_heading(get_string("nocoursesyet"));
1765 $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
1766 if (has_capability('moodle/course:create', $context)) {
1767 $options = array();
1768 $options['category'] = $category->id;
1769 echo '<div class="addcoursebutton">';
1770 print_single_button($CFG->wwwroot.'/course/edit.php', $options, get_string("addnewcourse"));
1771 echo '</div>';
1780 function print_course($course) {
1782 global $CFG, $USER;
1784 $context = get_context_instance(CONTEXT_COURSE, $course->id);
1786 $linkcss = $course->visible ? '' : ' class="dimmed" ';
1788 echo '<div class="coursebox">';
1789 echo '<div class="info">';
1790 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
1791 $linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.
1792 format_string($course->fullname).'</a></div>';
1794 /// first find all roles that are supposed to be displayed
1795 if ($managerroles = get_config('', 'coursemanager')) {
1796 $coursemanagerroles = split(',', $managerroles);
1797 $roles = get_records_select( 'role', '', 'sortorder' );
1798 foreach ($roles as $role) {
1799 if (in_array( $role->id, $coursemanagerroles )) {
1800 if ($users = get_role_users($role->id, $context, true, '', 'u.lastname ASC', true)) {
1801 foreach ($users as $teacher) {
1802 $fullname = fullname($teacher, has_capability('moodle/site:viewfullnames', $context));
1803 $namesarray[] = role_get_name($role, $context).': <a href="'.$CFG->wwwroot.'/user/view.php?id='.
1804 $teacher->id.'&amp;course='.SITEID.'">'.$fullname.'</a>';
1810 if (!empty($namesarray)) {
1811 echo "<ul class=\"teachers\">\n<li>";
1812 echo implode('</li><li>', $namesarray);
1813 echo "</li></ul>";
1817 require_once("$CFG->dirroot/enrol/enrol.class.php");
1818 $enrol = enrolment_factory::factory($course->enrol);
1819 echo $enrol->get_access_icons($course);
1821 echo '</div><div class="summary">';
1822 $options = NULL;
1823 $options->noclean = true;
1824 $options->para = false;
1825 echo format_text($course->summary, FORMAT_MOODLE, $options, $course->id);
1826 echo '</div>';
1827 echo '</div>';
1828 echo '<div class="clearer"></div>';
1832 function print_my_moodle() {
1833 /// Prints custom user information on the home page.
1834 /// Over time this can include all sorts of information
1836 global $USER, $CFG;
1838 if (empty($USER->id)) {
1839 error("It shouldn't be possible to see My Moodle without being logged in.");
1842 $courses = get_my_courses($USER->id);
1843 $rhosts = array();
1844 $rcourses = array();
1845 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
1846 $rcourses = get_my_remotecourses($USER->id);
1847 $rhosts = get_my_remotehosts();
1850 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
1852 if (!empty($courses)) {
1853 foreach ($courses as $course) {
1854 if ($course->id == SITEID) {
1855 continue;
1857 print_course($course, "100%");
1861 // MNET
1862 if (!empty($rcourses)) {
1863 // at the IDP, we know of all the remote courses
1864 foreach ($rcourses as $course) {
1865 print_remote_course($course, "100%");
1867 } elseif (!empty($rhosts)) {
1868 // non-IDP, we know of all the remote servers, but not courses
1869 foreach ($rhosts as $host) {
1870 print_remote_host($host, "100%");
1873 unset($course);
1874 unset($host);
1876 if (count_records("course") > (count($courses) + 1) ) { // Some courses not being displayed
1877 echo "<table width=\"100%\"><tr><td align=\"center\">";
1878 print_course_search("", false, "short");
1879 echo "</td><td align=\"center\">";
1880 print_single_button("$CFG->wwwroot/course/index.php", NULL, get_string("fulllistofcourses"), "get");
1881 echo "</td></tr></table>\n";
1884 } else {
1885 if (count_records("course_categories") > 1) {
1886 print_simple_box_start("center", "100%", "#FFFFFF", 5, "categorybox");
1887 print_whole_category_list();
1888 print_simple_box_end();
1889 } else {
1890 print_courses(0);
1896 function print_course_search($value="", $return=false, $format="plain") {
1898 global $CFG;
1899 static $count = 0;
1901 $count++;
1903 $id = 'coursesearch';
1905 if ($count > 1) {
1906 $id .= $count;
1909 $strsearchcourses= get_string("searchcourses");
1911 if ($format == 'plain') {
1912 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
1913 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
1914 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
1915 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
1916 $output .= '<input type="submit" value="'.get_string('go').'" />';
1917 $output .= '</fieldset></form>';
1918 } else if ($format == 'short') {
1919 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
1920 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
1921 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
1922 $output .= '<input type="text" id="coursesearchbox" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
1923 $output .= '<input type="submit" value="'.get_string('go').'" />';
1924 $output .= '</fieldset></form>';
1925 } else if ($format == 'navbar') {
1926 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
1927 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
1928 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
1929 $output .= '<input type="text" id="coursesearchbox" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
1930 $output .= '<input type="submit" value="'.get_string('go').'" />';
1931 $output .= '</fieldset></form>';
1934 if ($return) {
1935 return $output;
1937 echo $output;
1940 function print_remote_course($course, $width="100%") {
1942 global $CFG, $USER;
1944 $linkcss = '';
1946 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&amp;wantsurl=/course/view.php?id={$course->remoteid}";
1948 echo '<div class="coursebox remotecoursebox">';
1949 echo '<div class="info">';
1950 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
1951 $linkcss.' href="'.$url.'">'
1952 . format_string($course->fullname) .'</a><br />'
1953 . format_string($course->hostname) . ' : '
1954 . format_string($course->cat_name) . ' : '
1955 . format_string($course->shortname). '</div>';
1956 echo '</div><div class="summary">';
1957 $options = NULL;
1958 $options->noclean = true;
1959 $options->para = false;
1960 echo format_text($course->summary, FORMAT_MOODLE, $options);
1961 echo '</div>';
1962 echo '</div>';
1963 echo '<div class="clearer"></div>';
1966 function print_remote_host($host, $width="100%") {
1968 global $CFG, $USER;
1970 $linkcss = '';
1972 echo '<div class="coursebox">';
1973 echo '<div class="info">';
1974 echo '<div class="name">';
1975 echo '<img src="'.$CFG->pixpath.'/i/mnethost.gif" class="icon" alt="'.get_string('course').'" />';
1976 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
1977 . s($host['name']).'</a> - ';
1978 echo $host['count'] . ' ' . get_string('courses');
1979 echo '</div>';
1980 echo '</div>';
1981 echo '</div>';
1982 echo '<div class="clearer"></div>';
1986 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
1988 function add_course_module($mod) {
1990 $mod->added = time();
1991 unset($mod->id);
1993 return insert_record("course_modules", $mod);
1996 function add_mod_to_section($mod, $beforemod=NULL) {
1997 /// Given a full mod object with section and course already defined
1998 /// If $before is specified, then this is an existing ID which we
1999 /// will insert the new module before
2001 /// Returns the course_sections ID where the mod is inserted
2003 if ($section = get_record("course_sections", "course", "$mod->course", "section", "$mod->section")) {
2005 $section->sequence = trim($section->sequence);
2007 if (empty($section->sequence)) {
2008 $newsequence = "$mod->coursemodule";
2010 } else if ($beforemod) {
2011 $modarray = explode(",", $section->sequence);
2013 if ($key = array_keys ($modarray, $beforemod->id)) {
2014 $insertarray = array($mod->id, $beforemod->id);
2015 array_splice($modarray, $key[0], 1, $insertarray);
2016 $newsequence = implode(",", $modarray);
2018 } else { // Just tack it on the end anyway
2019 $newsequence = "$section->sequence,$mod->coursemodule";
2022 } else {
2023 $newsequence = "$section->sequence,$mod->coursemodule";
2026 if (set_field("course_sections", "sequence", $newsequence, "id", $section->id)) {
2027 return $section->id; // Return course_sections ID that was used.
2028 } else {
2029 return 0;
2032 } else { // Insert a new record
2033 $section->course = $mod->course;
2034 $section->section = $mod->section;
2035 $section->summary = "";
2036 $section->sequence = $mod->coursemodule;
2037 return insert_record("course_sections", $section);
2041 function set_coursemodule_groupmode($id, $groupmode) {
2042 return set_field("course_modules", "groupmode", $groupmode, "id", $id);
2045 function set_coursemodule_groupingid($id, $groupingid) {
2046 return set_field("course_modules", "groupingid", $groupingid, "id", $id);
2049 function set_coursemodule_groupmembersonly($id, $groupmembersonly) {
2050 return set_field("course_modules", "groupmembersonly", $groupmembersonly, "id", $id);
2053 function set_coursemodule_idnumber($id, $idnumber) {
2054 return set_field("course_modules", "idnumber", $idnumber, "id", $id);
2057 * $prevstateoverrides = true will set the visibility of the course module
2058 * to what is defined in visibleold. This enables us to remember the current
2059 * visibility when making a whole section hidden, so that when we toggle
2060 * that section back to visible, we are able to return the visibility of
2061 * the course module back to what it was originally.
2063 function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
2064 if (!$cm = get_record('course_modules', 'id', $id)) {
2065 return false;
2067 if (!$modulename = get_field('modules', 'name', 'id', $cm->module)) {
2068 return false;
2070 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
2071 foreach($events as $event) {
2072 if ($visible) {
2073 show_event($event);
2074 } else {
2075 hide_event($event);
2079 if ($prevstateoverrides) {
2080 if ($visible == '0') {
2081 // Remember the current visible state so we can toggle this back.
2082 set_field('course_modules', 'visibleold', $cm->visible, 'id', $id);
2083 } else {
2084 // Get the previous saved visible states.
2085 return set_field('course_modules', 'visible', $cm->visibleold, 'id', $id);
2088 return set_field("course_modules", "visible", $visible, "id", $id);
2092 * Delete a course module and any associated data at the course level (events)
2093 * Until 1.5 this function simply marked a deleted flag ... now it
2094 * deletes it completely.
2097 function delete_course_module($id) {
2098 global $CFG;
2099 require_once($CFG->libdir.'/gradelib.php');
2101 if (!$cm = get_record('course_modules', 'id', $id)) {
2102 return true;
2104 $modulename = get_field('modules', 'name', 'id', $cm->module);
2105 //delete events from calendar
2106 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
2107 foreach($events as $event) {
2108 delete_event($event->id);
2111 //delete grade items, outcome items and grades attached to modules
2112 if ($grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2113 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course))) {
2114 foreach ($grade_items as $grade_item) {
2115 $grade_item->delete('moddelete');
2119 return delete_records('course_modules', 'id', $cm->id);
2122 function delete_mod_from_section($mod, $section) {
2124 if ($section = get_record("course_sections", "id", "$section") ) {
2126 $modarray = explode(",", $section->sequence);
2128 if ($key = array_keys ($modarray, $mod)) {
2129 array_splice($modarray, $key[0], 1);
2130 $newsequence = implode(",", $modarray);
2131 return set_field("course_sections", "sequence", $newsequence, "id", $section->id);
2132 } else {
2133 return false;
2137 return false;
2140 function move_section($course, $section, $move) {
2141 /// Moves a whole course section up and down within the course
2142 global $USER;
2144 if (!$move) {
2145 return true;
2148 $sectiondest = $section + $move;
2150 if ($sectiondest > $course->numsections or $sectiondest < 1) {
2151 return false;
2154 if (!$sectionrecord = get_record("course_sections", "course", $course->id, "section", $section)) {
2155 return false;
2158 if (!$sectiondestrecord = get_record("course_sections", "course", $course->id, "section", $sectiondest)) {
2159 return false;
2162 if (!set_field("course_sections", "section", $sectiondest, "id", $sectionrecord->id)) {
2163 return false;
2165 if (!set_field("course_sections", "section", $section, "id", $sectiondestrecord->id)) {
2166 return false;
2168 // if the focus is on the section that is being moved, then move the focus along
2169 if (isset($USER->display[$course->id]) and ($USER->display[$course->id] == $section)) {
2170 course_set_display($course->id, $sectiondest);
2173 // Check for duplicates and fix order if needed.
2174 // There is a very rare case that some sections in the same course have the same section id.
2175 $sections = get_records_select('course_sections', "course = $course->id", 'section ASC');
2176 $n = 0;
2177 foreach ($sections as $section) {
2178 if ($section->section != $n) {
2179 if (!set_field('course_sections', 'section', $n, 'id', $section->id)) {
2180 return false;
2183 $n++;
2185 return true;
2189 function moveto_module($mod, $section, $beforemod=NULL) {
2190 /// All parameters are objects
2191 /// Move the module object $mod to the specified $section
2192 /// If $beforemod exists then that is the module
2193 /// before which $modid should be inserted
2195 /// Remove original module from original section
2197 if (! delete_mod_from_section($mod->id, $mod->section)) {
2198 notify("Could not delete module from existing section");
2201 /// Update module itself if necessary
2203 if ($mod->section != $section->id) {
2204 $mod->section = $section->id;
2205 if (!update_record("course_modules", $mod)) {
2206 return false;
2208 // if moving to a hidden section then hide module
2209 if (!$section->visible) {
2210 set_coursemodule_visible($mod->id, 0);
2214 /// Add the module into the new section
2216 $mod->course = $section->course;
2217 $mod->section = $section->section; // need relative reference
2218 $mod->coursemodule = $mod->id;
2220 if (! add_mod_to_section($mod, $beforemod)) {
2221 return false;
2224 return true;
2228 function make_editing_buttons($mod, $absolute=false, $moveselect=true, $indent=-1, $section=-1) {
2229 global $CFG, $USER;
2231 static $str;
2232 static $sesskey;
2234 $modcontext = get_context_instance(CONTEXT_MODULE, $mod->id);
2235 // no permission to edit
2236 if (!has_capability('moodle/course:manageactivities', $modcontext)) {
2237 return false;
2240 if (!isset($str)) {
2241 $str->delete = get_string("delete");
2242 $str->move = get_string("move");
2243 $str->moveup = get_string("moveup");
2244 $str->movedown = get_string("movedown");
2245 $str->moveright = get_string("moveright");
2246 $str->moveleft = get_string("moveleft");
2247 $str->update = get_string("update");
2248 $str->duplicate = get_string("duplicate");
2249 $str->hide = get_string("hide");
2250 $str->show = get_string("show");
2251 $str->clicktochange = get_string("clicktochange");
2252 $str->forcedmode = get_string("forcedmode");
2253 $str->groupsnone = get_string("groupsnone");
2254 $str->groupsseparate = get_string("groupsseparate");
2255 $str->groupsvisible = get_string("groupsvisible");
2256 $sesskey = sesskey();
2259 if ($section >= 0) {
2260 $section = '&amp;sr='.$section; // Section return
2261 } else {
2262 $section = '';
2265 if ($absolute) {
2266 $path = $CFG->wwwroot.'/course';
2267 } else {
2268 $path = '.';
2271 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
2272 if ($mod->visible) {
2273 $hideshow = '<a class="editing_hide" title="'.$str->hide.'" href="'.$path.'/mod.php?hide='.$mod->id.
2274 '&amp;sesskey='.$sesskey.$section.'"><img'.
2275 ' src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" '.
2276 ' alt="'.$str->hide.'" /></a>'."\n";
2277 } else {
2278 $hideshow = '<a class="editing_show" title="'.$str->show.'" href="'.$path.'/mod.php?show='.$mod->id.
2279 '&amp;sesskey='.$sesskey.$section.'"><img'.
2280 ' src="'.$CFG->pixpath.'/t/show.gif" class="iconsmall" '.
2281 ' alt="'.$str->show.'" /></a>'."\n";
2284 if ($mod->groupmode !== false) {
2285 if ($mod->groupmode == SEPARATEGROUPS) {
2286 $grouptitle = $str->groupsseparate;
2287 $groupclass = 'editing_groupsseparate';
2288 $groupimage = $CFG->pixpath.'/t/groups.gif';
2289 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=0&amp;sesskey='.$sesskey;
2290 } else if ($mod->groupmode == VISIBLEGROUPS) {
2291 $grouptitle = $str->groupsvisible;
2292 $groupclass = 'editing_groupsvisible';
2293 $groupimage = $CFG->pixpath.'/t/groupv.gif';
2294 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=1&amp;sesskey='.$sesskey;
2295 } else {
2296 $grouptitle = $str->groupsnone;
2297 $groupclass = 'editing_groupsnone';
2298 $groupimage = $CFG->pixpath.'/t/groupn.gif';
2299 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=2&amp;sesskey='.$sesskey;
2301 if ($mod->groupmodelink) {
2302 $groupmode = '<a class="'.$groupclass.'" title="'.$grouptitle.' ('.$str->clicktochange.')" href="'.$grouplink.'">'.
2303 '<img src="'.$groupimage.'" class="iconsmall" '.
2304 'alt="'.$grouptitle.'" /></a>';
2305 } else {
2306 $groupmode = '<img title="'.$grouptitle.' ('.$str->forcedmode.')" '.
2307 ' src="'.$groupimage.'" class="iconsmall" '.
2308 'alt="'.$grouptitle.'" />';
2310 } else {
2311 $groupmode = "";
2314 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $mod->course))) {
2315 if ($moveselect) {
2316 $move = '<a class="editing_move" title="'.$str->move.'" href="'.$path.'/mod.php?copy='.$mod->id.
2317 '&amp;sesskey='.$sesskey.$section.'"><img'.
2318 ' src="'.$CFG->pixpath.'/t/move.gif" class="iconsmall" '.
2319 ' alt="'.$str->move.'" /></a>'."\n";
2320 } else {
2321 $move = '<a class="editing_moveup" title="'.$str->moveup.'" href="'.$path.'/mod.php?id='.$mod->id.
2322 '&amp;move=-1&amp;sesskey='.$sesskey.$section.'"><img'.
2323 ' src="'.$CFG->pixpath.'/t/up.gif" class="iconsmall" '.
2324 ' alt="'.$str->moveup.'" /></a>'."\n".
2325 '<a class="editing_movedown" title="'.$str->movedown.'" href="'.$path.'/mod.php?id='.$mod->id.
2326 '&amp;move=1&amp;sesskey='.$sesskey.$section.'"><img'.
2327 ' src="'.$CFG->pixpath.'/t/down.gif" class="iconsmall" '.
2328 ' alt="'.$str->movedown.'" /></a>'."\n";
2330 } else {
2331 $move = '';
2334 $leftright = '';
2335 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $mod->course))) {
2337 if (right_to_left()) { // Exchange arrows on RTL
2338 $rightarrow = 'left.gif';
2339 $leftarrow = 'right.gif';
2340 } else {
2341 $rightarrow = 'right.gif';
2342 $leftarrow = 'left.gif';
2345 if ($indent > 0) {
2346 $leftright .= '<a class="editing_moveleft" title="'.$str->moveleft.'" href="'.$path.'/mod.php?id='.$mod->id.
2347 '&amp;indent=-1&amp;sesskey='.$sesskey.$section.'"><img'.
2348 ' src="'.$CFG->pixpath.'/t/'.$leftarrow.'" class="iconsmall" '.
2349 ' alt="'.$str->moveleft.'" /></a>'."\n";
2351 if ($indent >= 0) {
2352 $leftright .= '<a class="editing_moveright" title="'.$str->moveright.'" href="'.$path.'/mod.php?id='.$mod->id.
2353 '&amp;indent=1&amp;sesskey='.$sesskey.$section.'"><img'.
2354 ' src="'.$CFG->pixpath.'/t/'.$rightarrow.'" class="iconsmall" '.
2355 ' alt="'.$str->moveright.'" /></a>'."\n";
2359 return '<span class="commands">'."\n".$leftright.$move.
2360 '<a class="editing_update" title="'.$str->update.'" href="'.$path.'/mod.php?update='.$mod->id.
2361 '&amp;sesskey='.$sesskey.$section.'"><img'.
2362 ' src="'.$CFG->pixpath.'/t/edit.gif" class="iconsmall" '.
2363 ' alt="'.$str->update.'" /></a>'."\n".
2364 '<a class="editing_delete" title="'.$str->delete.'" href="'.$path.'/mod.php?delete='.$mod->id.
2365 '&amp;sesskey='.$sesskey.$section.'"><img'.
2366 ' src="'.$CFG->pixpath.'/t/delete.gif" class="iconsmall" '.
2367 ' alt="'.$str->delete.'" /></a>'."\n".$hideshow.$groupmode."\n".'</span>';
2371 * given a course object with shortname & fullname, this function will
2372 * truncate the the number of chars allowed and add ... if it was too long
2374 function course_format_name ($course,$max=100) {
2376 $str = $course->shortname.': '. $course->fullname;
2377 if (strlen($str) <= $max) {
2378 return $str;
2380 else {
2381 return substr($str,0,$max-3).'...';
2386 * This function will return true if the given course is a child course at all
2388 function course_in_meta ($course) {
2389 return record_exists("course_meta","child_course",$course->id);
2394 * Print standard form elements on module setup forms in mod/.../mod.html
2396 function print_standard_coursemodule_settings($form) {
2397 if (! $course = get_record('course', 'id', $form->course)) {
2398 error("This course doesn't exist");
2400 print_groupmode_setting($form, $course);
2401 print_visible_setting($form, $course);
2405 * Print groupmode form element on module setup forms in mod/.../mod.html
2407 function print_groupmode_setting($form, $course=NULL) {
2409 if (empty($course)) {
2410 if (! $course = get_record('course', 'id', $form->course)) {
2411 error("This course doesn't exist");
2414 if ($form->coursemodule) {
2415 if (! $cm = get_record('course_modules', 'id', $form->coursemodule)) {
2416 error("This course module doesn't exist");
2418 } else {
2419 $cm = null;
2421 $groupmode = groupmode($course, $cm);
2422 if ($course->groupmode or (!$course->groupmodeforce)) {
2423 echo '<tr valign="top">';
2424 echo '<td align="right"><b>'.get_string('groupmode').':</b></td>';
2425 echo '<td align="left">';
2426 unset($choices);
2427 $choices[NOGROUPS] = get_string('groupsnone');
2428 $choices[SEPARATEGROUPS] = get_string('groupsseparate');
2429 $choices[VISIBLEGROUPS] = get_string('groupsvisible');
2430 choose_from_menu($choices, 'groupmode', $groupmode, '', '', 0, false, $course->groupmodeforce);
2431 helpbutton('groupmode', get_string('groupmode'));
2432 echo '</td></tr>';
2437 * Print visibility setting form element on module setup forms in mod/.../mod.html
2439 function print_visible_setting($form, $course=NULL) {
2440 if (empty($course)) {
2441 if (! $course = get_record('course', 'id', $form->course)) {
2442 error("This course doesn't exist");
2445 if ($form->coursemodule) {
2446 $visible = get_field('course_modules', 'visible', 'id', $form->coursemodule);
2447 } else {
2448 $visible = true;
2451 if ($form->mode == 'add') { // in this case $form->section is the section number, not the id
2452 $hiddensection = !get_field('course_sections', 'visible', 'section', $form->section, 'course', $form->course);
2453 } else {
2454 $hiddensection = !get_field('course_sections', 'visible', 'id', $form->section);
2456 if ($hiddensection) {
2457 $visible = false;
2460 echo '<tr valign="top">';
2461 echo '<td align="right"><b>'.get_string('visible', '').':</b></td>';
2462 echo '<td align="left">';
2463 unset($choices);
2464 $choices[1] = get_string('show');
2465 $choices[0] = get_string('hide');
2466 choose_from_menu($choices, 'visible', $visible, '', '', 0, false, $hiddensection);
2467 echo '</td></tr>';
2470 function update_restricted_mods($course,$mods) {
2471 delete_records("course_allowed_modules","course",$course->id);
2472 if (empty($course->restrictmodules)) {
2473 return;
2475 else {
2476 foreach ($mods as $mod) {
2477 if ($mod == 0)
2478 continue; // this is the 'allow none' option
2479 $am->course = $course->id;
2480 $am->module = $mod;
2481 insert_record("course_allowed_modules",$am);
2487 * This function will take an int (module id) or a string (module name)
2488 * and return true or false, whether it's allowed in the given course (object)
2489 * $mod is not allowed to be an object, as the field for the module id is inconsistent
2490 * depending on where in the code it's called from (sometimes $mod->id, sometimes $mod->module)
2493 function course_allowed_module($course,$mod) {
2494 if (empty($course->restrictmodules)) {
2495 return true;
2498 // i am not sure this capability is correct
2499 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
2500 return true;
2502 if (is_numeric($mod)) {
2503 $modid = $mod;
2504 } else if (is_string($mod)) {
2505 if ($mod = get_field("modules","id","name",$mod))
2506 $modid = $mod;
2508 if (empty($modid)) {
2509 return false;
2511 return (record_exists("course_allowed_modules","course",$course->id,"module",$modid));
2514 /***
2515 *** Efficiently moves many courses around while maintaining
2516 *** sortorder in order.
2518 *** $courseids is an array of course ids
2522 function move_courses ($courseids, $categoryid) {
2524 global $CFG;
2526 if (!empty($courseids)) {
2528 $courseids = array_reverse($courseids);
2530 foreach ($courseids as $courseid) {
2532 if (! $course = get_record("course", "id", $courseid)) {
2533 notify("Error finding course $courseid");
2534 } else {
2535 // figure out a sortorder that we can use in the destination category
2536 $sortorder = get_field_sql('SELECT MIN(sortorder)-1 AS min
2537 FROM ' . $CFG->prefix . 'course WHERE category=' . $categoryid);
2538 if ($sortorder === false) {
2539 // the category is empty
2540 // rather than let the db default to 0
2541 // set it to > 100 and avoid extra work in fix_coursesortorder()
2542 $sortorder = 200;
2543 } else if ($sortorder < 10) {
2544 fix_course_sortorder($categoryid);
2547 $course->category = $categoryid;
2548 $course->sortorder = $sortorder;
2549 $course->fullname = addslashes($course->fullname);
2550 $course->shortname = addslashes($course->shortname);
2551 $course->summary = addslashes($course->summary);
2552 $course->password = addslashes($course->password);
2553 $course->teacher = addslashes($course->teacher);
2554 $course->teachers = addslashes($course->teachers);
2555 $course->student = addslashes($course->student);
2556 $course->students = addslashes($course->students);
2558 if (!update_record('course', $course)) {
2559 notify("An error occurred - course not moved!");
2561 // parents changed (course category)
2562 // rebuild this context and all children
2563 rebuild_context_rel(get_context_instance(CONTEXT_COURSE, $course->id));
2566 fix_course_sortorder();
2568 return true;
2572 * @param string $format Course format ID e.g. 'weeks'
2573 * @return Name that the course format prefers for sections
2575 function get_section_name($format) {
2576 $sectionname = get_string("name$format","format_$format");
2577 if($sectionname == "[[name$format]]") {
2578 $sectionname = get_string("name$format");
2580 return $sectionname;
2584 * Can the current user delete this course?
2585 * @param int $courseid
2586 * @return boolean
2588 * Exception here to fix MDL-7796.
2590 * FIXME
2591 * Course creators who can manage activities in the course
2592 * shoule be allowed to delete the course. We do it this
2593 * way because we need a quick fix to bring the functionality
2594 * in line with what we had pre-roles. We can't give the
2595 * default course creator role moodle/course:delete at
2596 * CONTEXT_SYSTEM level because this will allow them to
2597 * delete any course in the site. So we hard code this here
2598 * for now.
2600 * @author vyshane AT gmail.com
2602 function can_delete_course($courseid) {
2604 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2606 return ( has_capability('moodle/course:delete', $context)
2607 || (has_capability('moodle/legacy:coursecreator', $context)
2608 && has_capability('moodle/course:manageactivities', $context)) );
2613 * Create a course and either return a $course object or false
2615 * @param object $data - all the data needed for an entry in the 'course' table
2617 function create_course($data) {
2618 global $CFG, $USER;
2620 // preprocess allowed mods
2621 $allowedmods = empty($data->allowedmods) ? array() : $data->allowedmods;
2622 unset($data->allowedmods);
2623 if (!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
2624 if ($CFG->restrictmodulesfor == 'all') {
2625 $data->restrictmodules = 1;
2626 } else {
2627 $data->restrictmodules = 0;
2631 $data->timecreated = time();
2633 // place at beginning of category
2634 fix_course_sortorder();
2635 $data->sortorder = get_field_sql("SELECT min(sortorder)-1 FROM {$CFG->prefix}course WHERE category=$data->category");
2636 if (empty($data->sortorder)) {
2637 $data->sortorder = 100;
2640 if ($newcourseid = insert_record('course', $data)) { // Set up new course
2642 $course = get_record('course', 'id', $newcourseid);
2644 // Setup the blocks
2645 $page = page_create_object(PAGE_COURSE_VIEW, $course->id);
2646 blocks_repopulate_page($page); // Return value not checked because you can always edit later
2648 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
2649 update_restricted_mods($course, $allowedmods);
2652 $section = new object();
2653 $section->course = $course->id; // Create a default section.
2654 $section->section = 0;
2655 $section->id = insert_record('course_sections', $section);
2657 fix_course_sortorder();
2659 add_to_log(SITEID, 'course', 'new', 'view.php?id='.$course->id, $data->fullname.' (ID '.$course->id.')');
2661 return $course;
2664 return false; // error
2669 * Update a course and return true or false
2671 * @param object $data - all the data needed for an entry in the 'course' table
2673 function update_course($data) {
2674 global $USER, $CFG;
2676 // preprocess allowed mods
2677 $allowedmods = empty($data->allowedmods) ? array() : $data->allowedmods;
2678 unset($data->allowedmods);
2679 if (!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
2680 unset($data->restrictmodules);
2683 $oldcourse = get_record('course', 'id', $data->id); // should not fail, already tested above
2684 if (!has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $oldcourse->category))
2685 or !has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $data->category))) {
2686 // can not move to new category, keep the old one
2687 unset($data->category);
2690 // Update with the new data
2691 if (update_record('course', $data)) {
2693 $course = get_record('course', 'id', $data->id);
2695 add_to_log($course->id, "course", "update", "edit.php?id=$course->id", $course->id);
2697 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
2698 update_restricted_mods($course, $allowedmods);
2701 fix_course_sortorder();
2703 // Test for and remove blocks which aren't appropriate anymore
2704 $page = page_create_object(PAGE_COURSE_VIEW, $course->id);
2705 blocks_remove_inappropriate($page);
2707 // put custom role names into db
2708 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2710 foreach ($data as $dname => $dvalue) {
2712 // is this the right param?
2713 $dvalue = clean_param($dvalue, PARAM_NOTAGS);
2715 if (!strstr($dname, 'role_')) {
2716 continue;
2719 $dt = explode('_', $dname);
2720 $roleid = $dt[1];
2721 // make up our mind whether we want to delete, update or insert
2723 if (empty($dvalue)) {
2725 delete_records('role_names', 'contextid', $context->id, 'roleid', $roleid);
2727 } else if ($t = get_record('role_names', 'contextid', $context->id, 'roleid', $roleid)) {
2729 $t->text = $dvalue;
2730 update_record('role_names', $t);
2732 } else {
2734 $t->contextid = $context->id;
2735 $t->roleid = $roleid;
2736 $t->text = $dvalue;
2737 insert_record('role_names', $t);
2742 return true;
2746 return false;