Added new strings for question grade matching
[moodle-linuxchix.git] / course / lib.php
blob75f0628d718d963a24a39a39f2fecc9bbdec8879
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);
28 function print_recent_selector_form($course, $advancedfilter=0, $selecteduser=0, $selecteddate="lastlogin",
29 $mod="", $modid="activity/All", $modaction="", $selectedgroup="", $selectedsort="default") {
31 global $USER, $CFG;
33 $isteacher = isteacher($course->id);
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, $isteacher);
44 if ($guest = get_guest()) {
45 $users[$guest->id] = fullname($guest);
48 if (isadmin()) {
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 if ($modinfo = unserialize($course->modinfo)) {
66 $section = 0;
67 if ($course->format == 'weeks') { // Body
68 $strsection = get_string("week");
69 } else {
70 $strsection = get_string("topic");
73 $activities["activity/All"] = "All activities";
74 $activities["activity/Assignments"] = "All assignments";
75 $activities["activity/Chats"] = "All chats";
76 $activities["activity/Forums"] = "All forums";
77 $activities["activity/Quizzes"] = "All quizzes";
78 $activities["activity/Workshops"] = "All workshops";
80 $activities["section/individual"] = "------------- Individual Activities --------------";
82 foreach ($modinfo as $mod) {
83 if ($mod->mod == "label") {
84 continue;
86 if (!$mod->visible and !$isteacher) {
87 continue;
90 if ($mod->section > 0 and $section <> $mod->section) {
91 $activities["section/$mod->section"] = "-------------- $strsection $mod->section --------------";
93 $section = $mod->section;
94 $mod->name = strip_tags(format_string(urldecode($mod->name),true));
95 if (strlen($mod->name) > 55) {
96 $mod->name = substr($mod->name, 0, 50)."...";
98 if (!$mod->visible) {
99 $mod->name = "(".$mod->name.")";
101 $activities["$mod->cm"] = $mod->name;
103 if ($mod->cm == $modid) {
104 $selectedactivity = "$mod->cm";
109 $strftimedate = get_string("strftimedate");
110 $strftimedaydate = get_string("strftimedaydate");
112 asort($users);
114 // Get all the possible dates
115 // Note that we are keeping track of real (GMT) time and user time
116 // User time is only used in displays - all calcs and passing is GMT
118 $timenow = time(); // GMT
120 // What day is it now for the user, and when is midnight that day (in GMT).
121 $timemidnight = $today = usergetmidnight($timenow);
123 $dates = array();
124 $dates["$USER->lastlogin"] = get_string("lastlogin").", ".userdate($USER->lastlogin, $strftimedate);
125 $dates["$timemidnight"] = get_string("today").", ".userdate($timenow, $strftimedate);
127 if (!$course->startdate or ($course->startdate > $timenow)) {
128 $course->startdate = $course->timecreated;
131 $numdates = 1;
132 while ($timemidnight > $course->startdate and $numdates < 365) {
133 $timemidnight = $timemidnight - 86400;
134 $timenow = $timenow - 86400;
135 $dates["$timemidnight"] = userdate($timenow, $strftimedaydate);
136 $numdates++;
139 if ($selecteddate === "lastlogin") {
140 $selecteddate = $USER->lastlogin;
143 echo '<form action="recent.php" method="get">';
144 echo '<input type="hidden" name="chooserecent" value="1" />';
145 echo "<center>";
146 echo "<table>";
148 if (isadmin()) {
149 echo "<tr><td><b>" . get_string("courses") . "</b></td><td>";
150 choose_from_menu ($courses, "id", $course->id, "");
151 echo "</td></tr>";
152 } else {
153 echo '<input type="hidden" name="id" value="'.$course->id.'" />';
156 $sortfields = array("default" => get_string("bycourseorder"),"dateasc" => get_string("datemostrecentlast"), "datedesc" => get_string("datemostrecentfirst"));
158 echo "<tr><td><b>" . get_string("participants") . "</b></td><td>";
159 choose_from_menu ($users, "user", $selecteduser, get_string("allparticipants") );
160 echo "</td>";
162 echo '<td align="right"><b>' . get_string("since") . '</b></td><td>';
163 choose_from_menu ($dates, "date", $selecteddate, get_string("alldays"));
164 echo "</td></tr>";
166 echo "<tr><td><b>" . get_string("activities") . "</b></td><td>";
167 choose_from_menu ($activities, "modid", $selectedactivity, "");
168 echo "</td>";
170 echo '<td align="right"><b>' . get_string("sortby") . "</b></td><td>";
171 choose_from_menu ($sortfields, "sortby", $selectedsort, "");
172 echo "</td></tr>";
174 echo '<tr>';
176 $groupmode = groupmode($course);
178 if ($groupmode == VISIBLEGROUPS or ($groupmode and isteacheredit($course->id))) {
179 if ($groups = get_records_menu("groups", "courseid", $course->id, "name ASC", "id,name")) {
180 echo '<td><b>';
181 if ($groupmode == VISIBLEGROUPS) {
182 print_string('groupsvisible');
183 } else {
184 print_string('groupsseparate');
186 echo ':</b></td><td>';
187 choose_from_menu($groups, "selectedgroup", $selectedgroup, get_string("allgroups"), "", "");
188 echo '</td>';
193 echo '<td colspan="2" align="right">';
194 echo '<input type="submit" value="'.get_string('showrecent').'" />';
195 echo "</td></tr>";
197 echo "</table>";
199 $advancedlink = "<a href=\"$CFG->wwwroot/course/recent.php?id=$course->id&amp;advancedfilter=0\">" . get_string("normalfilter") . "</a>";
200 print_heading($advancedlink);
201 echo "</center>";
202 echo "</form>";
204 } else {
206 $day_list = array("1","7","14","21","30");
207 $strsince = get_string("since");
208 $strlastlogin = get_string("lastlogin");
209 $strday = get_string("day");
210 $strdays = get_string("days");
212 $heading = "";
213 foreach ($day_list as $count) {
214 if ($count == "1") {
215 $day = $strday;
216 } else {
217 $day = $strdays;
219 $tmpdate = time() - ($count * 3600 * 24);
220 $heading = $heading .
221 "<a href=\"$CFG->wwwroot/course/recent.php?id=$course->id&amp;date=$tmpdate\"> $count $day</a> | ";
224 $heading = $strsince . ": <a href=\"$CFG->wwwroot/course/recent.php?id=$course->id\">$strlastlogin</a>" . " | " . $heading;
225 print_heading($heading);
227 $advancedlink = "<a href=\"$CFG->wwwroot/course/recent.php?id=$course->id&amp;advancedfilter=1\">" . get_string("advancedfilter") . "</a>";
228 print_heading($advancedlink);
235 function make_log_url($module, $url) {
236 switch ($module) {
237 case "user":
238 case "course":
239 case "file":
240 case "login":
241 case "lib":
242 case "admin":
243 case "message":
244 case "calendar":
245 return "/$module/$url";
246 break;
247 case "upload":
248 return "$url";
249 break;
250 case "library":
251 case "":
252 return "/";
253 break;
254 default:
255 return "/mod/$module/$url";
256 break;
260 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
261 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
263 // It is assumed that $date is the GMT time of midnight for that day,
264 // and so the next 86400 seconds worth of logs are printed.
266 global $CFG, $db;
268 /// Setup for group handling.
269 $isteacher = isteacher($course->id);
270 $isteacheredit = isteacheredit($course->id);
272 /// If the group mode is separate, and this user does not have editing privileges,
273 /// then only the user's group can be viewed.
274 if ($course->groupmode == SEPARATEGROUPS and !$isteacheredit) {
275 $groupid = get_current_group($course->id);
277 /// If this course doesn't have groups, no groupid can be specified.
278 else if (!$course->groupmode) {
279 $groupid = 0;
282 $joins = array();
284 if ($course->category) {
285 $joins[] = "l.course='$course->id'";
286 } else {
287 $courses[0] = '';
288 if ($ccc = get_courses("all", "c.id ASC", "c.id,c.shortname")) {
289 foreach ($ccc as $cc) {
290 $courses[$cc->id] = "$cc->shortname";
295 if ($modname) {
296 $joins[] = "l.module = '$modname'";
299 if ('site_errors' === $modid) {
300 $joins[] = "( l.action='error' OR l.action='infected' )";
301 } else if ($modid) {
302 $joins[] = "l.cmid = '$modid'";
305 if ($modaction) {
306 $joins[] = "l.action = '$modaction'";
309 /// Getting all members of a group.
310 if ($groupid and !$user) {
311 if ($gusers = get_records('groups_members', 'groupid', $groupid)) {
312 $first = true;
313 foreach($gusers as $guser) {
314 if ($first) {
315 $gselect = '(l.userid='.$guser->userid;
316 $first = false;
318 else {
319 $gselect .= ' OR l.userid='.$guser->userid;
322 if (!$first) $gselect .= ')';
323 $joins[] = $gselect;
326 else if ($user) {
327 $joins[] = "l.userid = '$user'";
330 if ($date) {
331 $enddate = $date + 86400;
332 $joins[] = "l.time > '$date' AND l.time < '$enddate'";
335 $selector = '';
336 for ($i = 0; $i < count($joins); $i++) {
337 $selector .= $joins[$i] . (($i == count($joins)-1) ? " " : " AND ");
341 $totalcount = 0; // Initialise
343 if (!$logs = get_logs($selector, $order, $page*$perpage, $perpage, $totalcount)) {
344 notify("No logs found!");
345 print_footer($course);
346 exit;
349 $count=0;
350 $ldcache = array();
351 $tt = getdate(time());
352 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
354 $strftimedatetime = get_string("strftimedatetime");
355 $isteacher = isteacher($course->id);
357 echo "<p align=\"center\">\n";
358 print_string("displayingrecords", "", $totalcount);
359 echo "</p>\n";
362 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
364 echo "<table class=\"logtable\" border=\"0\" align=\"center\" cellpadding=\"3\" cellspacing=\"0\">\n";
365 echo "<tr>";
366 if ($course->id == SITEID) {
367 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
369 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
370 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
371 echo "<th class=\"c3 header\">".get_string('fullname')."</th>\n";
372 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
373 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
374 echo "</tr>\n";
376 $row = 1;
377 foreach ($logs as $log) {
379 $row = ($row + 1) % 2;
381 if (isset($ldcache[$log->module][$log->action])) {
382 $ld = $ldcache[$log->module][$log->action];
383 } else {
384 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
385 $ldcache[$log->module][$log->action] = $ld;
387 if ($ld && !empty($log->info)) {
388 // ugly hack to make sure fullname is shown correctly
389 if (($ld->mtable == 'user') and ($ld->field == 'CONCAT(firstname," ",lastname)')) {
390 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
391 } else {
392 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
396 //Filter log->info
397 $log->info = format_string($log->info);
399 $log->url = strip_tags(urldecode($log->url)); // Some XSS protection
400 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
401 $log->url = str_replace('&', '&amp;', $log->url); /// XHTML compatibility
403 echo '<tr class="r'.$row.'">';
404 if ($course->id == SITEID) {
405 echo "<td class=\"r$row c0\" nowrap=\"nowrap\">\n";
406 echo " <a href=\"view.php?id={$log->course}\">".$courses[$log->course]."</a>\n";
407 echo "</td>\n";
409 echo "<td class=\"r$row c1\" nowrap=\"nowrap\" align=\"right\">".userdate($log->time, '%a').
410 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
411 echo "<td class=\"r$row c2\" nowrap=\"nowrap\">\n";
412 link_to_popup_window("/iplookup/index.php?ip=$log->ip&amp;user=$log->userid", 'iplookup',$log->ip, 400, 700);
413 echo "</td>\n";
414 $fullname = fullname($log, $isteacher);
415 echo "<td class=\"r$row c3\" nowrap=\"nowrap\">\n";
416 echo " <a href=\"../user/view.php?id={$log->userid}&amp;course={$log->course}\">$fullname</a>\n";
417 echo "</td>\n";
418 echo "<td class=\"r$row c4\" nowrap=\"nowrap\">\n";
419 link_to_popup_window( make_log_url($log->module,$log->url), 'fromloglive',"$log->module $log->action", 400, 600);
420 echo "</td>\n";;
421 echo "<td class=\"r$row c5\" nowrap=\"nowrap\">{$log->info}</td>\n";
422 echo "</tr>\n";
424 echo "</table>\n";
426 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
430 function print_log_graph($course, $userid=0, $type="course.png", $date=0) {
431 global $CFG;
432 if (empty($CFG->gdversion)) {
433 echo "(".get_string("gdneed").")";
434 } else {
435 echo '<img src="'.$CFG->wwwroot.'/course/loggraph.php?id='.$course->id.
436 '&amp;user='.$userid.'&amp;type='.$type.'&amp;date='.$date.'" alt="" />';
441 function print_overview($courses) {
443 global $CFG, $USER;
446 $htmlarray = array();
447 if ($modules = get_records('modules')) {
448 foreach ($modules as $mod) {
449 if (file_exists(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php')) {
450 require_once(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php');
451 $fname = $mod->name.'_print_overview';
452 if (function_exists($fname)) {
453 $fname($courses,$htmlarray);
459 foreach ($courses as $course) {
460 print_simple_box_start('center', '100%', '', 5, "coursebox");
461 $linkcss = '';
462 if (empty($course->visible)) {
463 $linkcss = 'class="dimmed"';
465 print_heading('<a title="'.$course->fullname.'" '.$linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.$course->fullname.'</a>');
466 if (array_key_exists($course->id,$htmlarray)) {
467 foreach ($htmlarray[$course->id] as $modname => $html) {
468 echo $html;
471 print_simple_box_end();
477 function print_recent_activity($course) {
478 // $course is an object
479 // This function trawls through the logs looking for
480 // anything new since the user's last login
482 global $CFG, $USER, $SESSION;
484 $isteacher = isteacher($course->id);
486 $timestart = time() - COURSE_MAX_RECENT_PERIOD;
488 if (!empty($USER->timeaccess[$course->id])) {
489 if ($USER->timeaccess[$course->id] > $timestart) {
490 $timestart = $USER->timeaccess[$course->id];
494 echo '<div class="activitydate">';
495 echo get_string('activitysince', '', userdate($timestart));
496 echo '</div>';
497 echo '<div class="activityhead">';
499 echo '<a href="'.$CFG->wwwroot.'/course/recent.php?id='.$course->id.'">'.get_string('recentactivityreport').'</a>';
501 echo '</div>';
504 // Firstly, have there been any new enrolments?
506 $heading = false;
507 $content = false;
509 $users = get_recent_enrolments($course->id, $timestart);
511 if ($users) {
512 echo '<div class="newusers">';
513 foreach ($users as $user) {
514 if (! $heading) {
515 print_headline(get_string("newusers").':', 3);
516 $heading = true;
517 $content = true;
519 $fullname = fullname($user, $isteacher);
520 echo '<span class="name"><a href="'.$CFG->wwwroot."/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a></span><br />";
522 echo '</div>';
525 // Next, have there been any modifications to the course structure?
527 $logs = get_records_select('log', "time > '$timestart' AND course = '$course->id' AND
528 module = 'course' AND action LIKE '% mod'", "time ASC");
530 if ($logs) {
531 foreach ($logs as $key => $log) {
532 $info = split(' ', $log->info);
534 if ($info[0] == 'label') { // Labels are special activities
535 continue;
538 $modname = get_field($info[0], 'name', 'id', $info[1]);
539 //Create a temp valid module structure (course,id)
540 $tempmod->course = $log->course;
541 $tempmod->id = $info[1];
542 //Obtain the visible property from the instance
543 $modvisible = instance_is_visible($info[0],$tempmod);
545 //Only if the mod is visible
546 if ($modvisible) {
547 switch ($log->action) {
548 case 'add mod':
549 $stradded = get_string('added', 'moodle', get_string('modulename', $info[0]));
550 $changelist[$log->info] = array ('operation' => 'add', 'text' => "$stradded:<br /><a href=\"$CFG->wwwroot/course/$log->url\">".format_string($modname,true)."</a>");
551 break;
552 case 'update mod':
553 $strupdated = get_string('updated', 'moodle', get_string('modulename', $info[0]));
554 if (empty($changelist[$log->info])) {
555 $changelist[$log->info] = array ('operation' => 'update', 'text' => "$strupdated:<br /><a href=\"$CFG->wwwroot/course/$log->url\">".format_string($modname,true)."</a>");
557 break;
558 case 'delete mod':
559 if (!empty($changelist[$log->info]['operation']) and
560 $changelist[$log->info]['operation'] == 'add') {
561 $changelist[$log->info] = NULL;
562 } else {
563 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $info[0]));
564 $changelist[$log->info] = array ('operation' => 'delete', 'text' => $strdeleted);
566 break;
572 if (!empty($changelist)) {
573 foreach ($changelist as $changeinfo => $change) {
574 if ($change) {
575 $changes[$changeinfo] = $change;
578 if (isset($changes)){
579 if (count($changes) > 0) {
580 print_headline(get_string('courseupdates').':', 3);
581 $content = true;
582 foreach ($changes as $changeinfo => $change) {
583 echo '<p class="activity">'.$change['text'].'</p>';
589 // Now display new things from each module
591 $mods = get_records('modules', 'visible', '1', 'name', 'id, name');
593 foreach ($mods as $mod) { // Each module gets it's own logs and prints them
594 include_once($CFG->dirroot.'/mod/'.$mod->name.'/lib.php');
595 $print_recent_activity = $mod->name.'_print_recent_activity';
596 if (function_exists($print_recent_activity)) {
597 $modcontent = $print_recent_activity($course, $isteacher, $timestart);
598 if ($modcontent) {
599 $content = true;
604 if (! $content) {
605 echo '<p class="message">'.get_string('nothingnew').'</p>';
610 function get_array_of_activities($courseid) {
611 // For a given course, returns an array of course activity objects
612 // Each item in the array contains he following properties:
613 // cm - course module id
614 // mod - name of the module (eg forum)
615 // section - the number of the section (eg week or topic)
616 // name - the name of the instance
617 // visible - is the instance visible or not
618 // extra - contains extra string to include in any link
620 global $CFG;
622 $mod = array();
624 if (!$rawmods = get_course_mods($courseid)) {
625 return NULL;
628 if ($sections = get_records("course_sections", "course", $courseid, "section ASC")) {
629 foreach ($sections as $section) {
630 if (!empty($section->sequence)) {
631 $sequence = explode(",", $section->sequence);
632 foreach ($sequence as $seq) {
633 if (empty($rawmods[$seq])) {
634 continue;
636 $mod[$seq]->cm = $rawmods[$seq]->id;
637 $mod[$seq]->mod = $rawmods[$seq]->modname;
638 $mod[$seq]->section = $section->section;
639 $mod[$seq]->name = urlencode(get_field($rawmods[$seq]->modname, "name", "id", $rawmods[$seq]->instance));
640 $mod[$seq]->visible = $rawmods[$seq]->visible;
641 $mod[$seq]->extra = "";
643 $modname = $mod[$seq]->mod;
644 $functionname = $modname."_get_coursemodule_info";
646 include_once("$CFG->dirroot/mod/$modname/lib.php");
648 if (function_exists($functionname)) {
649 if ($info = $functionname($rawmods[$seq])) {
650 if (!empty($info->extra)) {
651 $mod[$seq]->extra = $info->extra;
653 if (!empty($info->icon)) {
654 $mod[$seq]->icon = $info->icon;
662 return $mod;
668 function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
669 // Returns a number of useful structures for course displays
671 $mods = NULL; // course modules indexed by id
672 $modnames = NULL; // all course module names (except resource!)
673 $modnamesplural= NULL; // all course module names (plural form)
674 $modnamesused = NULL; // course module names used
676 if ($allmods = get_records("modules")) {
677 foreach ($allmods as $mod) {
678 if ($mod->visible) {
679 $modnames[$mod->name] = get_string("modulename", "$mod->name");
680 $modnamesplural[$mod->name] = get_string("modulenameplural", "$mod->name");
683 asort($modnames);
684 } else {
685 error("No modules are installed!");
688 if ($rawmods = get_course_mods($courseid)) {
689 foreach($rawmods as $mod) { // Index the mods
690 if (empty($modnames[$mod->modname])) {
691 continue;
693 $mods[$mod->id] = $mod;
694 $mods[$mod->id]->modfullname = $modnames[$mod->modname];
695 if ($mod->visible or isteacher($courseid)) {
696 $modnamesused[$mod->modname] = $modnames[$mod->modname];
699 if ($modnamesused) {
700 asort($modnamesused);
704 unset($modnames['resource']);
705 unset($modnames['label']);
709 function get_all_sections($courseid) {
711 return get_records("course_sections", "course", "$courseid", "section",
712 "section, id, course, summary, sequence, visible");
715 function course_set_display($courseid, $display=0) {
716 global $USER;
718 if (empty($USER->id)) {
719 return false;
722 if ($display == "all" or empty($display)) {
723 $display = 0;
726 if (record_exists("course_display", "userid", $USER->id, "course", $courseid)) {
727 set_field("course_display", "display", $display, "userid", $USER->id, "course", $courseid);
728 } else {
729 $record->userid = $USER->id;
730 $record->course = $courseid;
731 $record->display = $display;
732 if (!insert_record("course_display", $record)) {
733 notify("Could not save your course display!");
737 return $USER->display[$courseid] = $display; // Note: = not ==
740 function set_section_visible($courseid, $sectionnumber, $visibility) {
741 /// For a given course section, markes it visible or hidden,
742 /// and does the same for every activity in that section
744 if ($section = get_record("course_sections", "course", $courseid, "section", $sectionnumber)) {
745 set_field("course_sections", "visible", "$visibility", "id", $section->id);
746 if (!empty($section->sequence)) {
747 $modules = explode(",", $section->sequence);
748 foreach ($modules as $moduleid) {
749 set_coursemodule_visible($moduleid, $visibility);
752 rebuild_course_cache($courseid);
757 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%") {
758 /// Prints a section full of activity modules
759 global $CFG, $USER;
761 static $groupbuttons;
762 static $groupbuttonslink;
763 static $isteacher;
764 static $isediting;
765 static $ismoving;
766 static $strmovehere;
767 static $strmovefull;
768 static $strunreadpostsone;
770 static $untracked;
771 static $usetracking;
773 $labelformatoptions = New stdClass;
775 if (!isset($isteacher)) {
776 $groupbuttons = ($course->groupmode or (!$course->groupmodeforce));
777 $groupbuttonslink = (!$course->groupmodeforce);
778 $isteacher = isteacher($course->id);
779 $isediting = isediting($course->id);
780 $ismoving = $isediting && ismoving($course->id);
781 if ($ismoving) {
782 $strmovehere = get_string("movehere");
783 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
785 include_once($CFG->dirroot.'/mod/forum/lib.php');
786 if ($usetracking = forum_tp_can_track_forums()) {
787 $strunreadpostsone = get_string('unreadpostsone', 'forum');
788 $untracked = forum_tp_get_untracked_forums($USER->id, $course->id);
791 $labelformatoptions->noclean = true;
793 $modinfo = unserialize($course->modinfo);
795 echo '<table width="'.$width.'" class="section">';
796 if (!empty($section->sequence)) {
798 $sectionmods = explode(",", $section->sequence);
800 foreach ($sectionmods as $modnumber) {
801 if (empty($mods[$modnumber])) {
802 continue;
804 $mod = $mods[$modnumber];
806 if ($mod->visible or $isteacher) {
807 echo '<tr><td class="activity '.$mod->modname.'">';
808 if ($ismoving) {
809 if ($mod->id == $USER->activitycopy) {
810 continue;
812 echo '<a title="'.$strmovefull.'"'.
813 ' href="'.$CFG->wwwroot.'/course/mod.php?moveto='.$mod->id.'&amp;sesskey='.$USER->sesskey.'">'.
814 '<img class="movetarget" src="'.$CFG->pixpath.'/movehere.gif" '.
815 ' alt="'.$strmovehere.'" /></a><br />
818 $instancename = urldecode($modinfo[$modnumber]->name);
819 $instancename = format_string($instancename, true, $course->id);
821 if (!empty($modinfo[$modnumber]->extra)) {
822 $extra = urldecode($modinfo[$modnumber]->extra);
823 } else {
824 $extra = "";
827 if (!empty($modinfo[$modnumber]->icon)) {
828 $icon = "$CFG->pixpath/".urldecode($modinfo[$modnumber]->icon);
829 } else {
830 $icon = "$CFG->modpixpath/$mod->modname/icon.gif";
833 if ($mod->indent) {
834 print_spacer(12, 20 * $mod->indent, false);
837 if ($mod->modname == "label") {
838 if (!$mod->visible) {
839 echo "<span class=\"dimmed_text\">";
841 echo format_text($extra, FORMAT_HTML, $labelformatoptions);
842 if (!$mod->visible) {
843 echo "</span>";
846 } else { // Normal activity
847 $linkcss = $mod->visible ? "" : " class=\"dimmed\" ";
848 echo '<img src="'.$icon.'"'.
849 ' class="activityicon" alt="'.$mod->modfullname.'" />'.
850 ' <a title="'.$mod->modfullname.'" '.$linkcss.' '.$extra.
851 ' href="'.$CFG->wwwroot.'/mod/'.$mod->modname.'/view.php?id='.$mod->id.'">'.
852 $instancename.'</a>';
854 if ($usetracking && $mod->modname == 'forum') {
855 $groupmode = groupmode($course, $mod);
856 $groupid = ($groupmode == SEPARATEGROUPS && !isteacheredit($course->id)) ?
857 get_current_group($course->id) : false;
859 if (forum_tp_can_track_forums() && !isset($untracked[$mod->instance])) {
860 $unread = forum_tp_count_forum_unread_posts($USER->id, $mod->instance, $groupid);
861 if ($unread) {
862 echo '<span class="unread"> <a href="'.$CFG->wwwroot.'/mod/forum/view.php?id='.$mod->id.'">';
863 if ($unread == 1) {
864 echo $strunreadpostsone;
865 } else {
866 print_string('unreadpostsnumber', 'forum', $unread);
868 echo '</a> </span>';
873 if ($isediting) {
874 if ($groupbuttons and $mod->modname != 'label' and $mod->modname != 'resource') {
875 if (! $mod->groupmodelink = $groupbuttonslink) {
876 $mod->groupmode = $course->groupmode;
879 } else {
880 $mod->groupmode = false;
882 echo '&nbsp;&nbsp;';
883 echo make_editing_buttons($mod, $absolute, true, $mod->indent, $section->section);
885 echo "</td>";
886 echo "</tr>";
889 } else {
890 echo "<tr><td></td></tr>"; // needed for XHTML compatibility
892 if ($ismoving) {
893 echo '<tr><td><a title="'.$strmovefull.'"'.
894 ' href="'.$CFG->wwwroot.'/course/mod.php?movetosection='.$section->id.'&amp;sesskey='.$USER->sesskey.'">'.
895 '<img class="movetarget" src="'.$CFG->pixpath.'/movehere.gif" '.
896 ' alt="'.$strmovehere.'" /></a></td></tr>
899 echo "</table>\n\n";
903 function print_section_add_menus($course, $section, $modnames, $vertical=false, $return=false) {
904 // Prints the menus to add activities and resources
906 global $CFG, $USER;
907 static $straddactivity, $stractivities, $straddresource, $resources;
909 if (!isset($straddactivity)) {
910 $straddactivity = get_string('addactivity');
911 $straddresource = get_string('addresource');
913 /// Standard resource types
914 require_once("$CFG->dirroot/mod/resource/lib.php");
915 $resourceraw = resource_get_resource_types();
917 foreach ($resourceraw as $type => $name) {
918 $resources["resource&amp;type=$type"] = $name;
920 if (course_allowed_module($course,'label')) {
921 $resources['label'] = get_string('resourcetypelabel', 'resource');
925 $output = '<div style="text-align: right">';
926 if (course_allowed_module($course,'resource')) {
927 $resourceallowed = true;
928 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&amp;section=$section&amp;sesskey=$USER->sesskey&amp;add=",
929 $resources, "ressection$section", "", $straddresource, 'resource/types', $straddresource, true);
932 if ($vertical) {
933 $output .= '<div>';
936 // we need to loop through the forms and check to see if we can add them.
937 foreach ($modnames as $key) {
938 if (!course_allowed_module($course,$key))
939 unset($modnames[strtolower($key)]);
942 // this is stupid but labels get put into resource, so if resource is hidden and label is not, we're in trouble.
943 if (course_allowed_module($course,'label') && empty($resourceallowed)) {
944 $modnames['label'] = get_string('modulename', 'label');
947 $output .= ' ';
948 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&amp;section=$section&amp;sesskey=$USER->sesskey&amp;add=",
949 $modnames, "section$section", "", $straddactivity, 'mods', $straddactivity, true);
951 if ($vertical) {
952 $output .= '</div>';
955 $output .= '</div>';
957 if ($return) {
958 return $output;
959 } else {
960 echo $output;
964 function rebuild_course_cache($courseid=0) {
965 // Rebuilds the cached list of course activities stored in the database
966 // If a courseid is not specified, then all are rebuilt
968 if ($courseid) {
969 $select = "id = '$courseid'";
970 } else {
971 $select = "";
974 if ($courses = get_records_select("course", $select,'','id,fullname')) {
975 foreach ($courses as $course) {
976 $modinfo = serialize(get_array_of_activities($course->id));
977 if (!set_field("course", "modinfo", $modinfo, "id", $course->id)) {
978 notify("Could not cache module information for course '$course->fullname'!");
986 function make_categories_list(&$list, &$parents, $category=NULL, $path="") {
987 /// Given an empty array, this function recursively travels the
988 /// categories, building up a nice list for display. It also makes
989 /// an array that list all the parents for each category.
991 // initialize the arrays if needed
992 if (!is_array($list)) {
993 $list = array();
995 if (!is_array($parents)) {
996 $parents = array();
999 if ($category) {
1000 if ($path) {
1001 $path = $path.' / '.$category->name;
1002 } else {
1003 $path = $category->name;
1005 $list[$category->id] = $path;
1006 } else {
1007 $category->id = 0;
1010 if ($categories = get_categories($category->id)) { // Print all the children recursively
1011 foreach ($categories as $cat) {
1012 if (!empty($category->id)) {
1013 if (isset($parents[$category->id])) {
1014 $parents[$cat->id] = $parents[$category->id];
1016 $parents[$cat->id][] = $category->id;
1018 make_categories_list($list, $parents, $cat, $path);
1024 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1) {
1025 /// Recursive function to print out all the categories in a nice format
1026 /// with or without courses included
1027 global $CFG;
1029 if (isset($CFG->max_category_depth) && ($depth >= $CFG->max_category_depth)) {
1030 return;
1033 if (!$displaylist) {
1034 make_categories_list($displaylist, $parentslist);
1037 if ($category) {
1038 if ($category->visible or iscreator()) {
1039 print_category_info($category, $depth);
1040 } else {
1041 return; // Don't bother printing children of invisible categories
1044 } else {
1045 $category->id = "0";
1048 if ($categories = get_categories($category->id)) { // Print all the children recursively
1049 $countcats = count($categories);
1050 $count = 0;
1051 $first = true;
1052 $last = false;
1053 foreach ($categories as $cat) {
1054 $count++;
1055 if ($count == $countcats) {
1056 $last = true;
1058 $up = $first ? false : true;
1059 $down = $last ? false : true;
1060 $first = false;
1062 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1);
1067 // this function will return $options array for choose_from_menu, with whitespace to denote nesting.
1069 function make_categories_options() {
1070 make_categories_list($cats,$parents);
1071 foreach ($cats as $key => $value) {
1072 if (array_key_exists($key,$parents)) {
1073 if ($indent = count($parents[$key])) {
1074 for ($i = 0; $i < $indent; $i++) {
1075 $cats[$key] = '&nbsp;'.$cats[$key];
1080 return $cats;
1083 function print_category_info($category, $depth) {
1084 /// Prints the category info in indented fashion
1085 /// This function is only used by print_whole_category_list() above
1087 global $CFG;
1088 static $strallowguests, $strrequireskey, $strsummary;
1090 if (empty($strsummary)) {
1091 $strallowguests = get_string('allowguests');
1092 $strrequireskey = get_string('requireskey');
1093 $strsummary = get_string('summary');
1096 $catlinkcss = $category->visible ? '' : ' class="dimmed" ';
1098 $frontpage = explode(',', $CFG->frontpage);
1099 $frontpage = $frontpage?array_flip($frontpage):array();
1100 $coursecount = count_records('course') <= 200;
1101 if (isset($frontpage[FRONTPAGECATEGORYNAMES]) && !isset($frontpage[FRONTPAGECOURSELIST]) && $coursecount) {
1102 $catimage = '<img src="'.$CFG->pixpath.'/i/course.gif" width="16" height="16" border="0" alt="" />';
1103 } else {
1104 $catimage = "&nbsp;";
1107 echo "\n\n".'<table border="0" cellpadding="3" cellspacing="0" width="100%">';
1109 if (isset($frontpage[FRONTPAGECATEGORYNAMES]) && !isset($frontpage[FRONTPAGECOURSELIST]) && $coursecount) {
1110 $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');
1112 echo "<tr>";
1114 if ($depth) {
1115 $indent = $depth*30;
1116 $rows = count($courses) + 1;
1117 echo '<td rowspan="'.$rows.'" valign="top" width="'.$indent.'">';
1118 print_spacer(10, $indent);
1119 echo '</td>';
1122 echo '<td valign="top">'.$catimage.'</td>';
1123 echo '<td valign="top" width="100%" class="category name">';
1124 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot.'/course/category.php?id='.$category->id.'">'.$category->name.'</a>';
1125 echo '</td>';
1126 echo '<td class="category info">&nbsp;</td>';
1127 echo '</tr>';
1129 if ($courses && !(isset($CFG->max_category_depth)&&($depth>=$CFG->max_category_depth-1))) {
1130 foreach ($courses as $course) {
1131 $linkcss = $course->visible ? '' : ' class="dimmed" ';
1132 echo '<tr><td valign="top" width="30">&nbsp;';
1133 echo '</td><td valign="top" width="100%" class="course name">';
1134 echo '<a '.$linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.$course->fullname.'</a>';
1135 echo '</td><td align="right" valign="top" nowrap="nowrap" class="course info">';
1136 if ($course->guest ) {
1137 echo '<a title="'.$strallowguests.'" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">';
1138 echo '<img hspace="1" alt="'.$strallowguests.'" height="16" width="16" border="0" src="'.$CFG->pixpath.'/i/guest.gif" /></a>';
1139 } else {
1140 echo '<img alt="" height="16" width="18" border="0" src="'.$CFG->pixpath.'/spacer.gif" />';
1142 if ($course->password) {
1143 echo '<a title="'.$strrequireskey.'" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">';
1144 echo '<img hspace="1" alt="'.$strrequireskey.'" height="16" width="16" border="0" src="'.$CFG->pixpath.'/i/key.gif" /></a>';
1145 } else {
1146 echo '<img alt="" height="16" width="18" border="0" src="'.$CFG->pixpath.'/spacer.gif" />';
1148 if ($course->summary) {
1149 link_to_popup_window ('/course/info.php?id='.$course->id, 'courseinfo',
1150 '<img hspace="1" alt="'.$strsummary.'" height="16" width="16" border="0" src="'.$CFG->pixpath.'/i/info.gif" />',
1151 400, 500, $strsummary);
1152 } else {
1153 echo '<img alt="" height="16" width="18" border="0" src="'.$CFG->pixpath.'/spacer.gif" />';
1155 echo '</td></tr>';
1158 } else {
1160 echo '<tr>';
1162 if ($depth) {
1163 $indent = $depth*20;
1164 echo '<td valign="top" width="'.$indent.'">';
1165 print_spacer(10, $indent);
1166 echo '</td>';
1169 echo '<td valign="top" width="100%" class="category name">';
1170 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot.'/course/category.php?id='.$category->id.'">'.$category->name.'</a>';
1171 echo '</td>';
1172 echo '<td valign="top" class="category number">';
1173 if ($category->coursecount) {
1174 echo $category->coursecount;
1176 echo '</td></tr>';
1178 echo '</table>';
1182 function print_courses($category, $width="100%", $hidesitecourse = false) {
1183 /// Category is 0 (for all courses) or an object
1185 global $CFG;
1187 if (empty($category)) {
1188 $categories = get_categories(0); // Parent = 0 ie top-level categories only
1189 if (count($categories) == 1) {
1190 $category = array_shift($categories);
1191 $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');
1192 } else {
1193 $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');
1195 unset($categories);
1196 } else {
1197 $categories = get_categories($category->id); // sub categories
1198 $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');
1201 if ($courses) {
1202 foreach ($courses as $course) {
1203 if ($hidesitecourse && !$course->category) {
1204 continue;
1206 print_course($course, $width);
1208 } else {
1209 print_heading(get_string("nocoursesyet"));
1215 function print_course($course, $width="100%") {
1217 global $CFG, $USER;
1219 require_once("$CFG->dirroot/enrol/enrol.class.php");
1221 $enrol = enrolment_factory::factory($course->enrol);
1223 print_simple_box_start("center", "$width", '', 5, "coursebox");
1225 $linkcss = $course->visible ? "" : " class=\"dimmed\" ";
1227 echo "<table width=\"100%\">";
1228 echo '<tr valign="top">';
1229 echo '<td valign="top" width="50%" class="info">';
1230 echo '<b><a title="'.get_string('entercourse').'"'.
1231 $linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.
1232 $course->fullname.'</a></b><br />';
1233 if ($teachers = get_course_teachers($course->id)) {
1234 echo "<span class=\"teachers\">\n";
1235 foreach ($teachers as $teacher) {
1236 if ($teacher->authority > 0) {
1237 if (!$teacher->role) {
1238 $teacher->role = $course->teacher;
1240 $fullname = fullname($teacher, isteacher($course->id)); // is the USER a teacher of that course
1241 echo $teacher->role.': <a href="'.$CFG->wwwroot.'/user/view.php?id='.$teacher->id.
1242 '&amp;course='.SITEID.'">'.$fullname.'</a><br />';
1245 echo "</span>\n";
1248 echo $enrol->get_access_icons($course);
1250 echo '</td><td valign="top" width="50%" class="summary">';
1251 $options = NULL;
1252 $options->noclean = true;
1253 $options->para = false;
1254 echo format_text($course->summary, FORMAT_MOODLE, $options, $course->id);
1255 echo "</td></tr>";
1256 echo "</table>";
1258 print_simple_box_end();
1262 function print_my_moodle() {
1263 /// Prints custom user information on the home page.
1264 /// Over time this can include all sorts of information
1266 global $USER, $CFG;
1268 if (!isset($USER->id)) {
1269 error("It shouldn't be possible to see My Moodle without being logged in.");
1272 if ($courses = get_my_courses($USER->id)) {
1273 foreach ($courses as $course) {
1274 if (!$course->category) {
1275 continue;
1277 print_course($course, "100%");
1280 if (count_records("course") > (count($courses) + 1) ) { // Some courses not being displayed
1281 echo "<table width=\"100%\"><tr><td align=\"center\">";
1282 print_course_search("", false, "short");
1283 echo "</td><td align=\"center\">";
1284 print_single_button("$CFG->wwwroot/course/index.php", NULL, get_string("fulllistofcourses"), "get");
1285 echo "</td></tr></table>\n";
1287 } else {
1288 if (count_records("course_categories") > 1) {
1289 print_simple_box_start("center", "100%", "#FFFFFF", 5, "categorybox");
1290 print_whole_category_list();
1291 print_simple_box_end();
1292 } else {
1293 print_courses(0, "100%");
1299 function print_course_search($value="", $return=false, $format="plain") {
1301 global $CFG;
1303 $strsearchcourses= get_string("searchcourses");
1305 if ($format == 'plain') {
1306 $output = '<form name="coursesearch" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
1307 $output .= '<center><p align="center" class="coursesearchbox">';
1308 $output .= '<input type="text" size="30" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
1309 $output .= '<input type="submit" value="'.s($strsearchcourses).'" />';
1310 $output .= '</p></center></form>';
1311 } else if ($format == 'short') {
1312 $output = '<form name="coursesearch" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
1313 $output .= '<center><p align="center" class="coursesearchbox">';
1314 $output .= '<input type="text" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
1315 $output .= '<input type="submit" value="'.s($strsearchcourses).'" />';
1316 $output .= '</p></center></form>';
1317 } else if ($format == 'navbar') {
1318 $output = '<form name="coursesearch" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
1319 $output .= '<table border="0" cellpadding="0" cellspacing="0"><tr><td nowrap="nowrap">';
1320 $output .= '<input type="text" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
1321 $output .= '<input type="submit" value="'.s($strsearchcourses).'" />';
1322 $output .= '</td></tr></table>';
1323 $output .= '</form>';
1326 if ($return) {
1327 return $output;
1329 echo $output;
1332 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
1334 function add_course_module($mod) {
1336 $mod->added = time();
1337 unset($mod->id);
1339 return insert_record("course_modules", $mod);
1342 function add_mod_to_section($mod, $beforemod=NULL) {
1343 /// Given a full mod object with section and course already defined
1344 /// If $before is specified, then this is an existing ID which we
1345 /// will insert the new module before
1347 /// Returns the course_sections ID where the mod is inserted
1349 if ($section = get_record("course_sections", "course", "$mod->course", "section", "$mod->section")) {
1351 $section->sequence = trim($section->sequence);
1353 if (empty($section->sequence)) {
1354 $newsequence = "$mod->coursemodule";
1356 } else if ($beforemod) {
1357 $modarray = explode(",", $section->sequence);
1359 if ($key = array_keys ($modarray, $beforemod->id)) {
1360 $insertarray = array($mod->id, $beforemod->id);
1361 array_splice($modarray, $key[0], 1, $insertarray);
1362 $newsequence = implode(",", $modarray);
1364 } else { // Just tack it on the end anyway
1365 $newsequence = "$section->sequence,$mod->coursemodule";
1368 } else {
1369 $newsequence = "$section->sequence,$mod->coursemodule";
1372 if (set_field("course_sections", "sequence", $newsequence, "id", $section->id)) {
1373 return $section->id; // Return course_sections ID that was used.
1374 } else {
1375 return 0;
1378 } else { // Insert a new record
1379 $section->course = $mod->course;
1380 $section->section = $mod->section;
1381 $section->summary = "";
1382 $section->sequence = $mod->coursemodule;
1383 return insert_record("course_sections", $section);
1387 function set_coursemodule_groupmode($id, $groupmode) {
1388 return set_field("course_modules", "groupmode", $groupmode, "id", $id);
1391 function set_coursemodule_visible($id, $visible) {
1392 $cm = get_record('course_modules', 'id', $id);
1393 $modulename = get_field('modules', 'name', 'id', $cm->module);
1394 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
1395 foreach($events as $event) {
1396 if ($visible) {
1397 show_event($event);
1398 } else {
1399 hide_event($event);
1403 return set_field("course_modules", "visible", $visible, "id", $id);
1407 * Delete a course module and any associated data at the course level (events)
1408 * Until 1.5 this function simply marked a deleted flag ... now it
1409 * deletes it completely.
1412 function delete_course_module($id) {
1413 if (!$cm = get_record('course_modules', 'id', $id)) {
1414 return true;
1416 $modulename = get_field('modules', 'name', 'id', $cm->module);
1417 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
1418 foreach($events as $event) {
1419 delete_event($event);
1422 return delete_records('course_modules', 'id', $cm->id);
1425 function delete_mod_from_section($mod, $section) {
1427 if ($section = get_record("course_sections", "id", "$section") ) {
1429 $modarray = explode(",", $section->sequence);
1431 if ($key = array_keys ($modarray, $mod)) {
1432 array_splice($modarray, $key[0], 1);
1433 $newsequence = implode(",", $modarray);
1434 return set_field("course_sections", "sequence", $newsequence, "id", $section->id);
1435 } else {
1436 return false;
1440 return false;
1443 function move_section($course, $section, $move) {
1444 /// Moves a whole course section up and down within the course
1445 global $USER;
1447 if (!$move) {
1448 return true;
1451 $sectiondest = $section + $move;
1453 if ($sectiondest > $course->numsections or $sectiondest < 1) {
1454 return false;
1457 if (!$sectionrecord = get_record("course_sections", "course", $course->id, "section", $section)) {
1458 return false;
1461 if (!$sectiondestrecord = get_record("course_sections", "course", $course->id, "section", $sectiondest)) {
1462 return false;
1465 if (!set_field("course_sections", "section", $sectiondest, "id", $sectionrecord->id)) {
1466 return false;
1468 if (!set_field("course_sections", "section", $section, "id", $sectiondestrecord->id)) {
1469 return false;
1471 // if the focus is on the section that is being moved, then move the focus along
1472 if (isset($USER->display[$course->id]) and ($USER->display[$course->id] == $section)) {
1473 course_set_display($course->id, $sectiondest);
1476 // Check for duplicates.
1477 // There is a very rare case that some sections in the same course have the same section id.
1478 if (($count_section = count_records('course_sections', 'course', $course->id) - 1) != $course->numsections) {
1479 $sections = get_records_select('course_sections', "course = $course->id AND section > 0", 'section ASC');
1480 $n = 1;
1481 foreach ($sections as $section) {
1482 if (!set_field('course_sections', 'section', $n, 'id', $section->id)) {
1483 return false;
1485 $n++;
1487 if (!set_field('course', 'numsections', $count_section, 'id', $course->id)) {
1488 return false;
1491 return true;
1495 function moveto_module($mod, $section, $beforemod=NULL) {
1496 /// All parameters are objects
1497 /// Move the module object $mod to the specified $section
1498 /// If $beforemod exists then that is the module
1499 /// before which $modid should be inserted
1501 /// Remove original module from original section
1503 if (! delete_mod_from_section($mod->id, $mod->section)) {
1504 notify("Could not delete module from existing section");
1507 /// Update module itself if necessary
1509 if ($mod->section != $section->id) {
1510 $mod->section = $section->id;
1511 if (!update_record("course_modules", $mod)) {
1512 return false;
1514 // if moving to a hidden section then hide module
1515 if (!$section->visible) {
1516 set_coursemodule_visible($mod->id, 0);
1520 /// Add the module into the new section
1522 $mod->course = $section->course;
1523 $mod->section = $section->section; // need relative reference
1524 $mod->coursemodule = $mod->id;
1526 if (! add_mod_to_section($mod, $beforemod)) {
1527 return false;
1530 return true;
1534 function make_editing_buttons($mod, $absolute=false, $moveselect=true, $indent=-1, $section=-1) {
1535 global $CFG, $USER;
1537 static $str;
1538 static $sesskey;
1540 if (!isset($str)) {
1541 $str->delete = get_string("delete");
1542 $str->move = get_string("move");
1543 $str->moveup = get_string("moveup");
1544 $str->movedown = get_string("movedown");
1545 $str->moveright = get_string("moveright");
1546 $str->moveleft = get_string("moveleft");
1547 $str->update = get_string("update");
1548 $str->duplicate = get_string("duplicate");
1549 $str->hide = get_string("hide");
1550 $str->show = get_string("show");
1551 $str->clicktochange = get_string("clicktochange");
1552 $str->forcedmode = get_string("forcedmode");
1553 $str->groupsnone = get_string("groupsnone");
1554 $str->groupsseparate = get_string("groupsseparate");
1555 $str->groupsvisible = get_string("groupsvisible");
1556 $sesskey = sesskey();
1559 if ($section >= 0) {
1560 $section = '&amp;sr='.$section; // Section return
1561 } else {
1562 $section = '';
1565 if ($absolute) {
1566 $path = $CFG->wwwroot.'/course';
1567 } else {
1568 $path = '.';
1571 if ($mod->visible) {
1572 $hideshow = '<a title="'.$str->hide.'" href="'.$path.'/mod.php?hide='.$mod->id.
1573 '&amp;sesskey='.$sesskey.$section.'"><img'.
1574 ' src="'.$CFG->pixpath.'/t/hide.gif" hspace="2" height="11" width="11" '.
1575 ' border="0" alt="'.$str->hide.'" /></a> ';
1576 } else {
1577 $hideshow = '<a title="'.$str->show.'" href="'.$path.'/mod.php?show='.$mod->id.
1578 '&amp;sesskey='.$sesskey.$section.'"><img'.
1579 ' src="'.$CFG->pixpath.'/t/show.gif" hspace="2" height="11" width="11" '.
1580 ' border="0" alt="'.$str->show.'" /></a> ';
1582 if ($mod->groupmode !== false) {
1583 if ($mod->groupmode == SEPARATEGROUPS) {
1584 $grouptitle = $str->groupsseparate;
1585 $groupimage = $CFG->pixpath.'/t/groups.gif';
1586 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=0&amp;sesskey='.$sesskey;
1587 } else if ($mod->groupmode == VISIBLEGROUPS) {
1588 $grouptitle = $str->groupsvisible;
1589 $groupimage = $CFG->pixpath.'/t/groupv.gif';
1590 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=1&amp;sesskey='.$sesskey;
1591 } else {
1592 $grouptitle = $str->groupsnone;
1593 $groupimage = $CFG->pixpath.'/t/groupn.gif';
1594 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=2&amp;sesskey='.$sesskey;
1596 if ($mod->groupmodelink) {
1597 $groupmode = '<a title="'.$grouptitle.' ('.$str->clicktochange.')" href="'.$grouplink.'">'.
1598 '<img src="'.$groupimage.'" hspace="2" height="11" width="11" '.
1599 'border="0" alt="'.$grouptitle.'" /></a>';
1600 } else {
1601 $groupmode = '<img title="'.$grouptitle.' ('.$str->forcedmode.')" '.
1602 ' src="'.$groupimage.'" hspace="2" height="11" width="11" '.
1603 'border="0" alt="'.$grouptitle.'" />';
1605 } else {
1606 $groupmode = "";
1609 if ($moveselect) {
1610 $move = '<a title="'.$str->move.'" href="'.$path.'/mod.php?copy='.$mod->id.
1611 '&amp;sesskey='.$sesskey.$section.'"><img'.
1612 ' src="'.$CFG->pixpath.'/t/move.gif" hspace="2" height="11" width="11" '.
1613 ' border="0" alt="'.$str->move.'" /></a>';
1614 } else {
1615 $move = '<a title="'.$str->moveup.'" href="'.$path.'/mod.php?id='.$mod->id.
1616 '&amp;move=-1&amp;sesskey='.$sesskey.$section.'"><img'.
1617 ' src="'.$CFG->pixpath.'/t/up.gif" hspace="2" height="11" width="11" '.
1618 ' border="0" alt="'.$str->moveup.'" /></a>'.
1619 '<a title="'.$str->movedown.'" href="'.$path.'/mod.php?id='.$mod->id.
1620 '&amp;move=1&amp;sesskey='.$sesskey.$section.'"><img'.
1621 ' src="'.$CFG->pixpath.'/t/down.gif" hspace="2" height="11" width="11" '.
1622 ' border="0" alt="'.$str->movedown.'" /></a>';
1625 $leftright = "";
1626 if ($indent > 0) {
1627 $leftright .= '<a title="'.$str->moveleft.'" href="'.$path.'/mod.php?id='.$mod->id.
1628 '&amp;indent=-1&amp;sesskey='.$sesskey.$section.'"><img'.
1629 ' src="'.$CFG->pixpath.'/t/left.gif" hspace="2" height="11" width="11" '.
1630 ' border="0" alt="'.$str->moveleft.'" /></a>';
1632 if ($indent >= 0) {
1633 $leftright .= '<a title="'.$str->moveright.'" href="'.$path.'/mod.php?id='.$mod->id.
1634 '&amp;indent=1&amp;sesskey='.$sesskey.$section.'"><img'.
1635 ' src="'.$CFG->pixpath.'/t/right.gif" hspace="2" height="11" width="11" '.
1636 ' border="0" alt="'.$str->moveright.'" /></a>';
1639 return '<span class="commands">'.$leftright.$move.
1640 '<a title="'.$str->update.'" href="'.$path.'/mod.php?update='.$mod->id.
1641 '&amp;sesskey='.$sesskey.$section.'"><img'.
1642 ' src="'.$CFG->pixpath.'/t/edit.gif" hspace="2" height="11" width="11" border="0" '.
1643 ' alt="'.$str->update.'" /></a>'.
1644 '<a title="'.$str->delete.'" href="'.$path.'/mod.php?delete='.$mod->id.
1645 '&amp;sesskey='.$sesskey.$section.'"><img'.
1646 ' src="'.$CFG->pixpath.'/t/delete.gif" hspace="2" height="11" width="11" border="0" '.
1647 ' alt="'.$str->delete.'" /></a>'.$hideshow.$groupmode.'</span>';
1651 * given a course object with shortname & fullname, this function will
1652 * truncate the the number of chars allowed and add ... if it was too long
1654 function course_format_name ($course,$max=100) {
1656 $str = $course->shortname.': '.$course->fullname;
1657 if (strlen($str) <= $max) {
1658 return $str;
1660 else {
1661 return substr($str,0,$max-3).'...';
1666 * This function will return true if the given course is a child course at all
1668 function course_in_meta ($course) {
1669 return record_exists("course_meta","child_course",$course->id);
1674 * Print standard form elements on module setup forms in mod/.../mod.html
1676 function print_standard_coursemodule_settings($form) {
1677 if (! $course = get_record('course', 'id', $form->course)) {
1678 error("This course doesn't exist");
1680 print_groupmode_setting($form, $course);
1681 print_visible_setting($form, $course);
1685 * Print groupmode form element on module setup forms in mod/.../mod.html
1687 function print_groupmode_setting($form, $course=NULL) {
1689 if (empty($course)) {
1690 if (! $course = get_record('course', 'id', $form->course)) {
1691 error("This course doesn't exist");
1694 if ($form->coursemodule) {
1695 if (! $cm = get_record('course_modules', 'id', $form->coursemodule)) {
1696 error("This course module doesn't exist");
1698 } else {
1699 $cm = null;
1701 $groupmode = groupmode($course, $cm);
1702 if ($course->groupmode or (!$course->groupmodeforce)) {
1703 echo '<tr valign="top">';
1704 echo '<td align="right"><b>'.get_string('groupmode').':</b></td>';
1705 echo '<td align="left">';
1706 unset($choices);
1707 $choices[NOGROUPS] = get_string('groupsnone');
1708 $choices[SEPARATEGROUPS] = get_string('groupsseparate');
1709 $choices[VISIBLEGROUPS] = get_string('groupsvisible');
1710 choose_from_menu($choices, 'groupmode', $groupmode, '', '', 0, false, $course->groupmodeforce);
1711 helpbutton('groupmode', get_string('groupmode'));
1712 echo '</td></tr>';
1717 * Print visibility setting form element on module setup forms in mod/.../mod.html
1719 function print_visible_setting($form, $course=NULL) {
1720 if (empty($course)) {
1721 if (! $course = get_record('course', 'id', $form->course)) {
1722 error("This course doesn't exist");
1725 if ($form->coursemodule) {
1726 $visible = get_field('course_modules', 'visible', 'id', $form->coursemodule);
1727 } else {
1728 $visible = true;
1731 if ($form->mode == 'add') { // in this case $form->section is the section number, not the id
1732 $hiddensection = !get_field('course_sections', 'visible', 'section', $form->section, 'course', $form->course);
1733 } else {
1734 $hiddensection = !get_field('course_sections', 'visible', 'id', $form->section);
1736 if ($hiddensection) {
1737 $visible = false;
1740 echo '<tr valign="top">';
1741 echo '<td align="right"><b>'.get_string('visibletostudents','',moodle_strtolower($course->students)).':</b></td>';
1742 echo '<td align="left">';
1743 unset($choices);
1744 $choices[1] = get_string('show');
1745 $choices[0] = get_string('hide');
1746 choose_from_menu($choices, 'visible', $visible, '', '', 0, false, $hiddensection);
1747 echo '</td></tr>';
1750 function update_restricted_mods($course,$mods) {
1751 delete_records("course_allowed_modules","course",$course->id);
1752 if (empty($course->restrictmodules)) {
1753 return;
1755 else {
1756 foreach ($mods as $mod) {
1757 if ($mod == 0)
1758 continue; // this is the 'allow none' option
1759 $am->course = $course->id;
1760 $am->module = $mod;
1761 insert_record("course_allowed_modules",$am);
1767 * This function will take an int (module id) or a string (module name)
1768 * and return true or false, whether it's allowed in the given course (object)
1769 * $mod is not allowed to be an object, as the field for the module id is inconsistent
1770 * depending on where in the code it's called from (sometimes $mod->id, sometimes $mod->module)
1773 function course_allowed_module($course,$mod) {
1774 if (empty($course->restrictmodules)) {
1775 return true;
1777 if (isadmin()) {
1778 return true;
1780 if (is_numeric($mod)) {
1781 $modid = $mod;
1782 } else if (is_string($mod)) {
1783 if ($mod = get_field("modules","id","name",strtolower($mod)))
1784 $modid = $mod;
1786 if (empty($modid)) {
1787 return false;
1789 return (record_exists("course_allowed_modules","course",$course->id,"module",$modid));
1792 /***
1793 *** Efficiently moves many courses around while maintaining
1794 *** sortorder in order.
1795 ***
1796 *** $courseids is an array of course ids
1800 function move_courses ($courseids, $categoryid) {
1802 global $CFG;
1804 if (!empty($courseids)) {
1806 $courseids = array_reverse($courseids);
1808 foreach ($courseids as $courseid) {
1810 if (! $course = get_record("course", "id", $courseid)) {
1811 notify("Error finding course $courseid");
1812 } else {
1813 // figure out a sortorder that we can use in the destination category
1814 $sortorder = get_field_sql('SELECT MIN(sortorder)-1 AS min
1815 FROM ' . $CFG->prefix . 'course WHERE category=' . $categoryid);
1816 if ($sortorder === false) {
1817 // the category is empty
1818 // rather than let the db default to 0
1819 // set it to > 100 and avoid extra work in fix_coursesortorder()
1820 $sortorder = 200;
1821 } else if ($sortorder < 10) {
1822 fix_course_sortorder($categoryid);
1825 $course->category = $categoryid;
1826 $course->sortorder = $sortorder;
1827 $course->fullname = addslashes($course->fullname);
1828 $course->shortname = addslashes($course->shortname);
1829 $course->summary = addslashes($course->summary);
1830 $course->password = addslashes($course->password);
1831 $course->teacher = addslashes($course->teacher);
1832 $course->teachers = addslashes($course->teachers);
1833 $course->student = addslashes($course->student);
1834 $course->students = addslashes($course->students);
1836 if (!update_record('course', $course)) {
1837 notify("An error occurred - course not moved!");
1841 fix_course_sortorder();
1843 return true;