MDL-8857
[moodle-linuxchix.git] / course / lib.php
blob42314fa7272537397883370da18e247dcf772db0
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 genearlbox boxaligncenter" summary="">'."\n";
476 // echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\" summary=\"\">\n";
477 echo "<tr>";
478 if ($course->id == SITEID) {
479 echo "<th class=\"c0 header\" scope=\"col\">".get_string('course')."</th>\n";
481 echo "<th class=\"c1 header\" scope=\"col\">".get_string('time')."</th>\n";
482 echo "<th class=\"c2 header\" scope=\"col\">".get_string('ip_address')."</th>\n";
483 echo "<th class=\"c3 header\" scope=\"col\">".get_string('fullname')."</th>\n";
484 echo "<th class=\"c4 header\" scope=\"col\">".get_string('action')."</th>\n";
485 echo "<th class=\"c5 header\" scope=\"col\">".get_string('info')."</th>\n";
486 echo "</tr>\n";
488 if (empty($logs['logs'])) {
489 echo "</table>\n";
490 return;
493 $row = 1;
494 foreach ($logs['logs'] as $log) {
496 $row = ($row + 1) % 2;
498 if (isset($ldcache[$log->module][$log->action])) {
499 $ld = $ldcache[$log->module][$log->action];
500 } else {
501 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
502 $ldcache[$log->module][$log->action] = $ld;
504 if ($ld && !empty($log->info)) {
505 // ugly hack to make sure fullname is shown correctly
506 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
507 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
508 } else {
509 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
513 //Filter log->info
514 $log->info = format_string($log->info);
516 $log->url = strip_tags(urldecode($log->url)); // Some XSS protection
517 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
518 $log->url = str_replace('&', '&amp;', $log->url); /// XHTML compatibility
520 echo '<tr class="r'.$row.'">';
521 if ($course->id == SITEID) {
522 echo "<td class=\"cell c0\">\n";
523 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courses[$log->course]."</a>\n";
524 echo "</td>\n";
526 echo "<td class=\"cell c1\" align=\"right\">".userdate($log->time, '%a').
527 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
528 echo "<td class=\"cell c2\">\n";
529 link_to_popup_window("/iplookup/index.php?ip=$log->ip&amp;user=$log->userid", 'iplookup',$log->ip, 400, 700);
530 echo "</td>\n";
531 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
532 echo "<td class=\"cell c3\">\n";
533 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}&amp;course={$log->course}\">$fullname</a>\n";
534 echo "</td>\n";
535 echo "<td class=\"cell c4\">\n";
536 link_to_popup_window( make_log_url($log->module,$log->url), 'fromloglive',"$log->module $log->action", 400, 600);
537 echo "</td>\n";;
538 echo "<td class=\"cell c5\">{$log->info}</td>\n";
539 echo "</tr>\n";
541 echo "</table>\n";
543 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
547 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
548 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
550 global $CFG;
552 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
553 $modname, $modid, $modaction, $groupid)) {
554 notify("No logs found!");
555 print_footer($course);
556 exit;
559 if ($course->id == SITEID) {
560 $courses[0] = '';
561 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
562 foreach ($ccc as $cc) {
563 $courses[$cc->id] = $cc->shortname;
568 $totalcount = $logs['totalcount'];
569 $count=0;
570 $ldcache = array();
571 $tt = getdate(time());
572 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
574 $strftimedatetime = get_string("strftimedatetime");
576 echo "<div class=\"info\">\n";
577 print_string("displayingrecords", "", $totalcount);
578 echo "</div>\n";
580 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
582 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
583 echo "<tr>";
584 if ($course->id == SITEID) {
585 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
587 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
588 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
589 echo "<th class=\"c3 header\">".get_string('fullname')."</th>\n";
590 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
591 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
592 echo "</tr>\n";
594 if (empty($logs['logs'])) {
595 echo "</table>\n";
596 return;
599 $row = 1;
600 foreach ($logs['logs'] as $log) {
602 $log->info = $log->coursename;
603 $row = ($row + 1) % 2;
605 if (isset($ldcache[$log->module][$log->action])) {
606 $ld = $ldcache[$log->module][$log->action];
607 } else {
608 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
609 $ldcache[$log->module][$log->action] = $ld;
611 if (0 && $ld && !empty($log->info)) {
612 // ugly hack to make sure fullname is shown correctly
613 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
614 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
615 } else {
616 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
620 //Filter log->info
621 $log->info = format_string($log->info);
623 $log->url = strip_tags(urldecode($log->url)); // Some XSS protection
624 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
625 $log->url = str_replace('&', '&amp;', $log->url); /// XHTML compatibility
627 echo '<tr class="r'.$row.'">';
628 if ($course->id == SITEID) {
629 echo "<td class=\"r$row c0\" >\n";
630 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courses[$log->course]."</a>\n";
631 echo "</td>\n";
633 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time, '%a').
634 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
635 echo "<td class=\"r$row c2\" >\n";
636 link_to_popup_window("/iplookup/index.php?ip=$log->ip&amp;user=$log->userid", 'iplookup',$log->ip, 400, 700);
637 echo "</td>\n";
638 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
639 echo "<td class=\"r$row c3\" >\n";
640 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
641 echo "</td>\n";
642 echo "<td class=\"r$row c4\">\n";
643 echo $log->action .': '.$log->module;
644 echo "</td>\n";;
645 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
646 echo "</tr>\n";
648 echo "</table>\n";
650 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
654 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
655 $modid, $modaction, $groupid) {
657 $text = get_string('course')."\t".get_string('time')."\t".get_string('ip_address')."\t".
658 get_string('fullname')."\t".get_string('action')."\t".get_string('info');
660 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
661 $modname, $modid, $modaction, $groupid)) {
662 return false;
665 $courses = array();
667 if ($course->id == SITEID) {
668 $courses[0] = '';
669 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
670 foreach ($ccc as $cc) {
671 $courses[$cc->id] = $cc->shortname;
674 } else {
675 $courses[$course->id] = $course->shortname;
678 $count=0;
679 $ldcache = array();
680 $tt = getdate(time());
681 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
683 $strftimedatetime = get_string("strftimedatetime");
685 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
686 $filename .= '.txt';
687 header("Content-Type: application/download\n");
688 header("Content-Disposition: attachment; filename=$filename");
689 header("Expires: 0");
690 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
691 header("Pragma: public");
693 echo get_string('savedat').userdate(time(), $strftimedatetime)."\n";
694 echo $text;
696 if (empty($logs['logs'])) {
697 return true;
700 foreach ($logs['logs'] as $log) {
701 if (isset($ldcache[$log->module][$log->action])) {
702 $ld = $ldcache[$log->module][$log->action];
703 } else {
704 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
705 $ldcache[$log->module][$log->action] = $ld;
707 if ($ld && !empty($log->info)) {
708 // ugly hack to make sure fullname is shown correctly
709 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
710 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
711 } else {
712 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
716 //Filter log->info
717 $log->info = format_string($log->info);
719 $log->url = strip_tags(urldecode($log->url)); // Some XSS protection
720 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
721 $log->url = str_replace('&', '&amp;', $log->url); // XHTML compatibility
723 $firstField = $courses[$log->course];
724 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
725 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action, $log->info);
726 $text = implode("\t", $row);
727 echo $text." \n";
729 return true;
733 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
734 $modid, $modaction, $groupid) {
736 global $CFG;
738 require_once("$CFG->libdir/excellib.class.php");
740 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
741 $modname, $modid, $modaction, $groupid)) {
742 return false;
745 $courses = array();
747 if ($course->id == SITEID) {
748 $courses[0] = '';
749 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
750 foreach ($ccc as $cc) {
751 $courses[$cc->id] = $cc->shortname;
754 } else {
755 $courses[$course->id] = $course->shortname;
758 $count=0;
759 $ldcache = array();
760 $tt = getdate(time());
761 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
763 $strftimedatetime = get_string("strftimedatetime");
765 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
766 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
767 $filename .= '.xls';
769 $workbook = new MoodleExcelWorkbook('-');
770 $workbook->send($filename);
772 $worksheet = array();
773 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
774 get_string('fullname'), get_string('action'), get_string('info'));
776 // Creating worksheets
777 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
778 $sheettitle = get_string('excel_sheettitle', 'logs', $wsnumber).$nroPages;
779 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
780 $worksheet[$wsnumber]->set_column(1, 1, 30);
781 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
782 userdate(time(), $strftimedatetime));
783 $col = 0;
784 foreach ($headers as $item) {
785 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
786 $col++;
790 if (empty($logs['logs'])) {
791 $workbook->close();
792 return true;
795 $formatDate =& $workbook->add_format();
796 $formatDate->set_num_format(get_string('log_excel_date_format'));
798 $row = FIRSTUSEDEXCELROW;
799 $wsnumber = 1;
800 $myxls =& $worksheet[$wsnumber];
801 foreach ($logs['logs'] as $log) {
802 if (isset($ldcache[$log->module][$log->action])) {
803 $ld = $ldcache[$log->module][$log->action];
804 } else {
805 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
806 $ldcache[$log->module][$log->action] = $ld;
808 if ($ld && !empty($log->info)) {
809 // ugly hack to make sure fullname is shown correctly
810 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
811 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
812 } else {
813 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
817 // Filter log->info
818 $log->info = format_string($log->info);
819 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
821 if ($nroPages>1) {
822 if ($row > EXCELROWS) {
823 $wsnumber++;
824 $myxls =& $worksheet[$wsnumber];
825 $row = FIRSTUSEDEXCELROW;
829 $myxls->write($row, 0, $courses[$log->course], '');
830 // Excel counts from 1/1/1900
831 $excelTime=25569+$log->time/(3600*24);
832 $myxls->write($row, 1, $excelTime, $formatDate);
833 $myxls->write($row, 2, $log->ip, '');
834 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
835 $myxls->write($row, 3, $fullname, '');
836 $myxls->write($row, 4, $log->module.' '.$log->action, '');
837 $myxls->write($row, 5, $log->info, '');
839 $row++;
842 $workbook->close();
843 return true;
846 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
847 $modid, $modaction, $groupid) {
849 global $CFG;
851 require_once("$CFG->libdir/odslib.class.php");
853 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
854 $modname, $modid, $modaction, $groupid)) {
855 return false;
858 $courses = array();
860 if ($course->id == SITEID) {
861 $courses[0] = '';
862 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
863 foreach ($ccc as $cc) {
864 $courses[$cc->id] = $cc->shortname;
867 } else {
868 $courses[$course->id] = $course->shortname;
871 $count=0;
872 $ldcache = array();
873 $tt = getdate(time());
874 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
876 $strftimedatetime = get_string("strftimedatetime");
878 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
879 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
880 $filename .= '.ods';
882 $workbook = new MoodleODSWorkbook('-');
883 $workbook->send($filename);
885 $worksheet = array();
886 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
887 get_string('fullname'), get_string('action'), get_string('info'));
889 // Creating worksheets
890 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
891 $sheettitle = get_string('excel_sheettitle', 'logs', $wsnumber).$nroPages;
892 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
893 $worksheet[$wsnumber]->set_column(1, 1, 30);
894 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
895 userdate(time(), $strftimedatetime));
896 $col = 0;
897 foreach ($headers as $item) {
898 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
899 $col++;
903 if (empty($logs['logs'])) {
904 $workbook->close();
905 return true;
908 $formatDate =& $workbook->add_format();
909 $formatDate->set_num_format(get_string('log_excel_date_format'));
911 $row = FIRSTUSEDEXCELROW;
912 $wsnumber = 1;
913 $myxls =& $worksheet[$wsnumber];
914 foreach ($logs['logs'] as $log) {
915 if (isset($ldcache[$log->module][$log->action])) {
916 $ld = $ldcache[$log->module][$log->action];
917 } else {
918 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
919 $ldcache[$log->module][$log->action] = $ld;
921 if ($ld && !empty($log->info)) {
922 // ugly hack to make sure fullname is shown correctly
923 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
924 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
925 } else {
926 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
930 // Filter log->info
931 $log->info = format_string($log->info);
932 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
934 if ($nroPages>1) {
935 if ($row > EXCELROWS) {
936 $wsnumber++;
937 $myxls =& $worksheet[$wsnumber];
938 $row = FIRSTUSEDEXCELROW;
942 $myxls->write_string($row, 0, $courses[$log->course]);
943 $myxls->write_date($row, 1, $log->time);
944 $myxls->write_string($row, 2, $log->ip);
945 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
946 $myxls->write_string($row, 3, $fullname);
947 $myxls->write_string($row, 4, $log->module.' '.$log->action);
948 $myxls->write_string($row, 5, $log->info);
950 $row++;
953 $workbook->close();
954 return true;
958 function print_log_graph($course, $userid=0, $type="course.png", $date=0) {
959 global $CFG;
960 if (empty($CFG->gdversion)) {
961 echo "(".get_string("gdneed").")";
962 } else {
963 echo '<img src="'.$CFG->wwwroot.'/course/report/log/graph.php?id='.$course->id.
964 '&amp;user='.$userid.'&amp;type='.$type.'&amp;date='.$date.'" alt="" />';
969 function print_overview($courses) {
971 global $CFG, $USER;
973 $htmlarray = array();
974 if ($modules = get_records('modules')) {
975 foreach ($modules as $mod) {
976 if (file_exists(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php')) {
977 require_once(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php');
978 $fname = $mod->name.'_print_overview';
979 if (function_exists($fname)) {
980 $fname($courses,$htmlarray);
985 foreach ($courses as $course) {
986 print_simple_box_start('center', '100%', '', 5, "coursebox");
987 $linkcss = '';
988 if (empty($course->visible)) {
989 $linkcss = 'class="dimmed"';
991 print_heading('<a title="'. format_string($course->fullname).'" '.$linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'. format_string($course->fullname).'</a>');
992 if (array_key_exists($course->id,$htmlarray)) {
993 foreach ($htmlarray[$course->id] as $modname => $html) {
994 echo $html;
997 print_simple_box_end();
1002 function print_recent_activity($course) {
1003 // $course is an object
1004 // This function trawls through the logs looking for
1005 // anything new since the user's last login
1007 global $CFG, $USER, $SESSION;
1009 $context = get_context_instance(CONTEXT_COURSE, $course->id);
1011 $timestart = time() - COURSE_MAX_RECENT_PERIOD;
1013 if (!has_capability('moodle/legacy:guest', $context, NULL, false)) {
1014 if (!empty($USER->lastcourseaccess[$course->id])) {
1015 if ($USER->lastcourseaccess[$course->id] > $timestart) {
1016 $timestart = $USER->lastcourseaccess[$course->id];
1021 echo '<div class="activitydate">';
1022 echo get_string('activitysince', '', userdate($timestart));
1023 echo '</div>';
1024 echo '<div class="activityhead">';
1026 echo '<a href="'.$CFG->wwwroot.'/course/recent.php?id='.$course->id.'">'.get_string('recentactivityreport').'</a>';
1028 echo "</div>\n";
1031 // Firstly, have there been any new enrolments?
1033 $heading = false;
1034 $content = false;
1036 $users = get_recent_enrolments($course->id, $timestart);
1038 //Accessibility: new users now appear in an <OL> list.
1039 if ($users) {
1040 echo '<div class="newusers">';
1041 if (! $heading) {
1042 print_headline(get_string("newusers").':', 3);
1043 $heading = true;
1044 $content = true;
1046 echo "<ol class=\"list\">\n";
1047 foreach ($users as $user) {
1049 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
1050 echo '<li class="name"><a href="'.$CFG->wwwroot."/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a></li>\n";
1052 echo "</ol>\n</div>\n";
1055 // Next, have there been any modifications to the course structure?
1057 $logs = get_records_select('log', "time > '$timestart' AND course = '$course->id' AND
1058 module = 'course' AND action LIKE '% mod'", "time ASC");
1060 if ($logs) {
1061 foreach ($logs as $key => $log) {
1062 $info = split(' ', $log->info);
1064 if ($info[0] == 'label') { // Labels are special activities
1065 continue;
1068 $modname = get_field($info[0], 'name', 'id', $info[1]);
1069 //Create a temp valid module structure (course,id)
1070 $tempmod->course = $log->course;
1071 $tempmod->id = $info[1];
1072 //Obtain the visible property from the instance
1073 $modvisible = instance_is_visible($info[0],$tempmod);
1075 //Only if the mod is visible
1076 if ($modvisible) {
1077 switch ($log->action) {
1078 case 'add mod':
1079 $stradded = get_string('added', 'moodle', get_string('modulename', $info[0]));
1080 $changelist[$log->info] = array ('operation' => 'add', 'text' => "$stradded:<br /><a href=\"$CFG->wwwroot/course/$log->url\">".format_string($modname,true)."</a>");
1081 break;
1082 case 'update mod':
1083 $strupdated = get_string('updated', 'moodle', get_string('modulename', $info[0]));
1084 if (empty($changelist[$log->info])) {
1085 $changelist[$log->info] = array ('operation' => 'update', 'text' => "$strupdated:<br /><a href=\"$CFG->wwwroot/course/$log->url\">".format_string($modname,true)."</a>");
1087 break;
1088 case 'delete mod':
1089 if (!empty($changelist[$log->info]['operation']) and
1090 $changelist[$log->info]['operation'] == 'add') {
1091 $changelist[$log->info] = NULL;
1092 } else {
1093 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $info[0]));
1094 $changelist[$log->info] = array ('operation' => 'delete', 'text' => $strdeleted);
1096 break;
1102 if (!empty($changelist)) {
1103 foreach ($changelist as $changeinfo => $change) {
1104 if ($change) {
1105 $changes[$changeinfo] = $change;
1108 if (isset($changes)){
1109 if (count($changes) > 0) {
1110 print_headline(get_string('courseupdates').':', 3);
1111 $content = true;
1112 foreach ($changes as $changeinfo => $change) {
1113 echo '<p class="activity">'.$change['text'].'</p>';
1119 // Now display new things from each module
1121 $mods = get_records('modules', 'visible', '1', 'name', 'id, name');
1123 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
1125 foreach ($mods as $mod) { // Each module gets it's own logs and prints them
1126 include_once($CFG->dirroot.'/mod/'.$mod->name.'/lib.php');
1127 $print_recent_activity = $mod->name.'_print_recent_activity';
1128 if (function_exists($print_recent_activity)) {
1130 // NOTE:
1131 // $isteacher (second parameter below) is to be deprecated!
1133 // TODO:
1134 // 1) Make sure that all _print_recent_activity functions are
1135 // not using the $isteacher value.
1136 // 2) Eventually, remove the $isteacher parameter from the
1137 // function calls.
1139 $modcontent = $print_recent_activity($course, $viewfullnames, $timestart);
1140 if ($modcontent) {
1141 $content = true;
1146 if (! $content) {
1147 echo '<p class="message">'.get_string('nothingnew').'</p>';
1152 function get_array_of_activities($courseid) {
1153 // For a given course, returns an array of course activity objects
1154 // Each item in the array contains he following properties:
1155 // cm - course module id
1156 // mod - name of the module (eg forum)
1157 // section - the number of the section (eg week or topic)
1158 // name - the name of the instance
1159 // visible - is the instance visible or not
1160 // extra - contains extra string to include in any link
1162 global $CFG;
1164 $mod = array();
1166 if (!$rawmods = get_course_mods($courseid)) {
1167 return NULL;
1170 if ($sections = get_records("course_sections", "course", $courseid, "section ASC")) {
1171 foreach ($sections as $section) {
1172 if (!empty($section->sequence)) {
1173 $sequence = explode(",", $section->sequence);
1174 foreach ($sequence as $seq) {
1175 if (empty($rawmods[$seq])) {
1176 continue;
1178 $mod[$seq]->cm = $rawmods[$seq]->id;
1179 $mod[$seq]->mod = $rawmods[$seq]->modname;
1180 $mod[$seq]->section = $section->section;
1181 $mod[$seq]->name = urlencode(get_field($rawmods[$seq]->modname, "name", "id", $rawmods[$seq]->instance));
1182 $mod[$seq]->visible = $rawmods[$seq]->visible;
1183 $mod[$seq]->extra = "";
1185 $modname = $mod[$seq]->mod;
1186 $functionname = $modname."_get_coursemodule_info";
1188 include_once("$CFG->dirroot/mod/$modname/lib.php");
1190 if (function_exists($functionname)) {
1191 if ($info = $functionname($rawmods[$seq])) {
1192 if (!empty($info->extra)) {
1193 $mod[$seq]->extra = $info->extra;
1195 if (!empty($info->icon)) {
1196 $mod[$seq]->icon = $info->icon;
1204 return $mod;
1210 function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
1211 // Returns a number of useful structures for course displays
1213 $mods = NULL; // course modules indexed by id
1214 $modnames = NULL; // all course module names (except resource!)
1215 $modnamesplural= NULL; // all course module names (plural form)
1216 $modnamesused = NULL; // course module names used
1218 if ($allmods = get_records("modules")) {
1219 foreach ($allmods as $mod) {
1220 if ($mod->visible) {
1221 $modnames[$mod->name] = get_string("modulename", "$mod->name");
1222 $modnamesplural[$mod->name] = get_string("modulenameplural", "$mod->name");
1225 asort($modnames);
1226 } else {
1227 error("No modules are installed!");
1230 if ($rawmods = get_course_mods($courseid)) {
1231 foreach($rawmods as $mod) { // Index the mods
1232 if (empty($modnames[$mod->modname])) {
1233 continue;
1235 $mods[$mod->id] = $mod;
1236 $mods[$mod->id]->modfullname = $modnames[$mod->modname];
1237 if ($mod->visible or has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_COURSE, $courseid))) {
1238 $modnamesused[$mod->modname] = $modnames[$mod->modname];
1241 if ($modnamesused) {
1242 asort($modnamesused);
1248 function get_all_sections($courseid) {
1250 return get_records("course_sections", "course", "$courseid", "section",
1251 "section, id, course, summary, sequence, visible");
1254 function course_set_display($courseid, $display=0) {
1255 global $USER;
1257 if ($display == "all" or empty($display)) {
1258 $display = 0;
1261 if (empty($USER->id) or $USER->username == 'guest') {
1262 //do not store settings in db for guests
1263 } else if (record_exists("course_display", "userid", $USER->id, "course", $courseid)) {
1264 set_field("course_display", "display", $display, "userid", $USER->id, "course", $courseid);
1265 } else {
1266 $record->userid = $USER->id;
1267 $record->course = $courseid;
1268 $record->display = $display;
1269 if (!insert_record("course_display", $record)) {
1270 notify("Could not save your course display!");
1274 return $USER->display[$courseid] = $display; // Note: = not ==
1277 function set_section_visible($courseid, $sectionnumber, $visibility) {
1278 /// For a given course section, markes it visible or hidden,
1279 /// and does the same for every activity in that section
1281 if ($section = get_record("course_sections", "course", $courseid, "section", $sectionnumber)) {
1282 set_field("course_sections", "visible", "$visibility", "id", $section->id);
1283 if (!empty($section->sequence)) {
1284 $modules = explode(",", $section->sequence);
1285 foreach ($modules as $moduleid) {
1286 set_coursemodule_visible($moduleid, $visibility, true);
1289 rebuild_course_cache($courseid);
1294 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%") {
1295 /// Prints a section full of activity modules
1296 global $CFG, $USER;
1298 static $groupbuttons;
1299 static $groupbuttonslink;
1300 static $isteacher;
1301 static $isediting;
1302 static $ismoving;
1303 static $strmovehere;
1304 static $strmovefull;
1305 static $strunreadpostsone;
1307 static $untracked;
1308 static $usetracking;
1310 $labelformatoptions = New stdClass;
1312 if (!isset($isteacher)) {
1313 $groupbuttons = ($course->groupmode or (!$course->groupmodeforce));
1314 $groupbuttonslink = (!$course->groupmodeforce);
1315 $isediting = isediting($course->id);
1316 $ismoving = $isediting && ismoving($course->id);
1317 if ($ismoving) {
1318 $strmovehere = get_string("movehere");
1319 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1321 include_once($CFG->dirroot.'/mod/forum/lib.php');
1322 if ($usetracking = forum_tp_can_track_forums()) {
1323 $strunreadpostsone = get_string('unreadpostsone', 'forum');
1324 $untracked = forum_tp_get_untracked_forums($USER->id, $course->id);
1327 $labelformatoptions->noclean = true;
1329 /// Casting $course->modinfo to string prevents one notice when the field is null
1330 $modinfo = unserialize((string)$course->modinfo);
1332 //Acccessibility: replace table with list <ul>, but don't output empty list.
1333 if (!empty($section->sequence)) {
1335 // Fix bug #5027, don't want style=\"width:$width\".
1336 echo "<ul class=\"section\">\n";
1337 $sectionmods = explode(",", $section->sequence);
1339 foreach ($sectionmods as $modnumber) {
1340 if (empty($mods[$modnumber])) {
1341 continue;
1343 $mod = $mods[$modnumber];
1345 if ($mod->visible or has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_COURSE, $course->id))) {
1346 echo '<li class="activity '.$mod->modname.'" id="module-'.$modnumber.'">'; // Unique ID
1347 if ($ismoving) {
1348 if ($mod->id == $USER->activitycopy) {
1349 continue;
1351 echo '<a title="'.$strmovefull.'"'.
1352 ' href="'.$CFG->wwwroot.'/course/mod.php?moveto='.$mod->id.'&amp;sesskey='.$USER->sesskey.'">'.
1353 '<img class="movetarget" src="'.$CFG->pixpath.'/movehere.gif" '.
1354 ' alt="'.$strmovehere.'" /></a><br />
1357 $instancename = urldecode($modinfo[$modnumber]->name);
1358 $instancename = format_string($instancename, true, $course->id);
1360 if (!empty($modinfo[$modnumber]->extra)) {
1361 $extra = urldecode($modinfo[$modnumber]->extra);
1362 } else {
1363 $extra = "";
1366 if (!empty($modinfo[$modnumber]->icon)) {
1367 $icon = "$CFG->pixpath/".urldecode($modinfo[$modnumber]->icon);
1368 } else {
1369 $icon = "$CFG->modpixpath/$mod->modname/icon.gif";
1372 if ($mod->indent) {
1373 print_spacer(12, 20 * $mod->indent, false);
1376 if ($mod->modname == "label") {
1377 if (!$mod->visible) {
1378 echo "<span class=\"dimmed_text\">";
1380 echo format_text($extra, FORMAT_HTML, $labelformatoptions);
1381 if (!$mod->visible) {
1382 echo "</span>";
1385 } else { // Normal activity
1387 if (!empty($USER->screenreader)) {
1388 $typestring = '('.get_string('modulename',$mod->modname).') ';
1389 } else {
1390 $typestring = '';
1393 $linkcss = $mod->visible ? "" : " class=\"dimmed\" ";
1394 echo '<img src="'.$icon.'"'.
1395 ' class="activityicon" alt="'.$mod->modfullname.'" />'.
1396 ' <a title="'.$mod->modfullname.'" '.$linkcss.' '.$extra.
1397 ' href="'.$CFG->wwwroot.'/mod/'.$mod->modname.'/view.php?id='.$mod->id.'">'.
1398 $typestring.$instancename.'</a>';
1400 if ($usetracking && $mod->modname == 'forum') {
1401 $groupmode = groupmode($course, $mod);
1402 $groupid = ($groupmode == SEPARATEGROUPS && !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) ?
1403 get_current_group($course->id) : false;
1405 if (forum_tp_can_track_forums() && !isset($untracked[$mod->instance])) {
1406 $unread = forum_tp_count_forum_unread_posts($USER->id, $mod->instance, $groupid);
1407 if ($unread) {
1408 echo '<span class="unread"> <a href="'.$CFG->wwwroot.'/mod/forum/view.php?id='.$mod->id.'">';
1409 if ($unread == 1) {
1410 echo $strunreadpostsone;
1411 } else {
1412 print_string('unreadpostsnumber', 'forum', $unread);
1414 echo '</a> </span>';
1419 if ($isediting) {
1420 if ($groupbuttons and $mod->modname != 'label' and $mod->modname != 'resource') {
1421 if (! $mod->groupmodelink = $groupbuttonslink) {
1422 $mod->groupmode = $course->groupmode;
1425 } else {
1426 $mod->groupmode = false;
1428 echo '&nbsp;&nbsp;';
1429 echo make_editing_buttons($mod, $absolute, true, $mod->indent, $section->section);
1431 echo "</li>\n";
1434 } elseif ($ismoving) {
1435 echo "<ul class=\"section\">\n";
1437 if ($ismoving) {
1438 echo '<li><a title="'.$strmovefull.'"'.
1439 ' href="'.$CFG->wwwroot.'/course/mod.php?movetosection='.$section->id.'&amp;sesskey='.$USER->sesskey.'">'.
1440 '<img class="movetarget" src="'.$CFG->pixpath.'/movehere.gif" '.
1441 ' alt="'.$strmovehere.'" /></a></li>
1444 if (!empty($section->sequence) || $ismoving) {
1445 echo "</ul><!--class='section'-->\n\n";
1450 * Prints the menus to add activities and resources.
1452 function print_section_add_menus($course, $section, $modnames, $vertical=false, $return=false) {
1453 global $CFG;
1455 // check to see if user can add menus
1456 if (!has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $course->id))) {
1457 return false;
1460 static $resources = false;
1461 static $activities = false;
1463 if ($resources === false) {
1464 $resources = array();
1465 $activities = array();
1467 foreach($modnames as $modname=>$modnamestr) {
1468 if (!course_allowed_module($course, $modname)) {
1469 continue;
1472 require_once("$CFG->dirroot/mod/$modname/lib.php");
1473 $gettypesfunc = $modname.'_get_types';
1474 if (function_exists($gettypesfunc)) {
1475 $types = $gettypesfunc();
1476 foreach($types as $type) {
1477 if ($type->modclass == MOD_CLASS_RESOURCE) {
1478 $resources[$type->type] = $type->typestr;
1479 } else {
1480 $activities[$type->type] = $type->typestr;
1483 } else {
1484 // all mods without type are considered activity
1485 $activities[$modname] = $modnamestr;
1490 $straddactivity = get_string('addactivity');
1491 $straddresource = get_string('addresource');
1493 $output = '<div class="section_add_menus">';
1495 if (!$vertical) {
1496 $output .= '<div class="horizontal">';
1499 if (!empty($resources)) {
1500 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&amp;section=$section&amp;sesskey=".sesskey()."&amp;add=",
1501 $resources, "ressection$section", "", $straddresource, 'resource/types', $straddresource, true);
1504 if (!empty($activities)) {
1505 $output .= ' ';
1506 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&amp;section=$section&amp;sesskey=".sesskey()."&amp;add=",
1507 $activities, "section$section", "", $straddactivity, 'mods', $straddactivity, true);
1510 if (!$vertical) {
1511 $output .= '</div>';
1514 $output .= '</div>';
1516 if ($return) {
1517 return $output;
1518 } else {
1519 echo $output;
1523 function rebuild_course_cache($courseid=0) {
1524 // Rebuilds the cached list of course activities stored in the database
1525 // If a courseid is not specified, then all are rebuilt
1527 if ($courseid) {
1528 $select = "id = '$courseid'";
1529 } else {
1530 $select = "";
1533 if ($courses = get_records_select("course", $select,'','id,fullname')) {
1534 foreach ($courses as $course) {
1535 $modinfo = serialize(get_array_of_activities($course->id));
1536 if (!set_field("course", "modinfo", $modinfo, "id", $course->id)) {
1537 notify("Could not cache module information for course '" . format_string($course->fullname) . "'!");
1545 function make_categories_list(&$list, &$parents, $category=NULL, $path="") {
1546 /// Given an empty array, this function recursively travels the
1547 /// categories, building up a nice list for display. It also makes
1548 /// an array that list all the parents for each category.
1550 // initialize the arrays if needed
1551 if (!is_array($list)) {
1552 $list = array();
1554 if (!is_array($parents)) {
1555 $parents = array();
1558 if ($category) {
1559 if ($path) {
1560 $path = $path.' / '.format_string($category->name);
1561 } else {
1562 $path = format_string($category->name);
1564 $list[$category->id] = $path;
1565 } else {
1566 $category->id = 0;
1569 if ($categories = get_categories($category->id)) { // Print all the children recursively
1570 foreach ($categories as $cat) {
1571 if (!empty($category->id)) {
1572 if (isset($parents[$category->id])) {
1573 $parents[$cat->id] = $parents[$category->id];
1575 $parents[$cat->id][] = $category->id;
1577 make_categories_list($list, $parents, $cat, $path);
1583 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $files = true) {
1584 /// Recursive function to print out all the categories in a nice format
1585 /// with or without courses included
1586 global $CFG;
1588 if (isset($CFG->max_category_depth) && ($depth >= $CFG->max_category_depth)) {
1589 return;
1592 if (!$displaylist) {
1593 make_categories_list($displaylist, $parentslist);
1596 if ($category) {
1597 if ($category->visible or has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
1598 print_category_info($category, $depth, $files);
1599 } else {
1600 return; // Don't bother printing children of invisible categories
1603 } else {
1604 $category->id = "0";
1607 if ($categories = get_categories($category->id)) { // Print all the children recursively
1608 $countcats = count($categories);
1609 $count = 0;
1610 $first = true;
1611 $last = false;
1612 foreach ($categories as $cat) {
1613 $count++;
1614 if ($count == $countcats) {
1615 $last = true;
1617 $up = $first ? false : true;
1618 $down = $last ? false : true;
1619 $first = false;
1621 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1, $files);
1626 // this function will return $options array for choose_from_menu, with whitespace to denote nesting.
1628 function make_categories_options() {
1629 make_categories_list($cats,$parents);
1630 foreach ($cats as $key => $value) {
1631 if (array_key_exists($key,$parents)) {
1632 if ($indent = count($parents[$key])) {
1633 for ($i = 0; $i < $indent; $i++) {
1634 $cats[$key] = '&nbsp;'.$cats[$key];
1639 return $cats;
1642 function print_category_info($category, $depth, $files = false) {
1643 /// Prints the category info in indented fashion
1644 /// This function is only used by print_whole_category_list() above
1646 global $CFG;
1647 static $strallowguests, $strrequireskey, $strsummary;
1649 if (empty($strsummary)) {
1650 $strallowguests = get_string('allowguests');
1651 $strrequireskey = get_string('requireskey');
1652 $strsummary = get_string('summary');
1655 $catlinkcss = $category->visible ? '' : ' class="dimmed" ';
1657 $coursecount = count_records('course') <= FRONTPAGECOURSELIMIT;
1658 if ($files and $coursecount) {
1659 $catimage = '<img src="'.$CFG->pixpath.'/i/course.gif" alt="" />';
1660 } else {
1661 $catimage = "&nbsp;";
1664 echo "\n\n".'<table class="categorylist">';
1666 if ($files and $coursecount) {
1667 $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');
1669 echo '<tr>';
1671 if ($depth) {
1672 $indent = $depth*30;
1673 $rows = count($courses) + 1;
1674 echo '<td rowspan="'.$rows.'" valign="top" width="'.$indent.'">';
1675 print_spacer(10, $indent);
1676 echo '</td>';
1679 echo '<td valign="top" class="category image">'.$catimage.'</td>';
1680 echo '<td valign="top" class="category name">';
1681 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot.'/course/category.php?id='.$category->id.'">'. format_string($category->name).'</a>';
1682 echo '</td>';
1683 echo '<td class="category info">&nbsp;</td>';
1684 echo '</tr>';
1686 if ($courses && !(isset($CFG->max_category_depth)&&($depth>=$CFG->max_category_depth-1))) {
1687 foreach ($courses as $course) {
1688 $linkcss = $course->visible ? '' : ' class="dimmed" ';
1689 echo '<tr><td valign="top">&nbsp;';
1690 echo '</td><td valign="top" class="course name">';
1691 echo '<a '.$linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'. format_string($course->fullname).'</a>';
1692 echo '</td><td align="right" valign="top" class="course info">';
1693 if ($course->guest ) {
1694 echo '<a title="'.$strallowguests.'" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">';
1695 echo '<img alt="'.$strallowguests.'" src="'.$CFG->pixpath.'/i/guest.gif" /></a>';
1696 } else {
1697 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath.'/spacer.gif" />';
1699 if ($course->password) {
1700 echo '<a title="'.$strrequireskey.'" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">';
1701 echo '<img alt="'.$strrequireskey.'" src="'.$CFG->pixpath.'/i/key.gif" /></a>';
1702 } else {
1703 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath.'/spacer.gif" />';
1705 if ($course->summary) {
1706 link_to_popup_window ('/course/info.php?id='.$course->id, 'courseinfo',
1707 '<img alt="'.$strsummary.'" src="'.$CFG->pixpath.'/i/info.gif" />',
1708 400, 500, $strsummary);
1709 } else {
1710 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath.'/spacer.gif" />';
1712 echo '</td></tr>';
1715 } else {
1717 echo '<tr>';
1719 if ($depth) {
1720 $indent = $depth*20;
1721 echo '<td valign="top" width="'.$indent.'">';
1722 print_spacer(10, $indent);
1723 echo '</td>';
1726 echo '<td valign="top" class="category name">';
1727 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot.'/course/category.php?id='.$category->id.'">'. format_string($category->name).'</a>';
1728 echo '</td>';
1729 echo '<td valign="top" class="category number">';
1730 if ($category->coursecount) {
1731 echo $category->coursecount;
1733 echo '</td></tr>';
1735 echo '</table>';
1739 function print_courses($category, $hidesitecourse = false) {
1740 /// Category is 0 (for all courses) or an object
1742 global $CFG;
1744 if (empty($category)) {
1745 $categories = get_categories(0); // Parent = 0 ie top-level categories only
1746 if (count($categories) == 1) {
1747 $category = array_shift($categories);
1748 $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');
1749 } else {
1750 $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');
1752 unset($categories);
1753 } else {
1754 $categories = get_categories($category->id); // sub categories
1755 $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');
1758 if ($courses) {
1759 foreach ($courses as $course) {
1760 if ($hidesitecourse and ($course->id == SITEID)) {
1761 continue;
1763 print_course($course);
1765 } else {
1766 print_heading(get_string("nocoursesyet"));
1767 $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
1768 if (has_capability('moodle/course:create', $context)) {
1769 $options = array();
1770 $options['category'] = $category->id;
1771 echo '<div class="addcoursebutton">';
1772 print_single_button($CFG->wwwroot.'/course/edit.php', $options, get_string("addnewcourse"));
1773 echo '</div>';
1782 function print_course($course) {
1784 global $CFG, $USER;
1786 $context = get_context_instance(CONTEXT_COURSE, $course->id);
1788 $linkcss = $course->visible ? '' : ' class="dimmed" ';
1790 echo '<div class="coursebox">';
1791 echo '<div class="info">';
1792 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
1793 $linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.
1794 format_string($course->fullname).'</a></div>';
1796 /// first find all roles that are supposed to be displayed
1797 if ($managerroles = get_config('', 'coursemanager')) {
1798 $coursemanagerroles = split(',', $managerroles);
1799 foreach ($coursemanagerroles as $roleid) {
1800 $role = get_record('role','id',$roleid);
1801 if ($users = get_role_users($roleid, $context, true, '', 'u.lastname ASC', true)) {
1802 foreach ($users as $teacher) {
1803 $fullname = fullname($teacher, has_capability('moodle/site:viewfullnames', $context));
1804 $namesarray[] = format_string($role->name).': <a href="'.$CFG->wwwroot.'/user/view.php?id='.
1805 $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 .= '<input type="text" size="30" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
1915 $output .= '<input type="submit" value="'.s($strsearchcourses).'" />';
1916 $output .= '</fieldset></form>';
1917 } else if ($format == 'short') {
1918 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
1919 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
1920 $output .= '<input type="text" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
1921 $output .= '<input type="submit" value="'.s($strsearchcourses).'" />';
1922 $output .= '</fieldset></form>';
1923 } else if ($format == 'navbar') {
1924 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
1925 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
1926 $output .= '<input type="text" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
1927 $output .= '<input type="submit" value="'.s($strsearchcourses).'" />';
1928 $output .= '</fieldset></form>';
1931 if ($return) {
1932 return $output;
1934 echo $output;
1937 function print_remote_course($course, $width="100%") {
1939 global $CFG, $USER;
1941 $linkcss = '';
1943 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&amp;wantsurl=/course/view.php?id={$course->remoteid}";
1945 echo '<div class="coursebox remotecoursebox">';
1946 echo '<div class="info">';
1947 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
1948 $linkcss.' href="'.$url.'">'
1949 . format_string($course->fullname) .'</a><br />'
1950 . format_string($course->hostname) . ' : '
1951 . format_string($course->cat_name) . ' : '
1952 . format_string($course->shortname). '</div>';
1953 echo '</div><div class="summary">';
1954 $options = NULL;
1955 $options->noclean = true;
1956 $options->para = false;
1957 echo format_text($course->summary, FORMAT_MOODLE, $options);
1958 echo '</div>';
1959 echo '</div>';
1960 echo '<div class="clearer"></div>';
1963 function print_remote_host($host, $width="100%") {
1965 global $CFG, $USER;
1967 $linkcss = '';
1969 echo '<div class="coursebox">';
1970 echo '<div class="info">';
1971 echo '<div class="name">';
1972 echo '<img src="'.$CFG->pixpath.'/i/mnethost.gif" class="icon" alt="'.get_string('course').'" />';
1973 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
1974 . s($host['name']).'</a> - ';
1975 echo $host['count'] . ' ' . get_string('courses');
1976 echo '</div>';
1977 echo '</div>';
1978 echo '</div>';
1979 echo '<div class="clearer"></div>';
1983 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
1985 function add_course_module($mod) {
1987 $mod->added = time();
1988 unset($mod->id);
1990 return insert_record("course_modules", $mod);
1993 function add_mod_to_section($mod, $beforemod=NULL) {
1994 /// Given a full mod object with section and course already defined
1995 /// If $before is specified, then this is an existing ID which we
1996 /// will insert the new module before
1998 /// Returns the course_sections ID where the mod is inserted
2000 if ($section = get_record("course_sections", "course", "$mod->course", "section", "$mod->section")) {
2002 $section->sequence = trim($section->sequence);
2004 if (empty($section->sequence)) {
2005 $newsequence = "$mod->coursemodule";
2007 } else if ($beforemod) {
2008 $modarray = explode(",", $section->sequence);
2010 if ($key = array_keys ($modarray, $beforemod->id)) {
2011 $insertarray = array($mod->id, $beforemod->id);
2012 array_splice($modarray, $key[0], 1, $insertarray);
2013 $newsequence = implode(",", $modarray);
2015 } else { // Just tack it on the end anyway
2016 $newsequence = "$section->sequence,$mod->coursemodule";
2019 } else {
2020 $newsequence = "$section->sequence,$mod->coursemodule";
2023 if (set_field("course_sections", "sequence", $newsequence, "id", $section->id)) {
2024 return $section->id; // Return course_sections ID that was used.
2025 } else {
2026 return 0;
2029 } else { // Insert a new record
2030 $section->course = $mod->course;
2031 $section->section = $mod->section;
2032 $section->summary = "";
2033 $section->sequence = $mod->coursemodule;
2034 return insert_record("course_sections", $section);
2038 function set_coursemodule_groupmode($id, $groupmode) {
2039 return set_field("course_modules", "groupmode", $groupmode, "id", $id);
2043 * $prevstateoverrides = true will set the visibility of the course module
2044 * to what is defined in visibleold. This enables us to remember the current
2045 * visibility when making a whole section hidden, so that when we toggle
2046 * that section back to visible, we are able to return the visibility of
2047 * the course module back to what it was originally.
2049 function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
2050 if (!$cm = get_record('course_modules', 'id', $id)) {
2051 return false;
2053 if (!$modulename = get_field('modules', 'name', 'id', $cm->module)) {
2054 return false;
2056 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
2057 foreach($events as $event) {
2058 if ($visible) {
2059 show_event($event);
2060 } else {
2061 hide_event($event);
2065 if ($prevstateoverrides) {
2066 if ($visible == '0') {
2067 // Remember the current visible state so we can toggle this back.
2068 set_field('course_modules', 'visibleold', $cm->visible, 'id', $id);
2069 } else {
2070 // Get the previous saved visible states.
2071 return set_field('course_modules', 'visible', $cm->visibleold, 'id', $id);
2074 return set_field("course_modules", "visible", $visible, "id", $id);
2078 * Delete a course module and any associated data at the course level (events)
2079 * Until 1.5 this function simply marked a deleted flag ... now it
2080 * deletes it completely.
2083 function delete_course_module($id) {
2084 if (!$cm = get_record('course_modules', 'id', $id)) {
2085 return true;
2087 $modulename = get_field('modules', 'name', 'id', $cm->module);
2088 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
2089 foreach($events as $event) {
2090 delete_event($event);
2093 return delete_records('course_modules', 'id', $cm->id);
2096 function delete_mod_from_section($mod, $section) {
2098 if ($section = get_record("course_sections", "id", "$section") ) {
2100 $modarray = explode(",", $section->sequence);
2102 if ($key = array_keys ($modarray, $mod)) {
2103 array_splice($modarray, $key[0], 1);
2104 $newsequence = implode(",", $modarray);
2105 return set_field("course_sections", "sequence", $newsequence, "id", $section->id);
2106 } else {
2107 return false;
2111 return false;
2114 function move_section($course, $section, $move) {
2115 /// Moves a whole course section up and down within the course
2116 global $USER;
2118 if (!$move) {
2119 return true;
2122 $sectiondest = $section + $move;
2124 if ($sectiondest > $course->numsections or $sectiondest < 1) {
2125 return false;
2128 if (!$sectionrecord = get_record("course_sections", "course", $course->id, "section", $section)) {
2129 return false;
2132 if (!$sectiondestrecord = get_record("course_sections", "course", $course->id, "section", $sectiondest)) {
2133 return false;
2136 if (!set_field("course_sections", "section", $sectiondest, "id", $sectionrecord->id)) {
2137 return false;
2139 if (!set_field("course_sections", "section", $section, "id", $sectiondestrecord->id)) {
2140 return false;
2142 // if the focus is on the section that is being moved, then move the focus along
2143 if (isset($USER->display[$course->id]) and ($USER->display[$course->id] == $section)) {
2144 course_set_display($course->id, $sectiondest);
2147 // Check for duplicates and fix order if needed.
2148 // There is a very rare case that some sections in the same course have the same section id.
2149 $sections = get_records_select('course_sections', "course = $course->id", 'section ASC');
2150 $n = 0;
2151 foreach ($sections as $section) {
2152 if ($section->section != $n) {
2153 if (!set_field('course_sections', 'section', $n, 'id', $section->id)) {
2154 return false;
2157 $n++;
2159 return true;
2163 function moveto_module($mod, $section, $beforemod=NULL) {
2164 /// All parameters are objects
2165 /// Move the module object $mod to the specified $section
2166 /// If $beforemod exists then that is the module
2167 /// before which $modid should be inserted
2169 /// Remove original module from original section
2171 if (! delete_mod_from_section($mod->id, $mod->section)) {
2172 notify("Could not delete module from existing section");
2175 /// Update module itself if necessary
2177 if ($mod->section != $section->id) {
2178 $mod->section = $section->id;
2179 if (!update_record("course_modules", $mod)) {
2180 return false;
2182 // if moving to a hidden section then hide module
2183 if (!$section->visible) {
2184 set_coursemodule_visible($mod->id, 0);
2188 /// Add the module into the new section
2190 $mod->course = $section->course;
2191 $mod->section = $section->section; // need relative reference
2192 $mod->coursemodule = $mod->id;
2194 if (! add_mod_to_section($mod, $beforemod)) {
2195 return false;
2198 return true;
2202 function make_editing_buttons($mod, $absolute=false, $moveselect=true, $indent=-1, $section=-1) {
2203 global $CFG, $USER;
2205 static $str;
2206 static $sesskey;
2208 $modcontext = get_context_instance(CONTEXT_MODULE, $mod->id);
2209 // no permission to edit
2210 if (!has_capability('moodle/course:manageactivities', $modcontext)) {
2211 return false;
2214 if (!isset($str)) {
2215 $str->delete = get_string("delete");
2216 $str->move = get_string("move");
2217 $str->moveup = get_string("moveup");
2218 $str->movedown = get_string("movedown");
2219 $str->moveright = get_string("moveright");
2220 $str->moveleft = get_string("moveleft");
2221 $str->update = get_string("update");
2222 $str->duplicate = get_string("duplicate");
2223 $str->hide = get_string("hide");
2224 $str->show = get_string("show");
2225 $str->clicktochange = get_string("clicktochange");
2226 $str->forcedmode = get_string("forcedmode");
2227 $str->groupsnone = get_string("groupsnone");
2228 $str->groupsseparate = get_string("groupsseparate");
2229 $str->groupsvisible = get_string("groupsvisible");
2230 $sesskey = sesskey();
2233 if ($section >= 0) {
2234 $section = '&amp;sr='.$section; // Section return
2235 } else {
2236 $section = '';
2239 if ($absolute) {
2240 $path = $CFG->wwwroot.'/course';
2241 } else {
2242 $path = '.';
2245 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
2246 if ($mod->visible) {
2247 $hideshow = '<a class="editing_hide" title="'.$str->hide.'" href="'.$path.'/mod.php?hide='.$mod->id.
2248 '&amp;sesskey='.$sesskey.$section.'"><img'.
2249 ' src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" '.
2250 ' alt="'.$str->hide.'" /></a>'."\n";
2251 } else {
2252 $hideshow = '<a class="editing_show" title="'.$str->show.'" href="'.$path.'/mod.php?show='.$mod->id.
2253 '&amp;sesskey='.$sesskey.$section.'"><img'.
2254 ' src="'.$CFG->pixpath.'/t/show.gif" class="iconsmall" '.
2255 ' alt="'.$str->show.'" /></a>'."\n";
2258 if ($mod->groupmode !== false) {
2259 if ($mod->groupmode == SEPARATEGROUPS) {
2260 $grouptitle = $str->groupsseparate;
2261 $groupclass = 'editing_groupseparate';
2262 $groupimage = $CFG->pixpath.'/t/groups.gif';
2263 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=0&amp;sesskey='.$sesskey;
2264 } else if ($mod->groupmode == VISIBLEGROUPS) {
2265 $grouptitle = $str->groupsvisible;
2266 $groupclass = 'editing_groupvisible';
2267 $groupimage = $CFG->pixpath.'/t/groupv.gif';
2268 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=1&amp;sesskey='.$sesskey;
2269 } else {
2270 $grouptitle = $str->groupsnone;
2271 $groupclass = 'editing_groupsnone';
2272 $groupimage = $CFG->pixpath.'/t/groupn.gif';
2273 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=2&amp;sesskey='.$sesskey;
2275 if ($mod->groupmodelink) {
2276 $groupmode = '<a class="'.$groupclass.'" title="'.$grouptitle.' ('.$str->clicktochange.')" href="'.$grouplink.'">'.
2277 '<img src="'.$groupimage.'" class="iconsmall" '.
2278 'alt="'.$grouptitle.'" /></a>';
2279 } else {
2280 $groupmode = '<img title="'.$grouptitle.' ('.$str->forcedmode.')" '.
2281 ' src="'.$groupimage.'" class="iconsmall" '.
2282 'alt="'.$grouptitle.'" />';
2284 } else {
2285 $groupmode = "";
2288 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $mod->course))) {
2289 if ($moveselect) {
2290 $move = '<a class="editing_move" title="'.$str->move.'" href="'.$path.'/mod.php?copy='.$mod->id.
2291 '&amp;sesskey='.$sesskey.$section.'"><img'.
2292 ' src="'.$CFG->pixpath.'/t/move.gif" class="iconsmall" '.
2293 ' alt="'.$str->move.'" /></a>'."\n";
2294 } else {
2295 $move = '<a class="editing_moveup" title="'.$str->moveup.'" href="'.$path.'/mod.php?id='.$mod->id.
2296 '&amp;move=-1&amp;sesskey='.$sesskey.$section.'"><img'.
2297 ' src="'.$CFG->pixpath.'/t/up.gif" class="iconsmall" '.
2298 ' alt="'.$str->moveup.'" /></a>'."\n".
2299 '<a class="editing_movedown" title="'.$str->movedown.'" href="'.$path.'/mod.php?id='.$mod->id.
2300 '&amp;move=1&amp;sesskey='.$sesskey.$section.'"><img'.
2301 ' src="'.$CFG->pixpath.'/t/down.gif" class="iconsmall" '.
2302 ' alt="'.$str->movedown.'" /></a>'."\n";
2306 $leftright = "";
2307 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $mod->course))) {
2308 if ($indent > 0) {
2309 $leftright .= '<a class="editing_moveleft" title="'.$str->moveleft.'" href="'.$path.'/mod.php?id='.$mod->id.
2310 '&amp;indent=-1&amp;sesskey='.$sesskey.$section.'"><img'.
2311 ' src="'.$CFG->pixpath.'/t/left.gif" class="iconsmall" '.
2312 ' alt="'.$str->moveleft.'" /></a>'."\n";
2314 if ($indent >= 0) {
2315 $leftright .= '<a class="editing_moveright" title="'.$str->moveright.'" href="'.$path.'/mod.php?id='.$mod->id.
2316 '&amp;indent=1&amp;sesskey='.$sesskey.$section.'"><img'.
2317 ' src="'.$CFG->pixpath.'/t/right.gif" class="iconsmall" '.
2318 ' alt="'.$str->moveright.'" /></a>'."\n";
2322 return '<span class="commands">'."\n".$leftright.$move.
2323 '<a class="editing_update" title="'.$str->update.'" href="'.$path.'/mod.php?update='.$mod->id.
2324 '&amp;sesskey='.$sesskey.$section.'"><img'.
2325 ' src="'.$CFG->pixpath.'/t/edit.gif" class="iconsmall" '.
2326 ' alt="'.$str->update.'" /></a>'."\n".
2327 '<a class="editing_delete" title="'.$str->delete.'" href="'.$path.'/mod.php?delete='.$mod->id.
2328 '&amp;sesskey='.$sesskey.$section.'"><img'.
2329 ' src="'.$CFG->pixpath.'/t/delete.gif" class="iconsmall" '.
2330 ' alt="'.$str->delete.'" /></a>'."\n".$hideshow.$groupmode."\n".'</span>';
2334 * given a course object with shortname & fullname, this function will
2335 * truncate the the number of chars allowed and add ... if it was too long
2337 function course_format_name ($course,$max=100) {
2339 $str = $course->shortname.': '. $course->fullname;
2340 if (strlen($str) <= $max) {
2341 return $str;
2343 else {
2344 return substr($str,0,$max-3).'...';
2349 * This function will return true if the given course is a child course at all
2351 function course_in_meta ($course) {
2352 return record_exists("course_meta","child_course",$course->id);
2357 * Print standard form elements on module setup forms in mod/.../mod.html
2359 function print_standard_coursemodule_settings($form) {
2360 if (! $course = get_record('course', 'id', $form->course)) {
2361 error("This course doesn't exist");
2363 print_groupmode_setting($form, $course);
2364 print_visible_setting($form, $course);
2368 * Print groupmode form element on module setup forms in mod/.../mod.html
2370 function print_groupmode_setting($form, $course=NULL) {
2372 if (empty($course)) {
2373 if (! $course = get_record('course', 'id', $form->course)) {
2374 error("This course doesn't exist");
2377 if ($form->coursemodule) {
2378 if (! $cm = get_record('course_modules', 'id', $form->coursemodule)) {
2379 error("This course module doesn't exist");
2381 } else {
2382 $cm = null;
2384 $groupmode = groupmode($course, $cm);
2385 if ($course->groupmode or (!$course->groupmodeforce)) {
2386 echo '<tr valign="top">';
2387 echo '<td align="right"><b>'.get_string('groupmode').':</b></td>';
2388 echo '<td align="left">';
2389 unset($choices);
2390 $choices[NOGROUPS] = get_string('groupsnone');
2391 $choices[SEPARATEGROUPS] = get_string('groupsseparate');
2392 $choices[VISIBLEGROUPS] = get_string('groupsvisible');
2393 choose_from_menu($choices, 'groupmode', $groupmode, '', '', 0, false, $course->groupmodeforce);
2394 helpbutton('groupmode', get_string('groupmode'));
2395 echo '</td></tr>';
2400 * Print visibility setting form element on module setup forms in mod/.../mod.html
2402 function print_visible_setting($form, $course=NULL) {
2403 if (empty($course)) {
2404 if (! $course = get_record('course', 'id', $form->course)) {
2405 error("This course doesn't exist");
2408 if ($form->coursemodule) {
2409 $visible = get_field('course_modules', 'visible', 'id', $form->coursemodule);
2410 } else {
2411 $visible = true;
2414 if ($form->mode == 'add') { // in this case $form->section is the section number, not the id
2415 $hiddensection = !get_field('course_sections', 'visible', 'section', $form->section, 'course', $form->course);
2416 } else {
2417 $hiddensection = !get_field('course_sections', 'visible', 'id', $form->section);
2419 if ($hiddensection) {
2420 $visible = false;
2423 echo '<tr valign="top">';
2424 echo '<td align="right"><b>'.get_string('visible', '').':</b></td>';
2425 echo '<td align="left">';
2426 unset($choices);
2427 $choices[1] = get_string('show');
2428 $choices[0] = get_string('hide');
2429 choose_from_menu($choices, 'visible', $visible, '', '', 0, false, $hiddensection);
2430 echo '</td></tr>';
2433 function update_restricted_mods($course,$mods) {
2434 delete_records("course_allowed_modules","course",$course->id);
2435 if (empty($course->restrictmodules)) {
2436 return;
2438 else {
2439 foreach ($mods as $mod) {
2440 if ($mod == 0)
2441 continue; // this is the 'allow none' option
2442 $am->course = $course->id;
2443 $am->module = $mod;
2444 insert_record("course_allowed_modules",$am);
2450 * This function will take an int (module id) or a string (module name)
2451 * and return true or false, whether it's allowed in the given course (object)
2452 * $mod is not allowed to be an object, as the field for the module id is inconsistent
2453 * depending on where in the code it's called from (sometimes $mod->id, sometimes $mod->module)
2456 function course_allowed_module($course,$mod) {
2457 if (empty($course->restrictmodules)) {
2458 return true;
2461 // i am not sure this capability is correct
2462 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
2463 return true;
2465 if (is_numeric($mod)) {
2466 $modid = $mod;
2467 } else if (is_string($mod)) {
2468 if ($mod = get_field("modules","id","name",$mod))
2469 $modid = $mod;
2471 if (empty($modid)) {
2472 return false;
2474 return (record_exists("course_allowed_modules","course",$course->id,"module",$modid));
2477 /***
2478 *** Efficiently moves many courses around while maintaining
2479 *** sortorder in order.
2481 *** $courseids is an array of course ids
2485 function move_courses ($courseids, $categoryid) {
2487 global $CFG;
2489 if (!empty($courseids)) {
2491 $courseids = array_reverse($courseids);
2493 foreach ($courseids as $courseid) {
2495 if (! $course = get_record("course", "id", $courseid)) {
2496 notify("Error finding course $courseid");
2497 } else {
2498 // figure out a sortorder that we can use in the destination category
2499 $sortorder = get_field_sql('SELECT MIN(sortorder)-1 AS min
2500 FROM ' . $CFG->prefix . 'course WHERE category=' . $categoryid);
2501 if ($sortorder === false) {
2502 // the category is empty
2503 // rather than let the db default to 0
2504 // set it to > 100 and avoid extra work in fix_coursesortorder()
2505 $sortorder = 200;
2506 } else if ($sortorder < 10) {
2507 fix_course_sortorder($categoryid);
2510 $course->category = $categoryid;
2511 $course->sortorder = $sortorder;
2512 $course->fullname = addslashes($course->fullname);
2513 $course->shortname = addslashes($course->shortname);
2514 $course->summary = addslashes($course->summary);
2515 $course->password = addslashes($course->password);
2516 $course->teacher = addslashes($course->teacher);
2517 $course->teachers = addslashes($course->teachers);
2518 $course->student = addslashes($course->student);
2519 $course->students = addslashes($course->students);
2521 if (!update_record('course', $course)) {
2522 notify("An error occurred - course not moved!");
2524 // parents changed (course category), do not delete child context relations
2525 insert_context_rel(get_context_instance(CONTEXT_COURSE, $course->id), false);
2528 fix_course_sortorder();
2530 return true;
2534 * @param string $format Course format ID e.g. 'weeks'
2535 * @return Name that the course format prefers for sections
2537 function get_section_name($format) {
2538 $sectionname = get_string("name$format","format_$format");
2539 if($sectionname == "[[name$format]]") {
2540 $sectionname = get_string("name$format");
2542 return $sectionname;
2546 * Can the current user delete this course?
2547 * @param int $courseid
2548 * @return boolean
2550 * Exception here to fix MDL-7796.
2552 * FIXME
2553 * Course creators who can manage activities in the course
2554 * shoule be allowed to delete the course. We do it this
2555 * way because we need a quick fix to bring the functionality
2556 * in line with what we had pre-roles. We can't give the
2557 * default course creator role moodle/course:delete at
2558 * CONTEXT_SYSTEM level because this will allow them to
2559 * delete any course in the site. So we hard code this here
2560 * for now.
2562 * @author vyshane AT gmail.com
2564 function can_delete_course($courseid) {
2566 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2568 return ( has_capability('moodle/course:delete', $context)
2569 || (has_capability('moodle/legacy:coursecreator', $context)
2570 && has_capability('moodle/course:manageactivities', $context)) );