Fixes bug MDL-8234, "New groups code & AS keyword"
[moodle-pu.git] / course / lib.php
blobb796f34761aefebb45df26b2ea7e3f290338e76d
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 'blog':
247 return "/$module/$url";
248 break;
249 case 'upload':
250 return $url;
251 break;
252 case 'library':
253 case '':
254 return '/';
255 break;
256 default:
257 return "/mod/$module/$url";
258 break;
263 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
264 $modname="", $modid=0, $modaction="", $groupid=0) {
266 global $CFG;
268 // It is assumed that $date is the GMT time of midnight for that day,
269 // and so the next 86400 seconds worth of logs are printed.
271 /// Setup for group handling.
273 // TODO: I don't understand group/context/etc. enough to be able to do
274 // something interesting with it here
275 // What is the context of a remote course?
277 /// If the group mode is separate, and this user does not have editing privileges,
278 /// then only the user's group can be viewed.
279 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
280 // $groupid = get_current_group($course->id);
282 /// If this course doesn't have groups, no groupid can be specified.
283 //else if (!$course->groupmode) {
284 // $groupid = 0;
286 $groupid = 0;
288 $joins = array();
290 $qry = "
291 SELECT
292 l.*,
293 u.firstname,
294 u.lastname,
295 u.picture
296 FROM
297 {$CFG->prefix}mnet_log l
298 LEFT JOIN
299 {$CFG->prefix}user u
301 l.userid = u.id
302 WHERE
305 $where .= "l.hostid = '$hostid'";
307 // TODO: Is 1 really a magic number referring to the sitename?
308 if ($course != 1 || $modid != 0) {
309 $where .= " AND\n l.course='$course'";
312 if ($modname) {
313 $where .= " AND\n l.module = '$modname'";
316 if ('site_errors' === $modid) {
317 $where .= " AND\n ( l.action='error' OR l.action='infected' )";
318 } else if ($modid) {
319 //TODO: This assumes that modids are the same across sites... probably
320 //not true
321 $where .= " AND\n l.cmid = '$modid'";
324 if ($modaction) {
325 $firstletter = substr($modaction, 0, 1);
326 if (ctype_alpha($firstletter)) {
327 $where .= " AND\n lower(l.action) LIKE '%" . strtolower($modaction) . "%'";
328 } else if ($firstletter == '-') {
329 $where .= " AND\n lower(l.action) NOT LIKE '%" . strtolower(substr($modaction, 1)) . "%'";
333 if ($user) {
334 $where .= " AND\n l.userid = '$user'";
337 if ($date) {
338 $enddate = $date + 86400;
339 $where .= " AND\n l.time > '$date' AND l.time < '$enddate'";
342 $result = array();
343 $result['totalcount'] = count_records_sql("SELECT COUNT(*) FROM {$CFG->prefix}mnet_log l WHERE $where");
344 if(!empty($result['totalcount'])) {
345 $where .= "\n ORDER BY\n $order";
346 $result['logs'] = get_records_sql($qry.$where, $limitfrom, $limitnum);
347 } else {
348 $result['logs'] = array();
350 return $result;
353 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
354 $modname="", $modid=0, $modaction="", $groupid=0) {
356 // It is assumed that $date is the GMT time of midnight for that day,
357 // and so the next 86400 seconds worth of logs are printed.
359 /// Setup for group handling.
361 /// If the group mode is separate, and this user does not have editing privileges,
362 /// then only the user's group can be viewed.
363 if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
364 $groupid = get_current_group($course->id);
366 /// If this course doesn't have groups, no groupid can be specified.
367 else if (!$course->groupmode) {
368 $groupid = 0;
371 $joins = array();
373 if ($course->id != SITEID || $modid != 0) {
374 $joins[] = "l.course='$course->id'";
377 if ($modname) {
378 $joins[] = "l.module = '$modname'";
381 if ('site_errors' === $modid) {
382 $joins[] = "( l.action='error' OR l.action='infected' )";
383 } else if ($modid) {
384 $joins[] = "l.cmid = '$modid'";
387 if ($modaction) {
388 $firstletter = substr($modaction, 0, 1);
389 if (ctype_alpha($firstletter)) {
390 $joins[] = "lower(l.action) LIKE '%" . strtolower($modaction) . "%'";
391 } else if ($firstletter == '-') {
392 $joins[] = "lower(l.action) NOT LIKE '%" . strtolower(substr($modaction, 1)) . "%'";
396 /// Getting all members of a group.
397 if ($groupid and !$user) {
398 if ($gusers = groups_get_members($groupid)) { //TODO:check.
399 $first = true;
400 foreach($gusers as $guser) {
401 if ($first) {
402 $gselect = '(l.userid='.$guser->userid;
403 $first = false;
405 else {
406 $gselect .= ' OR l.userid='.$guser->userid;
409 if (!$first) $gselect .= ')';
410 $joins[] = $gselect;
413 else if ($user) {
414 $joins[] = "l.userid = '$user'";
417 if ($date) {
418 $enddate = $date + 86400;
419 $joins[] = "l.time > '$date' AND l.time < '$enddate'";
422 $selector = '';
423 for ($i = 0; $i < count($joins); $i++) {
424 $selector .= $joins[$i] . (($i == count($joins)-1) ? " " : " AND ");
427 $totalcount = 0; // Initialise
429 $result = array();
430 $result['logs'] = get_logs($selector, $order, $limitfrom, $limitnum, $totalcount);
431 $result['totalcount'] = $totalcount;
432 return $result;
436 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
437 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
439 global $CFG;
441 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
442 $modname, $modid, $modaction, $groupid)) {
443 notify("No logs found!");
444 print_footer($course);
445 exit;
448 $courses = array();
450 if ($course->id == SITEID) {
451 $courses[0] = '';
452 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
453 foreach ($ccc as $cc) {
454 $courses[$cc->id] = $cc->shortname;
457 } else {
458 $courses[$course->id] = $course->shortname;
461 $totalcount = $logs['totalcount'];
462 $count=0;
463 $ldcache = array();
464 $tt = getdate(time());
465 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
467 $strftimedatetime = get_string("strftimedatetime");
469 echo "<div class=\"info\">\n";
470 print_string("displayingrecords", "", $totalcount);
471 echo "</div>\n";
473 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
475 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\" summary=\"\">\n";
476 echo "<tr>";
477 if ($course->id == SITEID) {
478 echo "<th class=\"c0 header\" scope=\"col\">".get_string('course')."</th>\n";
480 echo "<th class=\"c1 header\" scope=\"col\">".get_string('time')."</th>\n";
481 echo "<th class=\"c2 header\" scope=\"col\">".get_string('ip_address')."</th>\n";
482 echo "<th class=\"c3 header\" scope=\"col\">".get_string('fullname')."</th>\n";
483 echo "<th class=\"c4 header\" scope=\"col\">".get_string('action')."</th>\n";
484 echo "<th class=\"c5 header\" scope=\"col\">".get_string('info')."</th>\n";
485 echo "</tr>\n";
487 if (empty($logs['logs'])) {
488 echo "</table>\n";
489 return;
492 $row = 1;
493 foreach ($logs['logs'] as $log) {
495 $row = ($row + 1) % 2;
497 if (isset($ldcache[$log->module][$log->action])) {
498 $ld = $ldcache[$log->module][$log->action];
499 } else {
500 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
501 $ldcache[$log->module][$log->action] = $ld;
503 if ($ld && !empty($log->info)) {
504 // ugly hack to make sure fullname is shown correctly
505 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
506 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
507 } else {
508 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
512 //Filter log->info
513 $log->info = format_string($log->info);
515 $log->url = strip_tags(urldecode($log->url)); // Some XSS protection
516 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
517 $log->url = str_replace('&', '&amp;', $log->url); /// XHTML compatibility
519 echo '<tr class="r'.$row.'">';
520 if ($course->id == SITEID) {
521 echo "<td class=\"r$row c0\">\n";
522 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courses[$log->course]."</a>\n";
523 echo "</td>\n";
525 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time, '%a').
526 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
527 echo "<td class=\"r$row 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=\"r$row 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=\"r$row 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=\"r$row 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="'.$course->fullname.'" '.$linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.$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 echo '<li class="activity '.$mod->modname.'" id="module-'.$modnumber.'">'; // Unique ID
1346 if ($ismoving) {
1347 if ($mod->id == $USER->activitycopy) {
1348 continue;
1350 echo '<a title="'.$strmovefull.'"'.
1351 ' href="'.$CFG->wwwroot.'/course/mod.php?moveto='.$mod->id.'&amp;sesskey='.$USER->sesskey.'">'.
1352 '<img class="movetarget" src="'.$CFG->pixpath.'/movehere.gif" '.
1353 ' alt="'.$strmovehere.'" /></a><br />
1356 $instancename = urldecode($modinfo[$modnumber]->name);
1357 $instancename = format_string($instancename, true, $course->id);
1359 if (!empty($modinfo[$modnumber]->extra)) {
1360 $extra = urldecode($modinfo[$modnumber]->extra);
1361 } else {
1362 $extra = "";
1365 if (!empty($modinfo[$modnumber]->icon)) {
1366 $icon = "$CFG->pixpath/".urldecode($modinfo[$modnumber]->icon);
1367 } else {
1368 $icon = "$CFG->modpixpath/$mod->modname/icon.gif";
1371 if ($mod->indent) {
1372 print_spacer(12, 20 * $mod->indent, false);
1375 if ($mod->modname == "label") {
1376 if (!$mod->visible) {
1377 echo "<span class=\"dimmed_text\">";
1379 echo format_text($extra, FORMAT_HTML, $labelformatoptions);
1380 if (!$mod->visible) {
1381 echo "</span>";
1384 } else { // Normal activity
1386 if (!empty($USER->screenreader)) {
1387 $typestring = '('.get_string('modulename',$mod->modname).') ';
1388 } else {
1389 $typestring = '';
1392 $linkcss = $mod->visible ? "" : " class=\"dimmed\" ";
1393 echo '<img src="'.$icon.'"'.
1394 ' class="activityicon" alt="'.$mod->modfullname.'" />'.
1395 ' <a title="'.$mod->modfullname.'" '.$linkcss.' '.$extra.
1396 ' href="'.$CFG->wwwroot.'/mod/'.$mod->modname.'/view.php?id='.$mod->id.'">'.
1397 $typestring.$instancename.'</a>';
1399 if ($usetracking && $mod->modname == 'forum') {
1400 $groupmode = groupmode($course, $mod);
1401 $groupid = ($groupmode == SEPARATEGROUPS && !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) ?
1402 get_current_group($course->id) : false;
1404 if (forum_tp_can_track_forums() && !isset($untracked[$mod->instance])) {
1405 $unread = forum_tp_count_forum_unread_posts($USER->id, $mod->instance, $groupid);
1406 if ($unread) {
1407 echo '<span class="unread"> <a href="'.$CFG->wwwroot.'/mod/forum/view.php?id='.$mod->id.'">';
1408 if ($unread == 1) {
1409 echo $strunreadpostsone;
1410 } else {
1411 print_string('unreadpostsnumber', 'forum', $unread);
1413 echo '</a> </span>';
1418 if ($isediting) {
1419 if ($groupbuttons and $mod->modname != 'label' and $mod->modname != 'resource') {
1420 if (! $mod->groupmodelink = $groupbuttonslink) {
1421 $mod->groupmode = $course->groupmode;
1424 } else {
1425 $mod->groupmode = false;
1427 echo '&nbsp;&nbsp;';
1428 echo make_editing_buttons($mod, $absolute, true, $mod->indent, $section->section);
1430 echo "</li>\n";
1433 } elseif ($ismoving) {
1434 echo "<ul class=\"section\">\n";
1436 if ($ismoving) {
1437 echo '<li><a title="'.$strmovefull.'"'.
1438 ' href="'.$CFG->wwwroot.'/course/mod.php?movetosection='.$section->id.'&amp;sesskey='.$USER->sesskey.'">'.
1439 '<img class="movetarget" src="'.$CFG->pixpath.'/movehere.gif" '.
1440 ' alt="'.$strmovehere.'" /></a></li>
1443 if (!empty($section->sequence) || $ismoving) {
1444 echo "</ul><!--class='section'-->\n\n";
1449 * Prints the menus to add activities and resources.
1451 function print_section_add_menus($course, $section, $modnames, $vertical=false, $return=false) {
1452 global $CFG;
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 '$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.' / '.$category->name;
1555 } else {
1556 $path = $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">'.$catimage.'</td>';
1674 echo '<td valign="top" class="category name">';
1675 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot.'/course/category.php?id='.$category->id.'">'.$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.'">'.$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.'">'.$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, $width="100%", $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 (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, $width);
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, $width="100%") {
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 $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 foreach ($coursemanagerroles as $roleid) {
1794 $role = get_record('role','id',$roleid);
1795 if ($users = get_role_users($roleid, $context, true, '', 'u.lastname ASC', true)) {
1796 foreach ($users as $teacher) {
1797 $fullname = fullname($teacher, has_capability('moodle/site:viewfullnames', $context));
1798 $namesarray[] = format_string($role->name).': <a href="'.$CFG->wwwroot.'/user/view.php?id='.
1799 $teacher->id.'&amp;course='.SITEID.'">'.$fullname.'</a>';
1804 if (!empty($namesarray)) {
1805 echo "<ul class=\"teachers\">\n<li>";
1806 echo implode('</li><li>', $namesarray);
1807 echo "</li></ul>";
1811 require_once("$CFG->dirroot/enrol/enrol.class.php");
1812 $enrol = enrolment_factory::factory($course->enrol);
1813 echo $enrol->get_access_icons($course);
1815 echo '</div><div class="summary">';
1816 $options = NULL;
1817 $options->noclean = true;
1818 $options->para = false;
1819 echo format_text($course->summary, FORMAT_MOODLE, $options, $course->id);
1820 echo '</div>';
1821 echo '</div>';
1822 echo '<div class="clearer"></div>';
1826 function print_my_moodle() {
1827 /// Prints custom user information on the home page.
1828 /// Over time this can include all sorts of information
1830 global $USER, $CFG;
1832 if (empty($USER->id)) {
1833 error("It shouldn't be possible to see My Moodle without being logged in.");
1836 $courses = get_my_courses($USER->id);
1837 $rhosts = array();
1838 $rcourses = array();
1839 if ($CFG->mnet_dispatcher_mode === 'strict') {
1840 $rcourses = get_my_remotecourses($USER->id);
1841 $rhosts = get_my_remotehosts();
1844 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
1846 if (!empty($courses)) {
1847 foreach ($courses as $course) {
1848 if ($course->id == SITEID) {
1849 continue;
1851 print_course($course, "100%");
1855 // MNET
1856 if (!empty($rcourses)) {
1857 // at the IDP, we know of all the remote courses
1858 foreach ($rcourses as $course) {
1859 print_remote_course($course, "100%");
1861 } elseif (!empty($rhosts)) {
1862 // non-IDP, we know of all the remote servers, but not courses
1863 foreach ($rhosts as $host) {
1864 print_remote_host($host, "100%");
1867 unset($course);
1868 unset($host);
1870 if (count_records("course") > (count($courses) + 1) ) { // Some courses not being displayed
1871 echo "<table width=\"100%\"><tr><td align=\"center\">";
1872 print_course_search("", false, "short");
1873 echo "</td><td align=\"center\">";
1874 print_single_button("$CFG->wwwroot/course/index.php", NULL, get_string("fulllistofcourses"), "get");
1875 echo "</td></tr></table>\n";
1878 } else {
1879 if (count_records("course_categories") > 1) {
1880 print_simple_box_start("center", "100%", "#FFFFFF", 5, "categorybox");
1881 print_whole_category_list();
1882 print_simple_box_end();
1883 } else {
1884 print_courses(0, "100%");
1890 function print_course_search($value="", $return=false, $format="plain") {
1892 global $CFG;
1894 $strsearchcourses= get_string("searchcourses");
1896 if ($format == 'plain') {
1897 $output = '<form id="coursesearch" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
1898 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
1899 $output .= '<input type="text" size="30" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
1900 $output .= '<input type="submit" value="'.s($strsearchcourses).'" />';
1901 $output .= '</fieldset></form>';
1902 } else if ($format == 'short') {
1903 $output = '<form id="coursesearch" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
1904 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
1905 $output .= '<input type="text" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
1906 $output .= '<input type="submit" value="'.s($strsearchcourses).'" />';
1907 $output .= '</fieldset></form>';
1908 } else if ($format == 'navbar') {
1909 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
1910 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
1911 $output .= '<input type="text" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
1912 $output .= '<input type="submit" value="'.s($strsearchcourses).'" />';
1913 $output .= '</fieldset></form>';
1916 if ($return) {
1917 return $output;
1919 echo $output;
1922 function print_remote_course($course, $width="100%") {
1924 global $CFG, $USER;
1926 $linkcss = '';
1928 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&amp;wantsurl=/course/view.php?id={$course->remoteid}";
1930 echo '<div class="coursebox remotecoursebox">';
1931 echo '<div class="info">';
1932 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
1933 $linkcss.' href="'.$url.'">'
1934 . s($course->fullname) .'</a><br />'
1935 . s($course->hostname) . ' : '
1936 . s($course->cat_name) . ' : '
1937 . s($course->shortname). '</div>';
1938 echo '</div><div class="summary">';
1939 $options = NULL;
1940 $options->noclean = true;
1941 $options->para = false;
1942 echo format_text($course->summary, FORMAT_MOODLE, $options);
1943 echo '</div>';
1944 echo '</div>';
1945 echo '<div class="clearer"></div>';
1948 function print_remote_host($host, $width="100%") {
1950 global $CFG, $USER;
1952 $linkcss = '';
1954 echo '<div class="coursebox">';
1955 echo '<div class="info">';
1956 echo '<div class="name">';
1957 echo '<img src="'.$CFG->pixpath.'/i/mnethost.gif" class="icon" alt="'.get_string('course').'" />';
1958 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
1959 . s($host['name']).'</a> - ';
1960 echo $host['count'] . ' ' . get_string('courses');
1961 echo '</div>';
1962 echo '</div>';
1963 echo '</div>';
1964 echo '<div class="clearer"></div>';
1968 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
1970 function add_course_module($mod) {
1972 $mod->added = time();
1973 unset($mod->id);
1975 return insert_record("course_modules", $mod);
1978 function add_mod_to_section($mod, $beforemod=NULL) {
1979 /// Given a full mod object with section and course already defined
1980 /// If $before is specified, then this is an existing ID which we
1981 /// will insert the new module before
1983 /// Returns the course_sections ID where the mod is inserted
1985 if ($section = get_record("course_sections", "course", "$mod->course", "section", "$mod->section")) {
1987 $section->sequence = trim($section->sequence);
1989 if (empty($section->sequence)) {
1990 $newsequence = "$mod->coursemodule";
1992 } else if ($beforemod) {
1993 $modarray = explode(",", $section->sequence);
1995 if ($key = array_keys ($modarray, $beforemod->id)) {
1996 $insertarray = array($mod->id, $beforemod->id);
1997 array_splice($modarray, $key[0], 1, $insertarray);
1998 $newsequence = implode(",", $modarray);
2000 } else { // Just tack it on the end anyway
2001 $newsequence = "$section->sequence,$mod->coursemodule";
2004 } else {
2005 $newsequence = "$section->sequence,$mod->coursemodule";
2008 if (set_field("course_sections", "sequence", $newsequence, "id", $section->id)) {
2009 return $section->id; // Return course_sections ID that was used.
2010 } else {
2011 return 0;
2014 } else { // Insert a new record
2015 $section->course = $mod->course;
2016 $section->section = $mod->section;
2017 $section->summary = "";
2018 $section->sequence = $mod->coursemodule;
2019 return insert_record("course_sections", $section);
2023 function set_coursemodule_groupmode($id, $groupmode) {
2024 return set_field("course_modules", "groupmode", $groupmode, "id", $id);
2028 * $prevstateoverrides = true will set the visibility of the course module
2029 * to what is defined in visibleold. This enables us to remember the current
2030 * visibility when making a whole section hidden, so that when we toggle
2031 * that section back to visible, we are able to return the visibility of
2032 * the course module back to what it was originally.
2034 function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
2035 if (!$cm = get_record('course_modules', 'id', $id)) {
2036 return false;
2038 if (!$modulename = get_field('modules', 'name', 'id', $cm->module)) {
2039 return false;
2041 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
2042 foreach($events as $event) {
2043 if ($visible) {
2044 show_event($event);
2045 } else {
2046 hide_event($event);
2050 if ($prevstateoverrides) {
2051 if ($visible == '0') {
2052 // Remember the current visible state so we can toggle this back.
2053 set_field('course_modules', 'visibleold', $cm->visible, 'id', $id);
2054 } else {
2055 // Get the previous saved visible states.
2056 return set_field('course_modules', 'visible', $cm->visibleold, 'id', $id);
2059 return set_field("course_modules", "visible", $visible, "id", $id);
2063 * Delete a course module and any associated data at the course level (events)
2064 * Until 1.5 this function simply marked a deleted flag ... now it
2065 * deletes it completely.
2068 function delete_course_module($id) {
2069 if (!$cm = get_record('course_modules', 'id', $id)) {
2070 return true;
2072 $modulename = get_field('modules', 'name', 'id', $cm->module);
2073 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
2074 foreach($events as $event) {
2075 delete_event($event);
2078 return delete_records('course_modules', 'id', $cm->id);
2081 function delete_mod_from_section($mod, $section) {
2083 if ($section = get_record("course_sections", "id", "$section") ) {
2085 $modarray = explode(",", $section->sequence);
2087 if ($key = array_keys ($modarray, $mod)) {
2088 array_splice($modarray, $key[0], 1);
2089 $newsequence = implode(",", $modarray);
2090 return set_field("course_sections", "sequence", $newsequence, "id", $section->id);
2091 } else {
2092 return false;
2096 return false;
2099 function move_section($course, $section, $move) {
2100 /// Moves a whole course section up and down within the course
2101 global $USER;
2103 if (!$move) {
2104 return true;
2107 $sectiondest = $section + $move;
2109 if ($sectiondest > $course->numsections or $sectiondest < 1) {
2110 return false;
2113 if (!$sectionrecord = get_record("course_sections", "course", $course->id, "section", $section)) {
2114 return false;
2117 if (!$sectiondestrecord = get_record("course_sections", "course", $course->id, "section", $sectiondest)) {
2118 return false;
2121 if (!set_field("course_sections", "section", $sectiondest, "id", $sectionrecord->id)) {
2122 return false;
2124 if (!set_field("course_sections", "section", $section, "id", $sectiondestrecord->id)) {
2125 return false;
2127 // if the focus is on the section that is being moved, then move the focus along
2128 if (isset($USER->display[$course->id]) and ($USER->display[$course->id] == $section)) {
2129 course_set_display($course->id, $sectiondest);
2132 // Check for duplicates and fix order if needed.
2133 // There is a very rare case that some sections in the same course have the same section id.
2134 $sections = get_records_select('course_sections', "course = $course->id", 'section ASC');
2135 $n = 0;
2136 foreach ($sections as $section) {
2137 if ($section->section != $n) {
2138 if (!set_field('course_sections', 'section', $n, 'id', $section->id)) {
2139 return false;
2142 $n++;
2144 return true;
2148 function moveto_module($mod, $section, $beforemod=NULL) {
2149 /// All parameters are objects
2150 /// Move the module object $mod to the specified $section
2151 /// If $beforemod exists then that is the module
2152 /// before which $modid should be inserted
2154 /// Remove original module from original section
2156 if (! delete_mod_from_section($mod->id, $mod->section)) {
2157 notify("Could not delete module from existing section");
2160 /// Update module itself if necessary
2162 if ($mod->section != $section->id) {
2163 $mod->section = $section->id;
2164 if (!update_record("course_modules", $mod)) {
2165 return false;
2167 // if moving to a hidden section then hide module
2168 if (!$section->visible) {
2169 set_coursemodule_visible($mod->id, 0);
2173 /// Add the module into the new section
2175 $mod->course = $section->course;
2176 $mod->section = $section->section; // need relative reference
2177 $mod->coursemodule = $mod->id;
2179 if (! add_mod_to_section($mod, $beforemod)) {
2180 return false;
2183 return true;
2187 function make_editing_buttons($mod, $absolute=false, $moveselect=true, $indent=-1, $section=-1) {
2188 global $CFG, $USER;
2190 static $str;
2191 static $sesskey;
2193 if (!isset($str)) {
2194 $str->delete = get_string("delete");
2195 $str->move = get_string("move");
2196 $str->moveup = get_string("moveup");
2197 $str->movedown = get_string("movedown");
2198 $str->moveright = get_string("moveright");
2199 $str->moveleft = get_string("moveleft");
2200 $str->update = get_string("update");
2201 $str->duplicate = get_string("duplicate");
2202 $str->hide = get_string("hide");
2203 $str->show = get_string("show");
2204 $str->clicktochange = get_string("clicktochange");
2205 $str->forcedmode = get_string("forcedmode");
2206 $str->groupsnone = get_string("groupsnone");
2207 $str->groupsseparate = get_string("groupsseparate");
2208 $str->groupsvisible = get_string("groupsvisible");
2209 $sesskey = sesskey();
2212 if ($section >= 0) {
2213 $section = '&amp;sr='.$section; // Section return
2214 } else {
2215 $section = '';
2218 if ($absolute) {
2219 $path = $CFG->wwwroot.'/course';
2220 } else {
2221 $path = '.';
2224 if ($mod->visible) {
2225 $hideshow = '<a class="editing_hide" title="'.$str->hide.'" href="'.$path.'/mod.php?hide='.$mod->id.
2226 '&amp;sesskey='.$sesskey.$section.'"><img'.
2227 ' src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" '.
2228 ' alt="'.$str->hide.'" /></a>'."\n";
2229 } else {
2230 $hideshow = '<a class="editing_show" title="'.$str->show.'" href="'.$path.'/mod.php?show='.$mod->id.
2231 '&amp;sesskey='.$sesskey.$section.'"><img'.
2232 ' src="'.$CFG->pixpath.'/t/show.gif" class="iconsmall" '.
2233 ' alt="'.$str->show.'" /></a>'."\n";
2235 if ($mod->groupmode !== false) {
2236 if ($mod->groupmode == SEPARATEGROUPS) {
2237 $grouptitle = $str->groupsseparate;
2238 $groupclass = 'editing_groupseparate';
2239 $groupimage = $CFG->pixpath.'/t/groups.gif';
2240 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=0&amp;sesskey='.$sesskey;
2241 } else if ($mod->groupmode == VISIBLEGROUPS) {
2242 $grouptitle = $str->groupsvisible;
2243 $groupclass = 'editing_groupvisible';
2244 $groupimage = $CFG->pixpath.'/t/groupv.gif';
2245 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=1&amp;sesskey='.$sesskey;
2246 } else {
2247 $grouptitle = $str->groupsnone;
2248 $groupclass = 'editing_groupsnone';
2249 $groupimage = $CFG->pixpath.'/t/groupn.gif';
2250 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=2&amp;sesskey='.$sesskey;
2252 if ($mod->groupmodelink) {
2253 $groupmode = '<a class="'.$groupclass.'" title="'.$grouptitle.' ('.$str->clicktochange.')" href="'.$grouplink.'">'.
2254 '<img src="'.$groupimage.'" class="iconsmall" '.
2255 'alt="'.$grouptitle.'" /></a>';
2256 } else {
2257 $groupmode = '<img title="'.$grouptitle.' ('.$str->forcedmode.')" '.
2258 ' src="'.$groupimage.'" class="iconsmall" '.
2259 'alt="'.$grouptitle.'" />';
2261 } else {
2262 $groupmode = "";
2265 if ($moveselect) {
2266 $move = '<a class="editing_move" title="'.$str->move.'" href="'.$path.'/mod.php?copy='.$mod->id.
2267 '&amp;sesskey='.$sesskey.$section.'"><img'.
2268 ' src="'.$CFG->pixpath.'/t/move.gif" class="iconsmall" '.
2269 ' alt="'.$str->move.'" /></a>'."\n";
2270 } else {
2271 $move = '<a class="editing_moveup" title="'.$str->moveup.'" href="'.$path.'/mod.php?id='.$mod->id.
2272 '&amp;move=-1&amp;sesskey='.$sesskey.$section.'"><img'.
2273 ' src="'.$CFG->pixpath.'/t/up.gif" class="iconsmall" '.
2274 ' alt="'.$str->moveup.'" /></a>'."\n".
2275 '<a class="editing_movedown" title="'.$str->movedown.'" href="'.$path.'/mod.php?id='.$mod->id.
2276 '&amp;move=1&amp;sesskey='.$sesskey.$section.'"><img'.
2277 ' src="'.$CFG->pixpath.'/t/down.gif" class="iconsmall" '.
2278 ' alt="'.$str->movedown.'" /></a>'."\n";
2281 $leftright = "";
2282 if ($indent > 0) {
2283 $leftright .= '<a class="editing_moveleft" title="'.$str->moveleft.'" href="'.$path.'/mod.php?id='.$mod->id.
2284 '&amp;indent=-1&amp;sesskey='.$sesskey.$section.'"><img'.
2285 ' src="'.$CFG->pixpath.'/t/left.gif" class="iconsmall" '.
2286 ' alt="'.$str->moveleft.'" /></a>'."\n";
2288 if ($indent >= 0) {
2289 $leftright .= '<a class="editing_moveright" title="'.$str->moveright.'" href="'.$path.'/mod.php?id='.$mod->id.
2290 '&amp;indent=1&amp;sesskey='.$sesskey.$section.'"><img'.
2291 ' src="'.$CFG->pixpath.'/t/right.gif" class="iconsmall" '.
2292 ' alt="'.$str->moveright.'" /></a>'."\n";
2295 return '<span class="commands">'."\n".$leftright.$move.
2296 '<a class="editing_update" title="'.$str->update.'" href="'.$path.'/mod.php?update='.$mod->id.
2297 '&amp;sesskey='.$sesskey.$section.'"><img'.
2298 ' src="'.$CFG->pixpath.'/t/edit.gif" class="iconsmall" '.
2299 ' alt="'.$str->update.'" /></a>'."\n".
2300 '<a class="editing_delete" title="'.$str->delete.'" href="'.$path.'/mod.php?delete='.$mod->id.
2301 '&amp;sesskey='.$sesskey.$section.'"><img'.
2302 ' src="'.$CFG->pixpath.'/t/delete.gif" class="iconsmall" '.
2303 ' alt="'.$str->delete.'" /></a>'."\n".$hideshow.$groupmode."\n".'</span>';
2307 * given a course object with shortname & fullname, this function will
2308 * truncate the the number of chars allowed and add ... if it was too long
2310 function course_format_name ($course,$max=100) {
2312 $str = $course->shortname.': '.$course->fullname;
2313 if (strlen($str) <= $max) {
2314 return $str;
2316 else {
2317 return substr($str,0,$max-3).'...';
2322 * This function will return true if the given course is a child course at all
2324 function course_in_meta ($course) {
2325 return record_exists("course_meta","child_course",$course->id);
2330 * Print standard form elements on module setup forms in mod/.../mod.html
2332 function print_standard_coursemodule_settings($form) {
2333 if (! $course = get_record('course', 'id', $form->course)) {
2334 error("This course doesn't exist");
2336 print_groupmode_setting($form, $course);
2337 print_visible_setting($form, $course);
2341 * Print groupmode form element on module setup forms in mod/.../mod.html
2343 function print_groupmode_setting($form, $course=NULL) {
2345 if (empty($course)) {
2346 if (! $course = get_record('course', 'id', $form->course)) {
2347 error("This course doesn't exist");
2350 if ($form->coursemodule) {
2351 if (! $cm = get_record('course_modules', 'id', $form->coursemodule)) {
2352 error("This course module doesn't exist");
2354 } else {
2355 $cm = null;
2357 $groupmode = groupmode($course, $cm);
2358 if ($course->groupmode or (!$course->groupmodeforce)) {
2359 echo '<tr valign="top">';
2360 echo '<td align="right"><b>'.get_string('groupmode').':</b></td>';
2361 echo '<td align="left">';
2362 unset($choices);
2363 $choices[NOGROUPS] = get_string('groupsnone');
2364 $choices[SEPARATEGROUPS] = get_string('groupsseparate');
2365 $choices[VISIBLEGROUPS] = get_string('groupsvisible');
2366 choose_from_menu($choices, 'groupmode', $groupmode, '', '', 0, false, $course->groupmodeforce);
2367 helpbutton('groupmode', get_string('groupmode'));
2368 echo '</td></tr>';
2373 * Print visibility setting form element on module setup forms in mod/.../mod.html
2375 function print_visible_setting($form, $course=NULL) {
2376 if (empty($course)) {
2377 if (! $course = get_record('course', 'id', $form->course)) {
2378 error("This course doesn't exist");
2381 if ($form->coursemodule) {
2382 $visible = get_field('course_modules', 'visible', 'id', $form->coursemodule);
2383 } else {
2384 $visible = true;
2387 if ($form->mode == 'add') { // in this case $form->section is the section number, not the id
2388 $hiddensection = !get_field('course_sections', 'visible', 'section', $form->section, 'course', $form->course);
2389 } else {
2390 $hiddensection = !get_field('course_sections', 'visible', 'id', $form->section);
2392 if ($hiddensection) {
2393 $visible = false;
2396 echo '<tr valign="top">';
2397 echo '<td align="right"><b>'.get_string('visible', '').':</b></td>';
2398 echo '<td align="left">';
2399 unset($choices);
2400 $choices[1] = get_string('show');
2401 $choices[0] = get_string('hide');
2402 choose_from_menu($choices, 'visible', $visible, '', '', 0, false, $hiddensection);
2403 echo '</td></tr>';
2406 function update_restricted_mods($course,$mods) {
2407 delete_records("course_allowed_modules","course",$course->id);
2408 if (empty($course->restrictmodules)) {
2409 return;
2411 else {
2412 foreach ($mods as $mod) {
2413 if ($mod == 0)
2414 continue; // this is the 'allow none' option
2415 $am->course = $course->id;
2416 $am->module = $mod;
2417 insert_record("course_allowed_modules",$am);
2423 * This function will take an int (module id) or a string (module name)
2424 * and return true or false, whether it's allowed in the given course (object)
2425 * $mod is not allowed to be an object, as the field for the module id is inconsistent
2426 * depending on where in the code it's called from (sometimes $mod->id, sometimes $mod->module)
2429 function course_allowed_module($course,$mod) {
2430 if (empty($course->restrictmodules)) {
2431 return true;
2434 // i am not sure this capability is correct
2435 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
2436 return true;
2438 if (is_numeric($mod)) {
2439 $modid = $mod;
2440 } else if (is_string($mod)) {
2441 if ($mod = get_field("modules","id","name",$mod))
2442 $modid = $mod;
2444 if (empty($modid)) {
2445 return false;
2447 return (record_exists("course_allowed_modules","course",$course->id,"module",$modid));
2450 /***
2451 *** Efficiently moves many courses around while maintaining
2452 *** sortorder in order.
2454 *** $courseids is an array of course ids
2458 function move_courses ($courseids, $categoryid) {
2460 global $CFG;
2462 if (!empty($courseids)) {
2464 $courseids = array_reverse($courseids);
2466 foreach ($courseids as $courseid) {
2468 if (! $course = get_record("course", "id", $courseid)) {
2469 notify("Error finding course $courseid");
2470 } else {
2471 // figure out a sortorder that we can use in the destination category
2472 $sortorder = get_field_sql('SELECT MIN(sortorder)-1 AS min
2473 FROM ' . $CFG->prefix . 'course WHERE category=' . $categoryid);
2474 if ($sortorder === false) {
2475 // the category is empty
2476 // rather than let the db default to 0
2477 // set it to > 100 and avoid extra work in fix_coursesortorder()
2478 $sortorder = 200;
2479 } else if ($sortorder < 10) {
2480 fix_course_sortorder($categoryid);
2483 $course->category = $categoryid;
2484 $course->sortorder = $sortorder;
2485 $course->fullname = addslashes($course->fullname);
2486 $course->shortname = addslashes($course->shortname);
2487 $course->summary = addslashes($course->summary);
2488 $course->password = addslashes($course->password);
2489 $course->teacher = addslashes($course->teacher);
2490 $course->teachers = addslashes($course->teachers);
2491 $course->student = addslashes($course->student);
2492 $course->students = addslashes($course->students);
2494 if (!update_record('course', $course)) {
2495 notify("An error occurred - course not moved!");
2499 fix_course_sortorder();
2501 return true;
2505 * @param string $format Course format ID e.g. 'weeks'
2506 * @return Name that the course format prefers for sections
2508 function get_section_name($format) {
2509 $sectionname = get_string("name$format","format_$format");
2510 if($sectionname == "[[name$format]]") {
2511 $sectionname = get_string("name$format");
2513 return $sectionname;