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 $roles = get_records_select( 'role', '', 'sortorder' );
1787 foreach ($roles as $role) {
1788 if (in_array( $role->id
, $coursemanagerroles )) {
1789 if ($users = get_role_users($role->id
, $context, true, '', 'u.lastname ASC', true)) {
1790 foreach ($users as $teacher) {
1791 $fullname = fullname($teacher, has_capability('moodle/site:viewfullnames', $context));
1792 $namesarray[] = role_get_name($role, $context).': <a href="'.$CFG->wwwroot
.'/user/view.php?id='.
1793 $teacher->id
.'&course='.SITEID
.'">'.$fullname.'</a>';
1799 if (!empty($namesarray)) {
1800 echo "<ul class=\"teachers\">\n<li>";
1801 echo implode('</li><li>', $namesarray);
1806 require_once("$CFG->dirroot/enrol/enrol.class.php");
1807 $enrol = enrolment_factory
::factory($course->enrol
);
1808 echo $enrol->get_access_icons($course);
1810 echo '</div><div class="summary">';
1812 $options->noclean
= true;
1813 $options->para
= false;
1814 echo format_text($course->summary
, FORMAT_MOODLE
, $options, $course->id
);
1817 echo '<div class="clearer"></div>';
1821 function print_my_moodle() {
1822 /// Prints custom user information on the home page.
1823 /// Over time this can include all sorts of information
1827 if (empty($USER->id
)) {
1828 error("It shouldn't be possible to see My Moodle without being logged in.");
1831 $courses = get_my_courses($USER->id
);
1833 $rcourses = array();
1834 if (!empty($CFG->mnet_dispatcher_mode
) && $CFG->mnet_dispatcher_mode
==='strict') {
1835 $rcourses = get_my_remotecourses($USER->id
);
1836 $rhosts = get_my_remotehosts();
1839 if (!empty($courses) ||
!empty($rcourses) ||
!empty($rhosts)) {
1841 if (!empty($courses)) {
1842 foreach ($courses as $course) {
1843 if ($course->id
== SITEID
) {
1846 print_course($course, "100%");
1851 if (!empty($rcourses)) {
1852 // at the IDP, we know of all the remote courses
1853 foreach ($rcourses as $course) {
1854 print_remote_course($course, "100%");
1856 } elseif (!empty($rhosts)) {
1857 // non-IDP, we know of all the remote servers, but not courses
1858 foreach ($rhosts as $host) {
1859 print_remote_host($host, "100%");
1865 if (count_records("course") > (count($courses) +
1) ) { // Some courses not being displayed
1866 echo "<table width=\"100%\"><tr><td align=\"center\">";
1867 print_course_search("", false, "short");
1868 echo "</td><td align=\"center\">";
1869 print_single_button("$CFG->wwwroot/course/index.php", NULL, get_string("fulllistofcourses"), "get");
1870 echo "</td></tr></table>\n";
1874 if (count_records("course_categories") > 1) {
1875 print_simple_box_start("center", "100%", "#FFFFFF", 5, "categorybox");
1876 print_whole_category_list();
1877 print_simple_box_end();
1885 function print_course_search($value="", $return=false, $format="plain") {
1892 $id = 'coursesearch';
1898 $strsearchcourses= get_string("searchcourses");
1900 if ($format == 'plain') {
1901 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot
.'/course/search.php" method="get">';
1902 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
1903 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
1904 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
1905 $output .= '<input type="submit" value="'.get_string('go').'" />';
1906 $output .= '</fieldset></form>';
1907 } else if ($format == 'short') {
1908 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot
.'/course/search.php" method="get">';
1909 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
1910 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
1911 $output .= '<input type="text" id="coursesearchbox" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
1912 $output .= '<input type="submit" value="'.get_string('go').'" />';
1913 $output .= '</fieldset></form>';
1914 } else if ($format == 'navbar') {
1915 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot
.'/course/search.php" method="get">';
1916 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
1917 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
1918 $output .= '<input type="text" id="coursesearchbox" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
1919 $output .= '<input type="submit" value="'.get_string('go').'" />';
1920 $output .= '</fieldset></form>';
1929 function print_remote_course($course, $width="100%") {
1935 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&wantsurl=/course/view.php?id={$course->remoteid}";
1937 echo '<div class="coursebox remotecoursebox">';
1938 echo '<div class="info">';
1939 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
1940 $linkcss.' href="'.$url.'">'
1941 . format_string($course->fullname
) .'</a><br />'
1942 . format_string($course->hostname
) . ' : '
1943 . format_string($course->cat_name
) . ' : '
1944 . format_string($course->shortname
). '</div>';
1945 echo '</div><div class="summary">';
1947 $options->noclean
= true;
1948 $options->para
= false;
1949 echo format_text($course->summary
, FORMAT_MOODLE
, $options);
1952 echo '<div class="clearer"></div>';
1955 function print_remote_host($host, $width="100%") {
1961 echo '<div class="coursebox">';
1962 echo '<div class="info">';
1963 echo '<div class="name">';
1964 echo '<img src="'.$CFG->pixpath
.'/i/mnethost.gif" class="icon" alt="'.get_string('course').'" />';
1965 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
1966 . s($host['name']).'</a> - ';
1967 echo $host['count'] . ' ' . get_string('courses');
1971 echo '<div class="clearer"></div>';
1975 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
1977 function add_course_module($mod) {
1979 $mod->added
= time();
1982 return insert_record("course_modules", $mod);
1985 function add_mod_to_section($mod, $beforemod=NULL) {
1986 /// Given a full mod object with section and course already defined
1987 /// If $before is specified, then this is an existing ID which we
1988 /// will insert the new module before
1990 /// Returns the course_sections ID where the mod is inserted
1992 if ($section = get_record("course_sections", "course", "$mod->course", "section", "$mod->section")) {
1994 $section->sequence
= trim($section->sequence
);
1996 if (empty($section->sequence
)) {
1997 $newsequence = "$mod->coursemodule";
1999 } else if ($beforemod) {
2000 $modarray = explode(",", $section->sequence
);
2002 if ($key = array_keys ($modarray, $beforemod->id
)) {
2003 $insertarray = array($mod->id
, $beforemod->id
);
2004 array_splice($modarray, $key[0], 1, $insertarray);
2005 $newsequence = implode(",", $modarray);
2007 } else { // Just tack it on the end anyway
2008 $newsequence = "$section->sequence,$mod->coursemodule";
2012 $newsequence = "$section->sequence,$mod->coursemodule";
2015 if (set_field("course_sections", "sequence", $newsequence, "id", $section->id
)) {
2016 return $section->id
; // Return course_sections ID that was used.
2021 } else { // Insert a new record
2022 $section->course
= $mod->course
;
2023 $section->section
= $mod->section
;
2024 $section->summary
= "";
2025 $section->sequence
= $mod->coursemodule
;
2026 return insert_record("course_sections", $section);
2030 function set_coursemodule_groupmode($id, $groupmode) {
2031 return set_field("course_modules", "groupmode", $groupmode, "id", $id);
2034 function set_coursemodule_idnumber($id, $idnumber) {
2035 return set_field("course_modules", "idnumber", $idnumber, "id", $id);
2038 * $prevstateoverrides = true will set the visibility of the course module
2039 * to what is defined in visibleold. This enables us to remember the current
2040 * visibility when making a whole section hidden, so that when we toggle
2041 * that section back to visible, we are able to return the visibility of
2042 * the course module back to what it was originally.
2044 function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
2045 if (!$cm = get_record('course_modules', 'id', $id)) {
2048 if (!$modulename = get_field('modules', 'name', 'id', $cm->module
)) {
2051 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
2052 foreach($events as $event) {
2060 if ($prevstateoverrides) {
2061 if ($visible == '0') {
2062 // Remember the current visible state so we can toggle this back.
2063 set_field('course_modules', 'visibleold', $cm->visible
, 'id', $id);
2065 // Get the previous saved visible states.
2066 return set_field('course_modules', 'visible', $cm->visibleold
, 'id', $id);
2069 return set_field("course_modules", "visible", $visible, "id", $id);
2073 * Delete a course module and any associated data at the course level (events)
2074 * Until 1.5 this function simply marked a deleted flag ... now it
2075 * deletes it completely.
2078 function delete_course_module($id) {
2079 if (!$cm = get_record('course_modules', 'id', $id)) {
2082 $modulename = get_field('modules', 'name', 'id', $cm->module
);
2083 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
2084 foreach($events as $event) {
2085 delete_event($event);
2088 return delete_records('course_modules', 'id', $cm->id
);
2091 function delete_mod_from_section($mod, $section) {
2093 if ($section = get_record("course_sections", "id", "$section") ) {
2095 $modarray = explode(",", $section->sequence
);
2097 if ($key = array_keys ($modarray, $mod)) {
2098 array_splice($modarray, $key[0], 1);
2099 $newsequence = implode(",", $modarray);
2100 return set_field("course_sections", "sequence", $newsequence, "id", $section->id
);
2109 function move_section($course, $section, $move) {
2110 /// Moves a whole course section up and down within the course
2117 $sectiondest = $section +
$move;
2119 if ($sectiondest > $course->numsections
or $sectiondest < 1) {
2123 if (!$sectionrecord = get_record("course_sections", "course", $course->id
, "section", $section)) {
2127 if (!$sectiondestrecord = get_record("course_sections", "course", $course->id
, "section", $sectiondest)) {
2131 if (!set_field("course_sections", "section", $sectiondest, "id", $sectionrecord->id
)) {
2134 if (!set_field("course_sections", "section", $section, "id", $sectiondestrecord->id
)) {
2137 // if the focus is on the section that is being moved, then move the focus along
2138 if (isset($USER->display
[$course->id
]) and ($USER->display
[$course->id
] == $section)) {
2139 course_set_display($course->id
, $sectiondest);
2142 // Check for duplicates and fix order if needed.
2143 // There is a very rare case that some sections in the same course have the same section id.
2144 $sections = get_records_select('course_sections', "course = $course->id", 'section ASC');
2146 foreach ($sections as $section) {
2147 if ($section->section
!= $n) {
2148 if (!set_field('course_sections', 'section', $n, 'id', $section->id
)) {
2158 function moveto_module($mod, $section, $beforemod=NULL) {
2159 /// All parameters are objects
2160 /// Move the module object $mod to the specified $section
2161 /// If $beforemod exists then that is the module
2162 /// before which $modid should be inserted
2164 /// Remove original module from original section
2166 if (! delete_mod_from_section($mod->id
, $mod->section
)) {
2167 notify("Could not delete module from existing section");
2170 /// Update module itself if necessary
2172 if ($mod->section
!= $section->id
) {
2173 $mod->section
= $section->id
;
2174 if (!update_record("course_modules", $mod)) {
2177 // if moving to a hidden section then hide module
2178 if (!$section->visible
) {
2179 set_coursemodule_visible($mod->id
, 0);
2183 /// Add the module into the new section
2185 $mod->course
= $section->course
;
2186 $mod->section
= $section->section
; // need relative reference
2187 $mod->coursemodule
= $mod->id
;
2189 if (! add_mod_to_section($mod, $beforemod)) {
2197 function make_editing_buttons($mod, $absolute=false, $moveselect=true, $indent=-1, $section=-1) {
2203 $modcontext = get_context_instance(CONTEXT_MODULE
, $mod->id
);
2204 // no permission to edit
2205 if (!has_capability('moodle/course:manageactivities', $modcontext)) {
2210 $str->delete
= get_string("delete");
2211 $str->move
= get_string("move");
2212 $str->moveup
= get_string("moveup");
2213 $str->movedown
= get_string("movedown");
2214 $str->moveright
= get_string("moveright");
2215 $str->moveleft
= get_string("moveleft");
2216 $str->update
= get_string("update");
2217 $str->duplicate
= get_string("duplicate");
2218 $str->hide
= get_string("hide");
2219 $str->show
= get_string("show");
2220 $str->clicktochange
= get_string("clicktochange");
2221 $str->forcedmode
= get_string("forcedmode");
2222 $str->groupsnone
= get_string("groupsnone");
2223 $str->groupsseparate
= get_string("groupsseparate");
2224 $str->groupsvisible
= get_string("groupsvisible");
2225 $sesskey = sesskey();
2228 if ($section >= 0) {
2229 $section = '&sr='.$section; // Section return
2235 $path = $CFG->wwwroot
.'/course';
2240 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
2241 if ($mod->visible
) {
2242 $hideshow = '<a class="editing_hide" title="'.$str->hide
.'" href="'.$path.'/mod.php?hide='.$mod->id
.
2243 '&sesskey='.$sesskey.$section.'"><img'.
2244 ' src="'.$CFG->pixpath
.'/t/hide.gif" class="iconsmall" '.
2245 ' alt="'.$str->hide
.'" /></a>'."\n";
2247 $hideshow = '<a class="editing_show" title="'.$str->show
.'" href="'.$path.'/mod.php?show='.$mod->id
.
2248 '&sesskey='.$sesskey.$section.'"><img'.
2249 ' src="'.$CFG->pixpath
.'/t/show.gif" class="iconsmall" '.
2250 ' alt="'.$str->show
.'" /></a>'."\n";
2253 if ($mod->groupmode
!== false) {
2254 if ($mod->groupmode
== SEPARATEGROUPS
) {
2255 $grouptitle = $str->groupsseparate
;
2256 $groupclass = 'editing_groupsseparate';
2257 $groupimage = $CFG->pixpath
.'/t/groups.gif';
2258 $grouplink = $path.'/mod.php?id='.$mod->id
.'&groupmode=0&sesskey='.$sesskey;
2259 } else if ($mod->groupmode
== VISIBLEGROUPS
) {
2260 $grouptitle = $str->groupsvisible
;
2261 $groupclass = 'editing_groupsvisible';
2262 $groupimage = $CFG->pixpath
.'/t/groupv.gif';
2263 $grouplink = $path.'/mod.php?id='.$mod->id
.'&groupmode=1&sesskey='.$sesskey;
2265 $grouptitle = $str->groupsnone
;
2266 $groupclass = 'editing_groupsnone';
2267 $groupimage = $CFG->pixpath
.'/t/groupn.gif';
2268 $grouplink = $path.'/mod.php?id='.$mod->id
.'&groupmode=2&sesskey='.$sesskey;
2270 if ($mod->groupmodelink
) {
2271 $groupmode = '<a class="'.$groupclass.'" title="'.$grouptitle.' ('.$str->clicktochange
.')" href="'.$grouplink.'">'.
2272 '<img src="'.$groupimage.'" class="iconsmall" '.
2273 'alt="'.$grouptitle.'" /></a>';
2275 $groupmode = '<img title="'.$grouptitle.' ('.$str->forcedmode
.')" '.
2276 ' src="'.$groupimage.'" class="iconsmall" '.
2277 'alt="'.$grouptitle.'" />';
2283 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE
, $mod->course
))) {
2285 $move = '<a class="editing_move" title="'.$str->move
.'" href="'.$path.'/mod.php?copy='.$mod->id
.
2286 '&sesskey='.$sesskey.$section.'"><img'.
2287 ' src="'.$CFG->pixpath
.'/t/move.gif" class="iconsmall" '.
2288 ' alt="'.$str->move
.'" /></a>'."\n";
2290 $move = '<a class="editing_moveup" title="'.$str->moveup
.'" href="'.$path.'/mod.php?id='.$mod->id
.
2291 '&move=-1&sesskey='.$sesskey.$section.'"><img'.
2292 ' src="'.$CFG->pixpath
.'/t/up.gif" class="iconsmall" '.
2293 ' alt="'.$str->moveup
.'" /></a>'."\n".
2294 '<a class="editing_movedown" title="'.$str->movedown
.'" href="'.$path.'/mod.php?id='.$mod->id
.
2295 '&move=1&sesskey='.$sesskey.$section.'"><img'.
2296 ' src="'.$CFG->pixpath
.'/t/down.gif" class="iconsmall" '.
2297 ' alt="'.$str->movedown
.'" /></a>'."\n";
2304 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE
, $mod->course
))) {
2306 $leftright .= '<a class="editing_moveleft" title="'.$str->moveleft
.'" href="'.$path.'/mod.php?id='.$mod->id
.
2307 '&indent=-1&sesskey='.$sesskey.$section.'"><img'.
2308 ' src="'.$CFG->pixpath
.'/t/left.gif" class="iconsmall" '.
2309 ' alt="'.$str->moveleft
.'" /></a>'."\n";
2312 $leftright .= '<a class="editing_moveright" title="'.$str->moveright
.'" href="'.$path.'/mod.php?id='.$mod->id
.
2313 '&indent=1&sesskey='.$sesskey.$section.'"><img'.
2314 ' src="'.$CFG->pixpath
.'/t/right.gif" class="iconsmall" '.
2315 ' alt="'.$str->moveright
.'" /></a>'."\n";
2319 return '<span class="commands">'."\n".$leftright.$move.
2320 '<a class="editing_update" title="'.$str->update
.'" href="'.$path.'/mod.php?update='.$mod->id
.
2321 '&sesskey='.$sesskey.$section.'"><img'.
2322 ' src="'.$CFG->pixpath
.'/t/edit.gif" class="iconsmall" '.
2323 ' alt="'.$str->update
.'" /></a>'."\n".
2324 '<a class="editing_delete" title="'.$str->delete
.'" href="'.$path.'/mod.php?delete='.$mod->id
.
2325 '&sesskey='.$sesskey.$section.'"><img'.
2326 ' src="'.$CFG->pixpath
.'/t/delete.gif" class="iconsmall" '.
2327 ' alt="'.$str->delete
.'" /></a>'."\n".$hideshow.$groupmode."\n".'</span>';
2331 * given a course object with shortname & fullname, this function will
2332 * truncate the the number of chars allowed and add ... if it was too long
2334 function course_format_name ($course,$max=100) {
2336 $str = $course->shortname
.': '. $course->fullname
;
2337 if (strlen($str) <= $max) {
2341 return substr($str,0,$max-3).'...';
2346 * This function will return true if the given course is a child course at all
2348 function course_in_meta ($course) {
2349 return record_exists("course_meta","child_course",$course->id
);
2354 * Print standard form elements on module setup forms in mod/.../mod.html
2356 function print_standard_coursemodule_settings($form) {
2357 if (! $course = get_record('course', 'id', $form->course
)) {
2358 error("This course doesn't exist");
2360 print_groupmode_setting($form, $course);
2361 print_visible_setting($form, $course);
2365 * Print groupmode form element on module setup forms in mod/.../mod.html
2367 function print_groupmode_setting($form, $course=NULL) {
2369 if (empty($course)) {
2370 if (! $course = get_record('course', 'id', $form->course
)) {
2371 error("This course doesn't exist");
2374 if ($form->coursemodule
) {
2375 if (! $cm = get_record('course_modules', 'id', $form->coursemodule
)) {
2376 error("This course module doesn't exist");
2381 $groupmode = groupmode($course, $cm);
2382 if ($course->groupmode
or (!$course->groupmodeforce
)) {
2383 echo '<tr valign="top">';
2384 echo '<td align="right"><b>'.get_string('groupmode').':</b></td>';
2385 echo '<td align="left">';
2387 $choices[NOGROUPS
] = get_string('groupsnone');
2388 $choices[SEPARATEGROUPS
] = get_string('groupsseparate');
2389 $choices[VISIBLEGROUPS
] = get_string('groupsvisible');
2390 choose_from_menu($choices, 'groupmode', $groupmode, '', '', 0, false, $course->groupmodeforce
);
2391 helpbutton('groupmode', get_string('groupmode'));
2397 * Print visibility setting form element on module setup forms in mod/.../mod.html
2399 function print_visible_setting($form, $course=NULL) {
2400 if (empty($course)) {
2401 if (! $course = get_record('course', 'id', $form->course
)) {
2402 error("This course doesn't exist");
2405 if ($form->coursemodule
) {
2406 $visible = get_field('course_modules', 'visible', 'id', $form->coursemodule
);
2411 if ($form->mode
== 'add') { // in this case $form->section is the section number, not the id
2412 $hiddensection = !get_field('course_sections', 'visible', 'section', $form->section
, 'course', $form->course
);
2414 $hiddensection = !get_field('course_sections', 'visible', 'id', $form->section
);
2416 if ($hiddensection) {
2420 echo '<tr valign="top">';
2421 echo '<td align="right"><b>'.get_string('visible', '').':</b></td>';
2422 echo '<td align="left">';
2424 $choices[1] = get_string('show');
2425 $choices[0] = get_string('hide');
2426 choose_from_menu($choices, 'visible', $visible, '', '', 0, false, $hiddensection);
2430 function update_restricted_mods($course,$mods) {
2431 delete_records("course_allowed_modules","course",$course->id
);
2432 if (empty($course->restrictmodules
)) {
2436 foreach ($mods as $mod) {
2438 continue; // this is the 'allow none' option
2439 $am->course
= $course->id
;
2441 insert_record("course_allowed_modules",$am);
2447 * This function will take an int (module id) or a string (module name)
2448 * and return true or false, whether it's allowed in the given course (object)
2449 * $mod is not allowed to be an object, as the field for the module id is inconsistent
2450 * depending on where in the code it's called from (sometimes $mod->id, sometimes $mod->module)
2453 function course_allowed_module($course,$mod) {
2454 if (empty($course->restrictmodules
)) {
2458 // i am not sure this capability is correct
2459 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM
, SITEID
))) {
2462 if (is_numeric($mod)) {
2464 } else if (is_string($mod)) {
2465 if ($mod = get_field("modules","id","name",$mod))
2468 if (empty($modid)) {
2471 return (record_exists("course_allowed_modules","course",$course->id
,"module",$modid));
2475 *** Efficiently moves many courses around while maintaining
2476 *** sortorder in order.
2478 *** $courseids is an array of course ids
2482 function move_courses ($courseids, $categoryid) {
2486 if (!empty($courseids)) {
2488 $courseids = array_reverse($courseids);
2490 foreach ($courseids as $courseid) {
2492 if (! $course = get_record("course", "id", $courseid)) {
2493 notify("Error finding course $courseid");
2495 // figure out a sortorder that we can use in the destination category
2496 $sortorder = get_field_sql('SELECT MIN(sortorder)-1 AS min
2497 FROM ' . $CFG->prefix
. 'course WHERE category=' . $categoryid);
2498 if ($sortorder === false) {
2499 // the category is empty
2500 // rather than let the db default to 0
2501 // set it to > 100 and avoid extra work in fix_coursesortorder()
2503 } else if ($sortorder < 10) {
2504 fix_course_sortorder($categoryid);
2507 $course->category
= $categoryid;
2508 $course->sortorder
= $sortorder;
2509 $course->fullname
= addslashes($course->fullname
);
2510 $course->shortname
= addslashes($course->shortname
);
2511 $course->summary
= addslashes($course->summary
);
2512 $course->password
= addslashes($course->password
);
2513 $course->teacher
= addslashes($course->teacher
);
2514 $course->teachers
= addslashes($course->teachers
);
2515 $course->student
= addslashes($course->student
);
2516 $course->students
= addslashes($course->students
);
2518 if (!update_record('course', $course)) {
2519 notify("An error occurred - course not moved!");
2521 // parents changed (course category), do not delete child context relations
2522 insert_context_rel(get_context_instance(CONTEXT_COURSE
, $course->id
), false);
2525 fix_course_sortorder();
2531 * @param string $format Course format ID e.g. 'weeks'
2532 * @return Name that the course format prefers for sections
2534 function get_section_name($format) {
2535 $sectionname = get_string("name$format","format_$format");
2536 if($sectionname == "[[name$format]]") {
2537 $sectionname = get_string("name$format");
2539 return $sectionname;
2543 * Can the current user delete this course?
2544 * @param int $courseid
2547 * Exception here to fix MDL-7796.
2550 * Course creators who can manage activities in the course
2551 * shoule be allowed to delete the course. We do it this
2552 * way because we need a quick fix to bring the functionality
2553 * in line with what we had pre-roles. We can't give the
2554 * default course creator role moodle/course:delete at
2555 * CONTEXT_SYSTEM level because this will allow them to
2556 * delete any course in the site. So we hard code this here
2559 * @author vyshane AT gmail.com
2561 function can_delete_course($courseid) {
2563 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
2565 return ( has_capability('moodle/course:delete', $context)
2566 ||
(has_capability('moodle/legacy:coursecreator', $context)
2567 && has_capability('moodle/course:manageactivities', $context)) );
2572 * Create a course and either return a $course object or false
2574 * @param object $data - all the data needed for an entry in the 'course' table
2576 function create_course($data) {
2579 // preprocess allowed mods
2580 $allowedmods = empty($data->allowedmods
) ?
array() : $data->allowedmods
;
2581 unset($data->allowedmods
);
2582 if (!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM
))) {
2583 if ($CFG->restrictmodulesfor
== 'all') {
2584 $data->restrictmodules
= 1;
2586 $data->restrictmodules
= 0;
2590 $data->timecreated
= time();
2592 // place at beginning of category
2593 fix_course_sortorder();
2594 $data->sortorder
= get_field_sql("SELECT min(sortorder)-1 FROM {$CFG->prefix}course WHERE category=$data->category");
2595 if (empty($data->sortorder
)) {
2596 $data->sortorder
= 100;
2599 if ($newcourseid = insert_record('course', $data)) { // Set up new course
2601 $course = get_record('course', 'id', $newcourseid);
2604 $page = page_create_object(PAGE_COURSE_VIEW
, $course->id
);
2605 blocks_repopulate_page($page); // Return value not checked because you can always edit later
2607 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM
))) {
2608 update_restricted_mods($course, $allowedmods);
2611 $section = new object();
2612 $section->course
= $course->id
; // Create a default section.
2613 $section->section
= 0;
2614 $section->id
= insert_record('course_sections', $section);
2616 fix_course_sortorder();
2618 add_to_log(SITEID
, 'course', 'new', 'view.php?id='.$course->id
, $data->fullname
.' (ID '.$course->id
.')');
2623 return false; // error
2628 * Update a course and return true or false
2630 * @param object $data - all the data needed for an entry in the 'course' table
2632 function update_course($data) {
2635 // preprocess allowed mods
2636 $allowedmods = empty($data->allowedmods
) ?
array() : $data->allowedmods
;
2637 unset($data->allowedmods
);
2638 if (!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM
))) {
2639 unset($data->restrictmodules
);
2642 $oldcourse = get_record('course', 'id', $data->id
); // should not fail, already tested above
2643 if (!has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT
, $oldcourse->category
))
2644 or !has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT
, $data->category
))) {
2645 // can not move to new category, keep the old one
2646 unset($data->category
);
2649 // Update with the new data
2650 if (update_record('course', $data)) {
2652 $course = get_record('course', 'id', $data->id
);
2654 add_to_log($course->id
, "course", "update", "edit.php?id=$course->id", $course->id
);
2656 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM
))) {
2657 update_restricted_mods($course, $allowedmods);
2660 fix_course_sortorder();
2662 // Test for and remove blocks which aren't appropriate anymore
2663 $page = page_create_object(PAGE_COURSE_VIEW
, $course->id
);
2664 blocks_remove_inappropriate($page);
2666 // put custom role names into db
2667 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
2669 foreach ($data as $dname => $dvalue) {
2671 // is this the right param?
2672 $dvalue = clean_param($dvalue, PARAM_NOTAGS
);
2674 if (!strstr($dname, 'role_')) {
2678 $dt = explode('_', $dname);
2680 // make up our mind whether we want to delete, update or insert
2682 if (empty($dvalue)) {
2684 delete_records('role_names', 'contextid', $context->id
, 'roleid', $roleid);
2686 } else if ($t = get_record('role_names', 'contextid', $context->id
, 'roleid', $roleid)) {
2689 update_record('role_names', $t);
2693 $t->contextid
= $context->id
;
2694 $t->roleid
= $roleid;
2696 insert_record('role_names', $t);