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 $gusers = groups_get_members($groupid);
399 if (!empty($gusers)) {
400 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
402 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always by false.
406 $joins[] = "l.userid = '$user'";
410 $enddate = $date +
86400;
411 $joins[] = "l.time > '$date' AND l.time < '$enddate'";
414 $selector = implode(' AND ', $joins);
416 $totalcount = 0; // Initialise
418 $result['logs'] = get_logs($selector, $order, $limitfrom, $limitnum, $totalcount);
419 $result['totalcount'] = $totalcount;
424 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
425 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
429 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
430 $modname, $modid, $modaction, $groupid)) {
431 notify("No logs found!");
432 print_footer($course);
438 if ($course->id
== SITEID
) {
440 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
441 foreach ($ccc as $cc) {
442 $courses[$cc->id
] = $cc->shortname
;
446 $courses[$course->id
] = $course->shortname
;
449 $totalcount = $logs['totalcount'];
452 $tt = getdate(time());
453 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
455 $strftimedatetime = get_string("strftimedatetime");
457 echo "<div class=\"info\">\n";
458 print_string("displayingrecords", "", $totalcount);
461 print_paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage&");
463 echo '<table class="logtable genearlbox boxaligncenter" summary="">'."\n";
464 // echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\" summary=\"\">\n";
466 if ($course->id
== SITEID
) {
467 echo "<th class=\"c0 header\" scope=\"col\">".get_string('course')."</th>\n";
469 echo "<th class=\"c1 header\" scope=\"col\">".get_string('time')."</th>\n";
470 echo "<th class=\"c2 header\" scope=\"col\">".get_string('ip_address')."</th>\n";
471 echo "<th class=\"c3 header\" scope=\"col\">".get_string('fullname')."</th>\n";
472 echo "<th class=\"c4 header\" scope=\"col\">".get_string('action')."</th>\n";
473 echo "<th class=\"c5 header\" scope=\"col\">".get_string('info')."</th>\n";
476 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
477 if (empty($logs['logs'])) {
478 $logs['logs'] = array();
482 foreach ($logs['logs'] as $log) {
484 $row = ($row +
1) %
2;
486 if (isset($ldcache[$log->module
][$log->action
])) {
487 $ld = $ldcache[$log->module
][$log->action
];
489 $ld = get_record('log_display', 'module', $log->module
, 'action', $log->action
);
490 $ldcache[$log->module
][$log->action
] = $ld;
492 if ($ld && is_numeric($log->info
)) {
493 // ugly hack to make sure fullname is shown correctly
494 if (($ld->mtable
== 'user') and ($ld->field
== sql_concat('firstname', "' '" , 'lastname'))) {
495 $log->info
= fullname(get_record($ld->mtable
, 'id', $log->info
), true);
497 $log->info
= get_field($ld->mtable
, $ld->field
, 'id', $log->info
);
502 $log->info
= format_string($log->info
);
504 $log->url
= strip_tags(urldecode($log->url
)); // Some XSS protection
505 $log->info
= strip_tags(urldecode($log->info
)); // Some XSS protection
506 $log->url
= str_replace('&', '&', $log->url
); /// XHTML compatibility
508 echo '<tr class="r'.$row.'">';
509 if ($course->id
== SITEID
) {
510 echo "<td class=\"cell c0\">\n";
511 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course
])."</a>\n";
514 echo "<td class=\"cell c1\" align=\"right\">".userdate($log->time
, '%a').
515 ' '.userdate($log->time
, $strftimedatetime)."</td>\n";
516 echo "<td class=\"cell c2\">\n";
517 link_to_popup_window("/iplookup/index.php?ip=$log->ip&user=$log->userid", 'iplookup',$log->ip
, 400, 700);
519 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE
, $course->id
)));
520 echo "<td class=\"cell c3\">\n";
521 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}&course={$log->course}\">$fullname</a>\n";
523 echo "<td class=\"cell c4\">\n";
524 link_to_popup_window( make_log_url($log->module
,$log->url
), 'fromloglive',"$log->module $log->action", 400, 600);
526 echo "<td class=\"cell c5\">{$log->info}</td>\n";
531 print_paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage&");
535 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
536 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
540 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
541 $modname, $modid, $modaction, $groupid)) {
542 notify("No logs found!");
543 print_footer($course);
547 if ($course->id
== SITEID
) {
549 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
550 foreach ($ccc as $cc) {
551 $courses[$cc->id
] = $cc->shortname
;
556 $totalcount = $logs['totalcount'];
559 $tt = getdate(time());
560 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
562 $strftimedatetime = get_string("strftimedatetime");
564 echo "<div class=\"info\">\n";
565 print_string("displayingrecords", "", $totalcount);
568 print_paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage&");
570 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
572 if ($course->id
== SITEID
) {
573 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
575 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
576 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
577 echo "<th class=\"c3 header\">".get_string('fullname')."</th>\n";
578 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
579 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
582 if (empty($logs['logs'])) {
588 foreach ($logs['logs'] as $log) {
590 $log->info
= $log->coursename
;
591 $row = ($row +
1) %
2;
593 if (isset($ldcache[$log->module
][$log->action
])) {
594 $ld = $ldcache[$log->module
][$log->action
];
596 $ld = get_record('log_display', 'module', $log->module
, 'action', $log->action
);
597 $ldcache[$log->module
][$log->action
] = $ld;
599 if (0 && $ld && !empty($log->info
)) {
600 // ugly hack to make sure fullname is shown correctly
601 if (($ld->mtable
== 'user') and ($ld->field
== sql_concat('firstname', "' '" , 'lastname'))) {
602 $log->info
= fullname(get_record($ld->mtable
, 'id', $log->info
), true);
604 $log->info
= get_field($ld->mtable
, $ld->field
, 'id', $log->info
);
609 $log->info
= format_string($log->info
);
611 $log->url
= strip_tags(urldecode($log->url
)); // Some XSS protection
612 $log->info
= strip_tags(urldecode($log->info
)); // Some XSS protection
613 $log->url
= str_replace('&', '&', $log->url
); /// XHTML compatibility
615 echo '<tr class="r'.$row.'">';
616 if ($course->id
== SITEID
) {
617 echo "<td class=\"r$row c0\" >\n";
618 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courses[$log->course
]."</a>\n";
621 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time
, '%a').
622 ' '.userdate($log->time
, $strftimedatetime)."</td>\n";
623 echo "<td class=\"r$row c2\" >\n";
624 link_to_popup_window("/iplookup/index.php?ip=$log->ip&user=$log->userid", 'iplookup',$log->ip
, 400, 700);
626 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE
, $course->id
)));
627 echo "<td class=\"r$row c3\" >\n";
628 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
630 echo "<td class=\"r$row c4\">\n";
631 echo $log->action
.': '.$log->module
;
633 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
638 print_paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage&");
642 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
643 $modid, $modaction, $groupid) {
645 $text = get_string('course')."\t".get_string('time')."\t".get_string('ip_address')."\t".
646 get_string('fullname')."\t".get_string('action')."\t".get_string('info');
648 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
649 $modname, $modid, $modaction, $groupid)) {
655 if ($course->id
== SITEID
) {
657 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
658 foreach ($ccc as $cc) {
659 $courses[$cc->id
] = $cc->shortname
;
663 $courses[$course->id
] = $course->shortname
;
668 $tt = getdate(time());
669 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
671 $strftimedatetime = get_string("strftimedatetime");
673 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
675 header("Content-Type: application/download\n");
676 header("Content-Disposition: attachment; filename=$filename");
677 header("Expires: 0");
678 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
679 header("Pragma: public");
681 echo get_string('savedat').userdate(time(), $strftimedatetime)."\n";
684 if (empty($logs['logs'])) {
688 foreach ($logs['logs'] as $log) {
689 if (isset($ldcache[$log->module
][$log->action
])) {
690 $ld = $ldcache[$log->module
][$log->action
];
692 $ld = get_record('log_display', 'module', $log->module
, 'action', $log->action
);
693 $ldcache[$log->module
][$log->action
] = $ld;
695 if ($ld && !empty($log->info
)) {
696 // ugly hack to make sure fullname is shown correctly
697 if (($ld->mtable
== 'user') and ($ld->field
== sql_concat('firstname', "' '" , 'lastname'))) {
698 $log->info
= fullname(get_record($ld->mtable
, 'id', $log->info
), true);
700 $log->info
= get_field($ld->mtable
, $ld->field
, 'id', $log->info
);
705 $log->info
= format_string($log->info
);
707 $log->url
= strip_tags(urldecode($log->url
)); // Some XSS protection
708 $log->info
= strip_tags(urldecode($log->info
)); // Some XSS protection
709 $log->url
= str_replace('&', '&', $log->url
); // XHTML compatibility
711 $firstField = $courses[$log->course
];
712 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE
, $course->id
)));
713 $row = array($firstField, userdate($log->time
, $strftimedatetime), $log->ip
, $fullname, $log->module
.' '.$log->action
, $log->info
);
714 $text = implode("\t", $row);
721 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
722 $modid, $modaction, $groupid) {
726 require_once("$CFG->libdir/excellib.class.php");
728 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
729 $modname, $modid, $modaction, $groupid)) {
735 if ($course->id
== SITEID
) {
737 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
738 foreach ($ccc as $cc) {
739 $courses[$cc->id
] = $cc->shortname
;
743 $courses[$course->id
] = $course->shortname
;
748 $tt = getdate(time());
749 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
751 $strftimedatetime = get_string("strftimedatetime");
753 $nroPages = ceil(count($logs)/(EXCELROWS
-FIRSTUSEDEXCELROW+
1));
754 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
757 $workbook = new MoodleExcelWorkbook('-');
758 $workbook->send($filename);
760 $worksheet = array();
761 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
762 get_string('fullname'), get_string('action'), get_string('info'));
764 // Creating worksheets
765 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++
) {
766 $sheettitle = get_string('excel_sheettitle', 'logs', $wsnumber).$nroPages;
767 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
768 $worksheet[$wsnumber]->set_column(1, 1, 30);
769 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
770 userdate(time(), $strftimedatetime));
772 foreach ($headers as $item) {
773 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW
-1,$col,$item,'');
778 if (empty($logs['logs'])) {
783 $formatDate =& $workbook->add_format();
784 $formatDate->set_num_format(get_string('log_excel_date_format'));
786 $row = FIRSTUSEDEXCELROW
;
788 $myxls =& $worksheet[$wsnumber];
789 foreach ($logs['logs'] as $log) {
790 if (isset($ldcache[$log->module
][$log->action
])) {
791 $ld = $ldcache[$log->module
][$log->action
];
793 $ld = get_record('log_display', 'module', $log->module
, 'action', $log->action
);
794 $ldcache[$log->module
][$log->action
] = $ld;
796 if ($ld && !empty($log->info
)) {
797 // ugly hack to make sure fullname is shown correctly
798 if (($ld->mtable
== 'user') and ($ld->field
== sql_concat('firstname', "' '" , 'lastname'))) {
799 $log->info
= fullname(get_record($ld->mtable
, 'id', $log->info
), true);
801 $log->info
= get_field($ld->mtable
, $ld->field
, 'id', $log->info
);
806 $log->info
= format_string($log->info
);
807 $log->info
= strip_tags(urldecode($log->info
)); // Some XSS protection
810 if ($row > EXCELROWS
) {
812 $myxls =& $worksheet[$wsnumber];
813 $row = FIRSTUSEDEXCELROW
;
817 $myxls->write($row, 0, $courses[$log->course
], '');
818 // Excel counts from 1/1/1900
819 $excelTime=25569+
$log->time
/(3600*24);
820 $myxls->write($row, 1, $excelTime, $formatDate);
821 $myxls->write($row, 2, $log->ip
, '');
822 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE
, $course->id
)));
823 $myxls->write($row, 3, $fullname, '');
824 $myxls->write($row, 4, $log->module
.' '.$log->action
, '');
825 $myxls->write($row, 5, $log->info
, '');
834 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
835 $modid, $modaction, $groupid) {
839 require_once("$CFG->libdir/odslib.class.php");
841 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
842 $modname, $modid, $modaction, $groupid)) {
848 if ($course->id
== SITEID
) {
850 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
851 foreach ($ccc as $cc) {
852 $courses[$cc->id
] = $cc->shortname
;
856 $courses[$course->id
] = $course->shortname
;
861 $tt = getdate(time());
862 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
864 $strftimedatetime = get_string("strftimedatetime");
866 $nroPages = ceil(count($logs)/(EXCELROWS
-FIRSTUSEDEXCELROW+
1));
867 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
870 $workbook = new MoodleODSWorkbook('-');
871 $workbook->send($filename);
873 $worksheet = array();
874 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
875 get_string('fullname'), get_string('action'), get_string('info'));
877 // Creating worksheets
878 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++
) {
879 $sheettitle = get_string('excel_sheettitle', 'logs', $wsnumber).$nroPages;
880 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
881 $worksheet[$wsnumber]->set_column(1, 1, 30);
882 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
883 userdate(time(), $strftimedatetime));
885 foreach ($headers as $item) {
886 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW
-1,$col,$item,'');
891 if (empty($logs['logs'])) {
896 $formatDate =& $workbook->add_format();
897 $formatDate->set_num_format(get_string('log_excel_date_format'));
899 $row = FIRSTUSEDEXCELROW
;
901 $myxls =& $worksheet[$wsnumber];
902 foreach ($logs['logs'] as $log) {
903 if (isset($ldcache[$log->module
][$log->action
])) {
904 $ld = $ldcache[$log->module
][$log->action
];
906 $ld = get_record('log_display', 'module', $log->module
, 'action', $log->action
);
907 $ldcache[$log->module
][$log->action
] = $ld;
909 if ($ld && !empty($log->info
)) {
910 // ugly hack to make sure fullname is shown correctly
911 if (($ld->mtable
== 'user') and ($ld->field
== sql_concat('firstname', "' '" , 'lastname'))) {
912 $log->info
= fullname(get_record($ld->mtable
, 'id', $log->info
), true);
914 $log->info
= get_field($ld->mtable
, $ld->field
, 'id', $log->info
);
919 $log->info
= format_string($log->info
);
920 $log->info
= strip_tags(urldecode($log->info
)); // Some XSS protection
923 if ($row > EXCELROWS
) {
925 $myxls =& $worksheet[$wsnumber];
926 $row = FIRSTUSEDEXCELROW
;
930 $myxls->write_string($row, 0, $courses[$log->course
]);
931 $myxls->write_date($row, 1, $log->time
);
932 $myxls->write_string($row, 2, $log->ip
);
933 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE
, $course->id
)));
934 $myxls->write_string($row, 3, $fullname);
935 $myxls->write_string($row, 4, $log->module
.' '.$log->action
);
936 $myxls->write_string($row, 5, $log->info
);
946 function print_log_graph($course, $userid=0, $type="course.png", $date=0) {
948 if (empty($CFG->gdversion
)) {
949 echo "(".get_string("gdneed").")";
951 echo '<img src="'.$CFG->wwwroot
.'/course/report/log/graph.php?id='.$course->id
.
952 '&user='.$userid.'&type='.$type.'&date='.$date.'" alt="" />';
957 function print_overview($courses) {
961 $htmlarray = array();
962 if ($modules = get_records('modules')) {
963 foreach ($modules as $mod) {
964 if (file_exists(dirname(dirname(__FILE__
)).'/mod/'.$mod->name
.'/lib.php')) {
965 require_once(dirname(dirname(__FILE__
)).'/mod/'.$mod->name
.'/lib.php');
966 $fname = $mod->name
.'_print_overview';
967 if (function_exists($fname)) {
968 $fname($courses,$htmlarray);
973 foreach ($courses as $course) {
974 print_simple_box_start('center', '100%', '', 5, "coursebox");
976 if (empty($course->visible
)) {
977 $linkcss = 'class="dimmed"';
979 print_heading('<a title="'. format_string($course->fullname
).'" '.$linkcss.' href="'.$CFG->wwwroot
.'/course/view.php?id='.$course->id
.'">'. format_string($course->fullname
).'</a>');
980 if (array_key_exists($course->id
,$htmlarray)) {
981 foreach ($htmlarray[$course->id
] as $modname => $html) {
985 print_simple_box_end();
990 function print_recent_activity($course) {
991 // $course is an object
992 // This function trawls through the logs looking for
993 // anything new since the user's last login
995 global $CFG, $USER, $SESSION;
997 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
999 $timestart = time() - COURSE_MAX_RECENT_PERIOD
;
1001 if (!has_capability('moodle/legacy:guest', $context, NULL, false)) {
1002 if (!empty($USER->lastcourseaccess
[$course->id
])) {
1003 if ($USER->lastcourseaccess
[$course->id
] > $timestart) {
1004 $timestart = $USER->lastcourseaccess
[$course->id
];
1009 echo '<div class="activitydate">';
1010 echo get_string('activitysince', '', userdate($timestart));
1012 echo '<div class="activityhead">';
1014 echo '<a href="'.$CFG->wwwroot
.'/course/recent.php?id='.$course->id
.'">'.get_string('recentactivityreport').'</a>';
1019 // Firstly, have there been any new enrolments?
1024 $users = get_recent_enrolments($course->id
, $timestart);
1026 //Accessibility: new users now appear in an <OL> list.
1028 echo '<div class="newusers">';
1030 print_headline(get_string("newusers").':', 3);
1034 echo "<ol class=\"list\">\n";
1035 foreach ($users as $user) {
1037 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE
, $course->id
)));
1038 echo '<li class="name"><a href="'.$CFG->wwwroot
."/user/view.php?id=$user->id&course=$course->id\">$fullname</a></li>\n";
1040 echo "</ol>\n</div>\n";
1043 // Next, have there been any modifications to the course structure?
1045 $logs = get_records_select('log', "time > '$timestart' AND course = '$course->id' AND
1046 module = 'course' AND action LIKE '% mod'", "time ASC");
1049 foreach ($logs as $key => $log) {
1050 $info = split(' ', $log->info
);
1052 if ($info[0] == 'label') { // Labels are special activities
1056 $modname = get_field($info[0], 'name', 'id', $info[1]);
1057 //Create a temp valid module structure (course,id)
1058 $tempmod->course
= $log->course
;
1059 $tempmod->id
= $info[1];
1060 //Obtain the visible property from the instance
1061 $modvisible = instance_is_visible($info[0],$tempmod);
1063 //Only if the mod is visible
1065 switch ($log->action
) {
1067 $stradded = get_string('added', 'moodle', get_string('modulename', $info[0]));
1068 $changelist[$log->info
] = array ('operation' => 'add', 'text' => "$stradded:<br /><a href=\"$CFG->wwwroot/course/$log->url\">".format_string($modname,true)."</a>");
1071 $strupdated = get_string('updated', 'moodle', get_string('modulename', $info[0]));
1072 if (empty($changelist[$log->info
])) {
1073 $changelist[$log->info
] = array ('operation' => 'update', 'text' => "$strupdated:<br /><a href=\"$CFG->wwwroot/course/$log->url\">".format_string($modname,true)."</a>");
1077 if (!empty($changelist[$log->info
]['operation']) and
1078 $changelist[$log->info
]['operation'] == 'add') {
1079 $changelist[$log->info
] = NULL;
1081 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $info[0]));
1082 $changelist[$log->info
] = array ('operation' => 'delete', 'text' => $strdeleted);
1090 if (!empty($changelist)) {
1091 foreach ($changelist as $changeinfo => $change) {
1093 $changes[$changeinfo] = $change;
1096 if (isset($changes)){
1097 if (count($changes) > 0) {
1098 print_headline(get_string('courseupdates').':', 3);
1100 foreach ($changes as $changeinfo => $change) {
1101 echo '<p class="activity">'.$change['text'].'</p>';
1107 // Now display new things from each module
1109 $mods = get_records('modules', 'visible', '1', 'name', 'id, name');
1111 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
1113 foreach ($mods as $mod) { // Each module gets it's own logs and prints them
1114 include_once($CFG->dirroot
.'/mod/'.$mod->name
.'/lib.php');
1115 $print_recent_activity = $mod->name
.'_print_recent_activity';
1116 if (function_exists($print_recent_activity)) {
1119 // $isteacher (second parameter below) is to be deprecated!
1122 // 1) Make sure that all _print_recent_activity functions are
1123 // not using the $isteacher value.
1124 // 2) Eventually, remove the $isteacher parameter from the
1127 $modcontent = $print_recent_activity($course, $viewfullnames, $timestart);
1135 echo '<p class="message">'.get_string('nothingnew').'</p>';
1140 function get_array_of_activities($courseid) {
1141 // For a given course, returns an array of course activity objects
1142 // Each item in the array contains he following properties:
1143 // cm - course module id
1144 // mod - name of the module (eg forum)
1145 // section - the number of the section (eg week or topic)
1146 // name - the name of the instance
1147 // visible - is the instance visible or not
1148 // extra - contains extra string to include in any link
1154 if (!$rawmods = get_course_mods($courseid)) {
1158 if ($sections = get_records("course_sections", "course", $courseid, "section ASC")) {
1159 foreach ($sections as $section) {
1160 if (!empty($section->sequence
)) {
1161 $sequence = explode(",", $section->sequence
);
1162 foreach ($sequence as $seq) {
1163 if (empty($rawmods[$seq])) {
1166 $mod[$seq]->cm
= $rawmods[$seq]->id
;
1167 $mod[$seq]->mod
= $rawmods[$seq]->modname
;
1168 $mod[$seq]->section
= $section->section
;
1169 $mod[$seq]->name
= urlencode(get_field($rawmods[$seq]->modname
, "name", "id", $rawmods[$seq]->instance
));
1170 $mod[$seq]->visible
= $rawmods[$seq]->visible
;
1171 $mod[$seq]->extra
= "";
1173 $modname = $mod[$seq]->mod
;
1174 $functionname = $modname."_get_coursemodule_info";
1176 include_once("$CFG->dirroot/mod/$modname/lib.php");
1178 if (function_exists($functionname)) {
1179 if ($info = $functionname($rawmods[$seq])) {
1180 if (!empty($info->extra
)) {
1181 $mod[$seq]->extra
= $info->extra
;
1183 if (!empty($info->icon
)) {
1184 $mod[$seq]->icon
= $info->icon
;
1198 function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
1199 // Returns a number of useful structures for course displays
1201 $mods = NULL; // course modules indexed by id
1202 $modnames = NULL; // all course module names (except resource!)
1203 $modnamesplural= NULL; // all course module names (plural form)
1204 $modnamesused = NULL; // course module names used
1206 if ($allmods = get_records("modules")) {
1207 foreach ($allmods as $mod) {
1208 if ($mod->visible
) {
1209 $modnames[$mod->name
] = get_string("modulename", "$mod->name");
1210 $modnamesplural[$mod->name
] = get_string("modulenameplural", "$mod->name");
1215 error("No modules are installed!");
1218 if ($rawmods = get_course_mods($courseid)) {
1219 foreach($rawmods as $mod) { // Index the mods
1220 if (empty($modnames[$mod->modname
])) {
1223 $mods[$mod->id
] = $mod;
1224 $mods[$mod->id
]->modfullname
= $modnames[$mod->modname
];
1225 if ($mod->visible
or has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_COURSE
, $courseid))) {
1226 $modnamesused[$mod->modname
] = $modnames[$mod->modname
];
1229 if ($modnamesused) {
1230 asort($modnamesused);
1236 function get_all_sections($courseid) {
1238 return get_records("course_sections", "course", "$courseid", "section",
1239 "section, id, course, summary, sequence, visible");
1242 function course_set_display($courseid, $display=0) {
1245 if ($display == "all" or empty($display)) {
1249 if (empty($USER->id
) or $USER->username
== 'guest') {
1250 //do not store settings in db for guests
1251 } else if (record_exists("course_display", "userid", $USER->id
, "course", $courseid)) {
1252 set_field("course_display", "display", $display, "userid", $USER->id
, "course", $courseid);
1254 $record->userid
= $USER->id
;
1255 $record->course
= $courseid;
1256 $record->display
= $display;
1257 if (!insert_record("course_display", $record)) {
1258 notify("Could not save your course display!");
1262 return $USER->display
[$courseid] = $display; // Note: = not ==
1265 function set_section_visible($courseid, $sectionnumber, $visibility) {
1266 /// For a given course section, markes it visible or hidden,
1267 /// and does the same for every activity in that section
1269 if ($section = get_record("course_sections", "course", $courseid, "section", $sectionnumber)) {
1270 set_field("course_sections", "visible", "$visibility", "id", $section->id
);
1271 if (!empty($section->sequence
)) {
1272 $modules = explode(",", $section->sequence
);
1273 foreach ($modules as $moduleid) {
1274 set_coursemodule_visible($moduleid, $visibility, true);
1277 rebuild_course_cache($courseid);
1282 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%") {
1283 /// Prints a section full of activity modules
1286 static $groupbuttons;
1287 static $groupbuttonslink;
1291 static $strmovehere;
1292 static $strmovefull;
1293 static $strunreadpostsone;
1296 static $usetracking;
1298 $labelformatoptions = New stdClass
;
1300 if (!isset($isteacher)) {
1301 $groupbuttons = ($course->groupmode
or (!$course->groupmodeforce
));
1302 $groupbuttonslink = (!$course->groupmodeforce
);
1303 $isediting = isediting($course->id
);
1304 $ismoving = $isediting && ismoving($course->id
);
1306 $strmovehere = get_string("movehere");
1307 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1309 include_once($CFG->dirroot
.'/mod/forum/lib.php');
1310 if ($usetracking = forum_tp_can_track_forums()) {
1311 $strunreadpostsone = get_string('unreadpostsone', 'forum');
1312 $untracked = forum_tp_get_untracked_forums($USER->id
, $course->id
);
1315 $labelformatoptions->noclean
= true;
1317 /// Casting $course->modinfo to string prevents one notice when the field is null
1318 $modinfo = unserialize((string)$course->modinfo
);
1320 //Acccessibility: replace table with list <ul>, but don't output empty list.
1321 if (!empty($section->sequence
)) {
1323 // Fix bug #5027, don't want style=\"width:$width\".
1324 echo "<ul class=\"section\">\n";
1325 $sectionmods = explode(",", $section->sequence
);
1327 foreach ($sectionmods as $modnumber) {
1328 if (empty($mods[$modnumber])) {
1331 $mod = $mods[$modnumber];
1333 if (($mod->visible
or has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_COURSE
, $course->id
))) &&
1334 (!$ismoving ||
$mod->id
!= $USER->activitycopy
)) {
1335 echo '<li class="activity '.$mod->modname
.'" id="module-'.$modnumber.'">'; // Unique ID
1337 echo '<a title="'.$strmovefull.'"'.
1338 ' href="'.$CFG->wwwroot
.'/course/mod.php?moveto='.$mod->id
.'&sesskey='.$USER->sesskey
.'">'.
1339 '<img class="movetarget" src="'.$CFG->pixpath
.'/movehere.gif" '.
1340 ' alt="'.$strmovehere.'" /></a><br />
1343 $instancename = urldecode($modinfo[$modnumber]->name
);
1344 $instancename = format_string($instancename, true, $course->id
);
1346 if (!empty($modinfo[$modnumber]->extra
)) {
1347 $extra = urldecode($modinfo[$modnumber]->extra
);
1352 if (!empty($modinfo[$modnumber]->icon
)) {
1353 $icon = "$CFG->pixpath/".urldecode($modinfo[$modnumber]->icon
);
1355 $icon = "$CFG->modpixpath/$mod->modname/icon.gif";
1359 print_spacer(12, 20 * $mod->indent
, false);
1362 if ($mod->modname
== "label") {
1363 if (!$mod->visible
) {
1364 echo "<span class=\"dimmed_text\">";
1366 echo format_text($extra, FORMAT_HTML
, $labelformatoptions);
1367 if (!$mod->visible
) {
1371 } else { // Normal activity
1373 if (!empty($USER->screenreader
)) {
1374 $typestring = '('.get_string('modulename',$mod->modname
).') ';
1379 $linkcss = $mod->visible ?
"" : " class=\"dimmed\" ";
1380 echo '<img src="'.$icon.'"'.
1381 ' class="activityicon" alt="'.$mod->modfullname
.'" />'.
1382 ' <a title="'.$mod->modfullname
.'" '.$linkcss.' '.$extra.
1383 ' href="'.$CFG->wwwroot
.'/mod/'.$mod->modname
.'/view.php?id='.$mod->id
.'">'.
1384 $typestring.$instancename.'</a>';
1386 if ($usetracking && $mod->modname
== 'forum') {
1387 $groupmode = groupmode($course, $mod);
1388 $groupid = ($groupmode == SEPARATEGROUPS
&& !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE
, $course->id
))) ?
1389 get_current_group($course->id
) : false;
1391 if (forum_tp_can_track_forums() && !isset($untracked[$mod->instance
])) {
1392 $unread = forum_tp_count_forum_unread_posts($USER->id
, $mod->instance
, $groupid);
1394 echo '<span class="unread"> <a href="'.$CFG->wwwroot
.'/mod/forum/view.php?id='.$mod->id
.'">';
1396 echo $strunreadpostsone;
1398 print_string('unreadpostsnumber', 'forum', $unread);
1400 echo '</a> </span>';
1406 // TODO: we must define this as mod property!
1407 if ($groupbuttons and $mod->modname
!= 'label' and $mod->modname
!= 'resource' and $mod->modname
!= 'glossary') {
1408 if (! $mod->groupmodelink
= $groupbuttonslink) {
1409 $mod->groupmode
= $course->groupmode
;
1413 $mod->groupmode
= false;
1415 echo ' ';
1416 echo make_editing_buttons($mod, $absolute, true, $mod->indent
, $section->section
);
1421 } elseif ($ismoving) {
1422 echo "<ul class=\"section\">\n";
1425 echo '<li><a title="'.$strmovefull.'"'.
1426 ' href="'.$CFG->wwwroot
.'/course/mod.php?movetosection='.$section->id
.'&sesskey='.$USER->sesskey
.'">'.
1427 '<img class="movetarget" src="'.$CFG->pixpath
.'/movehere.gif" '.
1428 ' alt="'.$strmovehere.'" /></a></li>
1431 if (!empty($section->sequence
) ||
$ismoving) {
1432 echo "</ul><!--class='section'-->\n\n";
1437 * Prints the menus to add activities and resources.
1439 function print_section_add_menus($course, $section, $modnames, $vertical=false, $return=false) {
1442 // check to see if user can add menus
1443 if (!has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE
, $course->id
))) {
1447 static $resources = false;
1448 static $activities = false;
1450 if ($resources === false) {
1451 $resources = array();
1452 $activities = array();
1454 foreach($modnames as $modname=>$modnamestr) {
1455 if (!course_allowed_module($course, $modname)) {
1459 require_once("$CFG->dirroot/mod/$modname/lib.php");
1460 $gettypesfunc = $modname.'_get_types';
1461 if (function_exists($gettypesfunc)) {
1462 $types = $gettypesfunc();
1463 foreach($types as $type) {
1464 if ($type->modclass
== MOD_CLASS_RESOURCE
) {
1465 $resources[$type->type
] = $type->typestr
;
1467 $activities[$type->type
] = $type->typestr
;
1471 // all mods without type are considered activity
1472 $activities[$modname] = $modnamestr;
1477 $straddactivity = get_string('addactivity');
1478 $straddresource = get_string('addresource');
1480 $output = '<div class="section_add_menus">';
1483 $output .= '<div class="horizontal">';
1486 if (!empty($resources)) {
1487 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&section=$section&sesskey=".sesskey()."&add=",
1488 $resources, "ressection$section", "", $straddresource, 'resource/types', $straddresource, true);
1491 if (!empty($activities)) {
1493 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&section=$section&sesskey=".sesskey()."&add=",
1494 $activities, "section$section", "", $straddactivity, 'mods', $straddactivity, true);
1498 $output .= '</div>';
1501 $output .= '</div>';
1510 function rebuild_course_cache($courseid=0) {
1511 // Rebuilds the cached list of course activities stored in the database
1512 // If a courseid is not specified, then all are rebuilt
1515 $select = "id = '$courseid'";
1520 if ($courses = get_records_select("course", $select,'','id,fullname')) {
1521 foreach ($courses as $course) {
1522 $modinfo = serialize(get_array_of_activities($course->id
));
1523 if (!set_field("course", "modinfo", $modinfo, "id", $course->id
)) {
1524 notify("Could not cache module information for course '" . format_string($course->fullname
) . "'!");
1532 function make_categories_list(&$list, &$parents, $category=NULL, $path="") {
1533 /// Given an empty array, this function recursively travels the
1534 /// categories, building up a nice list for display. It also makes
1535 /// an array that list all the parents for each category.
1537 // initialize the arrays if needed
1538 if (!is_array($list)) {
1541 if (!is_array($parents)) {
1547 $path = $path.' / '.format_string($category->name
);
1549 $path = format_string($category->name
);
1551 $list[$category->id
] = $path;
1556 if ($categories = get_categories($category->id
)) { // Print all the children recursively
1557 foreach ($categories as $cat) {
1558 if (!empty($category->id
)) {
1559 if (isset($parents[$category->id
])) {
1560 $parents[$cat->id
] = $parents[$category->id
];
1562 $parents[$cat->id
][] = $category->id
;
1564 make_categories_list($list, $parents, $cat, $path);
1570 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $files = true) {
1571 /// Recursive function to print out all the categories in a nice format
1572 /// with or without courses included
1575 if (isset($CFG->max_category_depth
) && ($depth >= $CFG->max_category_depth
)) {
1579 if (!$displaylist) {
1580 make_categories_list($displaylist, $parentslist);
1584 if ($category->visible
or has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM
, SITEID
))) {
1585 print_category_info($category, $depth, $files);
1587 return; // Don't bother printing children of invisible categories
1591 $category->id
= "0";
1594 if ($categories = get_categories($category->id
)) { // Print all the children recursively
1595 $countcats = count($categories);
1599 foreach ($categories as $cat) {
1601 if ($count == $countcats) {
1604 $up = $first ?
false : true;
1605 $down = $last ?
false : true;
1608 print_whole_category_list($cat, $displaylist, $parentslist, $depth +
1, $files);
1613 // this function will return $options array for choose_from_menu, with whitespace to denote nesting.
1615 function make_categories_options() {
1616 make_categories_list($cats,$parents);
1617 foreach ($cats as $key => $value) {
1618 if (array_key_exists($key,$parents)) {
1619 if ($indent = count($parents[$key])) {
1620 for ($i = 0; $i < $indent; $i++
) {
1621 $cats[$key] = ' '.$cats[$key];
1629 function print_category_info($category, $depth, $files = false) {
1630 /// Prints the category info in indented fashion
1631 /// This function is only used by print_whole_category_list() above
1634 static $strallowguests, $strrequireskey, $strsummary;
1636 if (empty($strsummary)) {
1637 $strallowguests = get_string('allowguests');
1638 $strrequireskey = get_string('requireskey');
1639 $strsummary = get_string('summary');
1642 $catlinkcss = $category->visible ?
'' : ' class="dimmed" ';
1644 $coursecount = count_records('course') <= FRONTPAGECOURSELIMIT
;
1645 if ($files and $coursecount) {
1646 $catimage = '<img src="'.$CFG->pixpath
.'/i/course.gif" alt="" />';
1648 $catimage = " ";
1651 echo "\n\n".'<table class="categorylist">';
1653 if ($files and $coursecount) {
1654 $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');
1659 $indent = $depth*30;
1660 $rows = count($courses) +
1;
1661 echo '<td rowspan="'.$rows.'" valign="top" width="'.$indent.'">';
1662 print_spacer(10, $indent);
1666 echo '<td valign="top" class="category image">'.$catimage.'</td>';
1667 echo '<td valign="top" class="category name">';
1668 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot
.'/course/category.php?id='.$category->id
.'">'. format_string($category->name
).'</a>';
1670 echo '<td class="category info"> </td>';
1673 if ($courses && !(isset($CFG->max_category_depth
)&&($depth>=$CFG->max_category_depth
-1))) {
1674 foreach ($courses as $course) {
1675 $linkcss = $course->visible ?
'' : ' class="dimmed" ';
1676 echo '<tr><td valign="top"> ';
1677 echo '</td><td valign="top" class="course name">';
1678 echo '<a '.$linkcss.' href="'.$CFG->wwwroot
.'/course/view.php?id='.$course->id
.'">'. format_string($course->fullname
).'</a>';
1679 echo '</td><td align="right" valign="top" class="course info">';
1680 if ($course->guest
) {
1681 echo '<a title="'.$strallowguests.'" href="'.$CFG->wwwroot
.'/course/view.php?id='.$course->id
.'">';
1682 echo '<img alt="'.$strallowguests.'" src="'.$CFG->pixpath
.'/i/guest.gif" /></a>';
1684 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath
.'/spacer.gif" />';
1686 if ($course->password
) {
1687 echo '<a title="'.$strrequireskey.'" href="'.$CFG->wwwroot
.'/course/view.php?id='.$course->id
.'">';
1688 echo '<img alt="'.$strrequireskey.'" src="'.$CFG->pixpath
.'/i/key.gif" /></a>';
1690 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath
.'/spacer.gif" />';
1692 if ($course->summary
) {
1693 link_to_popup_window ('/course/info.php?id='.$course->id
, 'courseinfo',
1694 '<img alt="'.$strsummary.'" src="'.$CFG->pixpath
.'/i/info.gif" />',
1695 400, 500, $strsummary);
1697 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath
.'/spacer.gif" />';
1707 $indent = $depth*20;
1708 echo '<td valign="top" width="'.$indent.'">';
1709 print_spacer(10, $indent);
1713 echo '<td valign="top" class="category name">';
1714 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot
.'/course/category.php?id='.$category->id
.'">'. format_string($category->name
).'</a>';
1716 echo '<td valign="top" class="category number">';
1717 if ($category->coursecount
) {
1718 echo $category->coursecount
;
1726 function print_courses($category, $hidesitecourse = false) {
1727 /// Category is 0 (for all courses) or an object
1731 if (empty($category)) {
1732 $categories = get_categories(0); // Parent = 0 ie top-level categories only
1733 if ($categories != null and count($categories) == 1) {
1734 $category = array_shift($categories);
1735 $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');
1737 $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');
1741 $categories = get_categories($category->id
); // sub 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');
1746 foreach ($courses as $course) {
1747 if ($hidesitecourse and ($course->id
== SITEID
)) {
1750 print_course($course);
1753 print_heading(get_string("nocoursesyet"));
1754 $context = get_context_instance(CONTEXT_SYSTEM
, SITEID
);
1755 if (has_capability('moodle/course:create', $context)) {
1757 $options['category'] = $category->id
;
1758 echo '<div class="addcoursebutton">';
1759 print_single_button($CFG->wwwroot
.'/course/edit.php', $options, get_string("addnewcourse"));
1769 function print_course($course) {
1773 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
1775 $linkcss = $course->visible ?
'' : ' class="dimmed" ';
1777 echo '<div class="coursebox">';
1778 echo '<div class="info">';
1779 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
1780 $linkcss.' href="'.$CFG->wwwroot
.'/course/view.php?id='.$course->id
.'">'.
1781 format_string($course->fullname
).'</a></div>';
1783 /// first find all roles that are supposed to be displayed
1784 if ($managerroles = get_config('', 'coursemanager')) {
1785 $coursemanagerroles = split(',', $managerroles);
1786 foreach ($coursemanagerroles as $roleid) {
1787 $role = get_record('role','id',$roleid);
1788 if ($users = get_role_users($roleid, $context, true, '', 'u.lastname ASC', true)) {
1789 foreach ($users as $teacher) {
1790 $fullname = fullname($teacher, has_capability('moodle/site:viewfullnames', $context));
1791 $namesarray[] = role_get_name($role, $context).': <a href="'.$CFG->wwwroot
.'/user/view.php?id='.
1792 $teacher->id
.'&course='.SITEID
.'">'.$fullname.'</a>';
1797 if (!empty($namesarray)) {
1798 echo "<ul class=\"teachers\">\n<li>";
1799 echo implode('</li><li>', $namesarray);
1804 require_once("$CFG->dirroot/enrol/enrol.class.php");
1805 $enrol = enrolment_factory
::factory($course->enrol
);
1806 echo $enrol->get_access_icons($course);
1808 echo '</div><div class="summary">';
1810 $options->noclean
= true;
1811 $options->para
= false;
1812 echo format_text($course->summary
, FORMAT_MOODLE
, $options, $course->id
);
1815 echo '<div class="clearer"></div>';
1819 function print_my_moodle() {
1820 /// Prints custom user information on the home page.
1821 /// Over time this can include all sorts of information
1825 if (empty($USER->id
)) {
1826 error("It shouldn't be possible to see My Moodle without being logged in.");
1829 $courses = get_my_courses($USER->id
);
1831 $rcourses = array();
1832 if (!empty($CFG->mnet_dispatcher_mode
) && $CFG->mnet_dispatcher_mode
==='strict') {
1833 $rcourses = get_my_remotecourses($USER->id
);
1834 $rhosts = get_my_remotehosts();
1837 if (!empty($courses) ||
!empty($rcourses) ||
!empty($rhosts)) {
1839 if (!empty($courses)) {
1840 foreach ($courses as $course) {
1841 if ($course->id
== SITEID
) {
1844 print_course($course, "100%");
1849 if (!empty($rcourses)) {
1850 // at the IDP, we know of all the remote courses
1851 foreach ($rcourses as $course) {
1852 print_remote_course($course, "100%");
1854 } elseif (!empty($rhosts)) {
1855 // non-IDP, we know of all the remote servers, but not courses
1856 foreach ($rhosts as $host) {
1857 print_remote_host($host, "100%");
1863 if (count_records("course") > (count($courses) +
1) ) { // Some courses not being displayed
1864 echo "<table width=\"100%\"><tr><td align=\"center\">";
1865 print_course_search("", false, "short");
1866 echo "</td><td align=\"center\">";
1867 print_single_button("$CFG->wwwroot/course/index.php", NULL, get_string("fulllistofcourses"), "get");
1868 echo "</td></tr></table>\n";
1872 if (count_records("course_categories") > 1) {
1873 print_simple_box_start("center", "100%", "#FFFFFF", 5, "categorybox");
1874 print_whole_category_list();
1875 print_simple_box_end();
1883 function print_course_search($value="", $return=false, $format="plain") {
1890 $id = 'coursesearch';
1896 $strsearchcourses= get_string("searchcourses");
1898 if ($format == 'plain') {
1899 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot
.'/course/search.php" method="get">';
1900 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
1901 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
1902 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
1903 $output .= '<input type="submit" value="'.get_string('go').'" />';
1904 $output .= '</fieldset></form>';
1905 } else if ($format == 'short') {
1906 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot
.'/course/search.php" method="get">';
1907 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
1908 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
1909 $output .= '<input type="text" id="coursesearchbox" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
1910 $output .= '<input type="submit" value="'.get_string('go').'" />';
1911 $output .= '</fieldset></form>';
1912 } else if ($format == 'navbar') {
1913 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot
.'/course/search.php" method="get">';
1914 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
1915 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
1916 $output .= '<input type="text" id="coursesearchbox" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
1917 $output .= '<input type="submit" value="'.get_string('go').'" />';
1918 $output .= '</fieldset></form>';
1927 function print_remote_course($course, $width="100%") {
1933 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&wantsurl=/course/view.php?id={$course->remoteid}";
1935 echo '<div class="coursebox remotecoursebox">';
1936 echo '<div class="info">';
1937 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
1938 $linkcss.' href="'.$url.'">'
1939 . format_string($course->fullname
) .'</a><br />'
1940 . format_string($course->hostname
) . ' : '
1941 . format_string($course->cat_name
) . ' : '
1942 . format_string($course->shortname
). '</div>';
1943 echo '</div><div class="summary">';
1945 $options->noclean
= true;
1946 $options->para
= false;
1947 echo format_text($course->summary
, FORMAT_MOODLE
, $options);
1950 echo '<div class="clearer"></div>';
1953 function print_remote_host($host, $width="100%") {
1959 echo '<div class="coursebox">';
1960 echo '<div class="info">';
1961 echo '<div class="name">';
1962 echo '<img src="'.$CFG->pixpath
.'/i/mnethost.gif" class="icon" alt="'.get_string('course').'" />';
1963 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
1964 . s($host['name']).'</a> - ';
1965 echo $host['count'] . ' ' . get_string('courses');
1969 echo '<div class="clearer"></div>';
1973 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
1975 function add_course_module($mod) {
1977 $mod->added
= time();
1980 return insert_record("course_modules", $mod);
1983 function add_mod_to_section($mod, $beforemod=NULL) {
1984 /// Given a full mod object with section and course already defined
1985 /// If $before is specified, then this is an existing ID which we
1986 /// will insert the new module before
1988 /// Returns the course_sections ID where the mod is inserted
1990 if ($section = get_record("course_sections", "course", "$mod->course", "section", "$mod->section")) {
1992 $section->sequence
= trim($section->sequence
);
1994 if (empty($section->sequence
)) {
1995 $newsequence = "$mod->coursemodule";
1997 } else if ($beforemod) {
1998 $modarray = explode(",", $section->sequence
);
2000 if ($key = array_keys ($modarray, $beforemod->id
)) {
2001 $insertarray = array($mod->id
, $beforemod->id
);
2002 array_splice($modarray, $key[0], 1, $insertarray);
2003 $newsequence = implode(",", $modarray);
2005 } else { // Just tack it on the end anyway
2006 $newsequence = "$section->sequence,$mod->coursemodule";
2010 $newsequence = "$section->sequence,$mod->coursemodule";
2013 if (set_field("course_sections", "sequence", $newsequence, "id", $section->id
)) {
2014 return $section->id
; // Return course_sections ID that was used.
2019 } else { // Insert a new record
2020 $section->course
= $mod->course
;
2021 $section->section
= $mod->section
;
2022 $section->summary
= "";
2023 $section->sequence
= $mod->coursemodule
;
2024 return insert_record("course_sections", $section);
2028 function set_coursemodule_groupmode($id, $groupmode) {
2029 return set_field("course_modules", "groupmode", $groupmode, "id", $id);
2032 function set_coursemodule_idnumber($id, $idnumber) {
2033 return set_field("course_modules", "idnumber", $idnumber, "id", $id);
2036 * $prevstateoverrides = true will set the visibility of the course module
2037 * to what is defined in visibleold. This enables us to remember the current
2038 * visibility when making a whole section hidden, so that when we toggle
2039 * that section back to visible, we are able to return the visibility of
2040 * the course module back to what it was originally.
2042 function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
2043 if (!$cm = get_record('course_modules', 'id', $id)) {
2046 if (!$modulename = get_field('modules', 'name', 'id', $cm->module
)) {
2049 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
2050 foreach($events as $event) {
2058 if ($prevstateoverrides) {
2059 if ($visible == '0') {
2060 // Remember the current visible state so we can toggle this back.
2061 set_field('course_modules', 'visibleold', $cm->visible
, 'id', $id);
2063 // Get the previous saved visible states.
2064 return set_field('course_modules', 'visible', $cm->visibleold
, 'id', $id);
2067 return set_field("course_modules", "visible", $visible, "id", $id);
2071 * Delete a course module and any associated data at the course level (events)
2072 * Until 1.5 this function simply marked a deleted flag ... now it
2073 * deletes it completely.
2076 function delete_course_module($id) {
2077 if (!$cm = get_record('course_modules', 'id', $id)) {
2080 $modulename = get_field('modules', 'name', 'id', $cm->module
);
2081 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
2082 foreach($events as $event) {
2083 delete_event($event);
2086 return delete_records('course_modules', 'id', $cm->id
);
2089 function delete_mod_from_section($mod, $section) {
2091 if ($section = get_record("course_sections", "id", "$section") ) {
2093 $modarray = explode(",", $section->sequence
);
2095 if ($key = array_keys ($modarray, $mod)) {
2096 array_splice($modarray, $key[0], 1);
2097 $newsequence = implode(",", $modarray);
2098 return set_field("course_sections", "sequence", $newsequence, "id", $section->id
);
2107 function move_section($course, $section, $move) {
2108 /// Moves a whole course section up and down within the course
2115 $sectiondest = $section +
$move;
2117 if ($sectiondest > $course->numsections
or $sectiondest < 1) {
2121 if (!$sectionrecord = get_record("course_sections", "course", $course->id
, "section", $section)) {
2125 if (!$sectiondestrecord = get_record("course_sections", "course", $course->id
, "section", $sectiondest)) {
2129 if (!set_field("course_sections", "section", $sectiondest, "id", $sectionrecord->id
)) {
2132 if (!set_field("course_sections", "section", $section, "id", $sectiondestrecord->id
)) {
2135 // if the focus is on the section that is being moved, then move the focus along
2136 if (isset($USER->display
[$course->id
]) and ($USER->display
[$course->id
] == $section)) {
2137 course_set_display($course->id
, $sectiondest);
2140 // Check for duplicates and fix order if needed.
2141 // There is a very rare case that some sections in the same course have the same section id.
2142 $sections = get_records_select('course_sections', "course = $course->id", 'section ASC');
2144 foreach ($sections as $section) {
2145 if ($section->section
!= $n) {
2146 if (!set_field('course_sections', 'section', $n, 'id', $section->id
)) {
2156 function moveto_module($mod, $section, $beforemod=NULL) {
2157 /// All parameters are objects
2158 /// Move the module object $mod to the specified $section
2159 /// If $beforemod exists then that is the module
2160 /// before which $modid should be inserted
2162 /// Remove original module from original section
2164 if (! delete_mod_from_section($mod->id
, $mod->section
)) {
2165 notify("Could not delete module from existing section");
2168 /// Update module itself if necessary
2170 if ($mod->section
!= $section->id
) {
2171 $mod->section
= $section->id
;
2172 if (!update_record("course_modules", $mod)) {
2175 // if moving to a hidden section then hide module
2176 if (!$section->visible
) {
2177 set_coursemodule_visible($mod->id
, 0);
2181 /// Add the module into the new section
2183 $mod->course
= $section->course
;
2184 $mod->section
= $section->section
; // need relative reference
2185 $mod->coursemodule
= $mod->id
;
2187 if (! add_mod_to_section($mod, $beforemod)) {
2195 function make_editing_buttons($mod, $absolute=false, $moveselect=true, $indent=-1, $section=-1) {
2201 $modcontext = get_context_instance(CONTEXT_MODULE
, $mod->id
);
2202 // no permission to edit
2203 if (!has_capability('moodle/course:manageactivities', $modcontext)) {
2208 $str->delete
= get_string("delete");
2209 $str->move
= get_string("move");
2210 $str->moveup
= get_string("moveup");
2211 $str->movedown
= get_string("movedown");
2212 $str->moveright
= get_string("moveright");
2213 $str->moveleft
= get_string("moveleft");
2214 $str->update
= get_string("update");
2215 $str->duplicate
= get_string("duplicate");
2216 $str->hide
= get_string("hide");
2217 $str->show
= get_string("show");
2218 $str->clicktochange
= get_string("clicktochange");
2219 $str->forcedmode
= get_string("forcedmode");
2220 $str->groupsnone
= get_string("groupsnone");
2221 $str->groupsseparate
= get_string("groupsseparate");
2222 $str->groupsvisible
= get_string("groupsvisible");
2223 $sesskey = sesskey();
2226 if ($section >= 0) {
2227 $section = '&sr='.$section; // Section return
2233 $path = $CFG->wwwroot
.'/course';
2238 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
2239 if ($mod->visible
) {
2240 $hideshow = '<a class="editing_hide" title="'.$str->hide
.'" href="'.$path.'/mod.php?hide='.$mod->id
.
2241 '&sesskey='.$sesskey.$section.'"><img'.
2242 ' src="'.$CFG->pixpath
.'/t/hide.gif" class="iconsmall" '.
2243 ' alt="'.$str->hide
.'" /></a>'."\n";
2245 $hideshow = '<a class="editing_show" title="'.$str->show
.'" href="'.$path.'/mod.php?show='.$mod->id
.
2246 '&sesskey='.$sesskey.$section.'"><img'.
2247 ' src="'.$CFG->pixpath
.'/t/show.gif" class="iconsmall" '.
2248 ' alt="'.$str->show
.'" /></a>'."\n";
2251 if ($mod->groupmode
!== false) {
2252 if ($mod->groupmode
== SEPARATEGROUPS
) {
2253 $grouptitle = $str->groupsseparate
;
2254 $groupclass = 'editing_groupsseparate';
2255 $groupimage = $CFG->pixpath
.'/t/groups.gif';
2256 $grouplink = $path.'/mod.php?id='.$mod->id
.'&groupmode=0&sesskey='.$sesskey;
2257 } else if ($mod->groupmode
== VISIBLEGROUPS
) {
2258 $grouptitle = $str->groupsvisible
;
2259 $groupclass = 'editing_groupsvisible';
2260 $groupimage = $CFG->pixpath
.'/t/groupv.gif';
2261 $grouplink = $path.'/mod.php?id='.$mod->id
.'&groupmode=1&sesskey='.$sesskey;
2263 $grouptitle = $str->groupsnone
;
2264 $groupclass = 'editing_groupsnone';
2265 $groupimage = $CFG->pixpath
.'/t/groupn.gif';
2266 $grouplink = $path.'/mod.php?id='.$mod->id
.'&groupmode=2&sesskey='.$sesskey;
2268 if ($mod->groupmodelink
) {
2269 $groupmode = '<a class="'.$groupclass.'" title="'.$grouptitle.' ('.$str->clicktochange
.')" href="'.$grouplink.'">'.
2270 '<img src="'.$groupimage.'" class="iconsmall" '.
2271 'alt="'.$grouptitle.'" /></a>';
2273 $groupmode = '<img title="'.$grouptitle.' ('.$str->forcedmode
.')" '.
2274 ' src="'.$groupimage.'" class="iconsmall" '.
2275 'alt="'.$grouptitle.'" />';
2281 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE
, $mod->course
))) {
2283 $move = '<a class="editing_move" title="'.$str->move
.'" href="'.$path.'/mod.php?copy='.$mod->id
.
2284 '&sesskey='.$sesskey.$section.'"><img'.
2285 ' src="'.$CFG->pixpath
.'/t/move.gif" class="iconsmall" '.
2286 ' alt="'.$str->move
.'" /></a>'."\n";
2288 $move = '<a class="editing_moveup" title="'.$str->moveup
.'" href="'.$path.'/mod.php?id='.$mod->id
.
2289 '&move=-1&sesskey='.$sesskey.$section.'"><img'.
2290 ' src="'.$CFG->pixpath
.'/t/up.gif" class="iconsmall" '.
2291 ' alt="'.$str->moveup
.'" /></a>'."\n".
2292 '<a class="editing_movedown" title="'.$str->movedown
.'" href="'.$path.'/mod.php?id='.$mod->id
.
2293 '&move=1&sesskey='.$sesskey.$section.'"><img'.
2294 ' src="'.$CFG->pixpath
.'/t/down.gif" class="iconsmall" '.
2295 ' alt="'.$str->movedown
.'" /></a>'."\n";
2302 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE
, $mod->course
))) {
2304 $leftright .= '<a class="editing_moveleft" title="'.$str->moveleft
.'" href="'.$path.'/mod.php?id='.$mod->id
.
2305 '&indent=-1&sesskey='.$sesskey.$section.'"><img'.
2306 ' src="'.$CFG->pixpath
.'/t/left.gif" class="iconsmall" '.
2307 ' alt="'.$str->moveleft
.'" /></a>'."\n";
2310 $leftright .= '<a class="editing_moveright" title="'.$str->moveright
.'" href="'.$path.'/mod.php?id='.$mod->id
.
2311 '&indent=1&sesskey='.$sesskey.$section.'"><img'.
2312 ' src="'.$CFG->pixpath
.'/t/right.gif" class="iconsmall" '.
2313 ' alt="'.$str->moveright
.'" /></a>'."\n";
2317 return '<span class="commands">'."\n".$leftright.$move.
2318 '<a class="editing_update" title="'.$str->update
.'" href="'.$path.'/mod.php?update='.$mod->id
.
2319 '&sesskey='.$sesskey.$section.'"><img'.
2320 ' src="'.$CFG->pixpath
.'/t/edit.gif" class="iconsmall" '.
2321 ' alt="'.$str->update
.'" /></a>'."\n".
2322 '<a class="editing_delete" title="'.$str->delete
.'" href="'.$path.'/mod.php?delete='.$mod->id
.
2323 '&sesskey='.$sesskey.$section.'"><img'.
2324 ' src="'.$CFG->pixpath
.'/t/delete.gif" class="iconsmall" '.
2325 ' alt="'.$str->delete
.'" /></a>'."\n".$hideshow.$groupmode."\n".'</span>';
2329 * given a course object with shortname & fullname, this function will
2330 * truncate the the number of chars allowed and add ... if it was too long
2332 function course_format_name ($course,$max=100) {
2334 $str = $course->shortname
.': '. $course->fullname
;
2335 if (strlen($str) <= $max) {
2339 return substr($str,0,$max-3).'...';
2344 * This function will return true if the given course is a child course at all
2346 function course_in_meta ($course) {
2347 return record_exists("course_meta","child_course",$course->id
);
2352 * Print standard form elements on module setup forms in mod/.../mod.html
2354 function print_standard_coursemodule_settings($form) {
2355 if (! $course = get_record('course', 'id', $form->course
)) {
2356 error("This course doesn't exist");
2358 print_groupmode_setting($form, $course);
2359 print_visible_setting($form, $course);
2363 * Print groupmode form element on module setup forms in mod/.../mod.html
2365 function print_groupmode_setting($form, $course=NULL) {
2367 if (empty($course)) {
2368 if (! $course = get_record('course', 'id', $form->course
)) {
2369 error("This course doesn't exist");
2372 if ($form->coursemodule
) {
2373 if (! $cm = get_record('course_modules', 'id', $form->coursemodule
)) {
2374 error("This course module doesn't exist");
2379 $groupmode = groupmode($course, $cm);
2380 if ($course->groupmode
or (!$course->groupmodeforce
)) {
2381 echo '<tr valign="top">';
2382 echo '<td align="right"><b>'.get_string('groupmode').':</b></td>';
2383 echo '<td align="left">';
2385 $choices[NOGROUPS
] = get_string('groupsnone');
2386 $choices[SEPARATEGROUPS
] = get_string('groupsseparate');
2387 $choices[VISIBLEGROUPS
] = get_string('groupsvisible');
2388 choose_from_menu($choices, 'groupmode', $groupmode, '', '', 0, false, $course->groupmodeforce
);
2389 helpbutton('groupmode', get_string('groupmode'));
2395 * Print visibility setting form element on module setup forms in mod/.../mod.html
2397 function print_visible_setting($form, $course=NULL) {
2398 if (empty($course)) {
2399 if (! $course = get_record('course', 'id', $form->course
)) {
2400 error("This course doesn't exist");
2403 if ($form->coursemodule
) {
2404 $visible = get_field('course_modules', 'visible', 'id', $form->coursemodule
);
2409 if ($form->mode
== 'add') { // in this case $form->section is the section number, not the id
2410 $hiddensection = !get_field('course_sections', 'visible', 'section', $form->section
, 'course', $form->course
);
2412 $hiddensection = !get_field('course_sections', 'visible', 'id', $form->section
);
2414 if ($hiddensection) {
2418 echo '<tr valign="top">';
2419 echo '<td align="right"><b>'.get_string('visible', '').':</b></td>';
2420 echo '<td align="left">';
2422 $choices[1] = get_string('show');
2423 $choices[0] = get_string('hide');
2424 choose_from_menu($choices, 'visible', $visible, '', '', 0, false, $hiddensection);
2428 function update_restricted_mods($course,$mods) {
2429 delete_records("course_allowed_modules","course",$course->id
);
2430 if (empty($course->restrictmodules
)) {
2434 foreach ($mods as $mod) {
2436 continue; // this is the 'allow none' option
2437 $am->course
= $course->id
;
2439 insert_record("course_allowed_modules",$am);
2445 * This function will take an int (module id) or a string (module name)
2446 * and return true or false, whether it's allowed in the given course (object)
2447 * $mod is not allowed to be an object, as the field for the module id is inconsistent
2448 * depending on where in the code it's called from (sometimes $mod->id, sometimes $mod->module)
2451 function course_allowed_module($course,$mod) {
2452 if (empty($course->restrictmodules
)) {
2456 // i am not sure this capability is correct
2457 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM
, SITEID
))) {
2460 if (is_numeric($mod)) {
2462 } else if (is_string($mod)) {
2463 if ($mod = get_field("modules","id","name",$mod))
2466 if (empty($modid)) {
2469 return (record_exists("course_allowed_modules","course",$course->id
,"module",$modid));
2473 *** Efficiently moves many courses around while maintaining
2474 *** sortorder in order.
2476 *** $courseids is an array of course ids
2480 function move_courses ($courseids, $categoryid) {
2484 if (!empty($courseids)) {
2486 $courseids = array_reverse($courseids);
2488 foreach ($courseids as $courseid) {
2490 if (! $course = get_record("course", "id", $courseid)) {
2491 notify("Error finding course $courseid");
2493 // figure out a sortorder that we can use in the destination category
2494 $sortorder = get_field_sql('SELECT MIN(sortorder)-1 AS min
2495 FROM ' . $CFG->prefix
. 'course WHERE category=' . $categoryid);
2496 if ($sortorder === false) {
2497 // the category is empty
2498 // rather than let the db default to 0
2499 // set it to > 100 and avoid extra work in fix_coursesortorder()
2501 } else if ($sortorder < 10) {
2502 fix_course_sortorder($categoryid);
2505 $course->category
= $categoryid;
2506 $course->sortorder
= $sortorder;
2507 $course->fullname
= addslashes($course->fullname
);
2508 $course->shortname
= addslashes($course->shortname
);
2509 $course->summary
= addslashes($course->summary
);
2510 $course->password
= addslashes($course->password
);
2511 $course->teacher
= addslashes($course->teacher
);
2512 $course->teachers
= addslashes($course->teachers
);
2513 $course->student
= addslashes($course->student
);
2514 $course->students
= addslashes($course->students
);
2516 if (!update_record('course', $course)) {
2517 notify("An error occurred - course not moved!");
2519 // parents changed (course category), do not delete child context relations
2520 insert_context_rel(get_context_instance(CONTEXT_COURSE
, $course->id
), false);
2523 fix_course_sortorder();
2529 * @param string $format Course format ID e.g. 'weeks'
2530 * @return Name that the course format prefers for sections
2532 function get_section_name($format) {
2533 $sectionname = get_string("name$format","format_$format");
2534 if($sectionname == "[[name$format]]") {
2535 $sectionname = get_string("name$format");
2537 return $sectionname;
2541 * Can the current user delete this course?
2542 * @param int $courseid
2545 * Exception here to fix MDL-7796.
2548 * Course creators who can manage activities in the course
2549 * shoule be allowed to delete the course. We do it this
2550 * way because we need a quick fix to bring the functionality
2551 * in line with what we had pre-roles. We can't give the
2552 * default course creator role moodle/course:delete at
2553 * CONTEXT_SYSTEM level because this will allow them to
2554 * delete any course in the site. So we hard code this here
2557 * @author vyshane AT gmail.com
2559 function can_delete_course($courseid) {
2561 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
2563 return ( has_capability('moodle/course:delete', $context)
2564 ||
(has_capability('moodle/legacy:coursecreator', $context)
2565 && has_capability('moodle/course:manageactivities', $context)) );
2570 * Create a course and either return a $course object or false
2572 * @param object $data - all the data needed for an entry in the 'course' table
2574 function create_course($data) {
2577 // preprocess allowed mods
2578 $allowedmods = empty($data->allowedmods
) ?
array() : $data->allowedmods
;
2579 unset($data->allowedmods
);
2580 if (!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM
))) {
2581 if ($CFG->restrictmodulesfor
== 'all') {
2582 $data->restrictmodules
= 1;
2584 $data->restrictmodules
= 0;
2588 $data->timecreated
= time();
2590 // place at beginning of category
2591 fix_course_sortorder();
2592 $data->sortorder
= get_field_sql("SELECT min(sortorder)-1 FROM {$CFG->prefix}course WHERE category=$data->category");
2593 if (empty($data->sortorder
)) {
2594 $data->sortorder
= 100;
2597 if ($newcourseid = insert_record('course', $data)) { // Set up new course
2599 $course = get_record('course', 'id', $newcourseid);
2602 $page = page_create_object(PAGE_COURSE_VIEW
, $course->id
);
2603 blocks_repopulate_page($page); // Return value not checked because you can always edit later
2605 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM
))) {
2606 update_restricted_mods($course, $allowedmods);
2609 $section = new object();
2610 $section->course
= $course->id
; // Create a default section.
2611 $section->section
= 0;
2612 $section->id
= insert_record('course_sections', $section);
2614 fix_course_sortorder();
2616 add_to_log(SITEID
, 'course', 'new', 'view.php?id='.$course->id
, $data->fullname
.' (ID '.$course->id
.')');
2621 return false; // error
2626 * Update a course and return true or false
2628 * @param object $data - all the data needed for an entry in the 'course' table
2630 function update_course($data) {
2633 // preprocess allowed mods
2634 $allowedmods = empty($data->allowedmods
) ?
array() : $data->allowedmods
;
2635 unset($data->allowedmods
);
2636 if (!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM
))) {
2637 unset($data->restrictmodules
);
2640 $oldcourse = get_record('course', 'id', $data->id
); // should not fail, already tested above
2641 if (!has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT
, $oldcourse->category
))
2642 or !has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT
, $data->category
))) {
2643 // can not move to new category, keep the old one
2644 unset($data->category
);
2647 // Update with the new data
2648 if (update_record('course', $data)) {
2650 $course = get_record('course', 'id', $data->id
);
2652 add_to_log($course->id
, "course", "update", "edit.php?id=$course->id", $course->id
);
2654 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM
))) {
2655 update_restricted_mods($course, $allowedmods);
2658 fix_course_sortorder();
2660 // Test for and remove blocks which aren't appropriate anymore
2661 $page = page_create_object(PAGE_COURSE_VIEW
, $course->id
);
2662 blocks_remove_inappropriate($page);
2664 // put custom role names into db
2665 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
2667 foreach ($data as $dname => $dvalue) {
2669 // is this the right param?
2670 $dvalue = clean_param($dvalue, PARAM_NOTAGS
);
2672 if (!strstr($dname, 'role_')) {
2676 $dt = explode('_', $dname);
2678 // make up our mind whether we want to delete, update or insert
2680 if (empty($dvalue)) {
2682 delete_records('role_names', 'contextid', $context->id
, 'roleid', $roleid);
2684 } else if ($t = get_record('role_names', 'contextid', $context->id
, 'roleid', $roleid)) {
2687 update_record('role_names', $t);
2691 $t->contextid
= $context->id
;
2692 $t->roleid
= $roleid;
2694 insert_record('role_names', $t);