2 // Library of useful functions
5 if (defined('COURSE_MAX_LOG_DISPLAY')) { // Being included again - should never happen!!
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") {
34 if ($advancedfilter) {
36 // Get all the possible users
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) {
52 $courses["$cc->id"] = "$cc->fullname";
54 $courses["$cc->id"] = " $cc->fullname (Site)";
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
)) {
68 if ($course->format
== 'weeks') { // Body
69 $strsection = get_string("week");
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") {
87 if (!$mod->visible
and !has_capability('moodle/course:viewhiddenactivities',get_context_instance(CONTEXT_MODULE
, $mod->cm
))) {
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)."...";
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");
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);
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
;
133 while ($timemidnight > $course->startdate
and $numdates < 365) {
134 $timemidnight = $timemidnight - 86400;
135 $timenow = $timenow - 86400;
136 $dates["$timemidnight"] = userdate($timenow, $strftimedaydate);
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" />';
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
, "");
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") );
163 echo '<td align="right"><b>' . get_string("since") . '</b></td><td>';
164 choose_from_menu ($dates, "date", $selecteddate, get_string("alldays"));
167 echo "<tr><td><b>" . get_string("activities") . "</b></td><td>";
168 choose_from_menu ($activities, "modid", $selectedactivity, "");
171 echo '<td align="right"><b>' . get_string("sortby") . "</b></td><td>";
172 choose_from_menu ($sortfields, "sortby", $selectedsort, "");
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.
182 if ($groupmode == VISIBLEGROUPS
) {
183 print_string('groupsvisible');
185 print_string('groupsseparate');
187 echo ':</b></td><td>';
188 choose_from_menu($groups_names, "selectedgroup", $selectedgroup, get_string("allgroups"), "", "");
194 echo '<td colspan="2" align="right">';
195 echo '<input type="submit" value="'.get_string('showrecent').'" />';
200 $advancedlink = "<a href=\"$CFG->wwwroot/course/recent.php?id=$course->id&advancedfilter=0\">" . get_string("normalfilter") . "</a>";
201 print_heading($advancedlink);
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");
214 foreach ($day_list as $count) {
220 $tmpdate = time() - ($count * 3600 * 24);
221 $heading = $heading .
222 "<a href=\"$CFG->wwwroot/course/recent.php?id=$course->id&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&advancedfilter=1\">" . get_string("advancedfilter") . "</a>";
229 print_heading($advancedlink);
236 function make_log_url($module, $url) {
247 return "/$module/$url";
257 return "/mod/$module/$url";
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) {
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) {
297 {$CFG->prefix}mnet_log l
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'";
313 $where .= " AND\n l.module = '$modname'";
316 if ('site_errors' === $modid) {
317 $where .= " AND\n ( l.action='error' OR l.action='infected' )";
319 //TODO: This assumes that modids are the same across sites... probably
321 $where .= " AND\n l.cmid = '$modid'";
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)) . "%'";
334 $where .= " AND\n l.userid = '$user'";
338 $enddate = $date +
86400;
339 $where .= " AND\n l.time > '$date' AND l.time < '$enddate'";
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);
348 $result['logs'] = array();
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
) {
373 if ($course->id
!= SITEID ||
$modid != 0) {
374 $joins[] = "l.course='$course->id'";
378 $joins[] = "l.module = '$modname'";
381 if ('site_errors' === $modid) {
382 $joins[] = "( l.action='error' OR l.action='infected' )";
384 $joins[] = "l.cmid = '$modid'";
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.
400 foreach($gusers as $guser) {
402 $gselect = '(l.userid='.$guser->userid
;
406 $gselect .= ' OR l.userid='.$guser->userid
;
409 if (!$first) $gselect .= ')';
414 $joins[] = "l.userid = '$user'";
418 $enddate = $date +
86400;
419 $joins[] = "l.time > '$date' AND l.time < '$enddate'";
423 for ($i = 0; $i < count($joins); $i++
) {
424 $selector .= $joins[$i] . (($i == count($joins)-1) ?
" " : " AND ");
427 $totalcount = 0; // Initialise
430 $result['logs'] = get_logs($selector, $order, $limitfrom, $limitnum, $totalcount);
431 $result['totalcount'] = $totalcount;
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) {
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);
450 if ($course->id
== SITEID
) {
452 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
453 foreach ($ccc as $cc) {
454 $courses[$cc->id
] = $cc->shortname
;
458 $courses[$course->id
] = $course->shortname
;
461 $totalcount = $logs['totalcount'];
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);
473 print_paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage&");
475 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\" summary=\"\">\n";
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";
487 if (empty($logs['logs'])) {
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
];
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);
508 $log->info
= get_field($ld->mtable
, $ld->field
, 'id', $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('&', '&', $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";
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&user=$log->userid", 'iplookup',$log->ip
, 400, 700);
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}&course={$log->course}\">$fullname</a>\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);
537 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
542 print_paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage&");
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) {
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);
558 if ($course->id
== SITEID
) {
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'];
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);
579 print_paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage&");
581 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
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";
593 if (empty($logs['logs'])) {
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
];
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);
615 $log->info
= get_field($ld->mtable
, $ld->field
, 'id', $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('&', '&', $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";
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&user=$log->userid", 'iplookup',$log->ip
, 400, 700);
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";
641 echo "<td class=\"r$row c4\">\n";
642 echo $log->action
.': '.$log->module
;
644 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
649 print_paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage&");
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)) {
666 if ($course->id
== SITEID
) {
668 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
669 foreach ($ccc as $cc) {
670 $courses[$cc->id
] = $cc->shortname
;
674 $courses[$course->id
] = $course->shortname
;
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);
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";
695 if (empty($logs['logs'])) {
699 foreach ($logs['logs'] as $log) {
700 if (isset($ldcache[$log->module
][$log->action
])) {
701 $ld = $ldcache[$log->module
][$log->action
];
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);
711 $log->info
= get_field($ld->mtable
, $ld->field
, 'id', $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('&', '&', $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);
732 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
733 $modid, $modaction, $groupid) {
737 require_once("$CFG->libdir/excellib.class.php");
739 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
740 $modname, $modid, $modaction, $groupid)) {
746 if ($course->id
== SITEID
) {
748 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
749 foreach ($ccc as $cc) {
750 $courses[$cc->id
] = $cc->shortname
;
754 $courses[$course->id
] = $course->shortname
;
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);
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));
783 foreach ($headers as $item) {
784 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW
-1,$col,$item,'');
789 if (empty($logs['logs'])) {
794 $formatDate =& $workbook->add_format();
795 $formatDate->set_num_format(get_string('log_excel_date_format'));
797 $row = FIRSTUSEDEXCELROW
;
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
];
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);
812 $log->info
= get_field($ld->mtable
, $ld->field
, 'id', $log->info
);
817 $log->info
= format_string($log->info
);
818 $log->info
= strip_tags(urldecode($log->info
)); // Some XSS protection
821 if ($row > EXCELROWS
) {
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
, '');
845 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
846 $modid, $modaction, $groupid) {
850 require_once("$CFG->libdir/odslib.class.php");
852 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
853 $modname, $modid, $modaction, $groupid)) {
859 if ($course->id
== SITEID
) {
861 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
862 foreach ($ccc as $cc) {
863 $courses[$cc->id
] = $cc->shortname
;
867 $courses[$course->id
] = $course->shortname
;
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);
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));
896 foreach ($headers as $item) {
897 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW
-1,$col,$item,'');
902 if (empty($logs['logs'])) {
907 $formatDate =& $workbook->add_format();
908 $formatDate->set_num_format(get_string('log_excel_date_format'));
910 $row = FIRSTUSEDEXCELROW
;
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
];
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);
925 $log->info
= get_field($ld->mtable
, $ld->field
, 'id', $log->info
);
930 $log->info
= format_string($log->info
);
931 $log->info
= strip_tags(urldecode($log->info
)); // Some XSS protection
934 if ($row > EXCELROWS
) {
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
);
957 function print_log_graph($course, $userid=0, $type="course.png", $date=0) {
959 if (empty($CFG->gdversion
)) {
960 echo "(".get_string("gdneed").")";
962 echo '<img src="'.$CFG->wwwroot
.'/course/report/log/graph.php?id='.$course->id
.
963 '&user='.$userid.'&type='.$type.'&date='.$date.'" alt="" />';
968 function print_overview($courses) {
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");
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) {
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));
1023 echo '<div class="activityhead">';
1025 echo '<a href="'.$CFG->wwwroot
.'/course/recent.php?id='.$course->id
.'">'.get_string('recentactivityreport').'</a>';
1030 // Firstly, have there been any new enrolments?
1035 $users = get_recent_enrolments($course->id
, $timestart);
1037 //Accessibility: new users now appear in an <OL> list.
1039 echo '<div class="newusers">';
1041 print_headline(get_string("newusers").':', 3);
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&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");
1060 foreach ($logs as $key => $log) {
1061 $info = split(' ', $log->info
);
1063 if ($info[0] == 'label') { // Labels are special activities
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
1076 switch ($log->action
) {
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>");
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>");
1088 if (!empty($changelist[$log->info
]['operation']) and
1089 $changelist[$log->info
]['operation'] == 'add') {
1090 $changelist[$log->info
] = NULL;
1092 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $info[0]));
1093 $changelist[$log->info
] = array ('operation' => 'delete', 'text' => $strdeleted);
1101 if (!empty($changelist)) {
1102 foreach ($changelist as $changeinfo => $change) {
1104 $changes[$changeinfo] = $change;
1107 if (isset($changes)){
1108 if (count($changes) > 0) {
1109 print_headline(get_string('courseupdates').':', 3);
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)) {
1130 // $isteacher (second parameter below) is to be deprecated!
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
1138 $modcontent = $print_recent_activity($course, $viewfullnames, $timestart);
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
1165 if (!$rawmods = get_course_mods($courseid)) {
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])) {
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
;
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");
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
])) {
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) {
1256 if ($display == "all" or empty($display)) {
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);
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
1297 static $groupbuttons;
1298 static $groupbuttonslink;
1302 static $strmovehere;
1303 static $strmovefull;
1304 static $strunreadpostsone;
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
);
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])) {
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
1347 if ($mod->id
== $USER->activitycopy
) {
1350 echo '<a title="'.$strmovefull.'"'.
1351 ' href="'.$CFG->wwwroot
.'/course/mod.php?moveto='.$mod->id
.'&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
);
1365 if (!empty($modinfo[$modnumber]->icon
)) {
1366 $icon = "$CFG->pixpath/".urldecode($modinfo[$modnumber]->icon
);
1368 $icon = "$CFG->modpixpath/$mod->modname/icon.gif";
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
) {
1384 } else { // Normal activity
1386 if (!empty($USER->screenreader
)) {
1387 $typestring = '('.get_string('modulename',$mod->modname
).') ';
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);
1407 echo '<span class="unread"> <a href="'.$CFG->wwwroot
.'/mod/forum/view.php?id='.$mod->id
.'">';
1409 echo $strunreadpostsone;
1411 print_string('unreadpostsnumber', 'forum', $unread);
1413 echo '</a> </span>';
1419 if ($groupbuttons and $mod->modname
!= 'label' and $mod->modname
!= 'resource') {
1420 if (! $mod->groupmodelink
= $groupbuttonslink) {
1421 $mod->groupmode
= $course->groupmode
;
1425 $mod->groupmode
= false;
1427 echo ' ';
1428 echo make_editing_buttons($mod, $absolute, true, $mod->indent
, $section->section
);
1433 } elseif ($ismoving) {
1434 echo "<ul class=\"section\">\n";
1437 echo '<li><a title="'.$strmovefull.'"'.
1438 ' href="'.$CFG->wwwroot
.'/course/mod.php?movetosection='.$section->id
.'&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) {
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)) {
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
;
1474 $activities[$type->type
] = $type->typestr
;
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">';
1490 $output .= '<div class="horizontal">';
1493 if (!empty($resources)) {
1494 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&section=$section&sesskey=".sesskey()."&add=",
1495 $resources, "ressection$section", "", $straddresource, 'resource/types', $straddresource, true);
1498 if (!empty($activities)) {
1500 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&section=$section&sesskey=".sesskey()."&add=",
1501 $activities, "section$section", "", $straddactivity, 'mods', $straddactivity, true);
1505 $output .= '</div>';
1508 $output .= '</div>';
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
1522 $select = "id = '$courseid'";
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)) {
1548 if (!is_array($parents)) {
1554 $path = $path.' / '.$category->name
;
1556 $path = $category->name
;
1558 $list[$category->id
] = $path;
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
1582 if (isset($CFG->max_category_depth
) && ($depth >= $CFG->max_category_depth
)) {
1586 if (!$displaylist) {
1587 make_categories_list($displaylist, $parentslist);
1591 if ($category->visible
or has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM
, SITEID
))) {
1592 print_category_info($category, $depth, $files);
1594 return; // Don't bother printing children of invisible categories
1598 $category->id
= "0";
1601 if ($categories = get_categories($category->id
)) { // Print all the children recursively
1602 $countcats = count($categories);
1606 foreach ($categories as $cat) {
1608 if ($count == $countcats) {
1611 $up = $first ?
false : true;
1612 $down = $last ?
false : true;
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] = ' '.$cats[$key];
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
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="" />';
1655 $catimage = " ";
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');
1666 $indent = $depth*30;
1667 $rows = count($courses) +
1;
1668 echo '<td rowspan="'.$rows.'" valign="top" width="'.$indent.'">';
1669 print_spacer(10, $indent);
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>';
1677 echo '<td class="category info"> </td>';
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"> ';
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>';
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>';
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);
1704 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath
.'/spacer.gif" />';
1714 $indent = $depth*20;
1715 echo '<td valign="top" width="'.$indent.'">';
1716 print_spacer(10, $indent);
1720 echo '<td valign="top" class="category name">';
1721 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot
.'/course/category.php?id='.$category->id
.'">'.$category->name
.'</a>';
1723 echo '<td valign="top" class="category number">';
1724 if ($category->coursecount
) {
1725 echo $category->coursecount
;
1733 function print_courses($category, $width="100%", $hidesitecourse = false) {
1734 /// Category is 0 (for all courses) or an object
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');
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');
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');
1753 foreach ($courses as $course) {
1754 if ($hidesitecourse and ($course->id
== SITEID
)) {
1757 print_course($course, $width);
1760 print_heading(get_string("nocoursesyet"));
1761 $context = get_context_instance(CONTEXT_SYSTEM
, SITEID
);
1762 if (has_capability('moodle/course:create', $context)) {
1764 $options['category'] = $category->id
;
1765 echo '<div class="addcoursebutton">';
1766 print_single_button($CFG->wwwroot
.'/course/edit.php', $options, get_string("addnewcourse"));
1776 function print_course($course, $width="100%") {
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
.'&course='.SITEID
.'">'.$fullname.'</a>';
1804 if (!empty($namesarray)) {
1805 echo "<ul class=\"teachers\">\n<li>";
1806 echo implode('</li><li>', $namesarray);
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">';
1817 $options->noclean
= true;
1818 $options->para
= false;
1819 echo format_text($course->summary
, FORMAT_MOODLE
, $options, $course->id
);
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
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
);
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
) {
1851 print_course($course, "100%");
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%");
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";
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();
1884 print_courses(0, "100%");
1890 function print_course_search($value="", $return=false, $format="plain") {
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>';
1922 function print_remote_course($course, $width="100%") {
1928 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&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">';
1940 $options->noclean
= true;
1941 $options->para
= false;
1942 echo format_text($course->summary
, FORMAT_MOODLE
, $options);
1945 echo '<div class="clearer"></div>';
1948 function print_remote_host($host, $width="100%") {
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');
1964 echo '<div class="clearer"></div>';
1968 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
1970 function add_course_module($mod) {
1972 $mod->added
= time();
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";
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.
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)) {
2038 if (!$modulename = get_field('modules', 'name', 'id', $cm->module
)) {
2041 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
2042 foreach($events as $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);
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)) {
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
);
2099 function move_section($course, $section, $move) {
2100 /// Moves a whole course section up and down within the course
2107 $sectiondest = $section +
$move;
2109 if ($sectiondest > $course->numsections
or $sectiondest < 1) {
2113 if (!$sectionrecord = get_record("course_sections", "course", $course->id
, "section", $section)) {
2117 if (!$sectiondestrecord = get_record("course_sections", "course", $course->id
, "section", $sectiondest)) {
2121 if (!set_field("course_sections", "section", $sectiondest, "id", $sectionrecord->id
)) {
2124 if (!set_field("course_sections", "section", $section, "id", $sectiondestrecord->id
)) {
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');
2136 foreach ($sections as $section) {
2137 if ($section->section
!= $n) {
2138 if (!set_field('course_sections', 'section', $n, 'id', $section->id
)) {
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)) {
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)) {
2187 function make_editing_buttons($mod, $absolute=false, $moveselect=true, $indent=-1, $section=-1) {
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 = '&sr='.$section; // Section return
2219 $path = $CFG->wwwroot
.'/course';
2224 if ($mod->visible
) {
2225 $hideshow = '<a class="editing_hide" title="'.$str->hide
.'" href="'.$path.'/mod.php?hide='.$mod->id
.
2226 '&sesskey='.$sesskey.$section.'"><img'.
2227 ' src="'.$CFG->pixpath
.'/t/hide.gif" class="iconsmall" '.
2228 ' alt="'.$str->hide
.'" /></a>'."\n";
2230 $hideshow = '<a class="editing_show" title="'.$str->show
.'" href="'.$path.'/mod.php?show='.$mod->id
.
2231 '&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
.'&groupmode=0&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
.'&groupmode=1&sesskey='.$sesskey;
2247 $grouptitle = $str->groupsnone
;
2248 $groupclass = 'editing_groupsnone';
2249 $groupimage = $CFG->pixpath
.'/t/groupn.gif';
2250 $grouplink = $path.'/mod.php?id='.$mod->id
.'&groupmode=2&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>';
2257 $groupmode = '<img title="'.$grouptitle.' ('.$str->forcedmode
.')" '.
2258 ' src="'.$groupimage.'" class="iconsmall" '.
2259 'alt="'.$grouptitle.'" />';
2266 $move = '<a class="editing_move" title="'.$str->move
.'" href="'.$path.'/mod.php?copy='.$mod->id
.
2267 '&sesskey='.$sesskey.$section.'"><img'.
2268 ' src="'.$CFG->pixpath
.'/t/move.gif" class="iconsmall" '.
2269 ' alt="'.$str->move
.'" /></a>'."\n";
2271 $move = '<a class="editing_moveup" title="'.$str->moveup
.'" href="'.$path.'/mod.php?id='.$mod->id
.
2272 '&move=-1&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 '&move=1&sesskey='.$sesskey.$section.'"><img'.
2277 ' src="'.$CFG->pixpath
.'/t/down.gif" class="iconsmall" '.
2278 ' alt="'.$str->movedown
.'" /></a>'."\n";
2283 $leftright .= '<a class="editing_moveleft" title="'.$str->moveleft
.'" href="'.$path.'/mod.php?id='.$mod->id
.
2284 '&indent=-1&sesskey='.$sesskey.$section.'"><img'.
2285 ' src="'.$CFG->pixpath
.'/t/left.gif" class="iconsmall" '.
2286 ' alt="'.$str->moveleft
.'" /></a>'."\n";
2289 $leftright .= '<a class="editing_moveright" title="'.$str->moveright
.'" href="'.$path.'/mod.php?id='.$mod->id
.
2290 '&indent=1&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 '&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 '&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) {
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");
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">';
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'));
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
);
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
);
2390 $hiddensection = !get_field('course_sections', 'visible', 'id', $form->section
);
2392 if ($hiddensection) {
2396 echo '<tr valign="top">';
2397 echo '<td align="right"><b>'.get_string('visible', '').':</b></td>';
2398 echo '<td align="left">';
2400 $choices[1] = get_string('show');
2401 $choices[0] = get_string('hide');
2402 choose_from_menu($choices, 'visible', $visible, '', '', 0, false, $hiddensection);
2406 function update_restricted_mods($course,$mods) {
2407 delete_records("course_allowed_modules","course",$course->id
);
2408 if (empty($course->restrictmodules
)) {
2412 foreach ($mods as $mod) {
2414 continue; // this is the 'allow none' option
2415 $am->course
= $course->id
;
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
)) {
2434 // i am not sure this capability is correct
2435 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM
, SITEID
))) {
2438 if (is_numeric($mod)) {
2440 } else if (is_string($mod)) {
2441 if ($mod = get_field("modules","id","name",$mod))
2444 if (empty($modid)) {
2447 return (record_exists("course_allowed_modules","course",$course->id
,"module",$modid));
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) {
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");
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()
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();
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;