MDL-11515:
[moodle-linuxchix.git] / course / lib.php
blobc3e520fd0a794f8ad14286fd9f9bb555337f5ad5
1 <?php // $Id$
2 // Library of useful functions
5 if (defined('COURSE_MAX_LOG_DISPLAY')) { // Being included again - should never happen!!
6 return;
9 define('COURSE_MAX_LOG_DISPLAY', 150); // days
10 define('COURSE_MAX_LOGS_PER_PAGE', 1000); // records
11 define('COURSE_LIVELOG_REFRESH', 60); // Seconds
12 define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds
13 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10); // courses
14 define('COURSE_MAX_COURSES_PER_DROPDOWN',1000); // max courses in log dropdown before switching to optional
15 define('COURSE_MAX_USERS_PER_DROPDOWN',1000); // max users in log dropdown before switching to optional
16 define('FRONTPAGENEWS', 0);
17 define('FRONTPAGECOURSELIST', 1);
18 define('FRONTPAGECATEGORYNAMES', 2);
19 define('FRONTPAGETOPICONLY', 3);
20 define('FRONTPAGECATEGORYCOMBO', 4);
21 define('FRONTPAGECOURSELIMIT', 200); // maximum number of courses displayed on the frontpage
22 define('EXCELROWS', 65535);
23 define('FIRSTUSEDEXCELROW', 3);
25 define('MOD_CLASS_ACTIVITY', 0);
26 define('MOD_CLASS_RESOURCE', 1);
29 function print_recent_selector_form($course, $advancedfilter=0, $selecteduser=0, $selecteddate="lastlogin",
30 $mod="", $modid="activity/All", $modaction="", $selectedgroup="", $selectedsort="default") {
32 global $USER, $CFG;
34 if ($advancedfilter) {
36 // Get all the possible users
37 $users = array();
39 if ($courseusers = get_course_users($course->id, '', '', 'u.id, u.firstname, u.lastname')) {
40 foreach ($courseusers as $courseuser) {
41 $users[$courseuser->id] = fullname($courseuser, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
44 if ($guest = get_guest()) {
45 $users[$guest->id] = fullname($guest);
48 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
49 if ($ccc = get_records("course", "", "", "fullname")) {
50 foreach ($ccc as $cc) {
51 if ($cc->category) {
52 $courses["$cc->id"] = "$cc->fullname";
53 } else {
54 $courses["$cc->id"] = " $cc->fullname (Site)";
58 asort($courses);
61 $activities = array();
63 $selectedactivity = $modid;
65 /// Casting $course->modinfo to string prevents one notice when the field is null
66 if ($modinfo = unserialize((string)$course->modinfo)) {
67 $section = 0;
68 if ($course->format == 'weeks') { // Body
69 $strsection = get_string("week");
70 } else {
71 $strsection = get_string("topic");
74 $activities["activity/All"] = "All activities";
75 $activities["activity/Assignments"] = "All assignments";
76 $activities["activity/Chats"] = "All chats";
77 $activities["activity/Forums"] = "All forums";
78 $activities["activity/Quizzes"] = "All quizzes";
79 $activities["activity/Workshops"] = "All workshops";
81 $activities["section/individual"] = "------------- Individual Activities --------------";
83 foreach ($modinfo as $mod) {
84 if ($mod->mod == "label") {
85 continue;
87 if (!$mod->visible and !has_capability('moodle/course:viewhiddenactivities',get_context_instance(CONTEXT_MODULE, $mod->cm))) {
88 continue;
90 $mod->id = $mod->cm;
91 if (!groups_course_module_visible($mod)) {
92 continue;
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");
117 asort($users);
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);
128 $dates = array();
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;
136 $numdates = 1;
137 while ($timemidnight > $course->startdate and $numdates < 365) {
138 $timemidnight = $timemidnight - 86400;
139 $timenow = $timenow - 86400;
140 $dates["$timemidnight"] = userdate($timenow, $strftimedaydate);
141 $numdates++;
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" />';
150 echo "<center>";
151 echo "<table>";
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, "");
156 echo "</td></tr>";
157 } else {
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") );
165 echo "</td>";
167 echo '<td align="right"><b>' . get_string("since") . '</b></td><td>';
168 choose_from_menu ($dates, "date", $selecteddate, get_string("alldays"));
169 echo "</td></tr>";
171 echo "<tr><td><b>" . get_string("activities") . "</b></td><td>";
172 choose_from_menu ($activities, "modid", $selectedactivity, "");
173 echo "</td>";
175 echo '<td align="right"><b>' . get_string("sortby") . "</b></td><td>";
176 choose_from_menu ($sortfields, "sortby", $selectedsort, "");
177 echo "</td></tr>";
179 echo '<tr>';
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);
189 echo '<td><b>';
190 if ($groupmode == VISIBLEGROUPS) {
191 print_string('groupsvisible');
192 } else {
193 print_string('groupsseparate');
195 echo ':</b></td><td>';
196 choose_from_menu($group_names, "selectedgroup", $selectedgroup, get_string("allgroups"), "", "");
197 echo '</td>';
202 echo '<td colspan="2" align="right">';
203 echo '<input type="submit" value="'.get_string('showrecent').'" />';
204 echo "</td></tr>";
206 echo "</table>";
208 $advancedlink = "<a href=\"$CFG->wwwroot/course/recent.php?id=$course->id&amp;advancedfilter=0\">" . get_string("normalfilter") . "</a>";
209 print_heading($advancedlink);
210 echo "</center>";
211 echo "</form>";
213 } else {
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");
221 $heading = "";
222 foreach ($day_list as $count) {
223 if ($count == "1") {
224 $day = $strday;
225 } else {
226 $day = $strdays;
228 $tmpdate = time() - ($count * 3600 * 24);
229 $heading = $heading .
230 "<a href=\"$CFG->wwwroot/course/recent.php?id=$course->id&amp;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&amp;advancedfilter=1\">" . get_string("advancedfilter") . "</a>";
237 print_heading($advancedlink);
244 function make_log_url($module, $url) {
245 switch ($module) {
246 case 'user':
247 case 'course':
248 case 'file':
249 case 'login':
250 case 'lib':
251 case 'admin':
252 case 'message':
253 case 'calendar':
254 case 'mnet course':
255 return "/course/$url";
256 break;
257 case 'blog':
258 return "/$module/$url";
259 break;
260 case 'upload':
261 return $url;
262 break;
263 case 'library':
264 case '':
265 return '/';
266 break;
267 default:
268 return "/mod/$module/$url";
269 break;
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) {
277 global $CFG;
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) {
295 // $groupid = 0;
297 $groupid = 0;
299 $joins = array();
301 $qry = "
302 SELECT
303 l.*,
304 u.firstname,
305 u.lastname,
306 u.picture
307 FROM
308 {$CFG->prefix}mnet_log l
309 LEFT JOIN
310 {$CFG->prefix}user u
312 l.userid = u.id
313 WHERE
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'";
323 if ($modname) {
324 $where .= " AND\n l.module = '$modname'";
327 if ('site_errors' === $modid) {
328 $where .= " AND\n ( l.action='error' OR l.action='infected' )";
329 } else if ($modid) {
330 //TODO: This assumes that modids are the same across sites... probably
331 //not true
332 $where .= " AND\n l.cmid = '$modid'";
335 if ($modaction) {
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)) . "%'";
344 if ($user) {
345 $where .= " AND\n l.userid = '$user'";
348 if ($date) {
349 $enddate = $date + 86400;
350 $where .= " AND\n l.time > '$date' AND l.time < '$enddate'";
353 $result = array();
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);
358 } else {
359 $result['logs'] = array();
361 return $result;
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) {
379 $groupid = 0;
382 $joins = array();
384 if ($course->id != SITEID || $modid != 0) {
385 $joins[] = "l.course='$course->id'";
388 if ($modname) {
389 $joins[] = "l.module = '$modname'";
392 if ('site_errors' === $modid) {
393 $joins[] = "( l.action='error' OR l.action='infected' )";
394 } else if ($modid) {
395 $joins[] = "l.cmid = '$modid'";
398 if ($modaction) {
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)) . "%'";
408 /// Getting all members of a group.
409 if ($groupid and !$user) {
410 if ($gusers = groups_get_members($groupid)) {
411 $gusers = array_keys($gusers);
412 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
413 } else {
414 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
417 else if ($user) {
418 $joins[] = "l.userid = '$user'";
421 if ($date) {
422 $enddate = $date + 86400;
423 $joins[] = "l.time > '$date' AND l.time < '$enddate'";
426 $selector = implode(' AND ', $joins);
428 $totalcount = 0; // Initialise
429 $result = array();
430 $result['logs'] = get_logs($selector, $order, $limitfrom, $limitnum, $totalcount);
431 $result['totalcount'] = $totalcount;
432 return $result;
436 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
437 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
439 global $CFG;
441 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
442 $modname, $modid, $modaction, $groupid)) {
443 notify("No logs found!");
444 print_footer($course);
445 exit;
448 $courses = array();
450 if ($course->id == SITEID) {
451 $courses[0] = '';
452 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
453 foreach ($ccc as $cc) {
454 $courses[$cc->id] = $cc->shortname;
457 } else {
458 $courses[$course->id] = $course->shortname;
461 $totalcount = $logs['totalcount'];
462 $count=0;
463 $ldcache = array();
464 $tt = getdate(time());
465 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
467 $strftimedatetime = get_string("strftimedatetime");
469 echo "<div class=\"info\">\n";
470 print_string("displayingrecords", "", $totalcount);
471 echo "</div>\n";
473 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
475 echo '<table class="logtable genearlbox boxaligncenter" summary="">'."\n";
476 // echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\" summary=\"\">\n";
477 echo "<tr>";
478 if ($course->id == SITEID) {
479 echo "<th class=\"c0 header\" scope=\"col\">".get_string('course')."</th>\n";
481 echo "<th class=\"c1 header\" scope=\"col\">".get_string('time')."</th>\n";
482 echo "<th class=\"c2 header\" scope=\"col\">".get_string('ip_address')."</th>\n";
483 echo "<th class=\"c3 header\" scope=\"col\">".get_string('fullname')."</th>\n";
484 echo "<th class=\"c4 header\" scope=\"col\">".get_string('action')."</th>\n";
485 echo "<th class=\"c5 header\" scope=\"col\">".get_string('info')."</th>\n";
486 echo "</tr>\n";
488 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
489 if (empty($logs['logs'])) {
490 $logs['logs'] = array();
493 $row = 1;
494 foreach ($logs['logs'] as $log) {
496 $row = ($row + 1) % 2;
498 if (isset($ldcache[$log->module][$log->action])) {
499 $ld = $ldcache[$log->module][$log->action];
500 } else {
501 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
502 $ldcache[$log->module][$log->action] = $ld;
504 if ($ld && is_numeric($log->info)) {
505 // ugly hack to make sure fullname is shown correctly
506 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
507 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
508 } else {
509 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
513 //Filter log->info
514 $log->info = format_string($log->info);
516 $log->url = strip_tags(urldecode($log->url)); // Some XSS protection
517 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
518 $log->url = s($log->url); /// XSS protection and XHTML compatibility - should be in link_to_popup_window() instead!!
520 echo '<tr class="r'.$row.'">';
521 if ($course->id == SITEID) {
522 echo "<td class=\"cell c0\">\n";
523 if (empty($log->course)) {
524 echo get_string('site') . "\n";
525 } else {
526 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course])."</a>\n";
528 echo "</td>\n";
530 echo "<td class=\"cell c1\" align=\"right\">".userdate($log->time, '%a').
531 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
532 echo "<td class=\"cell c2\">\n";
533 link_to_popup_window("/iplookup/index.php?ip=$log->ip&amp;user=$log->userid", 'iplookup',$log->ip, 400, 700);
534 echo "</td>\n";
535 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
536 echo "<td class=\"cell c3\">\n";
537 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}&amp;course={$log->course}\">$fullname</a>\n";
538 echo "</td>\n";
539 echo "<td class=\"cell c4\">\n";
540 link_to_popup_window( make_log_url($log->module,$log->url), 'fromloglive',"$log->module $log->action", 400, 600);
541 echo "</td>\n";;
542 echo "<td class=\"cell c5\">{$log->info}</td>\n";
543 echo "</tr>\n";
545 echo "</table>\n";
547 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
551 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
552 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
554 global $CFG;
556 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
557 $modname, $modid, $modaction, $groupid)) {
558 notify("No logs found!");
559 print_footer($course);
560 exit;
563 if ($course->id == SITEID) {
564 $courses[0] = '';
565 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
566 foreach ($ccc as $cc) {
567 $courses[$cc->id] = $cc->shortname;
572 $totalcount = $logs['totalcount'];
573 $count=0;
574 $ldcache = array();
575 $tt = getdate(time());
576 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
578 $strftimedatetime = get_string("strftimedatetime");
580 echo "<div class=\"info\">\n";
581 print_string("displayingrecords", "", $totalcount);
582 echo "</div>\n";
584 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
586 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
587 echo "<tr>";
588 if ($course->id == SITEID) {
589 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
591 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
592 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
593 echo "<th class=\"c3 header\">".get_string('fullname')."</th>\n";
594 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
595 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
596 echo "</tr>\n";
598 if (empty($logs['logs'])) {
599 echo "</table>\n";
600 return;
603 $row = 1;
604 foreach ($logs['logs'] as $log) {
606 $log->info = $log->coursename;
607 $row = ($row + 1) % 2;
609 if (isset($ldcache[$log->module][$log->action])) {
610 $ld = $ldcache[$log->module][$log->action];
611 } else {
612 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
613 $ldcache[$log->module][$log->action] = $ld;
615 if (0 && $ld && !empty($log->info)) {
616 // ugly hack to make sure fullname is shown correctly
617 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
618 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
619 } else {
620 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
624 //Filter log->info
625 $log->info = format_string($log->info);
627 $log->url = strip_tags(urldecode($log->url)); // Some XSS protection
628 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
629 $log->url = str_replace('&', '&amp;', $log->url); /// XHTML compatibility
631 echo '<tr class="r'.$row.'">';
632 if ($course->id == SITEID) {
633 echo "<td class=\"r$row c0\" >\n";
634 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courses[$log->course]."</a>\n";
635 echo "</td>\n";
637 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time, '%a').
638 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
639 echo "<td class=\"r$row c2\" >\n";
640 link_to_popup_window("/iplookup/index.php?ip=$log->ip&amp;user=$log->userid", 'iplookup',$log->ip, 400, 700);
641 echo "</td>\n";
642 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
643 echo "<td class=\"r$row c3\" >\n";
644 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
645 echo "</td>\n";
646 echo "<td class=\"r$row c4\">\n";
647 echo $log->action .': '.$log->module;
648 echo "</td>\n";;
649 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
650 echo "</tr>\n";
652 echo "</table>\n";
654 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
658 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
659 $modid, $modaction, $groupid) {
661 $text = get_string('course')."\t".get_string('time')."\t".get_string('ip_address')."\t".
662 get_string('fullname')."\t".get_string('action')."\t".get_string('info');
664 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
665 $modname, $modid, $modaction, $groupid)) {
666 return false;
669 $courses = array();
671 if ($course->id == SITEID) {
672 $courses[0] = '';
673 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
674 foreach ($ccc as $cc) {
675 $courses[$cc->id] = $cc->shortname;
678 } else {
679 $courses[$course->id] = $course->shortname;
682 $count=0;
683 $ldcache = array();
684 $tt = getdate(time());
685 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
687 $strftimedatetime = get_string("strftimedatetime");
689 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
690 $filename .= '.txt';
691 header("Content-Type: application/download\n");
692 header("Content-Disposition: attachment; filename=$filename");
693 header("Expires: 0");
694 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
695 header("Pragma: public");
697 echo get_string('savedat').userdate(time(), $strftimedatetime)."\n";
698 echo $text;
700 if (empty($logs['logs'])) {
701 return true;
704 foreach ($logs['logs'] as $log) {
705 if (isset($ldcache[$log->module][$log->action])) {
706 $ld = $ldcache[$log->module][$log->action];
707 } else {
708 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
709 $ldcache[$log->module][$log->action] = $ld;
711 if ($ld && !empty($log->info)) {
712 // ugly hack to make sure fullname is shown correctly
713 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
714 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
715 } else {
716 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
720 //Filter log->info
721 $log->info = format_string($log->info);
723 $log->url = strip_tags(urldecode($log->url)); // Some XSS protection
724 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
725 $log->url = str_replace('&', '&amp;', $log->url); // XHTML compatibility
727 $firstField = $courses[$log->course];
728 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
729 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action, $log->info);
730 $text = implode("\t", $row);
731 echo $text." \n";
733 return true;
737 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
738 $modid, $modaction, $groupid) {
740 global $CFG;
742 require_once("$CFG->libdir/excellib.class.php");
744 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
745 $modname, $modid, $modaction, $groupid)) {
746 return false;
749 $courses = array();
751 if ($course->id == SITEID) {
752 $courses[0] = '';
753 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
754 foreach ($ccc as $cc) {
755 $courses[$cc->id] = $cc->shortname;
758 } else {
759 $courses[$course->id] = $course->shortname;
762 $count=0;
763 $ldcache = array();
764 $tt = getdate(time());
765 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
767 $strftimedatetime = get_string("strftimedatetime");
769 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
770 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
771 $filename .= '.xls';
773 $workbook = new MoodleExcelWorkbook('-');
774 $workbook->send($filename);
776 $worksheet = array();
777 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
778 get_string('fullname'), get_string('action'), get_string('info'));
780 // Creating worksheets
781 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
782 $sheettitle = get_string('excel_sheettitle', 'logs', $wsnumber).$nroPages;
783 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
784 $worksheet[$wsnumber]->set_column(1, 1, 30);
785 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
786 userdate(time(), $strftimedatetime));
787 $col = 0;
788 foreach ($headers as $item) {
789 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
790 $col++;
794 if (empty($logs['logs'])) {
795 $workbook->close();
796 return true;
799 $formatDate =& $workbook->add_format();
800 $formatDate->set_num_format(get_string('log_excel_date_format'));
802 $row = FIRSTUSEDEXCELROW;
803 $wsnumber = 1;
804 $myxls =& $worksheet[$wsnumber];
805 foreach ($logs['logs'] as $log) {
806 if (isset($ldcache[$log->module][$log->action])) {
807 $ld = $ldcache[$log->module][$log->action];
808 } else {
809 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
810 $ldcache[$log->module][$log->action] = $ld;
812 if ($ld && !empty($log->info)) {
813 // ugly hack to make sure fullname is shown correctly
814 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
815 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
816 } else {
817 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
821 // Filter log->info
822 $log->info = format_string($log->info);
823 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
825 if ($nroPages>1) {
826 if ($row > EXCELROWS) {
827 $wsnumber++;
828 $myxls =& $worksheet[$wsnumber];
829 $row = FIRSTUSEDEXCELROW;
833 $myxls->write($row, 0, $courses[$log->course], '');
834 // Excel counts from 1/1/1900
835 $excelTime=25569+$log->time/(3600*24);
836 $myxls->write($row, 1, $excelTime, $formatDate);
837 $myxls->write($row, 2, $log->ip, '');
838 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
839 $myxls->write($row, 3, $fullname, '');
840 $myxls->write($row, 4, $log->module.' '.$log->action, '');
841 $myxls->write($row, 5, $log->info, '');
843 $row++;
846 $workbook->close();
847 return true;
850 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
851 $modid, $modaction, $groupid) {
853 global $CFG;
855 require_once("$CFG->libdir/odslib.class.php");
857 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
858 $modname, $modid, $modaction, $groupid)) {
859 return false;
862 $courses = array();
864 if ($course->id == SITEID) {
865 $courses[0] = '';
866 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
867 foreach ($ccc as $cc) {
868 $courses[$cc->id] = $cc->shortname;
871 } else {
872 $courses[$course->id] = $course->shortname;
875 $count=0;
876 $ldcache = array();
877 $tt = getdate(time());
878 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
880 $strftimedatetime = get_string("strftimedatetime");
882 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
883 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
884 $filename .= '.ods';
886 $workbook = new MoodleODSWorkbook('-');
887 $workbook->send($filename);
889 $worksheet = array();
890 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
891 get_string('fullname'), get_string('action'), get_string('info'));
893 // Creating worksheets
894 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
895 $sheettitle = get_string('excel_sheettitle', 'logs', $wsnumber).$nroPages;
896 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
897 $worksheet[$wsnumber]->set_column(1, 1, 30);
898 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
899 userdate(time(), $strftimedatetime));
900 $col = 0;
901 foreach ($headers as $item) {
902 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
903 $col++;
907 if (empty($logs['logs'])) {
908 $workbook->close();
909 return true;
912 $formatDate =& $workbook->add_format();
913 $formatDate->set_num_format(get_string('log_excel_date_format'));
915 $row = FIRSTUSEDEXCELROW;
916 $wsnumber = 1;
917 $myxls =& $worksheet[$wsnumber];
918 foreach ($logs['logs'] as $log) {
919 if (isset($ldcache[$log->module][$log->action])) {
920 $ld = $ldcache[$log->module][$log->action];
921 } else {
922 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
923 $ldcache[$log->module][$log->action] = $ld;
925 if ($ld && !empty($log->info)) {
926 // ugly hack to make sure fullname is shown correctly
927 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
928 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
929 } else {
930 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
934 // Filter log->info
935 $log->info = format_string($log->info);
936 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
938 if ($nroPages>1) {
939 if ($row > EXCELROWS) {
940 $wsnumber++;
941 $myxls =& $worksheet[$wsnumber];
942 $row = FIRSTUSEDEXCELROW;
946 $myxls->write_string($row, 0, $courses[$log->course]);
947 $myxls->write_date($row, 1, $log->time);
948 $myxls->write_string($row, 2, $log->ip);
949 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
950 $myxls->write_string($row, 3, $fullname);
951 $myxls->write_string($row, 4, $log->module.' '.$log->action);
952 $myxls->write_string($row, 5, $log->info);
954 $row++;
957 $workbook->close();
958 return true;
962 function print_log_graph($course, $userid=0, $type="course.png", $date=0) {
963 global $CFG, $USER;
964 if (empty($CFG->gdversion)) {
965 echo "(".get_string("gdneed").")";
966 } else {
967 // MDL-10818, do not display broken graph when user has no permission to view graph
968 if (has_capability('moodle/site:viewreports', get_context_instance(CONTEXT_COURSE, $course->id)) ||
969 ($course->showreports and $USER->id == $userid)) {
970 echo '<img src="'.$CFG->wwwroot.'/course/report/log/graph.php?id='.$course->id.
971 '&amp;user='.$userid.'&amp;type='.$type.'&amp;date='.$date.'" alt="" />';
977 function print_overview($courses) {
979 global $CFG, $USER;
981 $htmlarray = array();
982 if ($modules = get_records('modules')) {
983 foreach ($modules as $mod) {
984 if (file_exists(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php')) {
985 require_once(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php');
986 $fname = $mod->name.'_print_overview';
987 if (function_exists($fname)) {
988 $fname($courses,$htmlarray);
993 foreach ($courses as $course) {
994 print_simple_box_start('center', '100%', '', 5, "coursebox");
995 $linkcss = '';
996 if (empty($course->visible)) {
997 $linkcss = 'class="dimmed"';
999 print_heading('<a title="'. format_string($course->fullname).'" '.$linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'. format_string($course->fullname).'</a>');
1000 if (array_key_exists($course->id,$htmlarray)) {
1001 foreach ($htmlarray[$course->id] as $modname => $html) {
1002 echo $html;
1005 print_simple_box_end();
1010 function print_recent_activity($course) {
1011 // $course is an object
1012 // This function trawls through the logs looking for
1013 // anything new since the user's last login
1015 global $CFG, $USER, $SESSION;
1017 $context = get_context_instance(CONTEXT_COURSE, $course->id);
1019 $timestart = time() - COURSE_MAX_RECENT_PERIOD;
1021 if (!has_capability('moodle/legacy:guest', $context, NULL, false)) {
1022 if (!empty($USER->lastcourseaccess[$course->id])) {
1023 if ($USER->lastcourseaccess[$course->id] > $timestart) {
1024 $timestart = $USER->lastcourseaccess[$course->id];
1029 echo '<div class="activitydate">';
1030 echo get_string('activitysince', '', userdate($timestart));
1031 echo '</div>';
1032 echo '<div class="activityhead">';
1034 echo '<a href="'.$CFG->wwwroot.'/course/recent.php?id='.$course->id.'">'.get_string('recentactivityreport').'</a>';
1036 echo "</div>\n";
1039 // Firstly, have there been any new enrolments?
1041 $heading = false;
1042 $content = false;
1044 $users = get_recent_enrolments($course->id, $timestart);
1046 //Accessibility: new users now appear in an <OL> list.
1047 if ($users) {
1048 echo '<div class="newusers">';
1049 if (! $heading) {
1050 print_headline(get_string("newusers").':', 3);
1051 $heading = true;
1052 $content = true;
1054 echo "<ol class=\"list\">\n";
1055 foreach ($users as $user) {
1057 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
1058 echo '<li class="name"><a href="'.$CFG->wwwroot."/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a></li>\n";
1060 echo "</ol>\n</div>\n";
1063 // Next, have there been any modifications to the course structure?
1065 $logs = get_records_select('log', "time > '$timestart' AND course = '$course->id' AND
1066 module = 'course' AND action LIKE '% mod'", "time ASC");
1068 if ($logs) {
1069 foreach ($logs as $key => $log) {
1070 $info = split(' ', $log->info);
1072 if ($info[0] == 'label') { // Labels are special activities
1073 continue;
1076 $modname = get_field($info[0], 'name', 'id', $info[1]);
1077 //Create a temp valid module structure (course,id)
1078 $tempmod->course = $log->course;
1079 $tempmod->id = $info[1];
1080 //Obtain the visible property from the instance
1081 $modvisible = instance_is_visible($info[0],$tempmod);
1083 //Only if the mod is visible
1084 if ($modvisible) {
1085 switch ($log->action) {
1086 case 'add mod':
1087 $stradded = get_string('added', 'moodle', get_string('modulename', $info[0]));
1088 $changelist[$log->info] = array ('operation' => 'add', 'text' => "$stradded:<br /><a href=\"$CFG->wwwroot/course/$log->url\">".format_string($modname,true)."</a>");
1089 break;
1090 case 'update mod':
1091 $strupdated = get_string('updated', 'moodle', get_string('modulename', $info[0]));
1092 if (empty($changelist[$log->info])) {
1093 $changelist[$log->info] = array ('operation' => 'update', 'text' => "$strupdated:<br /><a href=\"$CFG->wwwroot/course/$log->url\">".format_string($modname,true)."</a>");
1095 break;
1096 case 'delete mod':
1097 if (!empty($changelist[$log->info]['operation']) and
1098 $changelist[$log->info]['operation'] == 'add') {
1099 $changelist[$log->info] = NULL;
1100 } else {
1101 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $info[0]));
1102 $changelist[$log->info] = array ('operation' => 'delete', 'text' => $strdeleted);
1104 break;
1110 if (!empty($changelist)) {
1111 foreach ($changelist as $changeinfo => $change) {
1112 if ($change) {
1113 $changes[$changeinfo] = $change;
1116 if (isset($changes)){
1117 if (count($changes) > 0) {
1118 print_headline(get_string('courseupdates').':', 3);
1119 $content = true;
1120 foreach ($changes as $changeinfo => $change) {
1121 echo '<p class="activity">'.$change['text'].'</p>';
1127 // Now display new things from each module
1129 $mods = get_records('modules', 'visible', '1', 'name', 'id, name');
1131 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
1133 foreach ($mods as $mod) { // Each module gets it's own logs and prints them
1134 include_once($CFG->dirroot.'/mod/'.$mod->name.'/lib.php');
1135 $print_recent_activity = $mod->name.'_print_recent_activity';
1136 if (function_exists($print_recent_activity)) {
1138 // NOTE:
1139 // $isteacher (second parameter below) is to be deprecated!
1141 // TODO:
1142 // 1) Make sure that all _print_recent_activity functions are
1143 // not using the $isteacher value.
1144 // 2) Eventually, remove the $isteacher parameter from the
1145 // function calls.
1147 $modcontent = $print_recent_activity($course, $viewfullnames, $timestart);
1148 if ($modcontent) {
1149 $content = true;
1154 if (! $content) {
1155 echo '<p class="message">'.get_string('nothingnew').'</p>';
1160 function get_array_of_activities($courseid) {
1161 // For a given course, returns an array of course activity objects
1162 // Each item in the array contains he following properties:
1163 // cm - course module id
1164 // mod - name of the module (eg forum)
1165 // section - the number of the section (eg week or topic)
1166 // name - the name of the instance
1167 // visible - is the instance visible or not
1168 // groupingid - grouping id
1169 // groupmembersonly - is this instance visible to group members only
1170 // extra - contains extra string to include in any link
1172 global $CFG;
1174 $mod = array();
1176 if (!$rawmods = get_course_mods($courseid)) {
1177 return NULL;
1180 if ($sections = get_records("course_sections", "course", $courseid, "section ASC")) {
1181 foreach ($sections as $section) {
1182 if (!empty($section->sequence)) {
1183 $sequence = explode(",", $section->sequence);
1184 foreach ($sequence as $seq) {
1185 if (empty($rawmods[$seq])) {
1186 continue;
1188 $mod[$seq]->cm = $rawmods[$seq]->id;
1189 $mod[$seq]->mod = $rawmods[$seq]->modname;
1190 $mod[$seq]->section = $section->section;
1191 $mod[$seq]->name = urlencode(get_field($rawmods[$seq]->modname, "name", "id", $rawmods[$seq]->instance));
1192 $mod[$seq]->visible = $rawmods[$seq]->visible;
1193 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
1194 $mod[$seq]->groupmembersonly = $rawmods[$seq]->groupmembersonly;
1195 $mod[$seq]->extra = "";
1197 $modname = $mod[$seq]->mod;
1198 $functionname = $modname."_get_coursemodule_info";
1200 include_once("$CFG->dirroot/mod/$modname/lib.php");
1202 if (function_exists($functionname)) {
1203 if ($info = $functionname($rawmods[$seq])) {
1204 if (!empty($info->extra)) {
1205 $mod[$seq]->extra = $info->extra;
1207 if (!empty($info->icon)) {
1208 $mod[$seq]->icon = $info->icon;
1216 return $mod;
1222 function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
1223 // Returns a number of useful structures for course displays
1225 $mods = NULL; // course modules indexed by id
1226 $modnames = NULL; // all course module names (except resource!)
1227 $modnamesplural= NULL; // all course module names (plural form)
1228 $modnamesused = NULL; // course module names used
1230 if ($allmods = get_records("modules")) {
1231 foreach ($allmods as $mod) {
1232 if ($mod->visible) {
1233 $modnames[$mod->name] = get_string("modulename", "$mod->name");
1234 $modnamesplural[$mod->name] = get_string("modulenameplural", "$mod->name");
1237 asort($modnames);
1238 } else {
1239 error("No modules are installed!");
1242 if ($rawmods = get_course_mods($courseid)) {
1243 foreach($rawmods as $mod) { // Index the mods
1244 if (empty($modnames[$mod->modname])) {
1245 continue;
1247 // Check groupings
1248 if (!groups_course_module_visible($mod)) {
1249 continue;
1251 $mods[$mod->id] = $mod;
1252 $mods[$mod->id]->modfullname = $modnames[$mod->modname];
1253 if ($mod->visible or has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_COURSE, $courseid))) {
1254 $modnamesused[$mod->modname] = $modnames[$mod->modname];
1257 if ($modnamesused) {
1258 asort($modnamesused);
1264 function get_all_sections($courseid) {
1266 return get_records("course_sections", "course", "$courseid", "section",
1267 "section, id, course, summary, sequence, visible");
1270 function course_set_display($courseid, $display=0) {
1271 global $USER;
1273 if ($display == "all" or empty($display)) {
1274 $display = 0;
1277 if (empty($USER->id) or $USER->username == 'guest') {
1278 //do not store settings in db for guests
1279 } else if (record_exists("course_display", "userid", $USER->id, "course", $courseid)) {
1280 set_field("course_display", "display", $display, "userid", $USER->id, "course", $courseid);
1281 } else {
1282 $record->userid = $USER->id;
1283 $record->course = $courseid;
1284 $record->display = $display;
1285 if (!insert_record("course_display", $record)) {
1286 notify("Could not save your course display!");
1290 return $USER->display[$courseid] = $display; // Note: = not ==
1293 function set_section_visible($courseid, $sectionnumber, $visibility) {
1294 /// For a given course section, markes it visible or hidden,
1295 /// and does the same for every activity in that section
1297 if ($section = get_record("course_sections", "course", $courseid, "section", $sectionnumber)) {
1298 set_field("course_sections", "visible", "$visibility", "id", $section->id);
1299 if (!empty($section->sequence)) {
1300 $modules = explode(",", $section->sequence);
1301 foreach ($modules as $moduleid) {
1302 set_coursemodule_visible($moduleid, $visibility, true);
1305 rebuild_course_cache($courseid);
1310 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%") {
1311 /// Prints a section full of activity modules
1312 global $CFG, $USER;
1314 static $groupbuttons;
1315 static $groupbuttonslink;
1316 static $isteacher;
1317 static $isediting;
1318 static $ismoving;
1319 static $strmovehere;
1320 static $strmovefull;
1321 static $strunreadpostsone;
1323 static $untracked;
1324 static $usetracking;
1326 $labelformatoptions = New stdClass;
1328 if (!isset($isteacher)) {
1329 $groupbuttons = ($course->groupmode or (!$course->groupmodeforce));
1330 $groupbuttonslink = (!$course->groupmodeforce);
1331 $isediting = isediting($course->id);
1332 $ismoving = $isediting && ismoving($course->id);
1333 if ($ismoving) {
1334 $strmovehere = get_string("movehere");
1335 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1337 include_once($CFG->dirroot.'/mod/forum/lib.php');
1338 if ($usetracking = forum_tp_can_track_forums()) {
1339 $strunreadpostsone = get_string('unreadpostsone', 'forum');
1340 $untracked = forum_tp_get_untracked_forums($USER->id, $course->id);
1343 $labelformatoptions->noclean = true;
1345 /// Casting $course->modinfo to string prevents one notice when the field is null
1346 $modinfo = unserialize((string)$course->modinfo);
1348 $groupings = groups_get_all_groupings($course->id);
1350 //Acccessibility: replace table with list <ul>, but don't output empty list.
1351 if (!empty($section->sequence)) {
1353 // Fix bug #5027, don't want style=\"width:$width\".
1354 echo "<ul class=\"section img-text\">\n";
1355 $sectionmods = explode(",", $section->sequence);
1357 foreach ($sectionmods as $modnumber) {
1358 if (empty($mods[$modnumber])) {
1359 continue;
1361 $mod = $mods[$modnumber];
1363 if (($mod->visible or has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_COURSE, $course->id))) &&
1364 (!$ismoving || $mod->id != $USER->activitycopy) &&
1365 groups_course_module_visible($mod)) {
1366 echo '<li class="activity '.$mod->modname.'" id="module-'.$modnumber.'">'; // Unique ID
1367 if ($ismoving) {
1368 echo '<a title="'.$strmovefull.'"'.
1369 ' href="'.$CFG->wwwroot.'/course/mod.php?moveto='.$mod->id.'&amp;sesskey='.$USER->sesskey.'">'.
1370 '<img class="movetarget" src="'.$CFG->pixpath.'/movehere.gif" '.
1371 ' alt="'.$strmovehere.'" /></a><br />
1374 $instancename = urldecode($modinfo[$modnumber]->name);
1375 $instancename = format_string($instancename, true, $course->id);
1377 if (!empty($modinfo[$modnumber]->extra)) {
1378 $extra = urldecode($modinfo[$modnumber]->extra);
1379 } else {
1380 $extra = "";
1383 if (!empty($modinfo[$modnumber]->icon)) {
1384 $icon = "$CFG->pixpath/".urldecode($modinfo[$modnumber]->icon);
1385 } else {
1386 $icon = "$CFG->modpixpath/$mod->modname/icon.gif";
1389 if ($mod->indent) {
1390 print_spacer(12, 20 * $mod->indent, false);
1393 if ($mod->modname == "label") {
1394 if (!$mod->visible) {
1395 echo "<span class=\"dimmed_text\">";
1397 echo format_text($extra, FORMAT_HTML, $labelformatoptions);
1398 if (!$mod->visible) {
1399 echo "</span>";
1402 } else { // Normal activity
1404 //Accessibility: for files get description via icon.
1405 $altname = '';
1406 if ('resource'==$mod->modname) {
1407 if (!empty($modinfo[$modnumber]->icon)) {
1408 $possaltname = $modinfo[$modnumber]->icon;
1410 $mimetype = mimeinfo_from_icon('type', $possaltname);
1411 $altname = get_mimetype_description($mimetype);
1412 } else {
1413 $altname = $mod->modfullname;
1415 } else {
1416 $altname = $mod->modfullname;
1418 // Avoid unnecessary duplication.
1419 if (false!==stripos($instancename, $altname)) {
1420 $altname = '';
1422 // File type after name, for alphabetic lists (screen reader).
1423 if ($altname) {
1424 $altname = get_accesshide(' '.$altname);
1427 $linkcss = $mod->visible ? "" : " class=\"dimmed\" ";
1428 echo '<a '.$linkcss.' '.$extra. // Title unnecessary!
1429 ' href="'.$CFG->wwwroot.'/mod/'.$mod->modname.'/view.php?id='.$mod->id.'">'.
1430 '<img src="'.$icon.'" class="activityicon" alt="" /> <span>'.
1431 $instancename.$altname.'</span></a>';
1433 if (!empty($CFG->enablegroupings) && !empty($mod->groupingid) && has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
1434 echo " <span class=\"groupinglabel\"> - ".format_string($groupings[$mod->groupingid]->name).'</span>';
1437 if ($usetracking && $mod->modname == 'forum') {
1438 $groupmode = groups_get_course_groupmode($course, $mod);
1439 $groupid = ($groupmode == SEPARATEGROUPS && !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) ?
1440 groups_get_course_group($course, true) : false;
1442 if (forum_tp_can_track_forums() && !isset($untracked[$mod->instance])) {
1443 $unread = forum_tp_count_forum_unread_posts($USER->id, $mod->instance, $groupid);
1444 if ($unread) {
1445 echo '<span class="unread"> <a href="'.$CFG->wwwroot.'/mod/forum/view.php?id='.$mod->id.'">';
1446 if ($unread == 1) {
1447 echo $strunreadpostsone;
1448 } else {
1449 print_string('unreadpostsnumber', 'forum', $unread);
1451 echo '</a> </span>';
1456 if ($isediting) {
1457 // TODO: we must define this as mod property!
1458 if ($groupbuttons and $mod->modname != 'label' and $mod->modname != 'resource' and $mod->modname != 'glossary') {
1459 if (! $mod->groupmodelink = $groupbuttonslink) {
1460 $mod->groupmode = $course->groupmode;
1463 } else {
1464 $mod->groupmode = false;
1466 echo '&nbsp;&nbsp;';
1467 echo make_editing_buttons($mod, $absolute, true, $mod->indent, $section->section);
1469 echo "</li>\n";
1472 } elseif ($ismoving) {
1473 echo "<ul class=\"section\">\n";
1475 if ($ismoving) {
1476 echo '<li><a title="'.$strmovefull.'"'.
1477 ' href="'.$CFG->wwwroot.'/course/mod.php?movetosection='.$section->id.'&amp;sesskey='.$USER->sesskey.'">'.
1478 '<img class="movetarget" src="'.$CFG->pixpath.'/movehere.gif" '.
1479 ' alt="'.$strmovehere.'" /></a></li>
1482 if (!empty($section->sequence) || $ismoving) {
1483 echo "</ul><!--class='section'-->\n\n";
1488 * Prints the menus to add activities and resources.
1490 function print_section_add_menus($course, $section, $modnames, $vertical=false, $return=false) {
1491 global $CFG;
1493 // check to see if user can add menus
1494 if (!has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $course->id))) {
1495 return false;
1498 static $resources = false;
1499 static $activities = false;
1501 if ($resources === false) {
1502 $resources = array();
1503 $activities = array();
1505 foreach($modnames as $modname=>$modnamestr) {
1506 if (!course_allowed_module($course, $modname)) {
1507 continue;
1510 require_once("$CFG->dirroot/mod/$modname/lib.php");
1511 $gettypesfunc = $modname.'_get_types';
1512 if (function_exists($gettypesfunc)) {
1513 $types = $gettypesfunc();
1514 foreach($types as $type) {
1515 if ($type->modclass == MOD_CLASS_RESOURCE) {
1516 $resources[$type->type] = $type->typestr;
1517 } else {
1518 $activities[$type->type] = $type->typestr;
1521 } else {
1522 // all mods without type are considered activity
1523 $activities[$modname] = $modnamestr;
1528 $straddactivity = get_string('addactivity');
1529 $straddresource = get_string('addresource');
1531 $output = '<div class="section_add_menus">';
1533 if (!$vertical) {
1534 $output .= '<div class="horizontal">';
1537 if (!empty($resources)) {
1538 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&amp;section=$section&amp;sesskey=".sesskey()."&amp;add=",
1539 $resources, "ressection$section", "", $straddresource, 'resource/types', $straddresource, true);
1542 if (!empty($activities)) {
1543 $output .= ' ';
1544 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&amp;section=$section&amp;sesskey=".sesskey()."&amp;add=",
1545 $activities, "section$section", "", $straddactivity, 'mods', $straddactivity, true);
1548 if (!$vertical) {
1549 $output .= '</div>';
1552 $output .= '</div>';
1554 if ($return) {
1555 return $output;
1556 } else {
1557 echo $output;
1561 function rebuild_course_cache($courseid=0) {
1562 // Rebuilds the cached list of course activities stored in the database
1563 // If a courseid is not specified, then all are rebuilt
1565 if ($courseid) {
1566 $select = "id = '$courseid'";
1567 } else {
1568 $select = "";
1569 @set_time_limit(0); // this could take a while! MDL-10954
1572 if ($courses = get_records_select("course", $select,'','id,fullname')) {
1573 foreach ($courses as $course) {
1574 $modinfo = serialize(get_array_of_activities($course->id));
1575 if (!set_field("course", "modinfo", $modinfo, "id", $course->id)) {
1576 notify("Could not cache module information for course '" . format_string($course->fullname) . "'!");
1584 function make_categories_list(&$list, &$parents, $category=NULL, $path="") {
1585 /// Given an empty array, this function recursively travels the
1586 /// categories, building up a nice list for display. It also makes
1587 /// an array that list all the parents for each category.
1589 // initialize the arrays if needed
1590 if (!is_array($list)) {
1591 $list = array();
1593 if (!is_array($parents)) {
1594 $parents = array();
1597 if ($category) {
1598 if ($path) {
1599 $path = $path.' / '.format_string($category->name);
1600 } else {
1601 $path = format_string($category->name);
1603 $list[$category->id] = $path;
1604 } else {
1605 $category->id = 0;
1608 if ($categories = get_categories($category->id)) { // Print all the children recursively
1609 foreach ($categories as $cat) {
1610 if (!empty($category->id)) {
1611 if (isset($parents[$category->id])) {
1612 $parents[$cat->id] = $parents[$category->id];
1614 $parents[$cat->id][] = $category->id;
1616 make_categories_list($list, $parents, $cat, $path);
1622 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $files = true) {
1623 /// Recursive function to print out all the categories in a nice format
1624 /// with or without courses included
1625 global $CFG;
1627 if (isset($CFG->max_category_depth) && ($depth >= $CFG->max_category_depth)) {
1628 return;
1631 if (!$displaylist) {
1632 make_categories_list($displaylist, $parentslist);
1635 if ($category) {
1636 if ($category->visible or has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
1637 print_category_info($category, $depth, $files);
1638 } else {
1639 return; // Don't bother printing children of invisible categories
1642 } else {
1643 $category->id = "0";
1646 if ($categories = get_categories($category->id)) { // Print all the children recursively
1647 $countcats = count($categories);
1648 $count = 0;
1649 $first = true;
1650 $last = false;
1651 foreach ($categories as $cat) {
1652 $count++;
1653 if ($count == $countcats) {
1654 $last = true;
1656 $up = $first ? false : true;
1657 $down = $last ? false : true;
1658 $first = false;
1660 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1, $files);
1665 // this function will return $options array for choose_from_menu, with whitespace to denote nesting.
1667 function make_categories_options() {
1668 make_categories_list($cats,$parents);
1669 foreach ($cats as $key => $value) {
1670 if (array_key_exists($key,$parents)) {
1671 if ($indent = count($parents[$key])) {
1672 for ($i = 0; $i < $indent; $i++) {
1673 $cats[$key] = '&nbsp;'.$cats[$key];
1678 return $cats;
1681 function print_category_info($category, $depth, $files = false) {
1682 /// Prints the category info in indented fashion
1683 /// This function is only used by print_whole_category_list() above
1685 global $CFG;
1686 static $strallowguests, $strrequireskey, $strsummary;
1688 if (empty($strsummary)) {
1689 $strallowguests = get_string('allowguests');
1690 $strrequireskey = get_string('requireskey');
1691 $strsummary = get_string('summary');
1694 $catlinkcss = $category->visible ? '' : ' class="dimmed" ';
1696 $coursecount = count_records('course') <= FRONTPAGECOURSELIMIT;
1697 if ($files and $coursecount) {
1698 $catimage = '<img src="'.$CFG->pixpath.'/i/course.gif" alt="" />';
1699 } else {
1700 $catimage = "&nbsp;";
1703 echo "\n\n".'<table class="categorylist">';
1705 if ($files and $coursecount) {
1706 $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');
1708 echo '<tr>';
1710 if ($depth) {
1711 $indent = $depth*30;
1712 $rows = count($courses) + 1;
1713 echo '<td rowspan="'.$rows.'" valign="top" width="'.$indent.'">';
1714 print_spacer(10, $indent);
1715 echo '</td>';
1718 echo '<td valign="top" class="category image">'.$catimage.'</td>';
1719 echo '<td valign="top" class="category name">';
1720 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot.'/course/category.php?id='.$category->id.'">'. format_string($category->name).'</a>';
1721 echo '</td>';
1722 echo '<td class="category info">&nbsp;</td>';
1723 echo '</tr>';
1725 if ($courses && !(isset($CFG->max_category_depth)&&($depth>=$CFG->max_category_depth-1))) {
1726 foreach ($courses as $course) {
1727 $linkcss = $course->visible ? '' : ' class="dimmed" ';
1728 echo '<tr><td valign="top">&nbsp;';
1729 echo '</td><td valign="top" class="course name">';
1730 echo '<a '.$linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'. format_string($course->fullname).'</a>';
1731 echo '</td><td align="right" valign="top" class="course info">';
1732 if ($course->guest ) {
1733 echo '<a title="'.$strallowguests.'" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">';
1734 echo '<img alt="'.$strallowguests.'" src="'.$CFG->pixpath.'/i/guest.gif" /></a>';
1735 } else {
1736 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath.'/spacer.gif" />';
1738 if ($course->password) {
1739 echo '<a title="'.$strrequireskey.'" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">';
1740 echo '<img alt="'.$strrequireskey.'" src="'.$CFG->pixpath.'/i/key.gif" /></a>';
1741 } else {
1742 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath.'/spacer.gif" />';
1744 if ($course->summary) {
1745 link_to_popup_window ('/course/info.php?id='.$course->id, 'courseinfo',
1746 '<img alt="'.$strsummary.'" src="'.$CFG->pixpath.'/i/info.gif" />',
1747 400, 500, $strsummary);
1748 } else {
1749 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath.'/spacer.gif" />';
1751 echo '</td></tr>';
1754 } else {
1756 echo '<tr>';
1758 if ($depth) {
1759 $indent = $depth*20;
1760 echo '<td valign="top" width="'.$indent.'">';
1761 print_spacer(10, $indent);
1762 echo '</td>';
1765 echo '<td valign="top" class="category name">';
1766 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot.'/course/category.php?id='.$category->id.'">'. format_string($category->name).'</a>';
1767 echo '</td>';
1768 echo '<td valign="top" class="category number">';
1769 if ($category->coursecount) {
1770 echo $category->coursecount;
1772 echo '</td></tr>';
1774 echo '</table>';
1779 function print_courses($category) {
1780 /// Category is 0 (for all courses) or an object
1782 global $CFG;
1784 if (!is_object($category) && $category==0) {
1785 $categories = get_categories(0); // Parent = 0 ie top-level categories only
1786 if (is_array($categories) && count($categories) == 1) {
1787 $category = array_shift($categories);
1788 $courses = get_courses_wmanagers($category->id,
1789 'c.sortorder ASC',
1790 array('password','summary','currency'));
1791 } else {
1792 $courses = get_courses_wmanagers('all',
1793 'c.sortorder ASC',
1794 array('password','summary','currency'));
1796 unset($categories);
1797 } else {
1798 $courses = get_courses_wmanagers($category->id,
1799 'c.sortorder ASC',
1800 array('password','summary','currency'));
1803 if ($courses) {
1804 foreach ($courses as $course) {
1805 if ($course->visible == 1
1806 || has_capability('moodle/course:viewhidden',$course->context)) {
1807 print_course($course);
1810 } else {
1811 print_heading(get_string("nocoursesyet"));
1812 $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
1813 if (has_capability('moodle/course:create', $context)) {
1814 $options = array();
1815 $options['category'] = $category->id;
1816 echo '<div class="addcoursebutton">';
1817 print_single_button($CFG->wwwroot.'/course/edit.php', $options, get_string("addnewcourse"));
1818 echo '</div>';
1827 function print_course($course) {
1829 global $CFG, $USER;
1831 if (isset($course->context)) {
1832 $context = $course->context;
1833 } else {
1834 $context = get_context_instance(CONTEXT_COURSE, $course->id);
1837 $linkcss = $course->visible ? '' : ' class="dimmed" ';
1839 echo '<div class="coursebox">';
1840 echo '<div class="info">';
1841 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
1842 $linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.
1843 format_string($course->fullname).'</a></div>';
1845 /// first find all roles that are supposed to be displayed
1847 if (!empty($CFG->coursemanager)) {
1848 $managerroles = split(',', $CFG->coursemanager);
1849 $canseehidden = has_capability('moodle/role:viewhiddenassigns', $context);
1850 $namesarray = array();
1851 if (isset($course->managers)) {
1852 if (count($course->managers)) {
1853 $rusers = $course->managers;
1854 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
1855 foreach ($rusers as $ra) {
1856 if ($ra->hidden == 0 || $canseehidden) {
1857 $fullname = fullname($ra->user, $canviewfullnames);
1858 $namesarray[] = format_string($ra->rolename)
1859 . ': <a href="'.$CFG->wwwroot.'/user/view.php?id='.$ra->user->id.'&amp;course='.SITEID.'">'
1860 . $fullname . '</a>';
1864 } else {
1865 $rusers = get_role_users($managerroles, $context,
1866 true, '', 'r.sortorder ASC, u.lastname ASC', $canseehidden);
1867 if (is_array($rusers) && count($rusers)) {
1868 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
1869 foreach ($rusers as $teacher) {
1870 $fullname = fullname($teacher, $canviewfullnames);
1871 $namesarray[] = format_string($teacher->rolename)
1872 . ': <a href="'.$CFG->wwwroot.'/user/view.php?id='.$teacher->id.'&amp;course='.SITEID.'">'
1873 . $fullname . '</a>';
1878 if (!empty($namesarray)) {
1879 echo "<ul class=\"teachers\">\n<li>";
1880 echo implode('</li><li>', $namesarray);
1881 echo "</li></ul>";
1885 require_once("$CFG->dirroot/enrol/enrol.class.php");
1886 $enrol = enrolment_factory::factory($course->enrol);
1887 echo $enrol->get_access_icons($course);
1889 echo '</div><div class="summary">';
1890 $options = NULL;
1891 $options->noclean = true;
1892 $options->para = false;
1893 echo format_text($course->summary, FORMAT_MOODLE, $options, $course->id);
1894 echo '</div>';
1895 echo '</div>';
1896 echo '<div class="clearer"></div>';
1900 function print_my_moodle() {
1901 /// Prints custom user information on the home page.
1902 /// Over time this can include all sorts of information
1904 global $USER, $CFG;
1906 if (empty($USER->id)) {
1907 error("It shouldn't be possible to see My Moodle without being logged in.");
1910 $courses = get_my_courses($USER->id, 'visible DESC,sortorder ASC', array('summary'));
1911 $rhosts = array();
1912 $rcourses = array();
1913 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
1914 $rcourses = get_my_remotecourses($USER->id);
1915 $rhosts = get_my_remotehosts();
1918 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
1920 if (!empty($courses)) {
1921 foreach ($courses as $course) {
1922 if ($course->id == SITEID) {
1923 continue;
1925 print_course($course, "100%");
1929 // MNET
1930 if (!empty($rcourses)) {
1931 // at the IDP, we know of all the remote courses
1932 foreach ($rcourses as $course) {
1933 print_remote_course($course, "100%");
1935 } elseif (!empty($rhosts)) {
1936 // non-IDP, we know of all the remote servers, but not courses
1937 foreach ($rhosts as $host) {
1938 print_remote_host($host, "100%");
1941 unset($course);
1942 unset($host);
1944 if (count_records("course") > (count($courses) + 1) ) { // Some courses not being displayed
1945 echo "<table width=\"100%\"><tr><td align=\"center\">";
1946 print_course_search("", false, "short");
1947 echo "</td><td align=\"center\">";
1948 print_single_button("$CFG->wwwroot/course/index.php", NULL, get_string("fulllistofcourses"), "get");
1949 echo "</td></tr></table>\n";
1952 } else {
1953 if (count_records("course_categories") > 1) {
1954 print_simple_box_start("center", "100%", "#FFFFFF", 5, "categorybox");
1955 print_whole_category_list();
1956 print_simple_box_end();
1957 } else {
1958 print_courses(0);
1964 function print_course_search($value="", $return=false, $format="plain") {
1966 global $CFG;
1967 static $count = 0;
1969 $count++;
1971 $id = 'coursesearch';
1973 if ($count > 1) {
1974 $id .= $count;
1977 $strsearchcourses= get_string("searchcourses");
1979 if ($format == 'plain') {
1980 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
1981 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
1982 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
1983 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
1984 $output .= '<input type="submit" value="'.get_string('go').'" />';
1985 $output .= '</fieldset></form>';
1986 } else if ($format == 'short') {
1987 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
1988 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
1989 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
1990 $output .= '<input type="text" id="coursesearchbox" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
1991 $output .= '<input type="submit" value="'.get_string('go').'" />';
1992 $output .= '</fieldset></form>';
1993 } else if ($format == 'navbar') {
1994 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
1995 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
1996 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
1997 $output .= '<input type="text" id="coursesearchbox" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
1998 $output .= '<input type="submit" value="'.get_string('go').'" />';
1999 $output .= '</fieldset></form>';
2002 if ($return) {
2003 return $output;
2005 echo $output;
2008 function print_remote_course($course, $width="100%") {
2010 global $CFG, $USER;
2012 $linkcss = '';
2014 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&amp;wantsurl=/course/view.php?id={$course->remoteid}";
2016 echo '<div class="coursebox remotecoursebox">';
2017 echo '<div class="info">';
2018 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2019 $linkcss.' href="'.$url.'">'
2020 . format_string($course->fullname) .'</a><br />'
2021 . format_string($course->hostname) . ' : '
2022 . format_string($course->cat_name) . ' : '
2023 . format_string($course->shortname). '</div>';
2024 echo '</div><div class="summary">';
2025 $options = NULL;
2026 $options->noclean = true;
2027 $options->para = false;
2028 echo format_text($course->summary, FORMAT_MOODLE, $options);
2029 echo '</div>';
2030 echo '</div>';
2031 echo '<div class="clearer"></div>';
2034 function print_remote_host($host, $width="100%") {
2036 global $CFG, $USER;
2038 $linkcss = '';
2040 echo '<div class="coursebox">';
2041 echo '<div class="info">';
2042 echo '<div class="name">';
2043 echo '<img src="'.$CFG->pixpath.'/i/mnethost.gif" class="icon" alt="'.get_string('course').'" />';
2044 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2045 . s($host['name']).'</a> - ';
2046 echo $host['count'] . ' ' . get_string('courses');
2047 echo '</div>';
2048 echo '</div>';
2049 echo '</div>';
2050 echo '<div class="clearer"></div>';
2054 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2056 function add_course_module($mod) {
2058 $mod->added = time();
2059 unset($mod->id);
2061 return insert_record("course_modules", $mod);
2065 * Returns course section - creates new if does not exist yet.
2066 * @param int $relative section number
2067 * @param int $courseid
2068 * @return object $course_section object
2070 function get_course_section($section, $courseid) {
2071 if ($cw = get_record("course_sections", "section", $section, "course", $courseid)) {
2072 return $cw;
2074 $cw = new object();
2075 $cw->course = $courseid;
2076 $cw->section = $section;
2077 $cw->summary = "";
2078 $cw->sequence = "";
2079 $id = insert_record("course_sections", $cw);
2080 return get_record("course_sections", "id", $id);
2083 * Given a full mod object with section and course already defined, adds this module to that section.
2085 * @param object $mod
2086 * @param int $beforemod An existing ID which we will insert the new module before
2087 * @return int The course_sections ID where the mod is inserted
2089 function add_mod_to_section($mod, $beforemod=NULL) {
2091 if ($section = get_record("course_sections", "course", "$mod->course", "section", "$mod->section")) {
2093 $section->sequence = trim($section->sequence);
2095 if (empty($section->sequence)) {
2096 $newsequence = "$mod->coursemodule";
2098 } else if ($beforemod) {
2099 $modarray = explode(",", $section->sequence);
2101 if ($key = array_keys ($modarray, $beforemod->id)) {
2102 $insertarray = array($mod->id, $beforemod->id);
2103 array_splice($modarray, $key[0], 1, $insertarray);
2104 $newsequence = implode(",", $modarray);
2106 } else { // Just tack it on the end anyway
2107 $newsequence = "$section->sequence,$mod->coursemodule";
2110 } else {
2111 $newsequence = "$section->sequence,$mod->coursemodule";
2114 if (set_field("course_sections", "sequence", $newsequence, "id", $section->id)) {
2115 return $section->id; // Return course_sections ID that was used.
2116 } else {
2117 return 0;
2120 } else { // Insert a new record
2121 $section->course = $mod->course;
2122 $section->section = $mod->section;
2123 $section->summary = "";
2124 $section->sequence = $mod->coursemodule;
2125 return insert_record("course_sections", $section);
2129 function set_coursemodule_groupmode($id, $groupmode) {
2130 return set_field("course_modules", "groupmode", $groupmode, "id", $id);
2133 function set_coursemodule_groupingid($id, $groupingid) {
2134 return set_field("course_modules", "groupingid", $groupingid, "id", $id);
2137 function set_coursemodule_groupmembersonly($id, $groupmembersonly) {
2138 return set_field("course_modules", "groupmembersonly", $groupmembersonly, "id", $id);
2141 function set_coursemodule_idnumber($id, $idnumber) {
2142 return set_field("course_modules", "idnumber", $idnumber, "id", $id);
2145 * $prevstateoverrides = true will set the visibility of the course module
2146 * to what is defined in visibleold. This enables us to remember the current
2147 * visibility when making a whole section hidden, so that when we toggle
2148 * that section back to visible, we are able to return the visibility of
2149 * the course module back to what it was originally.
2151 function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
2152 if (!$cm = get_record('course_modules', 'id', $id)) {
2153 return false;
2155 if (!$modulename = get_field('modules', 'name', 'id', $cm->module)) {
2156 return false;
2158 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
2159 foreach($events as $event) {
2160 if ($visible) {
2161 show_event($event);
2162 } else {
2163 hide_event($event);
2167 if ($prevstateoverrides) {
2168 if ($visible == '0') {
2169 // Remember the current visible state so we can toggle this back.
2170 set_field('course_modules', 'visibleold', $cm->visible, 'id', $id);
2171 } else {
2172 // Get the previous saved visible states.
2173 return set_field('course_modules', 'visible', $cm->visibleold, 'id', $id);
2176 return set_field("course_modules", "visible", $visible, "id", $id);
2180 * Delete a course module and any associated data at the course level (events)
2181 * Until 1.5 this function simply marked a deleted flag ... now it
2182 * deletes it completely.
2185 function delete_course_module($id) {
2186 global $CFG;
2187 require_once($CFG->libdir.'/gradelib.php');
2189 if (!$cm = get_record('course_modules', 'id', $id)) {
2190 return true;
2192 $modulename = get_field('modules', 'name', 'id', $cm->module);
2193 //delete events from calendar
2194 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
2195 foreach($events as $event) {
2196 delete_event($event->id);
2199 //delete grade items, outcome items and grades attached to modules
2200 if ($grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2201 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course))) {
2202 foreach ($grade_items as $grade_item) {
2203 $grade_item->delete('moddelete');
2207 return delete_records('course_modules', 'id', $cm->id);
2210 function delete_mod_from_section($mod, $section) {
2212 if ($section = get_record("course_sections", "id", "$section") ) {
2214 $modarray = explode(",", $section->sequence);
2216 if ($key = array_keys ($modarray, $mod)) {
2217 array_splice($modarray, $key[0], 1);
2218 $newsequence = implode(",", $modarray);
2219 return set_field("course_sections", "sequence", $newsequence, "id", $section->id);
2220 } else {
2221 return false;
2225 return false;
2228 function move_section($course, $section, $move) {
2229 /// Moves a whole course section up and down within the course
2230 global $USER;
2232 if (!$move) {
2233 return true;
2236 $sectiondest = $section + $move;
2238 if ($sectiondest > $course->numsections or $sectiondest < 1) {
2239 return false;
2242 if (!$sectionrecord = get_record("course_sections", "course", $course->id, "section", $section)) {
2243 return false;
2246 if (!$sectiondestrecord = get_record("course_sections", "course", $course->id, "section", $sectiondest)) {
2247 return false;
2250 if (!set_field("course_sections", "section", $sectiondest, "id", $sectionrecord->id)) {
2251 return false;
2253 if (!set_field("course_sections", "section", $section, "id", $sectiondestrecord->id)) {
2254 return false;
2256 // if the focus is on the section that is being moved, then move the focus along
2257 if (isset($USER->display[$course->id]) and ($USER->display[$course->id] == $section)) {
2258 course_set_display($course->id, $sectiondest);
2261 // Check for duplicates and fix order if needed.
2262 // There is a very rare case that some sections in the same course have the same section id.
2263 $sections = get_records_select('course_sections', "course = $course->id", 'section ASC');
2264 $n = 0;
2265 foreach ($sections as $section) {
2266 if ($section->section != $n) {
2267 if (!set_field('course_sections', 'section', $n, 'id', $section->id)) {
2268 return false;
2271 $n++;
2273 return true;
2277 function moveto_module($mod, $section, $beforemod=NULL) {
2278 /// All parameters are objects
2279 /// Move the module object $mod to the specified $section
2280 /// If $beforemod exists then that is the module
2281 /// before which $modid should be inserted
2283 /// Remove original module from original section
2285 if (! delete_mod_from_section($mod->id, $mod->section)) {
2286 notify("Could not delete module from existing section");
2289 /// Update module itself if necessary
2291 if ($mod->section != $section->id) {
2292 $mod->section = $section->id;
2293 if (!update_record("course_modules", $mod)) {
2294 return false;
2296 // if moving to a hidden section then hide module
2297 if (!$section->visible) {
2298 set_coursemodule_visible($mod->id, 0);
2302 /// Add the module into the new section
2304 $mod->course = $section->course;
2305 $mod->section = $section->section; // need relative reference
2306 $mod->coursemodule = $mod->id;
2308 if (! add_mod_to_section($mod, $beforemod)) {
2309 return false;
2312 return true;
2316 function make_editing_buttons($mod, $absolute=false, $moveselect=true, $indent=-1, $section=-1) {
2317 global $CFG, $USER;
2319 static $str;
2320 static $sesskey;
2322 $modcontext = get_context_instance(CONTEXT_MODULE, $mod->id);
2323 // no permission to edit
2324 if (!has_capability('moodle/course:manageactivities', $modcontext)) {
2325 return false;
2328 if (!isset($str)) {
2329 $str->delete = get_string("delete");
2330 $str->move = get_string("move");
2331 $str->moveup = get_string("moveup");
2332 $str->movedown = get_string("movedown");
2333 $str->moveright = get_string("moveright");
2334 $str->moveleft = get_string("moveleft");
2335 $str->update = get_string("update");
2336 $str->duplicate = get_string("duplicate");
2337 $str->hide = get_string("hide");
2338 $str->show = get_string("show");
2339 $str->clicktochange = get_string("clicktochange");
2340 $str->forcedmode = get_string("forcedmode");
2341 $str->groupsnone = get_string("groupsnone");
2342 $str->groupsseparate = get_string("groupsseparate");
2343 $str->groupsvisible = get_string("groupsvisible");
2344 $sesskey = sesskey();
2347 if ($section >= 0) {
2348 $section = '&amp;sr='.$section; // Section return
2349 } else {
2350 $section = '';
2353 if ($absolute) {
2354 $path = $CFG->wwwroot.'/course';
2355 } else {
2356 $path = '.';
2359 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
2360 if ($mod->visible) {
2361 $hideshow = '<a class="editing_hide" title="'.$str->hide.'" href="'.$path.'/mod.php?hide='.$mod->id.
2362 '&amp;sesskey='.$sesskey.$section.'"><img'.
2363 ' src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" '.
2364 ' alt="'.$str->hide.'" /></a>'."\n";
2365 } else {
2366 $hideshow = '<a class="editing_show" title="'.$str->show.'" href="'.$path.'/mod.php?show='.$mod->id.
2367 '&amp;sesskey='.$sesskey.$section.'"><img'.
2368 ' src="'.$CFG->pixpath.'/t/show.gif" class="iconsmall" '.
2369 ' alt="'.$str->show.'" /></a>'."\n";
2372 if ($mod->groupmode !== false) {
2373 if ($mod->groupmode == SEPARATEGROUPS) {
2374 $grouptitle = $str->groupsseparate;
2375 $groupclass = 'editing_groupsseparate';
2376 $groupimage = $CFG->pixpath.'/t/groups.gif';
2377 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=0&amp;sesskey='.$sesskey;
2378 } else if ($mod->groupmode == VISIBLEGROUPS) {
2379 $grouptitle = $str->groupsvisible;
2380 $groupclass = 'editing_groupsvisible';
2381 $groupimage = $CFG->pixpath.'/t/groupv.gif';
2382 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=1&amp;sesskey='.$sesskey;
2383 } else {
2384 $grouptitle = $str->groupsnone;
2385 $groupclass = 'editing_groupsnone';
2386 $groupimage = $CFG->pixpath.'/t/groupn.gif';
2387 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=2&amp;sesskey='.$sesskey;
2389 if ($mod->groupmodelink) {
2390 $groupmode = '<a class="'.$groupclass.'" title="'.$grouptitle.' ('.$str->clicktochange.')" href="'.$grouplink.'">'.
2391 '<img src="'.$groupimage.'" class="iconsmall" '.
2392 'alt="'.$grouptitle.'" /></a>';
2393 } else {
2394 $groupmode = '<img title="'.$grouptitle.' ('.$str->forcedmode.')" '.
2395 ' src="'.$groupimage.'" class="iconsmall" '.
2396 'alt="'.$grouptitle.'" />';
2398 } else {
2399 $groupmode = "";
2402 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $mod->course))) {
2403 if ($moveselect) {
2404 $move = '<a class="editing_move" title="'.$str->move.'" href="'.$path.'/mod.php?copy='.$mod->id.
2405 '&amp;sesskey='.$sesskey.$section.'"><img'.
2406 ' src="'.$CFG->pixpath.'/t/move.gif" class="iconsmall" '.
2407 ' alt="'.$str->move.'" /></a>'."\n";
2408 } else {
2409 $move = '<a class="editing_moveup" title="'.$str->moveup.'" href="'.$path.'/mod.php?id='.$mod->id.
2410 '&amp;move=-1&amp;sesskey='.$sesskey.$section.'"><img'.
2411 ' src="'.$CFG->pixpath.'/t/up.gif" class="iconsmall" '.
2412 ' alt="'.$str->moveup.'" /></a>'."\n".
2413 '<a class="editing_movedown" title="'.$str->movedown.'" href="'.$path.'/mod.php?id='.$mod->id.
2414 '&amp;move=1&amp;sesskey='.$sesskey.$section.'"><img'.
2415 ' src="'.$CFG->pixpath.'/t/down.gif" class="iconsmall" '.
2416 ' alt="'.$str->movedown.'" /></a>'."\n";
2418 } else {
2419 $move = '';
2422 $leftright = '';
2423 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $mod->course))) {
2425 if (right_to_left()) { // Exchange arrows on RTL
2426 $rightarrow = 'left.gif';
2427 $leftarrow = 'right.gif';
2428 } else {
2429 $rightarrow = 'right.gif';
2430 $leftarrow = 'left.gif';
2433 if ($indent > 0) {
2434 $leftright .= '<a class="editing_moveleft" title="'.$str->moveleft.'" href="'.$path.'/mod.php?id='.$mod->id.
2435 '&amp;indent=-1&amp;sesskey='.$sesskey.$section.'"><img'.
2436 ' src="'.$CFG->pixpath.'/t/'.$leftarrow.'" class="iconsmall" '.
2437 ' alt="'.$str->moveleft.'" /></a>'."\n";
2439 if ($indent >= 0) {
2440 $leftright .= '<a class="editing_moveright" title="'.$str->moveright.'" href="'.$path.'/mod.php?id='.$mod->id.
2441 '&amp;indent=1&amp;sesskey='.$sesskey.$section.'"><img'.
2442 ' src="'.$CFG->pixpath.'/t/'.$rightarrow.'" class="iconsmall" '.
2443 ' alt="'.$str->moveright.'" /></a>'."\n";
2447 return '<span class="commands">'."\n".$leftright.$move.
2448 '<a class="editing_update" title="'.$str->update.'" href="'.$path.'/mod.php?update='.$mod->id.
2449 '&amp;sesskey='.$sesskey.$section.'"><img'.
2450 ' src="'.$CFG->pixpath.'/t/edit.gif" class="iconsmall" '.
2451 ' alt="'.$str->update.'" /></a>'."\n".
2452 '<a class="editing_delete" title="'.$str->delete.'" href="'.$path.'/mod.php?delete='.$mod->id.
2453 '&amp;sesskey='.$sesskey.$section.'"><img'.
2454 ' src="'.$CFG->pixpath.'/t/delete.gif" class="iconsmall" '.
2455 ' alt="'.$str->delete.'" /></a>'."\n".$hideshow.$groupmode."\n".'</span>';
2459 * given a course object with shortname & fullname, this function will
2460 * truncate the the number of chars allowed and add ... if it was too long
2462 function course_format_name ($course,$max=100) {
2464 $str = $course->shortname.': '. $course->fullname;
2465 if (strlen($str) <= $max) {
2466 return $str;
2468 else {
2469 return substr($str,0,$max-3).'...';
2474 * This function will return true if the given course is a child course at all
2476 function course_in_meta ($course) {
2477 return record_exists("course_meta","child_course",$course->id);
2482 * Print standard form elements on module setup forms in mod/.../mod.html
2484 function print_standard_coursemodule_settings($form, $features=null) {
2485 if (! $course = get_record('course', 'id', $form->course)) {
2486 error("This course doesn't exist");
2488 print_groupmode_setting($form, $course);
2489 if (!empty($features->groupings)) {
2490 print_grouping_settings($form, $course);
2492 print_visible_setting($form, $course);
2496 * Print groupmode form element on module setup forms in mod/.../mod.html
2498 function print_groupmode_setting($form, $course=NULL) {
2500 if (empty($course)) {
2501 if (! $course = get_record('course', 'id', $form->course)) {
2502 error("This course doesn't exist");
2505 if ($form->coursemodule) {
2506 if (! $cm = get_record('course_modules', 'id', $form->coursemodule)) {
2507 error("This course module doesn't exist");
2509 $groupmode = groups_get_activity_groupmode($cm);
2510 } else {
2511 $cm = null;
2512 $groupmode = groups_get_course_groupmode($course);
2514 if ($course->groupmode or (!$course->groupmodeforce)) {
2515 echo '<tr valign="top">';
2516 echo '<td align="right"><b>'.get_string('groupmode').':</b></td>';
2517 echo '<td align="left">';
2518 $choices = array();
2519 $choices[NOGROUPS] = get_string('groupsnone');
2520 $choices[SEPARATEGROUPS] = get_string('groupsseparate');
2521 $choices[VISIBLEGROUPS] = get_string('groupsvisible');
2522 choose_from_menu($choices, 'groupmode', $groupmode, '', '', 0, false, $course->groupmodeforce);
2523 helpbutton('groupmode', get_string('groupmode'));
2524 echo '</td></tr>';
2529 * Print groupmode form element on module setup forms in mod/.../mod.html
2531 function print_grouping_settings($form, $course=NULL) {
2533 if (empty($course)) {
2534 if (! $course = get_record('course', 'id', $form->course)) {
2535 error("This course doesn't exist");
2538 if ($form->coursemodule) {
2539 if (! $cm = get_record('course_modules', 'id', $form->coursemodule)) {
2540 error("This course module doesn't exist");
2542 } else {
2543 $cm = null;
2546 $groupings = get_records_menu('groupings', 'courseid', $course->id, 'name', 'id, name');
2547 if (!empty($groupings)) {
2548 echo '<tr valign="top">';
2549 echo '<td align="right"><b>'.get_string('grouping', 'group').':</b></td>';
2550 echo '<td align="left">';
2552 $groupings;
2553 $groupingid = isset($cm->groupingid) ? $cm->groupingid : 0;
2555 choose_from_menu($groupings, 'groupingid', $groupingid, get_string('none'), '', 0, false);
2556 echo '</td></tr>';
2558 $checked = empty($cm->groupmembersonly) ? '':'checked="checked"';
2559 echo '<tr valign="top">';
2560 echo '<td align="right"><b>'.get_string('groupmembersonly', 'group').':</b></td>';
2561 echo '<td align="left">';
2562 echo "<input type=\"checkbox\" name=\"groupmembersonly\" value=\"1\" $checked />";
2563 echo '</td></tr>';
2569 * Print visibility setting form element on module setup forms in mod/.../mod.html
2571 function print_visible_setting($form, $course=NULL) {
2572 if (empty($course)) {
2573 if (! $course = get_record('course', 'id', $form->course)) {
2574 error("This course doesn't exist");
2577 if ($form->coursemodule) {
2578 $visible = get_field('course_modules', 'visible', 'id', $form->coursemodule);
2579 } else {
2580 $visible = true;
2583 if ($form->mode == 'add') { // in this case $form->section is the section number, not the id
2584 $hiddensection = !get_field('course_sections', 'visible', 'section', $form->section, 'course', $form->course);
2585 } else {
2586 $hiddensection = !get_field('course_sections', 'visible', 'id', $form->section);
2588 if ($hiddensection) {
2589 $visible = false;
2592 echo '<tr valign="top">';
2593 echo '<td align="right"><b>'.get_string('visible', '').':</b></td>';
2594 echo '<td align="left">';
2595 unset($choices);
2596 $choices[1] = get_string('show');
2597 $choices[0] = get_string('hide');
2598 choose_from_menu($choices, 'visible', $visible, '', '', 0, false, $hiddensection);
2599 echo '</td></tr>';
2602 function update_restricted_mods($course,$mods) {
2603 delete_records("course_allowed_modules","course",$course->id);
2604 if (empty($course->restrictmodules)) {
2605 return;
2607 else {
2608 foreach ($mods as $mod) {
2609 if ($mod == 0)
2610 continue; // this is the 'allow none' option
2611 $am->course = $course->id;
2612 $am->module = $mod;
2613 insert_record("course_allowed_modules",$am);
2619 * This function will take an int (module id) or a string (module name)
2620 * and return true or false, whether it's allowed in the given course (object)
2621 * $mod is not allowed to be an object, as the field for the module id is inconsistent
2622 * depending on where in the code it's called from (sometimes $mod->id, sometimes $mod->module)
2625 function course_allowed_module($course,$mod) {
2626 if (empty($course->restrictmodules)) {
2627 return true;
2630 // i am not sure this capability is correct
2631 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
2632 return true;
2634 if (is_numeric($mod)) {
2635 $modid = $mod;
2636 } else if (is_string($mod)) {
2637 if ($mod = get_field("modules","id","name",$mod))
2638 $modid = $mod;
2640 if (empty($modid)) {
2641 return false;
2643 return (record_exists("course_allowed_modules","course",$course->id,"module",$modid));
2646 /***
2647 *** Efficiently moves many courses around while maintaining
2648 *** sortorder in order.
2650 *** $courseids is an array of course ids
2654 function move_courses ($courseids, $categoryid) {
2656 global $CFG;
2658 if (!empty($courseids)) {
2660 $courseids = array_reverse($courseids);
2662 foreach ($courseids as $courseid) {
2664 if (! $course = get_record("course", "id", $courseid)) {
2665 notify("Error finding course $courseid");
2666 } else {
2667 // figure out a sortorder that we can use in the destination category
2668 $sortorder = get_field_sql('SELECT MIN(sortorder)-1 AS min
2669 FROM ' . $CFG->prefix . 'course WHERE category=' . $categoryid);
2670 if ($sortorder === false) {
2671 // the category is empty
2672 // rather than let the db default to 0
2673 // set it to > 100 and avoid extra work in fix_coursesortorder()
2674 $sortorder = 200;
2675 } else if ($sortorder < 10) {
2676 fix_course_sortorder($categoryid);
2679 $course->category = $categoryid;
2680 $course->sortorder = $sortorder;
2681 $course->fullname = addslashes($course->fullname);
2682 $course->shortname = addslashes($course->shortname);
2683 $course->summary = addslashes($course->summary);
2684 $course->password = addslashes($course->password);
2685 $course->teacher = addslashes($course->teacher);
2686 $course->teachers = addslashes($course->teachers);
2687 $course->student = addslashes($course->student);
2688 $course->students = addslashes($course->students);
2690 if (!update_record('course', $course)) {
2691 notify("An error occurred - course not moved!");
2694 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2695 $newparent = get_context_instance(CONTEXT_COURSECAT, $course->category);
2696 context_moved($context, $newparent);
2699 fix_course_sortorder();
2701 return true;
2704 /***
2705 *** Efficiently moves a category - NOTE that this can have
2706 *** a huge impact access-control-wise...
2710 function move_category ($category, $newparentcat) {
2712 global $CFG;
2714 $context = get_context_instance(CONTEXT_COURSECAT, $category->id);
2716 if (empty($newparentcat->id)) {
2717 if (!set_field('course_categories', 'parent', 0, 'id', $category->id)) {
2718 return false;
2720 $newparent = get_context_instance(CONTEXT_SYSTEM);
2721 } else {
2722 if (!set_field('course_categories', 'parent', $newparentcat->id, 'id', $category->id)) {
2723 return false;
2725 $newparent = get_context_instance(CONTEXT_COURSECAT, $newparentcat->id);
2728 context_moved($context, $newparent);
2730 // The most effective thing would be to find the common parent,
2731 // until then, do it sitewide...
2732 fix_course_sortorder();
2735 return true;
2739 * @param string $format Course format ID e.g. 'weeks'
2740 * @return Name that the course format prefers for sections
2742 function get_section_name($format) {
2743 $sectionname = get_string("name$format","format_$format");
2744 if($sectionname == "[[name$format]]") {
2745 $sectionname = get_string("name$format");
2747 return $sectionname;
2751 * Can the current user delete this course?
2752 * @param int $courseid
2753 * @return boolean
2755 * Exception here to fix MDL-7796.
2757 * FIXME
2758 * Course creators who can manage activities in the course
2759 * shoule be allowed to delete the course. We do it this
2760 * way because we need a quick fix to bring the functionality
2761 * in line with what we had pre-roles. We can't give the
2762 * default course creator role moodle/course:delete at
2763 * CONTEXT_SYSTEM level because this will allow them to
2764 * delete any course in the site. So we hard code this here
2765 * for now.
2767 * @author vyshane AT gmail.com
2769 function can_delete_course($courseid) {
2771 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2773 return ( has_capability('moodle/course:delete', $context)
2774 || (has_capability('moodle/legacy:coursecreator', $context)
2775 && has_capability('moodle/course:manageactivities', $context)) );
2780 * Create a course and either return a $course object or false
2782 * @param object $data - all the data needed for an entry in the 'course' table
2784 function create_course($data) {
2785 global $CFG, $USER;
2787 // preprocess allowed mods
2788 $allowedmods = empty($data->allowedmods) ? array() : $data->allowedmods;
2789 unset($data->allowedmods);
2790 if (!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
2791 if ($CFG->restrictmodulesfor == 'all') {
2792 $data->restrictmodules = 1;
2793 } else {
2794 $data->restrictmodules = 0;
2798 $data->timecreated = time();
2800 // place at beginning of category
2801 fix_course_sortorder();
2802 $data->sortorder = get_field_sql("SELECT min(sortorder)-1 FROM {$CFG->prefix}course WHERE category=$data->category");
2803 if (empty($data->sortorder)) {
2804 $data->sortorder = 100;
2807 if ($newcourseid = insert_record('course', $data)) { // Set up new course
2809 $course = get_record('course', 'id', $newcourseid);
2811 // Setup the blocks
2812 $page = page_create_object(PAGE_COURSE_VIEW, $course->id);
2813 blocks_repopulate_page($page); // Return value not checked because you can always edit later
2815 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
2816 update_restricted_mods($course, $allowedmods);
2819 $section = new object();
2820 $section->course = $course->id; // Create a default section.
2821 $section->section = 0;
2822 $section->id = insert_record('course_sections', $section);
2824 fix_course_sortorder();
2826 add_to_log(SITEID, 'course', 'new', 'view.php?id='.$course->id, $data->fullname.' (ID '.$course->id.')');
2828 return $course;
2831 return false; // error
2836 * Update a course and return true or false
2838 * @param object $data - all the data needed for an entry in the 'course' table
2840 function update_course($data) {
2841 global $USER, $CFG;
2843 // preprocess allowed mods
2844 $allowedmods = empty($data->allowedmods) ? array() : $data->allowedmods;
2845 unset($data->allowedmods);
2846 if (!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
2847 unset($data->restrictmodules);
2850 $movecat = false;
2851 $oldcourse = get_record('course', 'id', $data->id); // should not fail, already tested above
2852 if (!has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $oldcourse->category))
2853 or !has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $data->category))) {
2854 // can not move to new category, keep the old one
2855 unset($data->category);
2856 } elseif ($oldcourse->category != $data->category) {
2857 $movecat = true;
2860 // Update with the new data
2861 if (update_record('course', $data)) {
2863 $course = get_record('course', 'id', $data->id);
2865 add_to_log($course->id, "course", "update", "edit.php?id=$course->id", $course->id);
2867 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
2868 update_restricted_mods($course, $allowedmods);
2871 if ($movecat) {
2872 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2873 $newparent = get_context_instance(CONTEXT_COURSECAT, $course->category);
2874 context_moved($context, $newparent);
2877 fix_course_sortorder();
2879 // Test for and remove blocks which aren't appropriate anymore
2880 $page = page_create_object(PAGE_COURSE_VIEW, $course->id);
2881 blocks_remove_inappropriate($page);
2883 // put custom role names into db
2884 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2886 foreach ($data as $dname => $dvalue) {
2888 // is this the right param?
2889 $dvalue = clean_param($dvalue, PARAM_NOTAGS);
2891 if (!strstr($dname, 'role_')) {
2892 continue;
2895 $dt = explode('_', $dname);
2896 $roleid = $dt[1];
2897 // make up our mind whether we want to delete, update or insert
2899 if (empty($dvalue)) {
2901 delete_records('role_names', 'contextid', $context->id, 'roleid', $roleid);
2903 } else if ($t = get_record('role_names', 'contextid', $context->id, 'roleid', $roleid)) {
2905 $t->text = $dvalue;
2906 update_record('role_names', $t);
2908 } else {
2910 $t->contextid = $context->id;
2911 $t->roleid = $roleid;
2912 $t->text = $dvalue;
2913 insert_record('role_names', $t);
2918 return true;
2922 return false;