Merged fixes from HEAD, bug MDL-6791
[moodle.git] / course / lib.php
blob1957a8df74500bb0389d7672de856d5d8a2a7f30
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
11 define('COURSE_MAX_LOGS_PER_PAGE', 1000); // records
13 define('COURSE_LIVELOG_REFRESH', 60); // Seconds
15 define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds
17 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10); // courses
19 define('COURSE_MAX_COURSES_PER_DROPDOWN',1000); // max courses in log dropdown before switching to optional
21 define('COURSE_MAX_USERS_PER_DROPDOWN',1000); // max users in log dropdown before switching to optional
23 define("FRONTPAGENEWS", 0);
24 define("FRONTPAGECOURSELIST", 1);
25 define("FRONTPAGECATEGORYNAMES", 2);
26 define("FRONTPAGETOPICONLY", 3);
27 define("FRONTPAGECATEGORYCOMBO", 4);
29 define("FRONTPAGECOURSELIMIT", 200); // maximum number of courses displayed on the frontpage
31 function print_recent_selector_form($course, $advancedfilter=0, $selecteduser=0, $selecteddate="lastlogin",
32 $mod="", $modid="activity/All", $modaction="", $selectedgroup="", $selectedsort="default") {
34 global $USER, $CFG;
36 $isteacher = isteacher($course->id);
37 if ($advancedfilter) {
39 // Get all the possible users
40 $users = array();
42 if ($courseusers = get_course_users($course->id, '', '', 'u.id, u.firstname, u.lastname')) {
43 foreach ($courseusers as $courseuser) {
44 $users[$courseuser->id] = fullname($courseuser, $isteacher);
47 if ($guest = get_guest()) {
48 $users[$guest->id] = fullname($guest);
51 if (isadmin()) {
52 if ($ccc = get_records("course", "", "", "fullname")) {
53 foreach ($ccc as $cc) {
54 if ($cc->category) {
55 $courses["$cc->id"] = "$cc->fullname";
56 } else {
57 $courses["$cc->id"] = " $cc->fullname (Site)";
61 asort($courses);
64 $activities = array();
66 $selectedactivity = $modid;
68 if ($modinfo = unserialize($course->modinfo)) {
69 $section = 0;
70 if ($course->format == 'weeks') { // Body
71 $strsection = get_string("week");
72 } else {
73 $strsection = get_string("topic");
76 $activities["activity/All"] = "All activities";
77 $activities["activity/Assignments"] = "All assignments";
78 $activities["activity/Chats"] = "All chats";
79 $activities["activity/Forums"] = "All forums";
80 $activities["activity/Quizzes"] = "All quizzes";
81 $activities["activity/Workshops"] = "All workshops";
83 $activities["section/individual"] = "------------- Individual Activities --------------";
85 foreach ($modinfo as $mod) {
86 if ($mod->mod == "label") {
87 continue;
89 if (!$mod->visible and !$isteacher) {
90 continue;
93 if ($mod->section > 0 and $section <> $mod->section) {
94 $activities["section/$mod->section"] = "-------------- $strsection $mod->section --------------";
96 $section = $mod->section;
97 $mod->name = strip_tags(format_string(urldecode($mod->name),true));
98 if (strlen($mod->name) > 55) {
99 $mod->name = substr($mod->name, 0, 50)."...";
101 if (!$mod->visible) {
102 $mod->name = "(".$mod->name.")";
104 $activities["$mod->cm"] = $mod->name;
106 if ($mod->cm == $modid) {
107 $selectedactivity = "$mod->cm";
112 $strftimedate = get_string("strftimedate");
113 $strftimedaydate = get_string("strftimedaydate");
115 asort($users);
117 // Get all the possible dates
118 // Note that we are keeping track of real (GMT) time and user time
119 // User time is only used in displays - all calcs and passing is GMT
121 $timenow = time(); // GMT
123 // What day is it now for the user, and when is midnight that day (in GMT).
124 $timemidnight = $today = usergetmidnight($timenow);
126 $dates = array();
127 $dates["$USER->lastlogin"] = get_string("lastlogin").", ".userdate($USER->lastlogin, $strftimedate);
128 $dates["$timemidnight"] = get_string("today").", ".userdate($timenow, $strftimedate);
130 if (!$course->startdate or ($course->startdate > $timenow)) {
131 $course->startdate = $course->timecreated;
134 $numdates = 1;
135 while ($timemidnight > $course->startdate and $numdates < 365) {
136 $timemidnight = $timemidnight - 86400;
137 $timenow = $timenow - 86400;
138 $dates["$timemidnight"] = userdate($timenow, $strftimedaydate);
139 $numdates++;
142 if ($selecteddate === "lastlogin") {
143 $selecteddate = $USER->lastlogin;
146 echo '<form action="recent.php" method="get">';
147 echo '<input type="hidden" name="chooserecent" value="1" />';
148 echo "<center>";
149 echo "<table>";
151 if (isadmin()) {
152 echo "<tr><td><b>" . get_string("courses") . "</b></td><td>";
153 choose_from_menu ($courses, "id", $course->id, "");
154 echo "</td></tr>";
155 } else {
156 echo '<input type="hidden" name="id" value="'.$course->id.'" />';
159 $sortfields = array("default" => get_string("bycourseorder"),"dateasc" => get_string("datemostrecentlast"), "datedesc" => get_string("datemostrecentfirst"));
161 echo "<tr><td><b>" . get_string("participants") . "</b></td><td>";
162 choose_from_menu ($users, "user", $selecteduser, get_string("allparticipants") );
163 echo "</td>";
165 echo '<td align="right"><b>' . get_string("since") . '</b></td><td>';
166 choose_from_menu ($dates, "date", $selecteddate, get_string("alldays"));
167 echo "</td></tr>";
169 echo "<tr><td><b>" . get_string("activities") . "</b></td><td>";
170 choose_from_menu ($activities, "modid", $selectedactivity, "");
171 echo "</td>";
173 echo '<td align="right"><b>' . get_string("sortby") . "</b></td><td>";
174 choose_from_menu ($sortfields, "sortby", $selectedsort, "");
175 echo "</td></tr>";
177 echo '<tr>';
179 $groupmode = groupmode($course);
181 if ($groupmode == VISIBLEGROUPS or ($groupmode and isteacheredit($course->id))) {
182 if ($groups = get_records_menu("groups", "courseid", $course->id, "name ASC", "id,name")) {
183 echo '<td><b>';
184 if ($groupmode == VISIBLEGROUPS) {
185 print_string('groupsvisible');
186 } else {
187 print_string('groupsseparate');
189 echo ':</b></td><td>';
190 choose_from_menu($groups, "selectedgroup", $selectedgroup, get_string("allgroups"), "", "");
191 echo '</td>';
196 echo '<td colspan="2" align="right">';
197 echo '<input type="submit" value="'.get_string('showrecent').'" />';
198 echo "</td></tr>";
200 echo "</table>";
202 $advancedlink = "<a href=\"$CFG->wwwroot/course/recent.php?id=$course->id&amp;advancedfilter=0\">" . get_string("normalfilter") . "</a>";
203 print_heading($advancedlink);
204 echo "</center>";
205 echo "</form>";
207 } else {
209 $day_list = array("1","7","14","21","30");
210 $strsince = get_string("since");
211 $strlastlogin = get_string("lastlogin");
212 $strday = get_string("day");
213 $strdays = get_string("days");
215 $heading = "";
216 foreach ($day_list as $count) {
217 if ($count == "1") {
218 $day = $strday;
219 } else {
220 $day = $strdays;
222 $tmpdate = time() - ($count * 3600 * 24);
223 $heading = $heading .
224 "<a href=\"$CFG->wwwroot/course/recent.php?id=$course->id&amp;date=$tmpdate\"> $count $day</a> | ";
227 $heading = $strsince . ": <a href=\"$CFG->wwwroot/course/recent.php?id=$course->id\">$strlastlogin</a>" . " | " . $heading;
228 print_heading($heading);
230 $advancedlink = "<a href=\"$CFG->wwwroot/course/recent.php?id=$course->id&amp;advancedfilter=1\">" . get_string("advancedfilter") . "</a>";
231 print_heading($advancedlink);
238 function make_log_url($module, $url) {
239 switch ($module) {
240 case 'user':
241 case 'course':
242 case 'file':
243 case 'login':
244 case 'lib':
245 case 'admin':
246 case 'message':
247 case 'calendar':
248 case 'blog':
249 return "/$module/$url";
250 break;
251 case 'upload':
252 return $url;
253 break;
254 case 'library':
255 case '':
256 return '/';
257 break;
258 default:
259 return "/mod/$module/$url";
260 break;
264 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
265 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
267 // It is assumed that $date is the GMT time of midnight for that day,
268 // and so the next 86400 seconds worth of logs are printed.
270 global $CFG, $db;
272 /// Setup for group handling.
273 $isteacher = isteacher($course->id);
274 $isteacheredit = isteacheredit($course->id);
276 /// If the group mode is separate, and this user does not have editing privileges,
277 /// then only the user's group can be viewed.
278 if ($course->groupmode == SEPARATEGROUPS and !$isteacheredit) {
279 $groupid = get_current_group($course->id);
281 /// If this course doesn't have groups, no groupid can be specified.
282 else if (!$course->groupmode) {
283 $groupid = 0;
286 $joins = array();
288 if ($course->id != SITEID || $modid != 0) {
289 $joins[] = "l.course='$course->id'";
291 if ($course->id == SITEID) {
292 $courses[0] = '';
293 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
294 foreach ($ccc as $cc) {
295 $courses[$cc->id] = $cc->shortname;
300 if ($modname) {
301 $joins[] = "l.module = '$modname'";
304 if ('site_errors' === $modid) {
305 $joins[] = "( l.action='error' OR l.action='infected' )";
306 } else if ($modid) {
307 $joins[] = "l.cmid = '$modid'";
310 if ($modaction) {
311 $firstletter = substr($modaction, 0, 1);
312 if (ctype_alpha($firstletter)) {
313 $joins[] = "lower(l.action) LIKE '%" . strtolower($modaction) . "%'";
314 } else if ($firstletter == '-') {
315 $joins[] = "lower(l.action) NOT LIKE '%" . strtolower(substr($modaction, 1)) . "%'";
319 /// Getting all members of a group.
320 if ($groupid and !$user) {
321 if ($gusers = get_records('groups_members', 'groupid', $groupid)) {
322 $first = true;
323 foreach($gusers as $guser) {
324 if ($first) {
325 $gselect = '(l.userid='.$guser->userid;
326 $first = false;
328 else {
329 $gselect .= ' OR l.userid='.$guser->userid;
332 if (!$first) $gselect .= ')';
333 $joins[] = $gselect;
336 else if ($user) {
337 $joins[] = "l.userid = '$user'";
340 if ($date) {
341 $enddate = $date + 86400;
342 $joins[] = "l.time > '$date' AND l.time < '$enddate'";
345 $selector = '';
346 for ($i = 0; $i < count($joins); $i++) {
347 $selector .= $joins[$i] . (($i == count($joins)-1) ? " " : " AND ");
351 $totalcount = 0; // Initialise
353 if (!$logs = get_logs($selector, $order, $page*$perpage, $perpage, $totalcount)) {
354 notify("No logs found!");
355 print_footer($course);
356 exit;
359 $count=0;
360 $ldcache = array();
361 $tt = getdate(time());
362 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
364 $strftimedatetime = get_string("strftimedatetime");
365 $isteacher = isteacher($course->id);
367 echo "<p align=\"center\">\n";
368 print_string("displayingrecords", "", $totalcount);
369 echo "</p>\n";
372 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
374 echo "<table class=\"logtable\" border=\"0\" align=\"center\" cellpadding=\"3\" cellspacing=\"0\">\n";
375 echo "<tr>";
376 if ($course->id == SITEID) {
377 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
379 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
380 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
381 echo "<th class=\"c3 header\">".get_string('fullname')."</th>\n";
382 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
383 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
384 echo "</tr>\n";
386 $row = 1;
387 foreach ($logs as $log) {
389 $row = ($row + 1) % 2;
391 if (isset($ldcache[$log->module][$log->action])) {
392 $ld = $ldcache[$log->module][$log->action];
393 } else {
394 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
395 $ldcache[$log->module][$log->action] = $ld;
397 if ($ld && !empty($log->info)) {
398 // ugly hack to make sure fullname is shown correctly
399 if (($ld->mtable == 'user') and ($ld->field == 'CONCAT(firstname," ",lastname)')) {
400 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
401 } else {
402 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
406 //Filter log->info
407 $log->info = format_string($log->info);
409 $log->url = strip_tags(urldecode($log->url)); // Some XSS protection
410 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
411 $log->url = str_replace('&', '&amp;', $log->url); /// XHTML compatibility
413 echo '<tr class="r'.$row.'">';
414 if ($course->id == SITEID) {
415 echo "<td class=\"r$row c0\" nowrap=\"nowrap\">\n";
416 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courses[$log->course]."</a>\n";
417 echo "</td>\n";
419 echo "<td class=\"r$row c1\" nowrap=\"nowrap\" align=\"right\">".userdate($log->time, '%a').
420 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
421 echo "<td class=\"r$row c2\" nowrap=\"nowrap\">\n";
422 link_to_popup_window("/iplookup/index.php?ip=$log->ip&amp;user=$log->userid", 'iplookup',$log->ip, 400, 700);
423 echo "</td>\n";
424 $fullname = fullname($log, $isteacher);
425 echo "<td class=\"r$row c3\" nowrap=\"nowrap\">\n";
426 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}&amp;course={$log->course}\">$fullname</a>\n";
427 echo "</td>\n";
428 echo "<td class=\"r$row c4\" nowrap=\"nowrap\">\n";
429 link_to_popup_window( make_log_url($log->module,$log->url), 'fromloglive',"$log->module $log->action", 400, 600);
430 echo "</td>\n";;
431 echo "<td class=\"r$row c5\" nowrap=\"nowrap\">{$log->info}</td>\n";
432 echo "</tr>\n";
434 echo "</table>\n";
436 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
440 function print_log_graph($course, $userid=0, $type="course.png", $date=0) {
441 global $CFG;
442 if (empty($CFG->gdversion)) {
443 echo "(".get_string("gdneed").")";
444 } else {
445 echo '<img src="'.$CFG->wwwroot.'/course/report/log/graph.php?id='.$course->id.
446 '&amp;user='.$userid.'&amp;type='.$type.'&amp;date='.$date.'" alt="" />';
451 function print_overview($courses) {
453 global $CFG, $USER;
456 $htmlarray = array();
457 if ($modules = get_records('modules')) {
458 foreach ($modules as $mod) {
459 if (file_exists(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php')) {
460 require_once(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php');
461 $fname = $mod->name.'_print_overview';
462 if (function_exists($fname)) {
463 $fname($courses,$htmlarray);
469 foreach ($courses as $course) {
470 print_simple_box_start('center', '100%', '', 5, "coursebox");
471 $linkcss = '';
472 if (empty($course->visible)) {
473 $linkcss = 'class="dimmed"';
475 print_heading('<a title="'.$course->fullname.'" '.$linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.$course->fullname.'</a>');
476 if (array_key_exists($course->id,$htmlarray)) {
477 foreach ($htmlarray[$course->id] as $modname => $html) {
478 echo $html;
481 print_simple_box_end();
487 function print_recent_activity($course) {
488 // $course is an object
489 // This function trawls through the logs looking for
490 // anything new since the user's last login
492 global $CFG, $USER, $SESSION;
494 $isteacher = isteacher($course->id);
496 $timestart = time() - COURSE_MAX_RECENT_PERIOD;
498 if (!empty($USER->timeaccess[$course->id])) {
499 if ($USER->timeaccess[$course->id] > $timestart) {
500 $timestart = $USER->timeaccess[$course->id];
504 echo '<div class="activitydate">';
505 echo get_string('activitysince', '', userdate($timestart));
506 echo '</div>';
507 echo '<div class="activityhead">';
509 echo '<a href="'.$CFG->wwwroot.'/course/recent.php?id='.$course->id.'">'.get_string('recentactivityreport').'</a>';
511 echo "</div>\n";
514 // Firstly, have there been any new enrolments?
516 $heading = false;
517 $content = false;
519 $users = get_recent_enrolments($course->id, $timestart);
521 //Accessibility: new users now appear in an <OL> list.
522 if ($users) {
523 echo '<div class="newusers">';
524 if (! $heading) {
525 print_headline(get_string("newusers").':', 3);
526 $heading = true;
527 $content = true;
529 echo "<ol class=\"list\">\n";
530 foreach ($users as $user) {
532 $fullname = fullname($user, $isteacher);
533 echo '<li class="name"><a href="'.$CFG->wwwroot."/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a></li>\n";
535 echo "</ol>\n</div>\n";
538 // Next, have there been any modifications to the course structure?
540 $logs = get_records_select('log', "time > '$timestart' AND course = '$course->id' AND
541 module = 'course' AND action LIKE '% mod'", "time ASC");
543 if ($logs) {
544 foreach ($logs as $key => $log) {
545 $info = split(' ', $log->info);
547 if ($info[0] == 'label') { // Labels are special activities
548 continue;
551 $modname = get_field($info[0], 'name', 'id', $info[1]);
552 //Create a temp valid module structure (course,id)
553 $tempmod->course = $log->course;
554 $tempmod->id = $info[1];
555 //Obtain the visible property from the instance
556 $modvisible = instance_is_visible($info[0],$tempmod);
558 //Only if the mod is visible
559 if ($modvisible) {
560 switch ($log->action) {
561 case 'add mod':
562 $stradded = get_string('added', 'moodle', get_string('modulename', $info[0]));
563 $changelist[$log->info] = array ('operation' => 'add', 'text' => "$stradded:<br /><a href=\"$CFG->wwwroot/course/$log->url\">".format_string($modname,true)."</a>");
564 break;
565 case 'update mod':
566 $strupdated = get_string('updated', 'moodle', get_string('modulename', $info[0]));
567 if (empty($changelist[$log->info])) {
568 $changelist[$log->info] = array ('operation' => 'update', 'text' => "$strupdated:<br /><a href=\"$CFG->wwwroot/course/$log->url\">".format_string($modname,true)."</a>");
570 break;
571 case 'delete mod':
572 if (!empty($changelist[$log->info]['operation']) and
573 $changelist[$log->info]['operation'] == 'add') {
574 $changelist[$log->info] = NULL;
575 } else {
576 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $info[0]));
577 $changelist[$log->info] = array ('operation' => 'delete', 'text' => $strdeleted);
579 break;
585 if (!empty($changelist)) {
586 foreach ($changelist as $changeinfo => $change) {
587 if ($change) {
588 $changes[$changeinfo] = $change;
591 if (isset($changes)){
592 if (count($changes) > 0) {
593 print_headline(get_string('courseupdates').':', 3);
594 $content = true;
595 foreach ($changes as $changeinfo => $change) {
596 echo '<p class="activity">'.$change['text'].'</p>';
602 // Now display new things from each module
604 $mods = get_records('modules', 'visible', '1', 'name', 'id, name');
606 foreach ($mods as $mod) { // Each module gets it's own logs and prints them
607 include_once($CFG->dirroot.'/mod/'.$mod->name.'/lib.php');
608 $print_recent_activity = $mod->name.'_print_recent_activity';
609 if (function_exists($print_recent_activity)) {
610 $modcontent = $print_recent_activity($course, $isteacher, $timestart);
611 if ($modcontent) {
612 $content = true;
617 if (! $content) {
618 echo '<p class="message">'.get_string('nothingnew').'</p>';
623 function get_array_of_activities($courseid) {
624 // For a given course, returns an array of course activity objects
625 // Each item in the array contains he following properties:
626 // cm - course module id
627 // mod - name of the module (eg forum)
628 // section - the number of the section (eg week or topic)
629 // name - the name of the instance
630 // visible - is the instance visible or not
631 // extra - contains extra string to include in any link
633 global $CFG;
635 $mod = array();
637 if (!$rawmods = get_course_mods($courseid)) {
638 return NULL;
641 if ($sections = get_records("course_sections", "course", $courseid, "section ASC")) {
642 foreach ($sections as $section) {
643 if (!empty($section->sequence)) {
644 $sequence = explode(",", $section->sequence);
645 foreach ($sequence as $seq) {
646 if (empty($rawmods[$seq])) {
647 continue;
649 $mod[$seq]->cm = $rawmods[$seq]->id;
650 $mod[$seq]->mod = $rawmods[$seq]->modname;
651 $mod[$seq]->section = $section->section;
652 $mod[$seq]->name = urlencode(get_field($rawmods[$seq]->modname, "name", "id", $rawmods[$seq]->instance));
653 $mod[$seq]->visible = $rawmods[$seq]->visible;
654 $mod[$seq]->extra = "";
656 $modname = $mod[$seq]->mod;
657 $functionname = $modname."_get_coursemodule_info";
659 include_once("$CFG->dirroot/mod/$modname/lib.php");
661 if (function_exists($functionname)) {
662 if ($info = $functionname($rawmods[$seq])) {
663 if (!empty($info->extra)) {
664 $mod[$seq]->extra = $info->extra;
666 if (!empty($info->icon)) {
667 $mod[$seq]->icon = $info->icon;
675 return $mod;
681 function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
682 // Returns a number of useful structures for course displays
684 $mods = NULL; // course modules indexed by id
685 $modnames = NULL; // all course module names (except resource!)
686 $modnamesplural= NULL; // all course module names (plural form)
687 $modnamesused = NULL; // course module names used
689 if ($allmods = get_records("modules")) {
690 foreach ($allmods as $mod) {
691 if ($mod->visible) {
692 $modnames[$mod->name] = get_string("modulename", "$mod->name");
693 $modnamesplural[$mod->name] = get_string("modulenameplural", "$mod->name");
696 asort($modnames);
697 } else {
698 error("No modules are installed!");
701 if ($rawmods = get_course_mods($courseid)) {
702 foreach($rawmods as $mod) { // Index the mods
703 if (empty($modnames[$mod->modname])) {
704 continue;
706 $mods[$mod->id] = $mod;
707 $mods[$mod->id]->modfullname = $modnames[$mod->modname];
708 if ($mod->visible or isteacher($courseid)) {
709 $modnamesused[$mod->modname] = $modnames[$mod->modname];
712 if ($modnamesused) {
713 asort($modnamesused);
717 unset($modnames['resource']);
718 unset($modnames['label']);
722 function get_all_sections($courseid) {
724 return get_records("course_sections", "course", "$courseid", "section",
725 "section, id, course, summary, sequence, visible");
728 function course_set_display($courseid, $display=0) {
729 global $USER;
731 if (empty($USER->id)) {
732 return false;
735 if ($display == "all" or empty($display)) {
736 $display = 0;
739 if (record_exists("course_display", "userid", $USER->id, "course", $courseid)) {
740 set_field("course_display", "display", $display, "userid", $USER->id, "course", $courseid);
741 } else {
742 $record->userid = $USER->id;
743 $record->course = $courseid;
744 $record->display = $display;
745 if (!insert_record("course_display", $record)) {
746 notify("Could not save your course display!");
750 return $USER->display[$courseid] = $display; // Note: = not ==
753 function set_section_visible($courseid, $sectionnumber, $visibility) {
754 /// For a given course section, markes it visible or hidden,
755 /// and does the same for every activity in that section
757 if ($section = get_record("course_sections", "course", $courseid, "section", $sectionnumber)) {
758 set_field("course_sections", "visible", "$visibility", "id", $section->id);
759 if (!empty($section->sequence)) {
760 $modules = explode(",", $section->sequence);
761 foreach ($modules as $moduleid) {
762 set_coursemodule_visible($moduleid, $visibility, true);
765 rebuild_course_cache($courseid);
770 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%") {
771 /// Prints a section full of activity modules
772 global $CFG, $USER;
774 static $groupbuttons;
775 static $groupbuttonslink;
776 static $isteacher;
777 static $isediting;
778 static $ismoving;
779 static $strmovehere;
780 static $strmovefull;
781 static $strunreadpostsone;
783 static $untracked;
784 static $usetracking;
786 $labelformatoptions = New stdClass;
788 if (!isset($isteacher)) {
789 $groupbuttons = ($course->groupmode or (!$course->groupmodeforce));
790 $groupbuttonslink = (!$course->groupmodeforce);
791 $isteacher = isteacher($course->id);
792 $isediting = isediting($course->id);
793 $ismoving = $isediting && ismoving($course->id);
794 if ($ismoving) {
795 $strmovehere = get_string("movehere");
796 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
798 include_once($CFG->dirroot.'/mod/forum/lib.php');
799 if ($usetracking = forum_tp_can_track_forums()) {
800 $strunreadpostsone = get_string('unreadpostsone', 'forum');
801 $untracked = forum_tp_get_untracked_forums($USER->id, $course->id);
804 $labelformatoptions->noclean = true;
806 $modinfo = unserialize($course->modinfo);
808 //Acccessibility: replace table with list <ul>, but don't output empty list.
809 if (!empty($section->sequence)) {
811 // Fix bug #5027, don't want style=\"width:$width\".
812 echo "<ul class=\"section\">\n";
813 $sectionmods = explode(",", $section->sequence);
815 foreach ($sectionmods as $modnumber) {
816 if (empty($mods[$modnumber])) {
817 continue;
819 $mod = $mods[$modnumber];
821 if ($mod->visible or $isteacher) {
822 echo '<li class="activity '.$mod->modname.'">';
823 if ($ismoving) {
824 if ($mod->id == $USER->activitycopy) {
825 continue;
827 echo '<a title="'.$strmovefull.'"'.
828 ' href="'.$CFG->wwwroot.'/course/mod.php?moveto='.$mod->id.'&amp;sesskey='.$USER->sesskey.'">'.
829 '<img class="movetarget" src="'.$CFG->pixpath.'/movehere.gif" '.
830 ' alt="'.$strmovehere.'" /></a><br />
833 $instancename = urldecode($modinfo[$modnumber]->name);
834 $instancename = format_string($instancename, true, $course->id);
836 if (!empty($modinfo[$modnumber]->extra)) {
837 $extra = urldecode($modinfo[$modnumber]->extra);
838 } else {
839 $extra = "";
842 if (!empty($modinfo[$modnumber]->icon)) {
843 $icon = "$CFG->pixpath/".urldecode($modinfo[$modnumber]->icon);
844 } else {
845 $icon = "$CFG->modpixpath/$mod->modname/icon.gif";
848 if ($mod->indent) {
849 print_spacer(12, 20 * $mod->indent, false);
852 if ($mod->modname == "label") {
853 if (!$mod->visible) {
854 echo "<span class=\"dimmed_text\">";
856 echo format_text($extra, FORMAT_HTML, $labelformatoptions);
857 if (!$mod->visible) {
858 echo "</span>";
861 } else { // Normal activity
862 $linkcss = $mod->visible ? "" : " class=\"dimmed\" ";
863 echo '<img src="'.$icon.'"'.
864 ' class="activityicon" alt="'.$mod->modfullname.'" />'.
865 ' <a title="'.$mod->modfullname.'" '.$linkcss.' '.$extra.
866 ' href="'.$CFG->wwwroot.'/mod/'.$mod->modname.'/view.php?id='.$mod->id.'">'.
867 $instancename.'</a>';
869 if ($usetracking && $mod->modname == 'forum') {
870 $groupmode = groupmode($course, $mod);
871 $groupid = ($groupmode == SEPARATEGROUPS && !isteacheredit($course->id)) ?
872 get_current_group($course->id) : false;
874 if (forum_tp_can_track_forums() && !isset($untracked[$mod->instance])) {
875 $unread = forum_tp_count_forum_unread_posts($USER->id, $mod->instance, $groupid);
876 if ($unread) {
877 echo '<span class="unread"> <a href="'.$CFG->wwwroot.'/mod/forum/view.php?id='.$mod->id.'">';
878 if ($unread == 1) {
879 echo $strunreadpostsone;
880 } else {
881 print_string('unreadpostsnumber', 'forum', $unread);
883 echo '</a> </span>';
888 if ($isediting) {
889 if ($groupbuttons and $mod->modname != 'label' and $mod->modname != 'resource') {
890 if (! $mod->groupmodelink = $groupbuttonslink) {
891 $mod->groupmode = $course->groupmode;
894 } else {
895 $mod->groupmode = false;
897 echo '&nbsp;&nbsp;';
898 echo make_editing_buttons($mod, $absolute, true, $mod->indent, $section->section);
900 echo "</li>\n";
903 } elseif ($ismoving) {
904 echo "<ul class=\"section\">\n";
906 if ($ismoving) {
907 echo '<li><a title="'.$strmovefull.'"'.
908 ' href="'.$CFG->wwwroot.'/course/mod.php?movetosection='.$section->id.'&amp;sesskey='.$USER->sesskey.'">'.
909 '<img class="movetarget" src="'.$CFG->pixpath.'/movehere.gif" '.
910 ' alt="'.$strmovehere.'" /></a></li>
913 if (!empty($section->sequence) || $ismoving) {
914 echo "</ul><!--class='section'-->\n\n";
919 function print_section_add_menus($course, $section, $modnames, $vertical=false, $return=false) {
920 // Prints the menus to add activities and resources
922 global $CFG, $USER;
923 static $straddactivity, $stractivities, $straddresource, $resources;
925 if (!isset($straddactivity)) {
926 $straddactivity = get_string('addactivity');
927 $straddresource = get_string('addresource');
929 /// Standard resource types
930 require_once("$CFG->dirroot/mod/resource/lib.php");
931 $resourceraw = resource_get_resource_types();
933 foreach ($resourceraw as $type => $name) {
934 $resources["resource&amp;type=$type"] = $name;
936 if (course_allowed_module($course,'label')) {
937 $resources['label'] = get_string('resourcetypelabel', 'resource');
941 $output = '<div style="text-align: right">';
942 if (course_allowed_module($course,'resource')) {
943 $resourceallowed = true;
944 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&amp;section=$section&amp;sesskey=$USER->sesskey&amp;add=",
945 $resources, "ressection$section", "", $straddresource, 'resource/types', $straddresource, true);
948 if ($vertical) {
949 $output .= '<div>';
952 // we need to loop through the forms and check to see if we can add them.
953 foreach ($modnames as $key=>$value) {
954 if (!course_allowed_module($course,$key))
955 unset($modnames[$key]);
958 // this is stupid but labels get put into resource, so if resource is hidden and label is not, we're in trouble.
959 if (course_allowed_module($course,'label') && empty($resourceallowed)) {
960 $modnames['label'] = get_string('modulename', 'label');
963 $output .= ' ';
964 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&amp;section=$section&amp;sesskey=$USER->sesskey&amp;add=",
965 $modnames, "section$section", "", $straddactivity, 'mods', $straddactivity, true);
967 if ($vertical) {
968 $output .= '</div>';
971 $output .= '</div>';
973 if ($return) {
974 return $output;
975 } else {
976 echo $output;
980 function rebuild_course_cache($courseid=0) {
981 // Rebuilds the cached list of course activities stored in the database
982 // If a courseid is not specified, then all are rebuilt
984 if ($courseid) {
985 $select = "id = '$courseid'";
986 } else {
987 $select = "";
990 if ($courses = get_records_select("course", $select,'','id,fullname')) {
991 foreach ($courses as $course) {
992 $modinfo = serialize(get_array_of_activities($course->id));
993 if (!set_field("course", "modinfo", $modinfo, "id", $course->id)) {
994 notify("Could not cache module information for course '$course->fullname'!");
1002 function make_categories_list(&$list, &$parents, $category=NULL, $path="") {
1003 /// Given an empty array, this function recursively travels the
1004 /// categories, building up a nice list for display. It also makes
1005 /// an array that list all the parents for each category.
1007 // initialize the arrays if needed
1008 if (!is_array($list)) {
1009 $list = array();
1011 if (!is_array($parents)) {
1012 $parents = array();
1015 if ($category) {
1016 if ($path) {
1017 $path = $path.' / '.$category->name;
1018 } else {
1019 $path = $category->name;
1021 $list[$category->id] = $path;
1022 } else {
1023 $category->id = 0;
1026 if ($categories = get_categories($category->id)) { // Print all the children recursively
1027 foreach ($categories as $cat) {
1028 if (!empty($category->id)) {
1029 if (isset($parents[$category->id])) {
1030 $parents[$cat->id] = $parents[$category->id];
1032 $parents[$cat->id][] = $category->id;
1034 make_categories_list($list, $parents, $cat, $path);
1040 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $files = true) {
1041 /// Recursive function to print out all the categories in a nice format
1042 /// with or without courses included
1043 global $CFG;
1045 if (isset($CFG->max_category_depth) && ($depth >= $CFG->max_category_depth)) {
1046 return;
1049 if (!$displaylist) {
1050 make_categories_list($displaylist, $parentslist);
1053 if ($category) {
1054 if ($category->visible or iscreator()) {
1055 print_category_info($category, $depth, $files);
1056 } else {
1057 return; // Don't bother printing children of invisible categories
1060 } else {
1061 $category->id = "0";
1064 if ($categories = get_categories($category->id)) { // Print all the children recursively
1065 $countcats = count($categories);
1066 $count = 0;
1067 $first = true;
1068 $last = false;
1069 foreach ($categories as $cat) {
1070 $count++;
1071 if ($count == $countcats) {
1072 $last = true;
1074 $up = $first ? false : true;
1075 $down = $last ? false : true;
1076 $first = false;
1078 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1, $files);
1083 // this function will return $options array for choose_from_menu, with whitespace to denote nesting.
1085 function make_categories_options() {
1086 make_categories_list($cats,$parents);
1087 foreach ($cats as $key => $value) {
1088 if (array_key_exists($key,$parents)) {
1089 if ($indent = count($parents[$key])) {
1090 for ($i = 0; $i < $indent; $i++) {
1091 $cats[$key] = '&nbsp;'.$cats[$key];
1096 return $cats;
1099 function print_category_info($category, $depth, $files = false) {
1100 /// Prints the category info in indented fashion
1101 /// This function is only used by print_whole_category_list() above
1103 global $CFG;
1104 static $strallowguests, $strrequireskey, $strsummary;
1106 if (empty($strsummary)) {
1107 $strallowguests = get_string('allowguests');
1108 $strrequireskey = get_string('requireskey');
1109 $strsummary = get_string('summary');
1112 $catlinkcss = $category->visible ? '' : ' class="dimmed" ';
1114 $coursecount = count_records('course') <= FRONTPAGECOURSELIMIT;
1115 if ($files and $coursecount) {
1116 $catimage = '<img src="'.$CFG->pixpath.'/i/course.gif" width="16" height="16" border="0" alt="" />';
1117 } else {
1118 $catimage = "&nbsp;";
1121 echo "\n\n".'<table border="0" cellpadding="3" cellspacing="0" width="100%">';
1123 if ($files and $coursecount) {
1124 $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');
1126 echo "<tr>";
1128 if ($depth) {
1129 $indent = $depth*30;
1130 $rows = count($courses) + 1;
1131 echo '<td rowspan="'.$rows.'" valign="top" width="'.$indent.'">';
1132 print_spacer(10, $indent);
1133 echo '</td>';
1136 echo '<td valign="top">'.$catimage.'</td>';
1137 echo '<td valign="top" width="100%" class="category name">';
1138 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot.'/course/category.php?id='.$category->id.'">'.$category->name.'</a>';
1139 echo '</td>';
1140 echo '<td class="category info">&nbsp;</td>';
1141 echo '</tr>';
1143 if ($courses && !(isset($CFG->max_category_depth)&&($depth>=$CFG->max_category_depth-1))) {
1144 foreach ($courses as $course) {
1145 $linkcss = $course->visible ? '' : ' class="dimmed" ';
1146 echo '<tr><td valign="top" width="30">&nbsp;';
1147 echo '</td><td valign="top" width="100%" class="course name">';
1148 echo '<a '.$linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.$course->fullname.'</a>';
1149 echo '</td><td align="right" valign="top" nowrap="nowrap" class="course info">';
1150 if ($course->guest ) {
1151 echo '<a title="'.$strallowguests.'" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">';
1152 echo '<img hspace="1" alt="'.$strallowguests.'" height="16" width="16" border="0" src="'.$CFG->pixpath.'/i/guest.gif" /></a>';
1153 } else {
1154 echo '<img alt="" height="16" width="18" border="0" src="'.$CFG->pixpath.'/spacer.gif" />';
1156 if ($course->password) {
1157 echo '<a title="'.$strrequireskey.'" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">';
1158 echo '<img hspace="1" alt="'.$strrequireskey.'" height="16" width="16" border="0" src="'.$CFG->pixpath.'/i/key.gif" /></a>';
1159 } else {
1160 echo '<img alt="" height="16" width="18" border="0" src="'.$CFG->pixpath.'/spacer.gif" />';
1162 if ($course->summary) {
1163 link_to_popup_window ('/course/info.php?id='.$course->id, 'courseinfo',
1164 '<img hspace="1" alt="'.$strsummary.'" height="16" width="16" border="0" src="'.$CFG->pixpath.'/i/info.gif" />',
1165 400, 500, $strsummary);
1166 } else {
1167 echo '<img alt="" height="16" width="18" border="0" src="'.$CFG->pixpath.'/spacer.gif" />';
1169 echo '</td></tr>';
1172 } else {
1174 echo '<tr>';
1176 if ($depth) {
1177 $indent = $depth*20;
1178 echo '<td valign="top" width="'.$indent.'">';
1179 print_spacer(10, $indent);
1180 echo '</td>';
1183 echo '<td valign="top" width="100%" class="category name">';
1184 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot.'/course/category.php?id='.$category->id.'">'.$category->name.'</a>';
1185 echo '</td>';
1186 echo '<td valign="top" class="category number">';
1187 if ($category->coursecount) {
1188 echo $category->coursecount;
1190 echo '</td></tr>';
1192 echo '</table>';
1196 function print_courses($category, $width="100%", $hidesitecourse = false) {
1197 /// Category is 0 (for all courses) or an object
1199 global $CFG;
1201 if (empty($category)) {
1202 $categories = get_categories(0); // Parent = 0 ie top-level categories only
1203 if (count($categories) == 1) {
1204 $category = array_shift($categories);
1205 $courses = get_courses($category->id, 'c.sortorder ASC', 'c.id,c.category,c.sortorder,c.visible,c.fullname,c.shortname,c.password,c.summary,c.teacher,c.cost,c.currency,c.enrol,c.guest');
1206 } else {
1207 $courses = get_courses('all', 'c.sortorder ASC', 'c.id,c.category,c.sortorder,c.visible,c.fullname,c.shortname,c.password,c.summary,c.teacher,c.cost,c.currency,c.enrol,c.guest');
1209 unset($categories);
1210 } else {
1211 $categories = get_categories($category->id); // sub categories
1212 $courses = get_courses($category->id, 'c.sortorder ASC', 'c.id,c.category,c.sortorder,c.visible,c.fullname,c.shortname,c.password,c.summary,c.teacher,c.cost,c.currency,c.enrol,c.guest');
1215 if ($courses) {
1216 foreach ($courses as $course) {
1217 if ($hidesitecourse && !$course->category) {
1218 continue;
1220 print_course($course, $width);
1222 } else {
1223 print_heading(get_string("nocoursesyet"));
1224 if (iscreator()) { // Make it obvious for newbies on new sites how to add a course
1225 $options = array();
1226 $options['category'] = $category->id;
1227 echo '<div class="addcoursebutton" align="center">';
1228 print_single_button($CFG->wwwroot.'/course/edit.php', $options, get_string("addnewcourse"));
1229 echo '</div>';
1236 function print_course($course, $width="100%") {
1238 global $CFG, $USER;
1240 require_once("$CFG->dirroot/enrol/enrol.class.php");
1242 $enrol = enrolment_factory::factory($course->enrol);
1244 print_simple_box_start("center", "$width", '', 5, "coursebox");
1246 $linkcss = $course->visible ? "" : " class=\"dimmed\" ";
1248 echo "<table width=\"100%\">";
1249 echo '<tr valign="top">';
1250 echo '<td valign="top" width="50%" class="info">';
1251 echo '<b><a title="'.get_string('entercourse').'"'.
1252 $linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.
1253 $course->fullname.'</a></b><br />';
1254 if ($teachers = get_course_teachers($course->id)) {
1255 echo "<span class=\"teachers\">\n";
1256 foreach ($teachers as $teacher) {
1257 if ($teacher->authority > 0) {
1258 if (!$teacher->role) {
1259 $teacher->role = $course->teacher;
1261 $fullname = fullname($teacher, isteacher($course->id)); // is the USER a teacher of that course
1262 echo $teacher->role.': <a href="'.$CFG->wwwroot.'/user/view.php?id='.$teacher->id.
1263 '&amp;course='.SITEID.'">'.$fullname.'</a><br />';
1266 echo "</span>\n";
1269 echo $enrol->get_access_icons($course);
1271 echo '</td><td valign="top" width="50%" class="summary">';
1272 $options = NULL;
1273 $options->noclean = true;
1274 $options->para = false;
1275 echo format_text($course->summary, FORMAT_MOODLE, $options, $course->id);
1276 echo "</td></tr>";
1277 echo "</table>";
1279 print_simple_box_end();
1283 function print_my_moodle() {
1284 /// Prints custom user information on the home page.
1285 /// Over time this can include all sorts of information
1287 global $USER, $CFG;
1289 if (!isset($USER->id)) {
1290 error("It shouldn't be possible to see My Moodle without being logged in.");
1293 if ($courses = get_my_courses($USER->id)) {
1294 foreach ($courses as $course) {
1295 if (!$course->category) {
1296 continue;
1298 print_course($course, "100%");
1301 if (count_records("course") > (count($courses) + 1) ) { // Some courses not being displayed
1302 echo "<table width=\"100%\"><tr><td align=\"center\">";
1303 print_course_search("", false, "short");
1304 echo "</td><td align=\"center\">";
1305 print_single_button("$CFG->wwwroot/course/index.php", NULL, get_string("fulllistofcourses"), "get");
1306 echo "</td></tr></table>\n";
1308 } else {
1309 if (count_records("course_categories") > 1) {
1310 print_simple_box_start("center", "100%", "#FFFFFF", 5, "categorybox");
1311 print_whole_category_list();
1312 print_simple_box_end();
1313 } else {
1314 print_courses(0, "100%");
1320 function print_course_search($value="", $return=false, $format="plain") {
1322 global $CFG;
1324 $strsearchcourses= get_string("searchcourses");
1326 if ($format == 'plain') {
1327 $output = '<form name="coursesearch" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
1328 $output .= '<center><p align="center" class="coursesearchbox">';
1329 $output .= '<input type="text" size="30" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
1330 $output .= '<input type="submit" value="'.s($strsearchcourses).'" />';
1331 $output .= '</p></center></form>';
1332 } else if ($format == 'short') {
1333 $output = '<form name="coursesearch" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
1334 $output .= '<center><p align="center" class="coursesearchbox">';
1335 $output .= '<input type="text" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
1336 $output .= '<input type="submit" value="'.s($strsearchcourses).'" />';
1337 $output .= '</p></center></form>';
1338 } else if ($format == 'navbar') {
1339 $output = '<form name="coursesearch" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
1340 $output .= '<table border="0" cellpadding="0" cellspacing="0"><tr><td nowrap="nowrap">';
1341 $output .= '<input type="text" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
1342 $output .= '<input type="submit" value="'.s($strsearchcourses).'" />';
1343 $output .= '</td></tr></table>';
1344 $output .= '</form>';
1347 if ($return) {
1348 return $output;
1350 echo $output;
1353 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
1355 function add_course_module($mod) {
1357 $mod->added = time();
1358 unset($mod->id);
1360 return insert_record("course_modules", $mod);
1363 function add_mod_to_section($mod, $beforemod=NULL) {
1364 /// Given a full mod object with section and course already defined
1365 /// If $before is specified, then this is an existing ID which we
1366 /// will insert the new module before
1368 /// Returns the course_sections ID where the mod is inserted
1370 if ($section = get_record("course_sections", "course", "$mod->course", "section", "$mod->section")) {
1372 $section->sequence = trim($section->sequence);
1374 if (empty($section->sequence)) {
1375 $newsequence = "$mod->coursemodule";
1377 } else if ($beforemod) {
1378 $modarray = explode(",", $section->sequence);
1380 if ($key = array_keys ($modarray, $beforemod->id)) {
1381 $insertarray = array($mod->id, $beforemod->id);
1382 array_splice($modarray, $key[0], 1, $insertarray);
1383 $newsequence = implode(",", $modarray);
1385 } else { // Just tack it on the end anyway
1386 $newsequence = "$section->sequence,$mod->coursemodule";
1389 } else {
1390 $newsequence = "$section->sequence,$mod->coursemodule";
1393 if (set_field("course_sections", "sequence", $newsequence, "id", $section->id)) {
1394 return $section->id; // Return course_sections ID that was used.
1395 } else {
1396 return 0;
1399 } else { // Insert a new record
1400 $section->course = $mod->course;
1401 $section->section = $mod->section;
1402 $section->summary = "";
1403 $section->sequence = $mod->coursemodule;
1404 return insert_record("course_sections", $section);
1408 function set_coursemodule_groupmode($id, $groupmode) {
1409 return set_field("course_modules", "groupmode", $groupmode, "id", $id);
1413 * $prevstateoverrides = true will set the visibility of the course module
1414 * to what is defined in visibleold. This enables us to remember the current
1415 * visibility when making a whole section hidden, so that when we toggle
1416 * that section back to visible, we are able to return the visibility of
1417 * the course module back to what it was originally.
1419 function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
1420 $cm = get_record('course_modules', 'id', $id);
1421 $modulename = get_field('modules', 'name', 'id', $cm->module);
1422 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
1423 foreach($events as $event) {
1424 if ($visible) {
1425 show_event($event);
1426 } else {
1427 hide_event($event);
1431 if ($prevstateoverrides) {
1432 if ($visible == '0') {
1433 // Remember the current visible state so we can toggle this back.
1434 set_field('course_modules', 'visibleold', $cm->visible, 'id', $id);
1435 } else {
1436 // Get the previous saved visible states.
1437 return set_field('course_modules', 'visible', $cm->visibleold, 'id', $id);
1440 return set_field("course_modules", "visible", $visible, "id", $id);
1444 * Delete a course module and any associated data at the course level (events)
1445 * Until 1.5 this function simply marked a deleted flag ... now it
1446 * deletes it completely.
1449 function delete_course_module($id) {
1450 if (!$cm = get_record('course_modules', 'id', $id)) {
1451 return true;
1453 $modulename = get_field('modules', 'name', 'id', $cm->module);
1454 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
1455 foreach($events as $event) {
1456 delete_event($event);
1459 return delete_records('course_modules', 'id', $cm->id);
1462 function delete_mod_from_section($mod, $section) {
1464 if ($section = get_record("course_sections", "id", "$section") ) {
1466 $modarray = explode(",", $section->sequence);
1468 if ($key = array_keys ($modarray, $mod)) {
1469 array_splice($modarray, $key[0], 1);
1470 $newsequence = implode(",", $modarray);
1471 return set_field("course_sections", "sequence", $newsequence, "id", $section->id);
1472 } else {
1473 return false;
1477 return false;
1480 function move_section($course, $section, $move) {
1481 /// Moves a whole course section up and down within the course
1482 global $USER;
1484 if (!$move) {
1485 return true;
1488 $sectiondest = $section + $move;
1490 if ($sectiondest > $course->numsections or $sectiondest < 1) {
1491 return false;
1494 if (!$sectionrecord = get_record("course_sections", "course", $course->id, "section", $section)) {
1495 return false;
1498 if (!$sectiondestrecord = get_record("course_sections", "course", $course->id, "section", $sectiondest)) {
1499 return false;
1502 if (!set_field("course_sections", "section", $sectiondest, "id", $sectionrecord->id)) {
1503 return false;
1505 if (!set_field("course_sections", "section", $section, "id", $sectiondestrecord->id)) {
1506 return false;
1508 // if the focus is on the section that is being moved, then move the focus along
1509 if (isset($USER->display[$course->id]) and ($USER->display[$course->id] == $section)) {
1510 course_set_display($course->id, $sectiondest);
1513 // Check for duplicates and fix order if needed.
1514 // There is a very rare case that some sections in the same course have the same section id.
1515 $sections = get_records_select('course_sections', "course = $course->id", 'section ASC');
1516 $n = 0;
1517 foreach ($sections as $section) {
1518 if ($section->section != $n) {
1519 if (!set_field('course_sections', 'section', $n, 'id', $section->id)) {
1520 return false;
1523 $n++;
1525 return true;
1529 function moveto_module($mod, $section, $beforemod=NULL) {
1530 /// All parameters are objects
1531 /// Move the module object $mod to the specified $section
1532 /// If $beforemod exists then that is the module
1533 /// before which $modid should be inserted
1535 /// Remove original module from original section
1537 if (! delete_mod_from_section($mod->id, $mod->section)) {
1538 notify("Could not delete module from existing section");
1541 /// Update module itself if necessary
1543 if ($mod->section != $section->id) {
1544 $mod->section = $section->id;
1545 if (!update_record("course_modules", $mod)) {
1546 return false;
1548 // if moving to a hidden section then hide module
1549 if (!$section->visible) {
1550 set_coursemodule_visible($mod->id, 0);
1554 /// Add the module into the new section
1556 $mod->course = $section->course;
1557 $mod->section = $section->section; // need relative reference
1558 $mod->coursemodule = $mod->id;
1560 if (! add_mod_to_section($mod, $beforemod)) {
1561 return false;
1564 return true;
1568 function make_editing_buttons($mod, $absolute=false, $moveselect=true, $indent=-1, $section=-1) {
1569 global $CFG, $USER;
1571 static $str;
1572 static $sesskey;
1574 if (!isset($str)) {
1575 $str->delete = get_string("delete");
1576 $str->move = get_string("move");
1577 $str->moveup = get_string("moveup");
1578 $str->movedown = get_string("movedown");
1579 $str->moveright = get_string("moveright");
1580 $str->moveleft = get_string("moveleft");
1581 $str->update = get_string("update");
1582 $str->duplicate = get_string("duplicate");
1583 $str->hide = get_string("hide");
1584 $str->show = get_string("show");
1585 $str->clicktochange = get_string("clicktochange");
1586 $str->forcedmode = get_string("forcedmode");
1587 $str->groupsnone = get_string("groupsnone");
1588 $str->groupsseparate = get_string("groupsseparate");
1589 $str->groupsvisible = get_string("groupsvisible");
1590 $sesskey = sesskey();
1593 if ($section >= 0) {
1594 $section = '&amp;sr='.$section; // Section return
1595 } else {
1596 $section = '';
1599 if ($absolute) {
1600 $path = $CFG->wwwroot.'/course';
1601 } else {
1602 $path = '.';
1605 if ($mod->visible) {
1606 $hideshow = '<a title="'.$str->hide.'" href="'.$path.'/mod.php?hide='.$mod->id.
1607 '&amp;sesskey='.$sesskey.$section.'"><img'.
1608 ' src="'.$CFG->pixpath.'/t/hide.gif" hspace="2" height="11" width="11" '.
1609 ' border="0" alt="'.$str->hide.'" /></a> ';
1610 } else {
1611 $hideshow = '<a title="'.$str->show.'" href="'.$path.'/mod.php?show='.$mod->id.
1612 '&amp;sesskey='.$sesskey.$section.'"><img'.
1613 ' src="'.$CFG->pixpath.'/t/show.gif" hspace="2" height="11" width="11" '.
1614 ' border="0" alt="'.$str->show.'" /></a> ';
1616 if ($mod->groupmode !== false) {
1617 if ($mod->groupmode == SEPARATEGROUPS) {
1618 $grouptitle = $str->groupsseparate;
1619 $groupimage = $CFG->pixpath.'/t/groups.gif';
1620 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=0&amp;sesskey='.$sesskey;
1621 } else if ($mod->groupmode == VISIBLEGROUPS) {
1622 $grouptitle = $str->groupsvisible;
1623 $groupimage = $CFG->pixpath.'/t/groupv.gif';
1624 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=1&amp;sesskey='.$sesskey;
1625 } else {
1626 $grouptitle = $str->groupsnone;
1627 $groupimage = $CFG->pixpath.'/t/groupn.gif';
1628 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=2&amp;sesskey='.$sesskey;
1630 if ($mod->groupmodelink) {
1631 $groupmode = '<a title="'.$grouptitle.' ('.$str->clicktochange.')" href="'.$grouplink.'">'.
1632 '<img src="'.$groupimage.'" hspace="2" height="11" width="11" '.
1633 'border="0" alt="'.$grouptitle.'" /></a>';
1634 } else {
1635 $groupmode = '<img title="'.$grouptitle.' ('.$str->forcedmode.')" '.
1636 ' src="'.$groupimage.'" hspace="2" height="11" width="11" '.
1637 'border="0" alt="'.$grouptitle.'" />';
1639 } else {
1640 $groupmode = "";
1643 if ($moveselect) {
1644 $move = '<a title="'.$str->move.'" href="'.$path.'/mod.php?copy='.$mod->id.
1645 '&amp;sesskey='.$sesskey.$section.'"><img'.
1646 ' src="'.$CFG->pixpath.'/t/move.gif" hspace="2" height="11" width="11" '.
1647 ' border="0" alt="'.$str->move.'" /></a>';
1648 } else {
1649 $move = '<a title="'.$str->moveup.'" href="'.$path.'/mod.php?id='.$mod->id.
1650 '&amp;move=-1&amp;sesskey='.$sesskey.$section.'"><img'.
1651 ' src="'.$CFG->pixpath.'/t/up.gif" hspace="2" height="11" width="11" '.
1652 ' border="0" alt="'.$str->moveup.'" /></a>'.
1653 '<a title="'.$str->movedown.'" href="'.$path.'/mod.php?id='.$mod->id.
1654 '&amp;move=1&amp;sesskey='.$sesskey.$section.'"><img'.
1655 ' src="'.$CFG->pixpath.'/t/down.gif" hspace="2" height="11" width="11" '.
1656 ' border="0" alt="'.$str->movedown.'" /></a>';
1659 $leftright = "";
1660 if ($indent > 0) {
1661 $leftright .= '<a title="'.$str->moveleft.'" href="'.$path.'/mod.php?id='.$mod->id.
1662 '&amp;indent=-1&amp;sesskey='.$sesskey.$section.'"><img'.
1663 ' src="'.$CFG->pixpath.'/t/left.gif" hspace="2" height="11" width="11" '.
1664 ' border="0" alt="'.$str->moveleft.'" /></a>';
1666 if ($indent >= 0) {
1667 $leftright .= '<a title="'.$str->moveright.'" href="'.$path.'/mod.php?id='.$mod->id.
1668 '&amp;indent=1&amp;sesskey='.$sesskey.$section.'"><img'.
1669 ' src="'.$CFG->pixpath.'/t/right.gif" hspace="2" height="11" width="11" '.
1670 ' border="0" alt="'.$str->moveright.'" /></a>';
1673 return '<span class="commands">'.$leftright.$move.
1674 '<a title="'.$str->update.'" href="'.$path.'/mod.php?update='.$mod->id.
1675 '&amp;sesskey='.$sesskey.$section.'"><img'.
1676 ' src="'.$CFG->pixpath.'/t/edit.gif" hspace="2" height="11" width="11" border="0" '.
1677 ' alt="'.$str->update.'" /></a>'.
1678 '<a title="'.$str->delete.'" href="'.$path.'/mod.php?delete='.$mod->id.
1679 '&amp;sesskey='.$sesskey.$section.'"><img'.
1680 ' src="'.$CFG->pixpath.'/t/delete.gif" hspace="2" height="11" width="11" border="0" '.
1681 ' alt="'.$str->delete.'" /></a>'.$hideshow.$groupmode.'</span>';
1685 * given a course object with shortname & fullname, this function will
1686 * truncate the the number of chars allowed and add ... if it was too long
1688 function course_format_name ($course,$max=100) {
1690 $str = $course->shortname.': '.$course->fullname;
1691 if (strlen($str) <= $max) {
1692 return $str;
1694 else {
1695 return substr($str,0,$max-3).'...';
1700 * This function will return true if the given course is a child course at all
1702 function course_in_meta ($course) {
1703 return record_exists("course_meta","child_course",$course->id);
1708 * Print standard form elements on module setup forms in mod/.../mod.html
1710 function print_standard_coursemodule_settings($form) {
1711 if (! $course = get_record('course', 'id', $form->course)) {
1712 error("This course doesn't exist");
1714 print_groupmode_setting($form, $course);
1715 print_visible_setting($form, $course);
1719 * Print groupmode form element on module setup forms in mod/.../mod.html
1721 function print_groupmode_setting($form, $course=NULL) {
1723 if (empty($course)) {
1724 if (! $course = get_record('course', 'id', $form->course)) {
1725 error("This course doesn't exist");
1728 if ($form->coursemodule) {
1729 if (! $cm = get_record('course_modules', 'id', $form->coursemodule)) {
1730 error("This course module doesn't exist");
1732 } else {
1733 $cm = null;
1735 $groupmode = groupmode($course, $cm);
1736 if ($course->groupmode or (!$course->groupmodeforce)) {
1737 echo '<tr valign="top">';
1738 echo '<td align="right"><b>'.get_string('groupmode').':</b></td>';
1739 echo '<td align="left">';
1740 unset($choices);
1741 $choices[NOGROUPS] = get_string('groupsnone');
1742 $choices[SEPARATEGROUPS] = get_string('groupsseparate');
1743 $choices[VISIBLEGROUPS] = get_string('groupsvisible');
1744 choose_from_menu($choices, 'groupmode', $groupmode, '', '', 0, false, $course->groupmodeforce);
1745 helpbutton('groupmode', get_string('groupmode'));
1746 echo '</td></tr>';
1751 * Print visibility setting form element on module setup forms in mod/.../mod.html
1753 function print_visible_setting($form, $course=NULL) {
1754 if (empty($course)) {
1755 if (! $course = get_record('course', 'id', $form->course)) {
1756 error("This course doesn't exist");
1759 if ($form->coursemodule) {
1760 $visible = get_field('course_modules', 'visible', 'id', $form->coursemodule);
1761 } else {
1762 $visible = true;
1765 if ($form->mode == 'add') { // in this case $form->section is the section number, not the id
1766 $hiddensection = !get_field('course_sections', 'visible', 'section', $form->section, 'course', $form->course);
1767 } else {
1768 $hiddensection = !get_field('course_sections', 'visible', 'id', $form->section);
1770 if ($hiddensection) {
1771 $visible = false;
1774 echo '<tr valign="top">';
1775 echo '<td align="right"><b>'.get_string('visibletostudents','',moodle_strtolower($course->students)).':</b></td>';
1776 echo '<td align="left">';
1777 unset($choices);
1778 $choices[1] = get_string('show');
1779 $choices[0] = get_string('hide');
1780 choose_from_menu($choices, 'visible', $visible, '', '', 0, false, $hiddensection);
1781 echo '</td></tr>';
1784 function update_restricted_mods($course,$mods) {
1785 delete_records("course_allowed_modules","course",$course->id);
1786 if (empty($course->restrictmodules)) {
1787 return;
1789 else {
1790 foreach ($mods as $mod) {
1791 if ($mod == 0)
1792 continue; // this is the 'allow none' option
1793 $am->course = $course->id;
1794 $am->module = $mod;
1795 insert_record("course_allowed_modules",$am);
1801 * This function will take an int (module id) or a string (module name)
1802 * and return true or false, whether it's allowed in the given course (object)
1803 * $mod is not allowed to be an object, as the field for the module id is inconsistent
1804 * depending on where in the code it's called from (sometimes $mod->id, sometimes $mod->module)
1807 function course_allowed_module($course,$mod) {
1808 if (empty($course->restrictmodules)) {
1809 return true;
1811 if (isadmin()) {
1812 return true;
1814 if (is_numeric($mod)) {
1815 $modid = $mod;
1816 } else if (is_string($mod)) {
1817 if ($mod = get_field("modules","id","name",$mod))
1818 $modid = $mod;
1820 if (empty($modid)) {
1821 return false;
1823 return (record_exists("course_allowed_modules","course",$course->id,"module",$modid));
1826 /***
1827 *** Efficiently moves many courses around while maintaining
1828 *** sortorder in order.
1829 ***
1830 *** $courseids is an array of course ids
1834 function move_courses ($courseids, $categoryid) {
1836 global $CFG;
1838 if (!empty($courseids)) {
1840 $courseids = array_reverse($courseids);
1842 foreach ($courseids as $courseid) {
1844 if (! $course = get_record("course", "id", $courseid)) {
1845 notify("Error finding course $courseid");
1846 } else {
1847 // figure out a sortorder that we can use in the destination category
1848 $sortorder = get_field_sql('SELECT MIN(sortorder)-1 AS min
1849 FROM ' . $CFG->prefix . 'course WHERE category=' . $categoryid);
1850 if ($sortorder === false) {
1851 // the category is empty
1852 // rather than let the db default to 0
1853 // set it to > 100 and avoid extra work in fix_coursesortorder()
1854 $sortorder = 200;
1855 } else if ($sortorder < 10) {
1856 fix_course_sortorder($categoryid);
1859 $course->category = $categoryid;
1860 $course->sortorder = $sortorder;
1861 $course->fullname = addslashes($course->fullname);
1862 $course->shortname = addslashes($course->shortname);
1863 $course->summary = addslashes($course->summary);
1864 $course->password = addslashes($course->password);
1865 $course->teacher = addslashes($course->teacher);
1866 $course->teachers = addslashes($course->teachers);
1867 $course->student = addslashes($course->student);
1868 $course->students = addslashes($course->students);
1870 if (!update_record('course', $course)) {
1871 notify("An error occurred - course not moved!");
1875 fix_course_sortorder();
1877 return true;