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 (!groups_course_module_visible($mod)) {
95 if ($mod->section
> 0 and $section <> $mod->section
) {
96 $activities["section/$mod->section"] = "-------------- $strsection $mod->section --------------";
98 $section = $mod->section
;
99 $mod->name
= strip_tags(format_string(urldecode($mod->name
),true));
100 if (strlen($mod->name
) > 55) {
101 $mod->name
= substr($mod->name
, 0, 50)."...";
103 if (!$mod->visible
) {
104 $mod->name
= "(".$mod->name
.")";
106 $activities["$mod->cm"] = $mod->name
;
108 if ($mod->cm
== $modid) {
109 $selectedactivity = "$mod->cm";
114 $strftimedate = get_string("strftimedate");
115 $strftimedaydate = get_string("strftimedaydate");
119 // Get all the possible dates
120 // Note that we are keeping track of real (GMT) time and user time
121 // User time is only used in displays - all calcs and passing is GMT
123 $timenow = time(); // GMT
125 // What day is it now for the user, and when is midnight that day (in GMT).
126 $timemidnight = $today = usergetmidnight($timenow);
129 $dates["$USER->lastlogin"] = get_string("lastlogin").", ".userdate($USER->lastlogin
, $strftimedate);
130 $dates["$timemidnight"] = get_string("today").", ".userdate($timenow, $strftimedate);
132 if (!$course->startdate
or ($course->startdate
> $timenow)) {
133 $course->startdate
= $course->timecreated
;
137 while ($timemidnight > $course->startdate
and $numdates < 365) {
138 $timemidnight = $timemidnight - 86400;
139 $timenow = $timenow - 86400;
140 $dates["$timemidnight"] = userdate($timenow, $strftimedaydate);
144 if ($selecteddate === "lastlogin") {
145 $selecteddate = $USER->lastlogin
;
148 echo '<form action="recent.php" method="get">';
149 echo '<input type="hidden" name="chooserecent" value="1" />';
153 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM
, SITEID
))) {
154 echo "<tr><td><b>" . get_string("courses") . "</b></td><td>";
155 choose_from_menu ($courses, "id", $course->id
, "");
158 echo '<input type="hidden" name="id" value="'.$course->id
.'" />';
161 $sortfields = array("default" => get_string("bycourseorder"),"dateasc" => get_string("datemostrecentlast"), "datedesc" => get_string("datemostrecentfirst"));
163 echo "<tr><td><b>" . get_string("participants") . "</b></td><td>";
164 choose_from_menu ($users, "user", $selecteduser, get_string("allparticipants") );
167 echo '<td align="right"><b>' . get_string("since") . '</b></td><td>';
168 choose_from_menu ($dates, "date", $selecteddate, get_string("alldays"));
171 echo "<tr><td><b>" . get_string("activities") . "</b></td><td>";
172 choose_from_menu ($activities, "modid", $selectedactivity, "");
175 echo '<td align="right"><b>' . get_string("sortby") . "</b></td><td>";
176 choose_from_menu ($sortfields, "sortby", $selectedsort, "");
181 $groupmode = groups_get_course_groupmode($course);
183 if ($groupmode == VISIBLEGROUPS
or ($groupmode and has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE
, $course->id
)))) {
184 if ($groups = groups_get_all_groups($course->id
)) {
185 $group_names = array();
186 foreach($groups as $group) {
187 $group_names[$group->id
] = format_string($group->name
);
190 if ($groupmode == VISIBLEGROUPS
) {
191 print_string('groupsvisible');
193 print_string('groupsseparate');
195 echo ':</b></td><td>';
196 choose_from_menu($group_names, "selectedgroup", $selectedgroup, get_string("allgroups"), "", "");
202 echo '<td colspan="2" align="right">';
203 echo '<input type="submit" value="'.get_string('showrecent').'" />';
208 $advancedlink = "<a href=\"$CFG->wwwroot/course/recent.php?id=$course->id&advancedfilter=0\">" . get_string("normalfilter") . "</a>";
209 print_heading($advancedlink);
215 $day_list = array("1","7","14","21","30");
216 $strsince = get_string("since");
217 $strlastlogin = get_string("lastlogin");
218 $strday = get_string("day");
219 $strdays = get_string("days");
222 foreach ($day_list as $count) {
228 $tmpdate = time() - ($count * 3600 * 24);
229 $heading = $heading .
230 "<a href=\"$CFG->wwwroot/course/recent.php?id=$course->id&date=$tmpdate\"> $count $day</a> | ";
233 $heading = $strsince . ": <a href=\"$CFG->wwwroot/course/recent.php?id=$course->id\">$strlastlogin</a>" . " | " . $heading;
234 print_heading($heading);
236 $advancedlink = "<a href=\"$CFG->wwwroot/course/recent.php?id=$course->id&advancedfilter=1\">" . get_string("advancedfilter") . "</a>";
237 print_heading($advancedlink);
244 function make_log_url($module, $url) {
255 return "/course/$url";
258 return "/$module/$url";
268 return "/mod/$module/$url";
274 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
275 $modname="", $modid=0, $modaction="", $groupid=0) {
279 // It is assumed that $date is the GMT time of midnight for that day,
280 // and so the next 86400 seconds worth of logs are printed.
282 /// Setup for group handling.
284 // TODO: I don't understand group/context/etc. enough to be able to do
285 // something interesting with it here
286 // What is the context of a remote course?
288 /// If the group mode is separate, and this user does not have editing privileges,
289 /// then only the user's group can be viewed.
290 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
291 // $groupid = get_current_group($course->id);
293 /// If this course doesn't have groups, no groupid can be specified.
294 //else if (!$course->groupmode) {
308 {$CFG->prefix}mnet_log l
316 $where .= "l.hostid = '$hostid'";
318 // TODO: Is 1 really a magic number referring to the sitename?
319 if ($course != 1 ||
$modid != 0) {
320 $where .= " AND\n l.course='$course'";
324 $where .= " AND\n l.module = '$modname'";
327 if ('site_errors' === $modid) {
328 $where .= " AND\n ( l.action='error' OR l.action='infected' )";
330 //TODO: This assumes that modids are the same across sites... probably
332 $where .= " AND\n l.cmid = '$modid'";
336 $firstletter = substr($modaction, 0, 1);
337 if (ctype_alpha($firstletter)) {
338 $where .= " AND\n lower(l.action) LIKE '%" . strtolower($modaction) . "%'";
339 } else if ($firstletter == '-') {
340 $where .= " AND\n lower(l.action) NOT LIKE '%" . strtolower(substr($modaction, 1)) . "%'";
345 $where .= " AND\n l.userid = '$user'";
349 $enddate = $date +
86400;
350 $where .= " AND\n l.time > '$date' AND l.time < '$enddate'";
354 $result['totalcount'] = count_records_sql("SELECT COUNT(*) FROM {$CFG->prefix}mnet_log l WHERE $where");
355 if(!empty($result['totalcount'])) {
356 $where .= "\n ORDER BY\n $order";
357 $result['logs'] = get_records_sql($qry.$where, $limitfrom, $limitnum);
359 $result['logs'] = array();
364 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
365 $modname="", $modid=0, $modaction="", $groupid=0) {
367 // It is assumed that $date is the GMT time of midnight for that day,
368 // and so the next 86400 seconds worth of logs are printed.
370 /// Setup for group handling.
372 /// If the group mode is separate, and this user does not have editing privileges,
373 /// then only the user's group can be viewed.
374 if ($course->groupmode
== SEPARATEGROUPS
and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE
, $course->id
))) {
375 $groupid = get_current_group($course->id
);
377 /// If this course doesn't have groups, no groupid can be specified.
378 else if (!$course->groupmode
) {
384 if ($course->id
!= SITEID ||
$modid != 0) {
385 $joins[] = "l.course='$course->id'";
389 $joins[] = "l.module = '$modname'";
392 if ('site_errors' === $modid) {
393 $joins[] = "( l.action='error' OR l.action='infected' )";
395 $joins[] = "l.cmid = '$modid'";
399 $firstletter = substr($modaction, 0, 1);
400 if (ctype_alpha($firstletter)) {
401 $joins[] = "lower(l.action) LIKE '%" . strtolower($modaction) . "%'";
402 } else if ($firstletter == '-') {
403 $joins[] = "lower(l.action) NOT LIKE '%" . strtolower(substr($modaction, 1)) . "%'";
407 /// Getting all members of a group.
408 if ($groupid and !$user) {
409 if ($gusers = groups_get_members($groupid)) {
410 $gusers = array_keys($gusers);
411 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
413 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always by false.
417 $joins[] = "l.userid = '$user'";
421 $enddate = $date +
86400;
422 $joins[] = "l.time > '$date' AND l.time < '$enddate'";
425 $selector = implode(' AND ', $joins);
427 $totalcount = 0; // Initialise
429 $result['logs'] = get_logs($selector, $order, $limitfrom, $limitnum, $totalcount);
430 $result['totalcount'] = $totalcount;
435 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
436 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
440 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
441 $modname, $modid, $modaction, $groupid)) {
442 notify("No logs found!");
443 print_footer($course);
449 if ($course->id
== SITEID
) {
451 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
452 foreach ($ccc as $cc) {
453 $courses[$cc->id
] = $cc->shortname
;
457 $courses[$course->id
] = $course->shortname
;
460 $totalcount = $logs['totalcount'];
463 $tt = getdate(time());
464 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
466 $strftimedatetime = get_string("strftimedatetime");
468 echo "<div class=\"info\">\n";
469 print_string("displayingrecords", "", $totalcount);
472 print_paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage&");
474 echo '<table class="logtable genearlbox boxaligncenter" summary="">'."\n";
475 // echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\" summary=\"\">\n";
477 if ($course->id
== SITEID
) {
478 echo "<th class=\"c0 header\" scope=\"col\">".get_string('course')."</th>\n";
480 echo "<th class=\"c1 header\" scope=\"col\">".get_string('time')."</th>\n";
481 echo "<th class=\"c2 header\" scope=\"col\">".get_string('ip_address')."</th>\n";
482 echo "<th class=\"c3 header\" scope=\"col\">".get_string('fullname')."</th>\n";
483 echo "<th class=\"c4 header\" scope=\"col\">".get_string('action')."</th>\n";
484 echo "<th class=\"c5 header\" scope=\"col\">".get_string('info')."</th>\n";
487 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
488 if (empty($logs['logs'])) {
489 $logs['logs'] = array();
493 foreach ($logs['logs'] as $log) {
495 $row = ($row +
1) %
2;
497 if (isset($ldcache[$log->module
][$log->action
])) {
498 $ld = $ldcache[$log->module
][$log->action
];
500 $ld = get_record('log_display', 'module', $log->module
, 'action', $log->action
);
501 $ldcache[$log->module
][$log->action
] = $ld;
503 if ($ld && is_numeric($log->info
)) {
504 // ugly hack to make sure fullname is shown correctly
505 if (($ld->mtable
== 'user') and ($ld->field
== sql_concat('firstname', "' '" , 'lastname'))) {
506 $log->info
= fullname(get_record($ld->mtable
, 'id', $log->info
), true);
508 $log->info
= get_field($ld->mtable
, $ld->field
, 'id', $log->info
);
513 $log->info
= format_string($log->info
);
515 $log->url
= strip_tags(urldecode($log->url
)); // Some XSS protection
516 $log->info
= strip_tags(urldecode($log->info
)); // Some XSS protection
517 $log->url
= str_replace('&', '&', $log->url
); /// XHTML compatibility
519 echo '<tr class="r'.$row.'">';
520 if ($course->id
== SITEID
) {
521 echo "<td class=\"cell c0\">\n";
522 if (empty($log->course
)) {
523 echo format_string($log->info
)."\n";
525 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course
])."</a>\n";
529 echo "<td class=\"cell c1\" align=\"right\">".userdate($log->time
, '%a').
530 ' '.userdate($log->time
, $strftimedatetime)."</td>\n";
531 echo "<td class=\"cell c2\">\n";
532 link_to_popup_window("/iplookup/index.php?ip=$log->ip&user=$log->userid", 'iplookup',$log->ip
, 400, 700);
534 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE
, $course->id
)));
535 echo "<td class=\"cell c3\">\n";
536 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}&course={$log->course}\">$fullname</a>\n";
538 echo "<td class=\"cell c4\">\n";
539 link_to_popup_window( make_log_url($log->module
,$log->url
), 'fromloglive',"$log->module $log->action", 400, 600);
541 echo "<td class=\"cell c5\">{$log->info}</td>\n";
546 print_paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage&");
550 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
551 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
555 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
556 $modname, $modid, $modaction, $groupid)) {
557 notify("No logs found!");
558 print_footer($course);
562 if ($course->id
== SITEID
) {
564 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
565 foreach ($ccc as $cc) {
566 $courses[$cc->id
] = $cc->shortname
;
571 $totalcount = $logs['totalcount'];
574 $tt = getdate(time());
575 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
577 $strftimedatetime = get_string("strftimedatetime");
579 echo "<div class=\"info\">\n";
580 print_string("displayingrecords", "", $totalcount);
583 print_paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage&");
585 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
587 if ($course->id
== SITEID
) {
588 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
590 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
591 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
592 echo "<th class=\"c3 header\">".get_string('fullname')."</th>\n";
593 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
594 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
597 if (empty($logs['logs'])) {
603 foreach ($logs['logs'] as $log) {
605 $log->info
= $log->coursename
;
606 $row = ($row +
1) %
2;
608 if (isset($ldcache[$log->module
][$log->action
])) {
609 $ld = $ldcache[$log->module
][$log->action
];
611 $ld = get_record('log_display', 'module', $log->module
, 'action', $log->action
);
612 $ldcache[$log->module
][$log->action
] = $ld;
614 if (0 && $ld && !empty($log->info
)) {
615 // ugly hack to make sure fullname is shown correctly
616 if (($ld->mtable
== 'user') and ($ld->field
== sql_concat('firstname', "' '" , 'lastname'))) {
617 $log->info
= fullname(get_record($ld->mtable
, 'id', $log->info
), true);
619 $log->info
= get_field($ld->mtable
, $ld->field
, 'id', $log->info
);
624 $log->info
= format_string($log->info
);
626 $log->url
= strip_tags(urldecode($log->url
)); // Some XSS protection
627 $log->info
= strip_tags(urldecode($log->info
)); // Some XSS protection
628 $log->url
= str_replace('&', '&', $log->url
); /// XHTML compatibility
630 echo '<tr class="r'.$row.'">';
631 if ($course->id
== SITEID
) {
632 echo "<td class=\"r$row c0\" >\n";
633 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courses[$log->course
]."</a>\n";
636 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time
, '%a').
637 ' '.userdate($log->time
, $strftimedatetime)."</td>\n";
638 echo "<td class=\"r$row c2\" >\n";
639 link_to_popup_window("/iplookup/index.php?ip=$log->ip&user=$log->userid", 'iplookup',$log->ip
, 400, 700);
641 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE
, $course->id
)));
642 echo "<td class=\"r$row c3\" >\n";
643 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
645 echo "<td class=\"r$row c4\">\n";
646 echo $log->action
.': '.$log->module
;
648 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
653 print_paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage&");
657 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
658 $modid, $modaction, $groupid) {
660 $text = get_string('course')."\t".get_string('time')."\t".get_string('ip_address')."\t".
661 get_string('fullname')."\t".get_string('action')."\t".get_string('info');
663 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
664 $modname, $modid, $modaction, $groupid)) {
670 if ($course->id
== SITEID
) {
672 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
673 foreach ($ccc as $cc) {
674 $courses[$cc->id
] = $cc->shortname
;
678 $courses[$course->id
] = $course->shortname
;
683 $tt = getdate(time());
684 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
686 $strftimedatetime = get_string("strftimedatetime");
688 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
690 header("Content-Type: application/download\n");
691 header("Content-Disposition: attachment; filename=$filename");
692 header("Expires: 0");
693 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
694 header("Pragma: public");
696 echo get_string('savedat').userdate(time(), $strftimedatetime)."\n";
699 if (empty($logs['logs'])) {
703 foreach ($logs['logs'] as $log) {
704 if (isset($ldcache[$log->module
][$log->action
])) {
705 $ld = $ldcache[$log->module
][$log->action
];
707 $ld = get_record('log_display', 'module', $log->module
, 'action', $log->action
);
708 $ldcache[$log->module
][$log->action
] = $ld;
710 if ($ld && !empty($log->info
)) {
711 // ugly hack to make sure fullname is shown correctly
712 if (($ld->mtable
== 'user') and ($ld->field
== sql_concat('firstname', "' '" , 'lastname'))) {
713 $log->info
= fullname(get_record($ld->mtable
, 'id', $log->info
), true);
715 $log->info
= get_field($ld->mtable
, $ld->field
, 'id', $log->info
);
720 $log->info
= format_string($log->info
);
722 $log->url
= strip_tags(urldecode($log->url
)); // Some XSS protection
723 $log->info
= strip_tags(urldecode($log->info
)); // Some XSS protection
724 $log->url
= str_replace('&', '&', $log->url
); // XHTML compatibility
726 $firstField = $courses[$log->course
];
727 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE
, $course->id
)));
728 $row = array($firstField, userdate($log->time
, $strftimedatetime), $log->ip
, $fullname, $log->module
.' '.$log->action
, $log->info
);
729 $text = implode("\t", $row);
736 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
737 $modid, $modaction, $groupid) {
741 require_once("$CFG->libdir/excellib.class.php");
743 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
744 $modname, $modid, $modaction, $groupid)) {
750 if ($course->id
== SITEID
) {
752 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
753 foreach ($ccc as $cc) {
754 $courses[$cc->id
] = $cc->shortname
;
758 $courses[$course->id
] = $course->shortname
;
763 $tt = getdate(time());
764 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
766 $strftimedatetime = get_string("strftimedatetime");
768 $nroPages = ceil(count($logs)/(EXCELROWS
-FIRSTUSEDEXCELROW+
1));
769 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
772 $workbook = new MoodleExcelWorkbook('-');
773 $workbook->send($filename);
775 $worksheet = array();
776 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
777 get_string('fullname'), get_string('action'), get_string('info'));
779 // Creating worksheets
780 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++
) {
781 $sheettitle = get_string('excel_sheettitle', 'logs', $wsnumber).$nroPages;
782 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
783 $worksheet[$wsnumber]->set_column(1, 1, 30);
784 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
785 userdate(time(), $strftimedatetime));
787 foreach ($headers as $item) {
788 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW
-1,$col,$item,'');
793 if (empty($logs['logs'])) {
798 $formatDate =& $workbook->add_format();
799 $formatDate->set_num_format(get_string('log_excel_date_format'));
801 $row = FIRSTUSEDEXCELROW
;
803 $myxls =& $worksheet[$wsnumber];
804 foreach ($logs['logs'] as $log) {
805 if (isset($ldcache[$log->module
][$log->action
])) {
806 $ld = $ldcache[$log->module
][$log->action
];
808 $ld = get_record('log_display', 'module', $log->module
, 'action', $log->action
);
809 $ldcache[$log->module
][$log->action
] = $ld;
811 if ($ld && !empty($log->info
)) {
812 // ugly hack to make sure fullname is shown correctly
813 if (($ld->mtable
== 'user') and ($ld->field
== sql_concat('firstname', "' '" , 'lastname'))) {
814 $log->info
= fullname(get_record($ld->mtable
, 'id', $log->info
), true);
816 $log->info
= get_field($ld->mtable
, $ld->field
, 'id', $log->info
);
821 $log->info
= format_string($log->info
);
822 $log->info
= strip_tags(urldecode($log->info
)); // Some XSS protection
825 if ($row > EXCELROWS
) {
827 $myxls =& $worksheet[$wsnumber];
828 $row = FIRSTUSEDEXCELROW
;
832 $myxls->write($row, 0, $courses[$log->course
], '');
833 // Excel counts from 1/1/1900
834 $excelTime=25569+
$log->time
/(3600*24);
835 $myxls->write($row, 1, $excelTime, $formatDate);
836 $myxls->write($row, 2, $log->ip
, '');
837 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE
, $course->id
)));
838 $myxls->write($row, 3, $fullname, '');
839 $myxls->write($row, 4, $log->module
.' '.$log->action
, '');
840 $myxls->write($row, 5, $log->info
, '');
849 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
850 $modid, $modaction, $groupid) {
854 require_once("$CFG->libdir/odslib.class.php");
856 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
857 $modname, $modid, $modaction, $groupid)) {
863 if ($course->id
== SITEID
) {
865 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
866 foreach ($ccc as $cc) {
867 $courses[$cc->id
] = $cc->shortname
;
871 $courses[$course->id
] = $course->shortname
;
876 $tt = getdate(time());
877 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
879 $strftimedatetime = get_string("strftimedatetime");
881 $nroPages = ceil(count($logs)/(EXCELROWS
-FIRSTUSEDEXCELROW+
1));
882 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
885 $workbook = new MoodleODSWorkbook('-');
886 $workbook->send($filename);
888 $worksheet = array();
889 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
890 get_string('fullname'), get_string('action'), get_string('info'));
892 // Creating worksheets
893 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++
) {
894 $sheettitle = get_string('excel_sheettitle', 'logs', $wsnumber).$nroPages;
895 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
896 $worksheet[$wsnumber]->set_column(1, 1, 30);
897 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
898 userdate(time(), $strftimedatetime));
900 foreach ($headers as $item) {
901 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW
-1,$col,$item,'');
906 if (empty($logs['logs'])) {
911 $formatDate =& $workbook->add_format();
912 $formatDate->set_num_format(get_string('log_excel_date_format'));
914 $row = FIRSTUSEDEXCELROW
;
916 $myxls =& $worksheet[$wsnumber];
917 foreach ($logs['logs'] as $log) {
918 if (isset($ldcache[$log->module
][$log->action
])) {
919 $ld = $ldcache[$log->module
][$log->action
];
921 $ld = get_record('log_display', 'module', $log->module
, 'action', $log->action
);
922 $ldcache[$log->module
][$log->action
] = $ld;
924 if ($ld && !empty($log->info
)) {
925 // ugly hack to make sure fullname is shown correctly
926 if (($ld->mtable
== 'user') and ($ld->field
== sql_concat('firstname', "' '" , 'lastname'))) {
927 $log->info
= fullname(get_record($ld->mtable
, 'id', $log->info
), true);
929 $log->info
= get_field($ld->mtable
, $ld->field
, 'id', $log->info
);
934 $log->info
= format_string($log->info
);
935 $log->info
= strip_tags(urldecode($log->info
)); // Some XSS protection
938 if ($row > EXCELROWS
) {
940 $myxls =& $worksheet[$wsnumber];
941 $row = FIRSTUSEDEXCELROW
;
945 $myxls->write_string($row, 0, $courses[$log->course
]);
946 $myxls->write_date($row, 1, $log->time
);
947 $myxls->write_string($row, 2, $log->ip
);
948 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE
, $course->id
)));
949 $myxls->write_string($row, 3, $fullname);
950 $myxls->write_string($row, 4, $log->module
.' '.$log->action
);
951 $myxls->write_string($row, 5, $log->info
);
961 function print_log_graph($course, $userid=0, $type="course.png", $date=0) {
963 if (empty($CFG->gdversion
)) {
964 echo "(".get_string("gdneed").")";
966 // MDL-10818, do not display broken graph when user has no permission to view graph
967 if (has_capability('moodle/site:viewreports', get_context_instance(CONTEXT_COURSE
, $course->id
)) ||
968 ($course->showreports
and $USER->id
== $userid)) {
969 echo '<img src="'.$CFG->wwwroot
.'/course/report/log/graph.php?id='.$course->id
.
970 '&user='.$userid.'&type='.$type.'&date='.$date.'" alt="" />';
976 function print_overview($courses) {
980 $htmlarray = array();
981 if ($modules = get_records('modules')) {
982 foreach ($modules as $mod) {
983 if (file_exists(dirname(dirname(__FILE__
)).'/mod/'.$mod->name
.'/lib.php')) {
984 require_once(dirname(dirname(__FILE__
)).'/mod/'.$mod->name
.'/lib.php');
985 $fname = $mod->name
.'_print_overview';
986 if (function_exists($fname)) {
987 $fname($courses,$htmlarray);
992 foreach ($courses as $course) {
993 print_simple_box_start('center', '100%', '', 5, "coursebox");
995 if (empty($course->visible
)) {
996 $linkcss = 'class="dimmed"';
998 print_heading('<a title="'. format_string($course->fullname
).'" '.$linkcss.' href="'.$CFG->wwwroot
.'/course/view.php?id='.$course->id
.'">'. format_string($course->fullname
).'</a>');
999 if (array_key_exists($course->id
,$htmlarray)) {
1000 foreach ($htmlarray[$course->id
] as $modname => $html) {
1004 print_simple_box_end();
1009 function print_recent_activity($course) {
1010 // $course is an object
1011 // This function trawls through the logs looking for
1012 // anything new since the user's last login
1014 global $CFG, $USER, $SESSION;
1016 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
1018 $timestart = time() - COURSE_MAX_RECENT_PERIOD
;
1020 if (!has_capability('moodle/legacy:guest', $context, NULL, false)) {
1021 if (!empty($USER->lastcourseaccess
[$course->id
])) {
1022 if ($USER->lastcourseaccess
[$course->id
] > $timestart) {
1023 $timestart = $USER->lastcourseaccess
[$course->id
];
1028 echo '<div class="activitydate">';
1029 echo get_string('activitysince', '', userdate($timestart));
1031 echo '<div class="activityhead">';
1033 echo '<a href="'.$CFG->wwwroot
.'/course/recent.php?id='.$course->id
.'">'.get_string('recentactivityreport').'</a>';
1038 // Firstly, have there been any new enrolments?
1043 $users = get_recent_enrolments($course->id
, $timestart);
1045 //Accessibility: new users now appear in an <OL> list.
1047 echo '<div class="newusers">';
1049 print_headline(get_string("newusers").':', 3);
1053 echo "<ol class=\"list\">\n";
1054 foreach ($users as $user) {
1056 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE
, $course->id
)));
1057 echo '<li class="name"><a href="'.$CFG->wwwroot
."/user/view.php?id=$user->id&course=$course->id\">$fullname</a></li>\n";
1059 echo "</ol>\n</div>\n";
1062 // Next, have there been any modifications to the course structure?
1064 $logs = get_records_select('log', "time > '$timestart' AND course = '$course->id' AND
1065 module = 'course' AND action LIKE '% mod'", "time ASC");
1068 foreach ($logs as $key => $log) {
1069 $info = split(' ', $log->info
);
1071 if ($info[0] == 'label') { // Labels are special activities
1075 $modname = get_field($info[0], 'name', 'id', $info[1]);
1076 //Create a temp valid module structure (course,id)
1077 $tempmod->course
= $log->course
;
1078 $tempmod->id
= $info[1];
1079 //Obtain the visible property from the instance
1080 $modvisible = instance_is_visible($info[0],$tempmod);
1082 //Only if the mod is visible
1084 switch ($log->action
) {
1086 $stradded = get_string('added', 'moodle', get_string('modulename', $info[0]));
1087 $changelist[$log->info
] = array ('operation' => 'add', 'text' => "$stradded:<br /><a href=\"$CFG->wwwroot/course/$log->url\">".format_string($modname,true)."</a>");
1090 $strupdated = get_string('updated', 'moodle', get_string('modulename', $info[0]));
1091 if (empty($changelist[$log->info
])) {
1092 $changelist[$log->info
] = array ('operation' => 'update', 'text' => "$strupdated:<br /><a href=\"$CFG->wwwroot/course/$log->url\">".format_string($modname,true)."</a>");
1096 if (!empty($changelist[$log->info
]['operation']) and
1097 $changelist[$log->info
]['operation'] == 'add') {
1098 $changelist[$log->info
] = NULL;
1100 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $info[0]));
1101 $changelist[$log->info
] = array ('operation' => 'delete', 'text' => $strdeleted);
1109 if (!empty($changelist)) {
1110 foreach ($changelist as $changeinfo => $change) {
1112 $changes[$changeinfo] = $change;
1115 if (isset($changes)){
1116 if (count($changes) > 0) {
1117 print_headline(get_string('courseupdates').':', 3);
1119 foreach ($changes as $changeinfo => $change) {
1120 echo '<p class="activity">'.$change['text'].'</p>';
1126 // Now display new things from each module
1128 $mods = get_records('modules', 'visible', '1', 'name', 'id, name');
1130 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
1132 foreach ($mods as $mod) { // Each module gets it's own logs and prints them
1133 include_once($CFG->dirroot
.'/mod/'.$mod->name
.'/lib.php');
1134 $print_recent_activity = $mod->name
.'_print_recent_activity';
1135 if (function_exists($print_recent_activity)) {
1138 // $isteacher (second parameter below) is to be deprecated!
1141 // 1) Make sure that all _print_recent_activity functions are
1142 // not using the $isteacher value.
1143 // 2) Eventually, remove the $isteacher parameter from the
1146 $modcontent = $print_recent_activity($course, $viewfullnames, $timestart);
1154 echo '<p class="message">'.get_string('nothingnew').'</p>';
1159 function get_array_of_activities($courseid) {
1160 // For a given course, returns an array of course activity objects
1161 // Each item in the array contains he following properties:
1162 // cm - course module id
1163 // mod - name of the module (eg forum)
1164 // section - the number of the section (eg week or topic)
1165 // name - the name of the instance
1166 // visible - is the instance visible or not
1167 // groupingid - grouping id
1168 // groupmembersonly - is this instance visible to group members only
1169 // extra - contains extra string to include in any link
1175 if (!$rawmods = get_course_mods($courseid)) {
1179 if ($sections = get_records("course_sections", "course", $courseid, "section ASC")) {
1180 foreach ($sections as $section) {
1181 if (!empty($section->sequence
)) {
1182 $sequence = explode(",", $section->sequence
);
1183 foreach ($sequence as $seq) {
1184 if (empty($rawmods[$seq])) {
1187 $mod[$seq]->cm
= $rawmods[$seq]->id
;
1188 $mod[$seq]->mod
= $rawmods[$seq]->modname
;
1189 $mod[$seq]->section
= $section->section
;
1190 $mod[$seq]->name
= urlencode(get_field($rawmods[$seq]->modname
, "name", "id", $rawmods[$seq]->instance
));
1191 $mod[$seq]->visible
= $rawmods[$seq]->visible
;
1192 $mod[$seq]->groupingid
= $rawmods[$seq]->groupingid
;
1193 $mod[$seq]->groupmembersonly
= $rawmods[$seq]->groupmembersonly
;
1194 $mod[$seq]->extra
= "";
1196 $modname = $mod[$seq]->mod
;
1197 $functionname = $modname."_get_coursemodule_info";
1199 include_once("$CFG->dirroot/mod/$modname/lib.php");
1201 if (function_exists($functionname)) {
1202 if ($info = $functionname($rawmods[$seq])) {
1203 if (!empty($info->extra
)) {
1204 $mod[$seq]->extra
= $info->extra
;
1206 if (!empty($info->icon
)) {
1207 $mod[$seq]->icon
= $info->icon
;
1221 function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
1222 // Returns a number of useful structures for course displays
1224 $mods = NULL; // course modules indexed by id
1225 $modnames = NULL; // all course module names (except resource!)
1226 $modnamesplural= NULL; // all course module names (plural form)
1227 $modnamesused = NULL; // course module names used
1229 if ($allmods = get_records("modules")) {
1230 foreach ($allmods as $mod) {
1231 if ($mod->visible
) {
1232 $modnames[$mod->name
] = get_string("modulename", "$mod->name");
1233 $modnamesplural[$mod->name
] = get_string("modulenameplural", "$mod->name");
1238 error("No modules are installed!");
1241 if ($rawmods = get_course_mods($courseid)) {
1242 foreach($rawmods as $mod) { // Index the mods
1243 if (empty($modnames[$mod->modname
])) {
1247 if (!groups_course_module_visible($mod)) {
1250 $mods[$mod->id
] = $mod;
1251 $mods[$mod->id
]->modfullname
= $modnames[$mod->modname
];
1252 if ($mod->visible
or has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_COURSE
, $courseid))) {
1253 $modnamesused[$mod->modname
] = $modnames[$mod->modname
];
1256 if ($modnamesused) {
1257 asort($modnamesused);
1263 function get_all_sections($courseid) {
1265 return get_records("course_sections", "course", "$courseid", "section",
1266 "section, id, course, summary, sequence, visible");
1269 function course_set_display($courseid, $display=0) {
1272 if ($display == "all" or empty($display)) {
1276 if (empty($USER->id
) or $USER->username
== 'guest') {
1277 //do not store settings in db for guests
1278 } else if (record_exists("course_display", "userid", $USER->id
, "course", $courseid)) {
1279 set_field("course_display", "display", $display, "userid", $USER->id
, "course", $courseid);
1281 $record->userid
= $USER->id
;
1282 $record->course
= $courseid;
1283 $record->display
= $display;
1284 if (!insert_record("course_display", $record)) {
1285 notify("Could not save your course display!");
1289 return $USER->display
[$courseid] = $display; // Note: = not ==
1292 function set_section_visible($courseid, $sectionnumber, $visibility) {
1293 /// For a given course section, markes it visible or hidden,
1294 /// and does the same for every activity in that section
1296 if ($section = get_record("course_sections", "course", $courseid, "section", $sectionnumber)) {
1297 set_field("course_sections", "visible", "$visibility", "id", $section->id
);
1298 if (!empty($section->sequence
)) {
1299 $modules = explode(",", $section->sequence
);
1300 foreach ($modules as $moduleid) {
1301 set_coursemodule_visible($moduleid, $visibility, true);
1304 rebuild_course_cache($courseid);
1309 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%") {
1310 /// Prints a section full of activity modules
1313 static $groupbuttons;
1314 static $groupbuttonslink;
1318 static $strmovehere;
1319 static $strmovefull;
1320 static $strunreadpostsone;
1323 static $usetracking;
1325 $labelformatoptions = New stdClass
;
1327 if (!isset($isteacher)) {
1328 $groupbuttons = ($course->groupmode
or (!$course->groupmodeforce
));
1329 $groupbuttonslink = (!$course->groupmodeforce
);
1330 $isediting = isediting($course->id
);
1331 $ismoving = $isediting && ismoving($course->id
);
1333 $strmovehere = get_string("movehere");
1334 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1336 include_once($CFG->dirroot
.'/mod/forum/lib.php');
1337 if ($usetracking = forum_tp_can_track_forums()) {
1338 $strunreadpostsone = get_string('unreadpostsone', 'forum');
1339 $untracked = forum_tp_get_untracked_forums($USER->id
, $course->id
);
1342 $labelformatoptions->noclean
= true;
1344 /// Casting $course->modinfo to string prevents one notice when the field is null
1345 $modinfo = unserialize((string)$course->modinfo
);
1347 //Acccessibility: replace table with list <ul>, but don't output empty list.
1348 if (!empty($section->sequence
)) {
1350 // Fix bug #5027, don't want style=\"width:$width\".
1351 echo "<ul class=\"section\">\n";
1352 $sectionmods = explode(",", $section->sequence
);
1354 foreach ($sectionmods as $modnumber) {
1355 if (empty($mods[$modnumber])) {
1358 $mod = $mods[$modnumber];
1360 if (($mod->visible
or has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_COURSE
, $course->id
))) &&
1361 (!$ismoving ||
$mod->id
!= $USER->activitycopy
) &&
1362 groups_course_module_visible($mod)) {
1363 echo '<li class="activity '.$mod->modname
.'" id="module-'.$modnumber.'">'; // Unique ID
1365 echo '<a title="'.$strmovefull.'"'.
1366 ' href="'.$CFG->wwwroot
.'/course/mod.php?moveto='.$mod->id
.'&sesskey='.$USER->sesskey
.'">'.
1367 '<img class="movetarget" src="'.$CFG->pixpath
.'/movehere.gif" '.
1368 ' alt="'.$strmovehere.'" /></a><br />
1371 $instancename = urldecode($modinfo[$modnumber]->name
);
1372 $instancename = format_string($instancename, true, $course->id
);
1374 if (!empty($modinfo[$modnumber]->extra
)) {
1375 $extra = urldecode($modinfo[$modnumber]->extra
);
1380 if (!empty($modinfo[$modnumber]->icon
)) {
1381 $icon = "$CFG->pixpath/".urldecode($modinfo[$modnumber]->icon
);
1383 $icon = "$CFG->modpixpath/$mod->modname/icon.gif";
1387 print_spacer(12, 20 * $mod->indent
, false);
1390 if ($mod->modname
== "label") {
1391 if (!$mod->visible
) {
1392 echo "<span class=\"dimmed_text\">";
1394 echo format_text($extra, FORMAT_HTML
, $labelformatoptions);
1395 if (!$mod->visible
) {
1399 } else { // Normal activity
1401 if (!empty($USER->screenreader
)) {
1402 $typestring = '('.get_string('modulename',$mod->modname
).') ';
1407 $linkcss = $mod->visible ?
"" : " class=\"dimmed\" ";
1408 echo '<img src="'.$icon.'"'.
1409 ' class="activityicon" alt="'.$mod->modfullname
.'" />'.
1410 ' <a title="'.$mod->modfullname
.'" '.$linkcss.' '.$extra.
1411 ' href="'.$CFG->wwwroot
.'/mod/'.$mod->modname
.'/view.php?id='.$mod->id
.'">'.
1412 $typestring.$instancename.'</a>';
1414 if ($usetracking && $mod->modname
== 'forum') {
1415 $groupmode = groups_get_course_groupmode($course, $mod);
1416 $groupid = ($groupmode == SEPARATEGROUPS
&& !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE
, $course->id
))) ?
1417 groups_get_course_group($course, true) : false;
1419 if (forum_tp_can_track_forums() && !isset($untracked[$mod->instance
])) {
1420 $unread = forum_tp_count_forum_unread_posts($USER->id
, $mod->instance
, $groupid);
1422 echo '<span class="unread"> <a href="'.$CFG->wwwroot
.'/mod/forum/view.php?id='.$mod->id
.'">';
1424 echo $strunreadpostsone;
1426 print_string('unreadpostsnumber', 'forum', $unread);
1428 echo '</a> </span>';
1434 // TODO: we must define this as mod property!
1435 if ($groupbuttons and $mod->modname
!= 'label' and $mod->modname
!= 'resource' and $mod->modname
!= 'glossary') {
1436 if (! $mod->groupmodelink
= $groupbuttonslink) {
1437 $mod->groupmode
= $course->groupmode
;
1441 $mod->groupmode
= false;
1443 echo ' ';
1444 echo make_editing_buttons($mod, $absolute, true, $mod->indent
, $section->section
);
1449 } elseif ($ismoving) {
1450 echo "<ul class=\"section\">\n";
1453 echo '<li><a title="'.$strmovefull.'"'.
1454 ' href="'.$CFG->wwwroot
.'/course/mod.php?movetosection='.$section->id
.'&sesskey='.$USER->sesskey
.'">'.
1455 '<img class="movetarget" src="'.$CFG->pixpath
.'/movehere.gif" '.
1456 ' alt="'.$strmovehere.'" /></a></li>
1459 if (!empty($section->sequence
) ||
$ismoving) {
1460 echo "</ul><!--class='section'-->\n\n";
1465 * Prints the menus to add activities and resources.
1467 function print_section_add_menus($course, $section, $modnames, $vertical=false, $return=false) {
1470 // check to see if user can add menus
1471 if (!has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE
, $course->id
))) {
1475 static $resources = false;
1476 static $activities = false;
1478 if ($resources === false) {
1479 $resources = array();
1480 $activities = array();
1482 foreach($modnames as $modname=>$modnamestr) {
1483 if (!course_allowed_module($course, $modname)) {
1487 require_once("$CFG->dirroot/mod/$modname/lib.php");
1488 $gettypesfunc = $modname.'_get_types';
1489 if (function_exists($gettypesfunc)) {
1490 $types = $gettypesfunc();
1491 foreach($types as $type) {
1492 if ($type->modclass
== MOD_CLASS_RESOURCE
) {
1493 $resources[$type->type
] = $type->typestr
;
1495 $activities[$type->type
] = $type->typestr
;
1499 // all mods without type are considered activity
1500 $activities[$modname] = $modnamestr;
1505 $straddactivity = get_string('addactivity');
1506 $straddresource = get_string('addresource');
1508 $output = '<div class="section_add_menus">';
1511 $output .= '<div class="horizontal">';
1514 if (!empty($resources)) {
1515 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&section=$section&sesskey=".sesskey()."&add=",
1516 $resources, "ressection$section", "", $straddresource, 'resource/types', $straddresource, true);
1519 if (!empty($activities)) {
1521 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&section=$section&sesskey=".sesskey()."&add=",
1522 $activities, "section$section", "", $straddactivity, 'mods', $straddactivity, true);
1526 $output .= '</div>';
1529 $output .= '</div>';
1538 function rebuild_course_cache($courseid=0) {
1539 // Rebuilds the cached list of course activities stored in the database
1540 // If a courseid is not specified, then all are rebuilt
1543 $select = "id = '$courseid'";
1546 @set_time_limit
(0); // this could take a while! MDL-10954
1549 if ($courses = get_records_select("course", $select,'','id,fullname')) {
1550 foreach ($courses as $course) {
1551 $modinfo = serialize(get_array_of_activities($course->id
));
1552 if (!set_field("course", "modinfo", $modinfo, "id", $course->id
)) {
1553 notify("Could not cache module information for course '" . format_string($course->fullname
) . "'!");
1561 function make_categories_list(&$list, &$parents, $category=NULL, $path="") {
1562 /// Given an empty array, this function recursively travels the
1563 /// categories, building up a nice list for display. It also makes
1564 /// an array that list all the parents for each category.
1566 // initialize the arrays if needed
1567 if (!is_array($list)) {
1570 if (!is_array($parents)) {
1576 $path = $path.' / '.format_string($category->name
);
1578 $path = format_string($category->name
);
1580 $list[$category->id
] = $path;
1585 if ($categories = get_categories($category->id
)) { // Print all the children recursively
1586 foreach ($categories as $cat) {
1587 if (!empty($category->id
)) {
1588 if (isset($parents[$category->id
])) {
1589 $parents[$cat->id
] = $parents[$category->id
];
1591 $parents[$cat->id
][] = $category->id
;
1593 make_categories_list($list, $parents, $cat, $path);
1599 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $files = true) {
1600 /// Recursive function to print out all the categories in a nice format
1601 /// with or without courses included
1604 if (isset($CFG->max_category_depth
) && ($depth >= $CFG->max_category_depth
)) {
1608 if (!$displaylist) {
1609 make_categories_list($displaylist, $parentslist);
1613 if ($category->visible
or has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM
, SITEID
))) {
1614 print_category_info($category, $depth, $files);
1616 return; // Don't bother printing children of invisible categories
1620 $category->id
= "0";
1623 if ($categories = get_categories($category->id
)) { // Print all the children recursively
1624 $countcats = count($categories);
1628 foreach ($categories as $cat) {
1630 if ($count == $countcats) {
1633 $up = $first ?
false : true;
1634 $down = $last ?
false : true;
1637 print_whole_category_list($cat, $displaylist, $parentslist, $depth +
1, $files);
1642 // this function will return $options array for choose_from_menu, with whitespace to denote nesting.
1644 function make_categories_options() {
1645 make_categories_list($cats,$parents);
1646 foreach ($cats as $key => $value) {
1647 if (array_key_exists($key,$parents)) {
1648 if ($indent = count($parents[$key])) {
1649 for ($i = 0; $i < $indent; $i++
) {
1650 $cats[$key] = ' '.$cats[$key];
1658 function print_category_info($category, $depth, $files = false) {
1659 /// Prints the category info in indented fashion
1660 /// This function is only used by print_whole_category_list() above
1663 static $strallowguests, $strrequireskey, $strsummary;
1665 if (empty($strsummary)) {
1666 $strallowguests = get_string('allowguests');
1667 $strrequireskey = get_string('requireskey');
1668 $strsummary = get_string('summary');
1671 $catlinkcss = $category->visible ?
'' : ' class="dimmed" ';
1673 $coursecount = count_records('course') <= FRONTPAGECOURSELIMIT
;
1674 if ($files and $coursecount) {
1675 $catimage = '<img src="'.$CFG->pixpath
.'/i/course.gif" alt="" />';
1677 $catimage = " ";
1680 echo "\n\n".'<table class="categorylist">';
1682 if ($files and $coursecount) {
1683 $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');
1688 $indent = $depth*30;
1689 $rows = count($courses) +
1;
1690 echo '<td rowspan="'.$rows.'" valign="top" width="'.$indent.'">';
1691 print_spacer(10, $indent);
1695 echo '<td valign="top" class="category image">'.$catimage.'</td>';
1696 echo '<td valign="top" class="category name">';
1697 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot
.'/course/category.php?id='.$category->id
.'">'. format_string($category->name
).'</a>';
1699 echo '<td class="category info"> </td>';
1702 if ($courses && !(isset($CFG->max_category_depth
)&&($depth>=$CFG->max_category_depth
-1))) {
1703 foreach ($courses as $course) {
1704 $linkcss = $course->visible ?
'' : ' class="dimmed" ';
1705 echo '<tr><td valign="top"> ';
1706 echo '</td><td valign="top" class="course name">';
1707 echo '<a '.$linkcss.' href="'.$CFG->wwwroot
.'/course/view.php?id='.$course->id
.'">'. format_string($course->fullname
).'</a>';
1708 echo '</td><td align="right" valign="top" class="course info">';
1709 if ($course->guest
) {
1710 echo '<a title="'.$strallowguests.'" href="'.$CFG->wwwroot
.'/course/view.php?id='.$course->id
.'">';
1711 echo '<img alt="'.$strallowguests.'" src="'.$CFG->pixpath
.'/i/guest.gif" /></a>';
1713 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath
.'/spacer.gif" />';
1715 if ($course->password
) {
1716 echo '<a title="'.$strrequireskey.'" href="'.$CFG->wwwroot
.'/course/view.php?id='.$course->id
.'">';
1717 echo '<img alt="'.$strrequireskey.'" src="'.$CFG->pixpath
.'/i/key.gif" /></a>';
1719 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath
.'/spacer.gif" />';
1721 if ($course->summary
) {
1722 link_to_popup_window ('/course/info.php?id='.$course->id
, 'courseinfo',
1723 '<img alt="'.$strsummary.'" src="'.$CFG->pixpath
.'/i/info.gif" />',
1724 400, 500, $strsummary);
1726 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath
.'/spacer.gif" />';
1736 $indent = $depth*20;
1737 echo '<td valign="top" width="'.$indent.'">';
1738 print_spacer(10, $indent);
1742 echo '<td valign="top" class="category name">';
1743 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot
.'/course/category.php?id='.$category->id
.'">'. format_string($category->name
).'</a>';
1745 echo '<td valign="top" class="category number">';
1746 if ($category->coursecount
) {
1747 echo $category->coursecount
;
1755 function print_courses($category) {
1756 /// Category is 0 (for all courses) or an object
1760 if (!is_object($category) && $category==0) {
1761 $categories = get_categories(0); // Parent = 0 ie top-level categories only
1762 if (is_array($categories) && count($categories) == 1) {
1763 $category = array_shift($categories);
1764 $courses = get_courses_wmanagers($category->id
,
1766 array('password','summary','currency'));
1768 $courses = get_courses_wmanagers('all',
1770 array('password','summary','currency'));
1774 $courses = get_courses_wmanagers($category->id
,
1776 array('password','summary','currency'));
1780 foreach ($courses as $course) {
1781 if ($course->visible
== 1
1782 ||
has_capability('moodle/course:viewhidden',$course->context
)) {
1783 print_course($course);
1787 print_heading(get_string("nocoursesyet"));
1788 $context = get_context_instance(CONTEXT_SYSTEM
, SITEID
);
1789 if (has_capability('moodle/course:create', $context)) {
1791 $options['category'] = $category->id
;
1792 echo '<div class="addcoursebutton">';
1793 print_single_button($CFG->wwwroot
.'/course/edit.php', $options, get_string("addnewcourse"));
1803 function print_course($course) {
1807 if (isset($course->context
)) {
1808 $context = $course->context
;
1810 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
1813 $linkcss = $course->visible ?
'' : ' class="dimmed" ';
1815 echo '<div class="coursebox">';
1816 echo '<div class="info">';
1817 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
1818 $linkcss.' href="'.$CFG->wwwroot
.'/course/view.php?id='.$course->id
.'">'.
1819 format_string($course->fullname
).'</a></div>';
1821 /// first find all roles that are supposed to be displayed
1823 if (!empty($CFG->coursemanager
)) {
1824 $managerroles = split(',', $CFG->coursemanager
);
1825 $canseehidden = has_capability('moodle/role:viewhiddenassigns', $context);
1826 $namesarray = array();
1827 if (isset($course->managers
)) {
1828 if (count($course->managers
)) {
1829 $rusers = $course->managers
;
1830 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
1831 foreach ($rusers as $ra) {
1832 if ($ra->hidden
== 0 ||
$canseehidden) {
1833 $fullname = fullname($ra->user
, $canviewfullnames);
1834 $namesarray[] = format_string($ra->rolename
)
1835 . ': <a href="'.$CFG->wwwroot
.'/user/view.php?id='.$ra->user
->id
.'&course='.SITEID
.'">'
1836 . $fullname . '</a>';
1841 $rusers = get_role_users($managerroles, $context,
1842 true, '', 'r.sortorder ASC, u.lastname ASC', $canseehidden);
1843 if (is_array($rusers) && count($rusers)) {
1844 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
1845 foreach ($rusers as $teacher) {
1846 $fullname = fullname($teacher, $canviewfullnames);
1847 $namesarray[] = format_string($teacher->rolename
)
1848 . ': <a href="'.$CFG->wwwroot
.'/user/view.php?id='.$teacher->id
.'&course='.SITEID
.'">'
1849 . $fullname . '</a>';
1854 if (!empty($namesarray)) {
1855 echo "<ul class=\"teachers\">\n<li>";
1856 echo implode('</li><li>', $namesarray);
1861 require_once("$CFG->dirroot/enrol/enrol.class.php");
1862 $enrol = enrolment_factory
::factory($course->enrol
);
1863 echo $enrol->get_access_icons($course);
1865 echo '</div><div class="summary">';
1867 $options->noclean
= true;
1868 $options->para
= false;
1869 echo format_text($course->summary
, FORMAT_MOODLE
, $options, $course->id
);
1872 echo '<div class="clearer"></div>';
1876 function print_my_moodle() {
1877 /// Prints custom user information on the home page.
1878 /// Over time this can include all sorts of information
1882 if (empty($USER->id
)) {
1883 error("It shouldn't be possible to see My Moodle without being logged in.");
1886 $courses = get_my_courses($USER->id
, 'visible DESC,sortorder ASC', array('summary'));
1888 $rcourses = array();
1889 if (!empty($CFG->mnet_dispatcher_mode
) && $CFG->mnet_dispatcher_mode
==='strict') {
1890 $rcourses = get_my_remotecourses($USER->id
);
1891 $rhosts = get_my_remotehosts();
1894 if (!empty($courses) ||
!empty($rcourses) ||
!empty($rhosts)) {
1896 if (!empty($courses)) {
1897 foreach ($courses as $course) {
1898 if ($course->id
== SITEID
) {
1901 print_course($course, "100%");
1906 if (!empty($rcourses)) {
1907 // at the IDP, we know of all the remote courses
1908 foreach ($rcourses as $course) {
1909 print_remote_course($course, "100%");
1911 } elseif (!empty($rhosts)) {
1912 // non-IDP, we know of all the remote servers, but not courses
1913 foreach ($rhosts as $host) {
1914 print_remote_host($host, "100%");
1920 if (count_records("course") > (count($courses) +
1) ) { // Some courses not being displayed
1921 echo "<table width=\"100%\"><tr><td align=\"center\">";
1922 print_course_search("", false, "short");
1923 echo "</td><td align=\"center\">";
1924 print_single_button("$CFG->wwwroot/course/index.php", NULL, get_string("fulllistofcourses"), "get");
1925 echo "</td></tr></table>\n";
1929 if (count_records("course_categories") > 1) {
1930 print_simple_box_start("center", "100%", "#FFFFFF", 5, "categorybox");
1931 print_whole_category_list();
1932 print_simple_box_end();
1940 function print_course_search($value="", $return=false, $format="plain") {
1947 $id = 'coursesearch';
1953 $strsearchcourses= get_string("searchcourses");
1955 if ($format == 'plain') {
1956 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot
.'/course/search.php" method="get">';
1957 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
1958 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
1959 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
1960 $output .= '<input type="submit" value="'.get_string('go').'" />';
1961 $output .= '</fieldset></form>';
1962 } else if ($format == 'short') {
1963 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot
.'/course/search.php" method="get">';
1964 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
1965 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
1966 $output .= '<input type="text" id="coursesearchbox" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
1967 $output .= '<input type="submit" value="'.get_string('go').'" />';
1968 $output .= '</fieldset></form>';
1969 } else if ($format == 'navbar') {
1970 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot
.'/course/search.php" method="get">';
1971 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
1972 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
1973 $output .= '<input type="text" id="coursesearchbox" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
1974 $output .= '<input type="submit" value="'.get_string('go').'" />';
1975 $output .= '</fieldset></form>';
1984 function print_remote_course($course, $width="100%") {
1990 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&wantsurl=/course/view.php?id={$course->remoteid}";
1992 echo '<div class="coursebox remotecoursebox">';
1993 echo '<div class="info">';
1994 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
1995 $linkcss.' href="'.$url.'">'
1996 . format_string($course->fullname
) .'</a><br />'
1997 . format_string($course->hostname
) . ' : '
1998 . format_string($course->cat_name
) . ' : '
1999 . format_string($course->shortname
). '</div>';
2000 echo '</div><div class="summary">';
2002 $options->noclean
= true;
2003 $options->para
= false;
2004 echo format_text($course->summary
, FORMAT_MOODLE
, $options);
2007 echo '<div class="clearer"></div>';
2010 function print_remote_host($host, $width="100%") {
2016 echo '<div class="coursebox">';
2017 echo '<div class="info">';
2018 echo '<div class="name">';
2019 echo '<img src="'.$CFG->pixpath
.'/i/mnethost.gif" class="icon" alt="'.get_string('course').'" />';
2020 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2021 . s($host['name']).'</a> - ';
2022 echo $host['count'] . ' ' . get_string('courses');
2026 echo '<div class="clearer"></div>';
2030 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2032 function add_course_module($mod) {
2034 $mod->added
= time();
2037 return insert_record("course_modules", $mod);
2041 * Returns course section - creates new if does not exist yet.
2042 * @param int $relative section number
2043 * @param int $courseid
2044 * @return object $course_section object
2046 function get_course_section($section, $courseid) {
2047 if ($cw = get_record("course_sections", "section", $section, "course", $courseid)) {
2051 $cw->course
= $courseid;
2052 $cw->section
= $section;
2055 $id = insert_record("course_sections", $cw);
2056 return get_record("course_sections", "id", $id);
2059 function add_mod_to_section($mod, $beforemod=NULL) {
2060 /// Given a full mod object with section and course already defined
2061 /// If $before is specified, then this is an existing ID which we
2062 /// will insert the new module before
2064 /// Returns the course_sections ID where the mod is inserted
2066 if ($section = get_record("course_sections", "course", "$mod->course", "section", "$mod->section")) {
2068 $section->sequence
= trim($section->sequence
);
2070 if (empty($section->sequence
)) {
2071 $newsequence = "$mod->coursemodule";
2073 } else if ($beforemod) {
2074 $modarray = explode(",", $section->sequence
);
2076 if ($key = array_keys ($modarray, $beforemod->id
)) {
2077 $insertarray = array($mod->id
, $beforemod->id
);
2078 array_splice($modarray, $key[0], 1, $insertarray);
2079 $newsequence = implode(",", $modarray);
2081 } else { // Just tack it on the end anyway
2082 $newsequence = "$section->sequence,$mod->coursemodule";
2086 $newsequence = "$section->sequence,$mod->coursemodule";
2089 if (set_field("course_sections", "sequence", $newsequence, "id", $section->id
)) {
2090 return $section->id
; // Return course_sections ID that was used.
2095 } else { // Insert a new record
2096 $section->course
= $mod->course
;
2097 $section->section
= $mod->section
;
2098 $section->summary
= "";
2099 $section->sequence
= $mod->coursemodule
;
2100 return insert_record("course_sections", $section);
2104 function set_coursemodule_groupmode($id, $groupmode) {
2105 return set_field("course_modules", "groupmode", $groupmode, "id", $id);
2108 function set_coursemodule_groupingid($id, $groupingid) {
2109 return set_field("course_modules", "groupingid", $groupingid, "id", $id);
2112 function set_coursemodule_groupmembersonly($id, $groupmembersonly) {
2113 return set_field("course_modules", "groupmembersonly", $groupmembersonly, "id", $id);
2116 function set_coursemodule_idnumber($id, $idnumber) {
2117 return set_field("course_modules", "idnumber", $idnumber, "id", $id);
2120 * $prevstateoverrides = true will set the visibility of the course module
2121 * to what is defined in visibleold. This enables us to remember the current
2122 * visibility when making a whole section hidden, so that when we toggle
2123 * that section back to visible, we are able to return the visibility of
2124 * the course module back to what it was originally.
2126 function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
2127 if (!$cm = get_record('course_modules', 'id', $id)) {
2130 if (!$modulename = get_field('modules', 'name', 'id', $cm->module
)) {
2133 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
2134 foreach($events as $event) {
2142 if ($prevstateoverrides) {
2143 if ($visible == '0') {
2144 // Remember the current visible state so we can toggle this back.
2145 set_field('course_modules', 'visibleold', $cm->visible
, 'id', $id);
2147 // Get the previous saved visible states.
2148 return set_field('course_modules', 'visible', $cm->visibleold
, 'id', $id);
2151 return set_field("course_modules", "visible", $visible, "id", $id);
2155 * Delete a course module and any associated data at the course level (events)
2156 * Until 1.5 this function simply marked a deleted flag ... now it
2157 * deletes it completely.
2160 function delete_course_module($id) {
2162 require_once($CFG->libdir
.'/gradelib.php');
2164 if (!$cm = get_record('course_modules', 'id', $id)) {
2167 $modulename = get_field('modules', 'name', 'id', $cm->module
);
2168 //delete events from calendar
2169 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
2170 foreach($events as $event) {
2171 delete_event($event->id
);
2174 //delete grade items, outcome items and grades attached to modules
2175 if ($grade_items = grade_item
::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2176 'iteminstance'=>$cm->instance
, 'courseid'=>$cm->course
))) {
2177 foreach ($grade_items as $grade_item) {
2178 $grade_item->delete('moddelete');
2182 return delete_records('course_modules', 'id', $cm->id
);
2185 function delete_mod_from_section($mod, $section) {
2187 if ($section = get_record("course_sections", "id", "$section") ) {
2189 $modarray = explode(",", $section->sequence
);
2191 if ($key = array_keys ($modarray, $mod)) {
2192 array_splice($modarray, $key[0], 1);
2193 $newsequence = implode(",", $modarray);
2194 return set_field("course_sections", "sequence", $newsequence, "id", $section->id
);
2203 function move_section($course, $section, $move) {
2204 /// Moves a whole course section up and down within the course
2211 $sectiondest = $section +
$move;
2213 if ($sectiondest > $course->numsections
or $sectiondest < 1) {
2217 if (!$sectionrecord = get_record("course_sections", "course", $course->id
, "section", $section)) {
2221 if (!$sectiondestrecord = get_record("course_sections", "course", $course->id
, "section", $sectiondest)) {
2225 if (!set_field("course_sections", "section", $sectiondest, "id", $sectionrecord->id
)) {
2228 if (!set_field("course_sections", "section", $section, "id", $sectiondestrecord->id
)) {
2231 // if the focus is on the section that is being moved, then move the focus along
2232 if (isset($USER->display
[$course->id
]) and ($USER->display
[$course->id
] == $section)) {
2233 course_set_display($course->id
, $sectiondest);
2236 // Check for duplicates and fix order if needed.
2237 // There is a very rare case that some sections in the same course have the same section id.
2238 $sections = get_records_select('course_sections', "course = $course->id", 'section ASC');
2240 foreach ($sections as $section) {
2241 if ($section->section
!= $n) {
2242 if (!set_field('course_sections', 'section', $n, 'id', $section->id
)) {
2252 function moveto_module($mod, $section, $beforemod=NULL) {
2253 /// All parameters are objects
2254 /// Move the module object $mod to the specified $section
2255 /// If $beforemod exists then that is the module
2256 /// before which $modid should be inserted
2258 /// Remove original module from original section
2260 if (! delete_mod_from_section($mod->id
, $mod->section
)) {
2261 notify("Could not delete module from existing section");
2264 /// Update module itself if necessary
2266 if ($mod->section
!= $section->id
) {
2267 $mod->section
= $section->id
;
2268 if (!update_record("course_modules", $mod)) {
2271 // if moving to a hidden section then hide module
2272 if (!$section->visible
) {
2273 set_coursemodule_visible($mod->id
, 0);
2277 /// Add the module into the new section
2279 $mod->course
= $section->course
;
2280 $mod->section
= $section->section
; // need relative reference
2281 $mod->coursemodule
= $mod->id
;
2283 if (! add_mod_to_section($mod, $beforemod)) {
2291 function make_editing_buttons($mod, $absolute=false, $moveselect=true, $indent=-1, $section=-1) {
2297 $modcontext = get_context_instance(CONTEXT_MODULE
, $mod->id
);
2298 // no permission to edit
2299 if (!has_capability('moodle/course:manageactivities', $modcontext)) {
2304 $str->delete
= get_string("delete");
2305 $str->move
= get_string("move");
2306 $str->moveup
= get_string("moveup");
2307 $str->movedown
= get_string("movedown");
2308 $str->moveright
= get_string("moveright");
2309 $str->moveleft
= get_string("moveleft");
2310 $str->update
= get_string("update");
2311 $str->duplicate
= get_string("duplicate");
2312 $str->hide
= get_string("hide");
2313 $str->show
= get_string("show");
2314 $str->clicktochange
= get_string("clicktochange");
2315 $str->forcedmode
= get_string("forcedmode");
2316 $str->groupsnone
= get_string("groupsnone");
2317 $str->groupsseparate
= get_string("groupsseparate");
2318 $str->groupsvisible
= get_string("groupsvisible");
2319 $sesskey = sesskey();
2322 if ($section >= 0) {
2323 $section = '&sr='.$section; // Section return
2329 $path = $CFG->wwwroot
.'/course';
2334 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
2335 if ($mod->visible
) {
2336 $hideshow = '<a class="editing_hide" title="'.$str->hide
.'" href="'.$path.'/mod.php?hide='.$mod->id
.
2337 '&sesskey='.$sesskey.$section.'"><img'.
2338 ' src="'.$CFG->pixpath
.'/t/hide.gif" class="iconsmall" '.
2339 ' alt="'.$str->hide
.'" /></a>'."\n";
2341 $hideshow = '<a class="editing_show" title="'.$str->show
.'" href="'.$path.'/mod.php?show='.$mod->id
.
2342 '&sesskey='.$sesskey.$section.'"><img'.
2343 ' src="'.$CFG->pixpath
.'/t/show.gif" class="iconsmall" '.
2344 ' alt="'.$str->show
.'" /></a>'."\n";
2347 if ($mod->groupmode
!== false) {
2348 if ($mod->groupmode
== SEPARATEGROUPS
) {
2349 $grouptitle = $str->groupsseparate
;
2350 $groupclass = 'editing_groupsseparate';
2351 $groupimage = $CFG->pixpath
.'/t/groups.gif';
2352 $grouplink = $path.'/mod.php?id='.$mod->id
.'&groupmode=0&sesskey='.$sesskey;
2353 } else if ($mod->groupmode
== VISIBLEGROUPS
) {
2354 $grouptitle = $str->groupsvisible
;
2355 $groupclass = 'editing_groupsvisible';
2356 $groupimage = $CFG->pixpath
.'/t/groupv.gif';
2357 $grouplink = $path.'/mod.php?id='.$mod->id
.'&groupmode=1&sesskey='.$sesskey;
2359 $grouptitle = $str->groupsnone
;
2360 $groupclass = 'editing_groupsnone';
2361 $groupimage = $CFG->pixpath
.'/t/groupn.gif';
2362 $grouplink = $path.'/mod.php?id='.$mod->id
.'&groupmode=2&sesskey='.$sesskey;
2364 if ($mod->groupmodelink
) {
2365 $groupmode = '<a class="'.$groupclass.'" title="'.$grouptitle.' ('.$str->clicktochange
.')" href="'.$grouplink.'">'.
2366 '<img src="'.$groupimage.'" class="iconsmall" '.
2367 'alt="'.$grouptitle.'" /></a>';
2369 $groupmode = '<img title="'.$grouptitle.' ('.$str->forcedmode
.')" '.
2370 ' src="'.$groupimage.'" class="iconsmall" '.
2371 'alt="'.$grouptitle.'" />';
2377 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE
, $mod->course
))) {
2379 $move = '<a class="editing_move" title="'.$str->move
.'" href="'.$path.'/mod.php?copy='.$mod->id
.
2380 '&sesskey='.$sesskey.$section.'"><img'.
2381 ' src="'.$CFG->pixpath
.'/t/move.gif" class="iconsmall" '.
2382 ' alt="'.$str->move
.'" /></a>'."\n";
2384 $move = '<a class="editing_moveup" title="'.$str->moveup
.'" href="'.$path.'/mod.php?id='.$mod->id
.
2385 '&move=-1&sesskey='.$sesskey.$section.'"><img'.
2386 ' src="'.$CFG->pixpath
.'/t/up.gif" class="iconsmall" '.
2387 ' alt="'.$str->moveup
.'" /></a>'."\n".
2388 '<a class="editing_movedown" title="'.$str->movedown
.'" href="'.$path.'/mod.php?id='.$mod->id
.
2389 '&move=1&sesskey='.$sesskey.$section.'"><img'.
2390 ' src="'.$CFG->pixpath
.'/t/down.gif" class="iconsmall" '.
2391 ' alt="'.$str->movedown
.'" /></a>'."\n";
2398 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE
, $mod->course
))) {
2400 if (right_to_left()) { // Exchange arrows on RTL
2401 $rightarrow = 'left.gif';
2402 $leftarrow = 'right.gif';
2404 $rightarrow = 'right.gif';
2405 $leftarrow = 'left.gif';
2409 $leftright .= '<a class="editing_moveleft" title="'.$str->moveleft
.'" href="'.$path.'/mod.php?id='.$mod->id
.
2410 '&indent=-1&sesskey='.$sesskey.$section.'"><img'.
2411 ' src="'.$CFG->pixpath
.'/t/'.$leftarrow.'" class="iconsmall" '.
2412 ' alt="'.$str->moveleft
.'" /></a>'."\n";
2415 $leftright .= '<a class="editing_moveright" title="'.$str->moveright
.'" href="'.$path.'/mod.php?id='.$mod->id
.
2416 '&indent=1&sesskey='.$sesskey.$section.'"><img'.
2417 ' src="'.$CFG->pixpath
.'/t/'.$rightarrow.'" class="iconsmall" '.
2418 ' alt="'.$str->moveright
.'" /></a>'."\n";
2422 return '<span class="commands">'."\n".$leftright.$move.
2423 '<a class="editing_update" title="'.$str->update
.'" href="'.$path.'/mod.php?update='.$mod->id
.
2424 '&sesskey='.$sesskey.$section.'"><img'.
2425 ' src="'.$CFG->pixpath
.'/t/edit.gif" class="iconsmall" '.
2426 ' alt="'.$str->update
.'" /></a>'."\n".
2427 '<a class="editing_delete" title="'.$str->delete
.'" href="'.$path.'/mod.php?delete='.$mod->id
.
2428 '&sesskey='.$sesskey.$section.'"><img'.
2429 ' src="'.$CFG->pixpath
.'/t/delete.gif" class="iconsmall" '.
2430 ' alt="'.$str->delete
.'" /></a>'."\n".$hideshow.$groupmode."\n".'</span>';
2434 * given a course object with shortname & fullname, this function will
2435 * truncate the the number of chars allowed and add ... if it was too long
2437 function course_format_name ($course,$max=100) {
2439 $str = $course->shortname
.': '. $course->fullname
;
2440 if (strlen($str) <= $max) {
2444 return substr($str,0,$max-3).'...';
2449 * This function will return true if the given course is a child course at all
2451 function course_in_meta ($course) {
2452 return record_exists("course_meta","child_course",$course->id
);
2457 * Print standard form elements on module setup forms in mod/.../mod.html
2459 function print_standard_coursemodule_settings($form, $features=null) {
2460 if (! $course = get_record('course', 'id', $form->course
)) {
2461 error("This course doesn't exist");
2463 print_groupmode_setting($form, $course);
2464 if (!empty($features->groupings
)) {
2465 print_grouping_settings($form, $course);
2467 print_visible_setting($form, $course);
2471 * Print groupmode form element on module setup forms in mod/.../mod.html
2473 function print_groupmode_setting($form, $course=NULL) {
2475 if (empty($course)) {
2476 if (! $course = get_record('course', 'id', $form->course
)) {
2477 error("This course doesn't exist");
2480 if ($form->coursemodule
) {
2481 if (! $cm = get_record('course_modules', 'id', $form->coursemodule
)) {
2482 error("This course module doesn't exist");
2484 $groupmode = groups_get_activity_groupmode($cm);
2487 $groupmode = groups_get_course_groupmode($course);
2489 if ($course->groupmode
or (!$course->groupmodeforce
)) {
2490 echo '<tr valign="top">';
2491 echo '<td align="right"><b>'.get_string('groupmode').':</b></td>';
2492 echo '<td align="left">';
2494 $choices[NOGROUPS
] = get_string('groupsnone');
2495 $choices[SEPARATEGROUPS
] = get_string('groupsseparate');
2496 $choices[VISIBLEGROUPS
] = get_string('groupsvisible');
2497 choose_from_menu($choices, 'groupmode', $groupmode, '', '', 0, false, $course->groupmodeforce
);
2498 helpbutton('groupmode', get_string('groupmode'));
2504 * Print groupmode form element on module setup forms in mod/.../mod.html
2506 function print_grouping_settings($form, $course=NULL) {
2508 if (empty($course)) {
2509 if (! $course = get_record('course', 'id', $form->course
)) {
2510 error("This course doesn't exist");
2513 if ($form->coursemodule
) {
2514 if (! $cm = get_record('course_modules', 'id', $form->coursemodule
)) {
2515 error("This course module doesn't exist");
2521 $groupings = get_records_menu('groupings', 'courseid', $course->id
, 'name', 'id, name');
2522 if (!empty($groupings)) {
2523 echo '<tr valign="top">';
2524 echo '<td align="right"><b>'.get_string('grouping', 'group').':</b></td>';
2525 echo '<td align="left">';
2528 $groupingid = isset($cm->groupingid
) ?
$cm->groupingid
: 0;
2530 choose_from_menu($groupings, 'groupingid', $groupingid, get_string('none'), '', 0, false);
2533 $checked = empty($cm->groupmembersonly
) ?
'':'checked="checked"';
2534 echo '<tr valign="top">';
2535 echo '<td align="right"><b>'.get_string('groupmembersonly', 'group').':</b></td>';
2536 echo '<td align="left">';
2537 echo "<input type=\"checkbox\" name=\"groupmembersonly\" value=\"1\" $checked />";
2544 * Print visibility setting form element on module setup forms in mod/.../mod.html
2546 function print_visible_setting($form, $course=NULL) {
2547 if (empty($course)) {
2548 if (! $course = get_record('course', 'id', $form->course
)) {
2549 error("This course doesn't exist");
2552 if ($form->coursemodule
) {
2553 $visible = get_field('course_modules', 'visible', 'id', $form->coursemodule
);
2558 if ($form->mode
== 'add') { // in this case $form->section is the section number, not the id
2559 $hiddensection = !get_field('course_sections', 'visible', 'section', $form->section
, 'course', $form->course
);
2561 $hiddensection = !get_field('course_sections', 'visible', 'id', $form->section
);
2563 if ($hiddensection) {
2567 echo '<tr valign="top">';
2568 echo '<td align="right"><b>'.get_string('visible', '').':</b></td>';
2569 echo '<td align="left">';
2571 $choices[1] = get_string('show');
2572 $choices[0] = get_string('hide');
2573 choose_from_menu($choices, 'visible', $visible, '', '', 0, false, $hiddensection);
2577 function update_restricted_mods($course,$mods) {
2578 delete_records("course_allowed_modules","course",$course->id
);
2579 if (empty($course->restrictmodules
)) {
2583 foreach ($mods as $mod) {
2585 continue; // this is the 'allow none' option
2586 $am->course
= $course->id
;
2588 insert_record("course_allowed_modules",$am);
2594 * This function will take an int (module id) or a string (module name)
2595 * and return true or false, whether it's allowed in the given course (object)
2596 * $mod is not allowed to be an object, as the field for the module id is inconsistent
2597 * depending on where in the code it's called from (sometimes $mod->id, sometimes $mod->module)
2600 function course_allowed_module($course,$mod) {
2601 if (empty($course->restrictmodules
)) {
2605 // i am not sure this capability is correct
2606 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM
, SITEID
))) {
2609 if (is_numeric($mod)) {
2611 } else if (is_string($mod)) {
2612 if ($mod = get_field("modules","id","name",$mod))
2615 if (empty($modid)) {
2618 return (record_exists("course_allowed_modules","course",$course->id
,"module",$modid));
2622 *** Efficiently moves many courses around while maintaining
2623 *** sortorder in order.
2625 *** $courseids is an array of course ids
2629 function move_courses ($courseids, $categoryid) {
2633 if (!empty($courseids)) {
2635 $courseids = array_reverse($courseids);
2637 foreach ($courseids as $courseid) {
2639 if (! $course = get_record("course", "id", $courseid)) {
2640 notify("Error finding course $courseid");
2642 // figure out a sortorder that we can use in the destination category
2643 $sortorder = get_field_sql('SELECT MIN(sortorder)-1 AS min
2644 FROM ' . $CFG->prefix
. 'course WHERE category=' . $categoryid);
2645 if ($sortorder === false) {
2646 // the category is empty
2647 // rather than let the db default to 0
2648 // set it to > 100 and avoid extra work in fix_coursesortorder()
2650 } else if ($sortorder < 10) {
2651 fix_course_sortorder($categoryid);
2654 $course->category
= $categoryid;
2655 $course->sortorder
= $sortorder;
2656 $course->fullname
= addslashes($course->fullname
);
2657 $course->shortname
= addslashes($course->shortname
);
2658 $course->summary
= addslashes($course->summary
);
2659 $course->password
= addslashes($course->password
);
2660 $course->teacher
= addslashes($course->teacher
);
2661 $course->teachers
= addslashes($course->teachers
);
2662 $course->student
= addslashes($course->student
);
2663 $course->students
= addslashes($course->students
);
2665 if (!update_record('course', $course)) {
2666 notify("An error occurred - course not moved!");
2669 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
2670 $newparent = get_context_instance(CONTEXT_COURSECAT
, $course->category
);
2671 context_moved($context, $newparent);
2674 fix_course_sortorder();
2680 *** Efficiently moves a category - NOTE that this can have
2681 *** a huge impact access-control-wise...
2685 function move_category ($category, $newparentcat) {
2689 if (!set_field('course_categories', 'parent', $newparentcat->id
, 'id', $category->id
)) {
2693 $context = get_context_instance(CONTEXT_COURSECAT
, $category->id
);
2694 $newparent = get_context_instance(CONTEXT_COURSECAT
, $newparentcat->id
);
2695 context_moved($context, $newparent);
2697 // The most effective thing would be to find the common parent,
2698 // until then, do it sitewide...
2699 fix_course_sortorder();
2706 * @param string $format Course format ID e.g. 'weeks'
2707 * @return Name that the course format prefers for sections
2709 function get_section_name($format) {
2710 $sectionname = get_string("name$format","format_$format");
2711 if($sectionname == "[[name$format]]") {
2712 $sectionname = get_string("name$format");
2714 return $sectionname;
2718 * Can the current user delete this course?
2719 * @param int $courseid
2722 * Exception here to fix MDL-7796.
2725 * Course creators who can manage activities in the course
2726 * shoule be allowed to delete the course. We do it this
2727 * way because we need a quick fix to bring the functionality
2728 * in line with what we had pre-roles. We can't give the
2729 * default course creator role moodle/course:delete at
2730 * CONTEXT_SYSTEM level because this will allow them to
2731 * delete any course in the site. So we hard code this here
2734 * @author vyshane AT gmail.com
2736 function can_delete_course($courseid) {
2738 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
2740 return ( has_capability('moodle/course:delete', $context)
2741 ||
(has_capability('moodle/legacy:coursecreator', $context)
2742 && has_capability('moodle/course:manageactivities', $context)) );
2747 * Create a course and either return a $course object or false
2749 * @param object $data - all the data needed for an entry in the 'course' table
2751 function create_course($data) {
2754 // preprocess allowed mods
2755 $allowedmods = empty($data->allowedmods
) ?
array() : $data->allowedmods
;
2756 unset($data->allowedmods
);
2757 if (!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM
))) {
2758 if ($CFG->restrictmodulesfor
== 'all') {
2759 $data->restrictmodules
= 1;
2761 $data->restrictmodules
= 0;
2765 $data->timecreated
= time();
2767 // place at beginning of category
2768 fix_course_sortorder();
2769 $data->sortorder
= get_field_sql("SELECT min(sortorder)-1 FROM {$CFG->prefix}course WHERE category=$data->category");
2770 if (empty($data->sortorder
)) {
2771 $data->sortorder
= 100;
2774 if ($newcourseid = insert_record('course', $data)) { // Set up new course
2776 $course = get_record('course', 'id', $newcourseid);
2779 $page = page_create_object(PAGE_COURSE_VIEW
, $course->id
);
2780 blocks_repopulate_page($page); // Return value not checked because you can always edit later
2782 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM
))) {
2783 update_restricted_mods($course, $allowedmods);
2786 $section = new object();
2787 $section->course
= $course->id
; // Create a default section.
2788 $section->section
= 0;
2789 $section->id
= insert_record('course_sections', $section);
2791 fix_course_sortorder();
2793 add_to_log(SITEID
, 'course', 'new', 'view.php?id='.$course->id
, $data->fullname
.' (ID '.$course->id
.')');
2798 return false; // error
2803 * Update a course and return true or false
2805 * @param object $data - all the data needed for an entry in the 'course' table
2807 function update_course($data) {
2810 // preprocess allowed mods
2811 $allowedmods = empty($data->allowedmods
) ?
array() : $data->allowedmods
;
2812 unset($data->allowedmods
);
2813 if (!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM
))) {
2814 unset($data->restrictmodules
);
2818 $oldcourse = get_record('course', 'id', $data->id
); // should not fail, already tested above
2819 if (!has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT
, $oldcourse->category
))
2820 or !has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT
, $data->category
))) {
2821 // can not move to new category, keep the old one
2822 unset($data->category
);
2823 } elseif ($oldcourse->category
!= $data->category
) {
2827 // Update with the new data
2828 if (update_record('course', $data)) {
2830 $course = get_record('course', 'id', $data->id
);
2832 add_to_log($course->id
, "course", "update", "edit.php?id=$course->id", $course->id
);
2834 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM
))) {
2835 update_restricted_mods($course, $allowedmods);
2839 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
2840 $newparent = get_context_instance(CONTEXT_COURSECAT
, $course->category
);
2841 context_moved($context, $newparent);
2844 fix_course_sortorder();
2846 // Test for and remove blocks which aren't appropriate anymore
2847 $page = page_create_object(PAGE_COURSE_VIEW
, $course->id
);
2848 blocks_remove_inappropriate($page);
2850 // put custom role names into db
2851 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
2853 foreach ($data as $dname => $dvalue) {
2855 // is this the right param?
2856 $dvalue = clean_param($dvalue, PARAM_NOTAGS
);
2858 if (!strstr($dname, 'role_')) {
2862 $dt = explode('_', $dname);
2864 // make up our mind whether we want to delete, update or insert
2866 if (empty($dvalue)) {
2868 delete_records('role_names', 'contextid', $context->id
, 'roleid', $roleid);
2870 } else if ($t = get_record('role_names', 'contextid', $context->id
, 'roleid', $roleid)) {
2873 update_record('role_names', $t);
2877 $t->contextid
= $context->id
;
2878 $t->roleid
= $roleid;
2880 insert_record('role_names', $t);