MDL-11517 reserved word MOD used in table alias in questions backup code
[moodle-pu.git] / course / lib.php
blobd4374ecfdb8b9577bd92c380b77586b691cb1c4a
1 <?php // $Id$
2 // Library of useful functions
5 if (defined('COURSE_MAX_LOG_DISPLAY')) { // Being included again - should never happen!!
6 return;
9 define('COURSE_MAX_LOG_DISPLAY', 150); // days
10 define('COURSE_MAX_LOGS_PER_PAGE', 1000); // records
11 define('COURSE_LIVELOG_REFRESH', 60); // Seconds
12 define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds
13 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10); // courses
14 define('COURSE_MAX_COURSES_PER_DROPDOWN',1000); // max courses in log dropdown before switching to optional
15 define('COURSE_MAX_USERS_PER_DROPDOWN',1000); // max users in log dropdown before switching to optional
16 define('FRONTPAGENEWS', 0);
17 define('FRONTPAGECOURSELIST', 1);
18 define('FRONTPAGECATEGORYNAMES', 2);
19 define('FRONTPAGETOPICONLY', 3);
20 define('FRONTPAGECATEGORYCOMBO', 4);
21 define('FRONTPAGECOURSELIMIT', 200); // maximum number of courses displayed on the frontpage
22 define('EXCELROWS', 65535);
23 define('FIRSTUSEDEXCELROW', 3);
25 define('MOD_CLASS_ACTIVITY', 0);
26 define('MOD_CLASS_RESOURCE', 1);
29 function print_recent_selector_form($course, $advancedfilter=0, $selecteduser=0, $selecteddate="lastlogin",
30 $mod="", $modid="activity/All", $modaction="", $selectedgroup="", $selectedsort="default") {
32 global $USER, $CFG;
34 if ($advancedfilter) {
36 // Get all the possible users
37 $users = array();
39 if ($courseusers = get_course_users($course->id, '', '', 'u.id, u.firstname, u.lastname')) {
40 foreach ($courseusers as $courseuser) {
41 $users[$courseuser->id] = fullname($courseuser, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
44 if ($guest = get_guest()) {
45 $users[$guest->id] = fullname($guest);
48 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
49 if ($ccc = get_records("course", "", "", "fullname")) {
50 foreach ($ccc as $cc) {
51 if ($cc->category) {
52 $courses["$cc->id"] = "$cc->fullname";
53 } else {
54 $courses["$cc->id"] = " $cc->fullname (Site)";
58 asort($courses);
61 $activities = array();
63 $selectedactivity = $modid;
65 /// Casting $course->modinfo to string prevents one notice when the field is null
66 if ($modinfo = unserialize((string)$course->modinfo)) {
67 $section = 0;
68 if ($course->format == 'weeks') { // Body
69 $strsection = get_string("week");
70 } else {
71 $strsection = get_string("topic");
74 $activities["activity/All"] = "All activities";
75 $activities["activity/Assignments"] = "All assignments";
76 $activities["activity/Chats"] = "All chats";
77 $activities["activity/Forums"] = "All forums";
78 $activities["activity/Quizzes"] = "All quizzes";
79 $activities["activity/Workshops"] = "All workshops";
81 $activities["section/individual"] = "------------- Individual Activities --------------";
83 foreach ($modinfo as $mod) {
84 if ($mod->mod == "label") {
85 continue;
87 if (!$mod->visible and !has_capability('moodle/course:viewhiddenactivities',get_context_instance(CONTEXT_MODULE, $mod->cm))) {
88 continue;
90 $mod->id = $mod->cm;
91 if (!groups_course_module_visible($mod)) {
92 continue;
95 if ($mod->section > 0 and $section <> $mod->section) {
96 $activities["section/$mod->section"] = "-------------- $strsection $mod->section --------------";
98 $section = $mod->section;
99 $mod->name = strip_tags(format_string(urldecode($mod->name),true));
100 if (strlen($mod->name) > 55) {
101 $mod->name = substr($mod->name, 0, 50)."...";
103 if (!$mod->visible) {
104 $mod->name = "(".$mod->name.")";
106 $activities["$mod->cm"] = $mod->name;
108 if ($mod->cm == $modid) {
109 $selectedactivity = "$mod->cm";
114 $strftimedate = get_string("strftimedate");
115 $strftimedaydate = get_string("strftimedaydate");
117 asort($users);
119 // Get all the possible dates
120 // Note that we are keeping track of real (GMT) time and user time
121 // User time is only used in displays - all calcs and passing is GMT
123 $timenow = time(); // GMT
125 // What day is it now for the user, and when is midnight that day (in GMT).
126 $timemidnight = $today = usergetmidnight($timenow);
128 $dates = array();
129 $dates["$USER->lastlogin"] = get_string("lastlogin").", ".userdate($USER->lastlogin, $strftimedate);
130 $dates["$timemidnight"] = get_string("today").", ".userdate($timenow, $strftimedate);
132 if (!$course->startdate or ($course->startdate > $timenow)) {
133 $course->startdate = $course->timecreated;
136 $numdates = 1;
137 while ($timemidnight > $course->startdate and $numdates < 365) {
138 $timemidnight = $timemidnight - 86400;
139 $timenow = $timenow - 86400;
140 $dates["$timemidnight"] = userdate($timenow, $strftimedaydate);
141 $numdates++;
144 if ($selecteddate === "lastlogin") {
145 $selecteddate = $USER->lastlogin;
148 echo '<form action="recent.php" method="get">';
149 echo '<input type="hidden" name="chooserecent" value="1" />';
150 echo "<center>";
151 echo "<table>";
153 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
154 echo "<tr><td><b>" . get_string("courses") . "</b></td><td>";
155 choose_from_menu ($courses, "id", $course->id, "");
156 echo "</td></tr>";
157 } else {
158 echo '<input type="hidden" name="id" value="'.$course->id.'" />';
161 $sortfields = array("default" => get_string("bycourseorder"),"dateasc" => get_string("datemostrecentlast"), "datedesc" => get_string("datemostrecentfirst"));
163 echo "<tr><td><b>" . get_string("participants") . "</b></td><td>";
164 choose_from_menu ($users, "user", $selecteduser, get_string("allparticipants") );
165 echo "</td>";
167 echo '<td align="right"><b>' . get_string("since") . '</b></td><td>';
168 choose_from_menu ($dates, "date", $selecteddate, get_string("alldays"));
169 echo "</td></tr>";
171 echo "<tr><td><b>" . get_string("activities") . "</b></td><td>";
172 choose_from_menu ($activities, "modid", $selectedactivity, "");
173 echo "</td>";
175 echo '<td align="right"><b>' . get_string("sortby") . "</b></td><td>";
176 choose_from_menu ($sortfields, "sortby", $selectedsort, "");
177 echo "</td></tr>";
179 echo '<tr>';
181 $groupmode = groups_get_course_groupmode($course);
183 if ($groupmode == VISIBLEGROUPS or ($groupmode and has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id)))) {
184 if ($groups = groups_get_all_groups($course->id)) {
185 $group_names = array();
186 foreach($groups as $group) {
187 $group_names[$group->id] = format_string($group->name);
189 echo '<td><b>';
190 if ($groupmode == VISIBLEGROUPS) {
191 print_string('groupsvisible');
192 } else {
193 print_string('groupsseparate');
195 echo ':</b></td><td>';
196 choose_from_menu($group_names, "selectedgroup", $selectedgroup, get_string("allgroups"), "", "");
197 echo '</td>';
202 echo '<td colspan="2" align="right">';
203 echo '<input type="submit" value="'.get_string('showrecent').'" />';
204 echo "</td></tr>";
206 echo "</table>";
208 $advancedlink = "<a href=\"$CFG->wwwroot/course/recent.php?id=$course->id&amp;advancedfilter=0\">" . get_string("normalfilter") . "</a>";
209 print_heading($advancedlink);
210 echo "</center>";
211 echo "</form>";
213 } else {
215 $day_list = array("1","7","14","21","30");
216 $strsince = get_string("since");
217 $strlastlogin = get_string("lastlogin");
218 $strday = get_string("day");
219 $strdays = get_string("days");
221 $heading = "";
222 foreach ($day_list as $count) {
223 if ($count == "1") {
224 $day = $strday;
225 } else {
226 $day = $strdays;
228 $tmpdate = time() - ($count * 3600 * 24);
229 $heading = $heading .
230 "<a href=\"$CFG->wwwroot/course/recent.php?id=$course->id&amp;date=$tmpdate\"> $count $day</a> | ";
233 $heading = $strsince . ": <a href=\"$CFG->wwwroot/course/recent.php?id=$course->id\">$strlastlogin</a>" . " | " . $heading;
234 print_heading($heading);
236 $advancedlink = "<a href=\"$CFG->wwwroot/course/recent.php?id=$course->id&amp;advancedfilter=1\">" . get_string("advancedfilter") . "</a>";
237 print_heading($advancedlink);
244 function make_log_url($module, $url) {
245 switch ($module) {
246 case 'user':
247 case 'course':
248 case 'file':
249 case 'login':
250 case 'lib':
251 case 'admin':
252 case 'message':
253 case 'calendar':
254 case 'mnet course':
255 return "/course/$url";
256 break;
257 case 'blog':
258 return "/$module/$url";
259 break;
260 case 'upload':
261 return $url;
262 break;
263 case 'library':
264 case '':
265 return '/';
266 break;
267 default:
268 return "/mod/$module/$url";
269 break;
274 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
275 $modname="", $modid=0, $modaction="", $groupid=0) {
277 global $CFG;
279 // It is assumed that $date is the GMT time of midnight for that day,
280 // and so the next 86400 seconds worth of logs are printed.
282 /// Setup for group handling.
284 // TODO: I don't understand group/context/etc. enough to be able to do
285 // something interesting with it here
286 // What is the context of a remote course?
288 /// If the group mode is separate, and this user does not have editing privileges,
289 /// then only the user's group can be viewed.
290 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
291 // $groupid = get_current_group($course->id);
293 /// If this course doesn't have groups, no groupid can be specified.
294 //else if (!$course->groupmode) {
295 // $groupid = 0;
297 $groupid = 0;
299 $joins = array();
301 $qry = "
302 SELECT
303 l.*,
304 u.firstname,
305 u.lastname,
306 u.picture
307 FROM
308 {$CFG->prefix}mnet_log l
309 LEFT JOIN
310 {$CFG->prefix}user u
312 l.userid = u.id
313 WHERE
316 $where .= "l.hostid = '$hostid'";
318 // TODO: Is 1 really a magic number referring to the sitename?
319 if ($course != 1 || $modid != 0) {
320 $where .= " AND\n l.course='$course'";
323 if ($modname) {
324 $where .= " AND\n l.module = '$modname'";
327 if ('site_errors' === $modid) {
328 $where .= " AND\n ( l.action='error' OR l.action='infected' )";
329 } else if ($modid) {
330 //TODO: This assumes that modids are the same across sites... probably
331 //not true
332 $where .= " AND\n l.cmid = '$modid'";
335 if ($modaction) {
336 $firstletter = substr($modaction, 0, 1);
337 if (ctype_alpha($firstletter)) {
338 $where .= " AND\n lower(l.action) LIKE '%" . strtolower($modaction) . "%'";
339 } else if ($firstletter == '-') {
340 $where .= " AND\n lower(l.action) NOT LIKE '%" . strtolower(substr($modaction, 1)) . "%'";
344 if ($user) {
345 $where .= " AND\n l.userid = '$user'";
348 if ($date) {
349 $enddate = $date + 86400;
350 $where .= " AND\n l.time > '$date' AND l.time < '$enddate'";
353 $result = array();
354 $result['totalcount'] = count_records_sql("SELECT COUNT(*) FROM {$CFG->prefix}mnet_log l WHERE $where");
355 if(!empty($result['totalcount'])) {
356 $where .= "\n ORDER BY\n $order";
357 $result['logs'] = get_records_sql($qry.$where, $limitfrom, $limitnum);
358 } else {
359 $result['logs'] = array();
361 return $result;
364 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
365 $modname="", $modid=0, $modaction="", $groupid=0) {
367 // It is assumed that $date is the GMT time of midnight for that day,
368 // and so the next 86400 seconds worth of logs are printed.
370 /// Setup for group handling.
372 /// If the group mode is separate, and this user does not have editing privileges,
373 /// then only the user's group can be viewed.
374 if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
375 $groupid = get_current_group($course->id);
377 /// If this course doesn't have groups, no groupid can be specified.
378 else if (!$course->groupmode) {
379 $groupid = 0;
382 $joins = array();
384 if ($course->id != SITEID || $modid != 0) {
385 $joins[] = "l.course='$course->id'";
388 if ($modname) {
389 $joins[] = "l.module = '$modname'";
392 if ('site_errors' === $modid) {
393 $joins[] = "( l.action='error' OR l.action='infected' )";
394 } else if ($modid) {
395 $joins[] = "l.cmid = '$modid'";
398 if ($modaction) {
399 $firstletter = substr($modaction, 0, 1);
400 if (ctype_alpha($firstletter)) {
401 $joins[] = "lower(l.action) LIKE '%" . strtolower($modaction) . "%'";
402 } else if ($firstletter == '-') {
403 $joins[] = "lower(l.action) NOT LIKE '%" . strtolower(substr($modaction, 1)) . "%'";
407 /// Getting all members of a group.
408 if ($groupid and !$user) {
409 if ($gusers = groups_get_members($groupid)) {
410 $gusers = array_keys($gusers);
411 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
412 } else {
413 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always by false.
416 else if ($user) {
417 $joins[] = "l.userid = '$user'";
420 if ($date) {
421 $enddate = $date + 86400;
422 $joins[] = "l.time > '$date' AND l.time < '$enddate'";
425 $selector = implode(' AND ', $joins);
427 $totalcount = 0; // Initialise
428 $result = array();
429 $result['logs'] = get_logs($selector, $order, $limitfrom, $limitnum, $totalcount);
430 $result['totalcount'] = $totalcount;
431 return $result;
435 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
436 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
438 global $CFG;
440 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
441 $modname, $modid, $modaction, $groupid)) {
442 notify("No logs found!");
443 print_footer($course);
444 exit;
447 $courses = array();
449 if ($course->id == SITEID) {
450 $courses[0] = '';
451 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
452 foreach ($ccc as $cc) {
453 $courses[$cc->id] = $cc->shortname;
456 } else {
457 $courses[$course->id] = $course->shortname;
460 $totalcount = $logs['totalcount'];
461 $count=0;
462 $ldcache = array();
463 $tt = getdate(time());
464 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
466 $strftimedatetime = get_string("strftimedatetime");
468 echo "<div class=\"info\">\n";
469 print_string("displayingrecords", "", $totalcount);
470 echo "</div>\n";
472 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
474 echo '<table class="logtable genearlbox boxaligncenter" summary="">'."\n";
475 // echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\" summary=\"\">\n";
476 echo "<tr>";
477 if ($course->id == SITEID) {
478 echo "<th class=\"c0 header\" scope=\"col\">".get_string('course')."</th>\n";
480 echo "<th class=\"c1 header\" scope=\"col\">".get_string('time')."</th>\n";
481 echo "<th class=\"c2 header\" scope=\"col\">".get_string('ip_address')."</th>\n";
482 echo "<th class=\"c3 header\" scope=\"col\">".get_string('fullname')."</th>\n";
483 echo "<th class=\"c4 header\" scope=\"col\">".get_string('action')."</th>\n";
484 echo "<th class=\"c5 header\" scope=\"col\">".get_string('info')."</th>\n";
485 echo "</tr>\n";
487 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
488 if (empty($logs['logs'])) {
489 $logs['logs'] = array();
492 $row = 1;
493 foreach ($logs['logs'] as $log) {
495 $row = ($row + 1) % 2;
497 if (isset($ldcache[$log->module][$log->action])) {
498 $ld = $ldcache[$log->module][$log->action];
499 } else {
500 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
501 $ldcache[$log->module][$log->action] = $ld;
503 if ($ld && is_numeric($log->info)) {
504 // ugly hack to make sure fullname is shown correctly
505 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
506 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
507 } else {
508 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
512 //Filter log->info
513 $log->info = format_string($log->info);
515 $log->url = strip_tags(urldecode($log->url)); // Some XSS protection
516 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
517 $log->url = s($log->url); /// XSS protection and XHTML compatibility - should be in link_to_popup_window() instead!!
519 echo '<tr class="r'.$row.'">';
520 if ($course->id == SITEID) {
521 echo "<td class=\"cell c0\">\n";
522 if (empty($log->course)) {
523 echo format_string($log->info)."\n";
524 } else {
525 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course])."</a>\n";
527 echo "</td>\n";
529 echo "<td class=\"cell c1\" align=\"right\">".userdate($log->time, '%a').
530 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
531 echo "<td class=\"cell c2\">\n";
532 link_to_popup_window("/iplookup/index.php?ip=$log->ip&amp;user=$log->userid", 'iplookup',$log->ip, 400, 700);
533 echo "</td>\n";
534 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
535 echo "<td class=\"cell c3\">\n";
536 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}&amp;course={$log->course}\">$fullname</a>\n";
537 echo "</td>\n";
538 echo "<td class=\"cell c4\">\n";
539 link_to_popup_window( make_log_url($log->module,$log->url), 'fromloglive',"$log->module $log->action", 400, 600);
540 echo "</td>\n";;
541 echo "<td class=\"cell c5\">{$log->info}</td>\n";
542 echo "</tr>\n";
544 echo "</table>\n";
546 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
550 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
551 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
553 global $CFG;
555 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
556 $modname, $modid, $modaction, $groupid)) {
557 notify("No logs found!");
558 print_footer($course);
559 exit;
562 if ($course->id == SITEID) {
563 $courses[0] = '';
564 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
565 foreach ($ccc as $cc) {
566 $courses[$cc->id] = $cc->shortname;
571 $totalcount = $logs['totalcount'];
572 $count=0;
573 $ldcache = array();
574 $tt = getdate(time());
575 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
577 $strftimedatetime = get_string("strftimedatetime");
579 echo "<div class=\"info\">\n";
580 print_string("displayingrecords", "", $totalcount);
581 echo "</div>\n";
583 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
585 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
586 echo "<tr>";
587 if ($course->id == SITEID) {
588 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
590 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
591 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
592 echo "<th class=\"c3 header\">".get_string('fullname')."</th>\n";
593 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
594 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
595 echo "</tr>\n";
597 if (empty($logs['logs'])) {
598 echo "</table>\n";
599 return;
602 $row = 1;
603 foreach ($logs['logs'] as $log) {
605 $log->info = $log->coursename;
606 $row = ($row + 1) % 2;
608 if (isset($ldcache[$log->module][$log->action])) {
609 $ld = $ldcache[$log->module][$log->action];
610 } else {
611 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
612 $ldcache[$log->module][$log->action] = $ld;
614 if (0 && $ld && !empty($log->info)) {
615 // ugly hack to make sure fullname is shown correctly
616 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
617 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
618 } else {
619 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
623 //Filter log->info
624 $log->info = format_string($log->info);
626 $log->url = strip_tags(urldecode($log->url)); // Some XSS protection
627 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
628 $log->url = str_replace('&', '&amp;', $log->url); /// XHTML compatibility
630 echo '<tr class="r'.$row.'">';
631 if ($course->id == SITEID) {
632 echo "<td class=\"r$row c0\" >\n";
633 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courses[$log->course]."</a>\n";
634 echo "</td>\n";
636 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time, '%a').
637 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
638 echo "<td class=\"r$row c2\" >\n";
639 link_to_popup_window("/iplookup/index.php?ip=$log->ip&amp;user=$log->userid", 'iplookup',$log->ip, 400, 700);
640 echo "</td>\n";
641 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
642 echo "<td class=\"r$row c3\" >\n";
643 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
644 echo "</td>\n";
645 echo "<td class=\"r$row c4\">\n";
646 echo $log->action .': '.$log->module;
647 echo "</td>\n";;
648 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
649 echo "</tr>\n";
651 echo "</table>\n";
653 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
657 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
658 $modid, $modaction, $groupid) {
660 $text = get_string('course')."\t".get_string('time')."\t".get_string('ip_address')."\t".
661 get_string('fullname')."\t".get_string('action')."\t".get_string('info');
663 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
664 $modname, $modid, $modaction, $groupid)) {
665 return false;
668 $courses = array();
670 if ($course->id == SITEID) {
671 $courses[0] = '';
672 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
673 foreach ($ccc as $cc) {
674 $courses[$cc->id] = $cc->shortname;
677 } else {
678 $courses[$course->id] = $course->shortname;
681 $count=0;
682 $ldcache = array();
683 $tt = getdate(time());
684 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
686 $strftimedatetime = get_string("strftimedatetime");
688 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
689 $filename .= '.txt';
690 header("Content-Type: application/download\n");
691 header("Content-Disposition: attachment; filename=$filename");
692 header("Expires: 0");
693 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
694 header("Pragma: public");
696 echo get_string('savedat').userdate(time(), $strftimedatetime)."\n";
697 echo $text;
699 if (empty($logs['logs'])) {
700 return true;
703 foreach ($logs['logs'] as $log) {
704 if (isset($ldcache[$log->module][$log->action])) {
705 $ld = $ldcache[$log->module][$log->action];
706 } else {
707 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
708 $ldcache[$log->module][$log->action] = $ld;
710 if ($ld && !empty($log->info)) {
711 // ugly hack to make sure fullname is shown correctly
712 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
713 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
714 } else {
715 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
719 //Filter log->info
720 $log->info = format_string($log->info);
722 $log->url = strip_tags(urldecode($log->url)); // Some XSS protection
723 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
724 $log->url = str_replace('&', '&amp;', $log->url); // XHTML compatibility
726 $firstField = $courses[$log->course];
727 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
728 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action, $log->info);
729 $text = implode("\t", $row);
730 echo $text." \n";
732 return true;
736 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
737 $modid, $modaction, $groupid) {
739 global $CFG;
741 require_once("$CFG->libdir/excellib.class.php");
743 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
744 $modname, $modid, $modaction, $groupid)) {
745 return false;
748 $courses = array();
750 if ($course->id == SITEID) {
751 $courses[0] = '';
752 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
753 foreach ($ccc as $cc) {
754 $courses[$cc->id] = $cc->shortname;
757 } else {
758 $courses[$course->id] = $course->shortname;
761 $count=0;
762 $ldcache = array();
763 $tt = getdate(time());
764 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
766 $strftimedatetime = get_string("strftimedatetime");
768 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
769 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
770 $filename .= '.xls';
772 $workbook = new MoodleExcelWorkbook('-');
773 $workbook->send($filename);
775 $worksheet = array();
776 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
777 get_string('fullname'), get_string('action'), get_string('info'));
779 // Creating worksheets
780 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
781 $sheettitle = get_string('excel_sheettitle', 'logs', $wsnumber).$nroPages;
782 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
783 $worksheet[$wsnumber]->set_column(1, 1, 30);
784 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
785 userdate(time(), $strftimedatetime));
786 $col = 0;
787 foreach ($headers as $item) {
788 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
789 $col++;
793 if (empty($logs['logs'])) {
794 $workbook->close();
795 return true;
798 $formatDate =& $workbook->add_format();
799 $formatDate->set_num_format(get_string('log_excel_date_format'));
801 $row = FIRSTUSEDEXCELROW;
802 $wsnumber = 1;
803 $myxls =& $worksheet[$wsnumber];
804 foreach ($logs['logs'] as $log) {
805 if (isset($ldcache[$log->module][$log->action])) {
806 $ld = $ldcache[$log->module][$log->action];
807 } else {
808 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
809 $ldcache[$log->module][$log->action] = $ld;
811 if ($ld && !empty($log->info)) {
812 // ugly hack to make sure fullname is shown correctly
813 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
814 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
815 } else {
816 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
820 // Filter log->info
821 $log->info = format_string($log->info);
822 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
824 if ($nroPages>1) {
825 if ($row > EXCELROWS) {
826 $wsnumber++;
827 $myxls =& $worksheet[$wsnumber];
828 $row = FIRSTUSEDEXCELROW;
832 $myxls->write($row, 0, $courses[$log->course], '');
833 // Excel counts from 1/1/1900
834 $excelTime=25569+$log->time/(3600*24);
835 $myxls->write($row, 1, $excelTime, $formatDate);
836 $myxls->write($row, 2, $log->ip, '');
837 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
838 $myxls->write($row, 3, $fullname, '');
839 $myxls->write($row, 4, $log->module.' '.$log->action, '');
840 $myxls->write($row, 5, $log->info, '');
842 $row++;
845 $workbook->close();
846 return true;
849 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
850 $modid, $modaction, $groupid) {
852 global $CFG;
854 require_once("$CFG->libdir/odslib.class.php");
856 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
857 $modname, $modid, $modaction, $groupid)) {
858 return false;
861 $courses = array();
863 if ($course->id == SITEID) {
864 $courses[0] = '';
865 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
866 foreach ($ccc as $cc) {
867 $courses[$cc->id] = $cc->shortname;
870 } else {
871 $courses[$course->id] = $course->shortname;
874 $count=0;
875 $ldcache = array();
876 $tt = getdate(time());
877 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
879 $strftimedatetime = get_string("strftimedatetime");
881 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
882 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
883 $filename .= '.ods';
885 $workbook = new MoodleODSWorkbook('-');
886 $workbook->send($filename);
888 $worksheet = array();
889 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
890 get_string('fullname'), get_string('action'), get_string('info'));
892 // Creating worksheets
893 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
894 $sheettitle = get_string('excel_sheettitle', 'logs', $wsnumber).$nroPages;
895 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
896 $worksheet[$wsnumber]->set_column(1, 1, 30);
897 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
898 userdate(time(), $strftimedatetime));
899 $col = 0;
900 foreach ($headers as $item) {
901 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
902 $col++;
906 if (empty($logs['logs'])) {
907 $workbook->close();
908 return true;
911 $formatDate =& $workbook->add_format();
912 $formatDate->set_num_format(get_string('log_excel_date_format'));
914 $row = FIRSTUSEDEXCELROW;
915 $wsnumber = 1;
916 $myxls =& $worksheet[$wsnumber];
917 foreach ($logs['logs'] as $log) {
918 if (isset($ldcache[$log->module][$log->action])) {
919 $ld = $ldcache[$log->module][$log->action];
920 } else {
921 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
922 $ldcache[$log->module][$log->action] = $ld;
924 if ($ld && !empty($log->info)) {
925 // ugly hack to make sure fullname is shown correctly
926 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
927 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
928 } else {
929 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
933 // Filter log->info
934 $log->info = format_string($log->info);
935 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
937 if ($nroPages>1) {
938 if ($row > EXCELROWS) {
939 $wsnumber++;
940 $myxls =& $worksheet[$wsnumber];
941 $row = FIRSTUSEDEXCELROW;
945 $myxls->write_string($row, 0, $courses[$log->course]);
946 $myxls->write_date($row, 1, $log->time);
947 $myxls->write_string($row, 2, $log->ip);
948 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
949 $myxls->write_string($row, 3, $fullname);
950 $myxls->write_string($row, 4, $log->module.' '.$log->action);
951 $myxls->write_string($row, 5, $log->info);
953 $row++;
956 $workbook->close();
957 return true;
961 function print_log_graph($course, $userid=0, $type="course.png", $date=0) {
962 global $CFG, $USER;
963 if (empty($CFG->gdversion)) {
964 echo "(".get_string("gdneed").")";
965 } else {
966 // MDL-10818, do not display broken graph when user has no permission to view graph
967 if (has_capability('moodle/site:viewreports', get_context_instance(CONTEXT_COURSE, $course->id)) ||
968 ($course->showreports and $USER->id == $userid)) {
969 echo '<img src="'.$CFG->wwwroot.'/course/report/log/graph.php?id='.$course->id.
970 '&amp;user='.$userid.'&amp;type='.$type.'&amp;date='.$date.'" alt="" />';
976 function print_overview($courses) {
978 global $CFG, $USER;
980 $htmlarray = array();
981 if ($modules = get_records('modules')) {
982 foreach ($modules as $mod) {
983 if (file_exists(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php')) {
984 require_once(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php');
985 $fname = $mod->name.'_print_overview';
986 if (function_exists($fname)) {
987 $fname($courses,$htmlarray);
992 foreach ($courses as $course) {
993 print_simple_box_start('center', '100%', '', 5, "coursebox");
994 $linkcss = '';
995 if (empty($course->visible)) {
996 $linkcss = 'class="dimmed"';
998 print_heading('<a title="'. format_string($course->fullname).'" '.$linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'. format_string($course->fullname).'</a>');
999 if (array_key_exists($course->id,$htmlarray)) {
1000 foreach ($htmlarray[$course->id] as $modname => $html) {
1001 echo $html;
1004 print_simple_box_end();
1009 function print_recent_activity($course) {
1010 // $course is an object
1011 // This function trawls through the logs looking for
1012 // anything new since the user's last login
1014 global $CFG, $USER, $SESSION;
1016 $context = get_context_instance(CONTEXT_COURSE, $course->id);
1018 $timestart = time() - COURSE_MAX_RECENT_PERIOD;
1020 if (!has_capability('moodle/legacy:guest', $context, NULL, false)) {
1021 if (!empty($USER->lastcourseaccess[$course->id])) {
1022 if ($USER->lastcourseaccess[$course->id] > $timestart) {
1023 $timestart = $USER->lastcourseaccess[$course->id];
1028 echo '<div class="activitydate">';
1029 echo get_string('activitysince', '', userdate($timestart));
1030 echo '</div>';
1031 echo '<div class="activityhead">';
1033 echo '<a href="'.$CFG->wwwroot.'/course/recent.php?id='.$course->id.'">'.get_string('recentactivityreport').'</a>';
1035 echo "</div>\n";
1038 // Firstly, have there been any new enrolments?
1040 $heading = false;
1041 $content = false;
1043 $users = get_recent_enrolments($course->id, $timestart);
1045 //Accessibility: new users now appear in an <OL> list.
1046 if ($users) {
1047 echo '<div class="newusers">';
1048 if (! $heading) {
1049 print_headline(get_string("newusers").':', 3);
1050 $heading = true;
1051 $content = true;
1053 echo "<ol class=\"list\">\n";
1054 foreach ($users as $user) {
1056 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
1057 echo '<li class="name"><a href="'.$CFG->wwwroot."/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a></li>\n";
1059 echo "</ol>\n</div>\n";
1062 // Next, have there been any modifications to the course structure?
1064 $logs = get_records_select('log', "time > '$timestart' AND course = '$course->id' AND
1065 module = 'course' AND action LIKE '% mod'", "time ASC");
1067 if ($logs) {
1068 foreach ($logs as $key => $log) {
1069 $info = split(' ', $log->info);
1071 if ($info[0] == 'label') { // Labels are special activities
1072 continue;
1075 $modname = get_field($info[0], 'name', 'id', $info[1]);
1076 //Create a temp valid module structure (course,id)
1077 $tempmod->course = $log->course;
1078 $tempmod->id = $info[1];
1079 //Obtain the visible property from the instance
1080 $modvisible = instance_is_visible($info[0],$tempmod);
1082 //Only if the mod is visible
1083 if ($modvisible) {
1084 switch ($log->action) {
1085 case 'add mod':
1086 $stradded = get_string('added', 'moodle', get_string('modulename', $info[0]));
1087 $changelist[$log->info] = array ('operation' => 'add', 'text' => "$stradded:<br /><a href=\"$CFG->wwwroot/course/$log->url\">".format_string($modname,true)."</a>");
1088 break;
1089 case 'update mod':
1090 $strupdated = get_string('updated', 'moodle', get_string('modulename', $info[0]));
1091 if (empty($changelist[$log->info])) {
1092 $changelist[$log->info] = array ('operation' => 'update', 'text' => "$strupdated:<br /><a href=\"$CFG->wwwroot/course/$log->url\">".format_string($modname,true)."</a>");
1094 break;
1095 case 'delete mod':
1096 if (!empty($changelist[$log->info]['operation']) and
1097 $changelist[$log->info]['operation'] == 'add') {
1098 $changelist[$log->info] = NULL;
1099 } else {
1100 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $info[0]));
1101 $changelist[$log->info] = array ('operation' => 'delete', 'text' => $strdeleted);
1103 break;
1109 if (!empty($changelist)) {
1110 foreach ($changelist as $changeinfo => $change) {
1111 if ($change) {
1112 $changes[$changeinfo] = $change;
1115 if (isset($changes)){
1116 if (count($changes) > 0) {
1117 print_headline(get_string('courseupdates').':', 3);
1118 $content = true;
1119 foreach ($changes as $changeinfo => $change) {
1120 echo '<p class="activity">'.$change['text'].'</p>';
1126 // Now display new things from each module
1128 $mods = get_records('modules', 'visible', '1', 'name', 'id, name');
1130 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
1132 foreach ($mods as $mod) { // Each module gets it's own logs and prints them
1133 include_once($CFG->dirroot.'/mod/'.$mod->name.'/lib.php');
1134 $print_recent_activity = $mod->name.'_print_recent_activity';
1135 if (function_exists($print_recent_activity)) {
1137 // NOTE:
1138 // $isteacher (second parameter below) is to be deprecated!
1140 // TODO:
1141 // 1) Make sure that all _print_recent_activity functions are
1142 // not using the $isteacher value.
1143 // 2) Eventually, remove the $isteacher parameter from the
1144 // function calls.
1146 $modcontent = $print_recent_activity($course, $viewfullnames, $timestart);
1147 if ($modcontent) {
1148 $content = true;
1153 if (! $content) {
1154 echo '<p class="message">'.get_string('nothingnew').'</p>';
1159 function get_array_of_activities($courseid) {
1160 // For a given course, returns an array of course activity objects
1161 // Each item in the array contains he following properties:
1162 // cm - course module id
1163 // mod - name of the module (eg forum)
1164 // section - the number of the section (eg week or topic)
1165 // name - the name of the instance
1166 // visible - is the instance visible or not
1167 // groupingid - grouping id
1168 // groupmembersonly - is this instance visible to group members only
1169 // extra - contains extra string to include in any link
1171 global $CFG;
1173 $mod = array();
1175 if (!$rawmods = get_course_mods($courseid)) {
1176 return NULL;
1179 if ($sections = get_records("course_sections", "course", $courseid, "section ASC")) {
1180 foreach ($sections as $section) {
1181 if (!empty($section->sequence)) {
1182 $sequence = explode(",", $section->sequence);
1183 foreach ($sequence as $seq) {
1184 if (empty($rawmods[$seq])) {
1185 continue;
1187 $mod[$seq]->cm = $rawmods[$seq]->id;
1188 $mod[$seq]->mod = $rawmods[$seq]->modname;
1189 $mod[$seq]->section = $section->section;
1190 $mod[$seq]->name = urlencode(get_field($rawmods[$seq]->modname, "name", "id", $rawmods[$seq]->instance));
1191 $mod[$seq]->visible = $rawmods[$seq]->visible;
1192 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
1193 $mod[$seq]->groupmembersonly = $rawmods[$seq]->groupmembersonly;
1194 $mod[$seq]->extra = "";
1196 $modname = $mod[$seq]->mod;
1197 $functionname = $modname."_get_coursemodule_info";
1199 include_once("$CFG->dirroot/mod/$modname/lib.php");
1201 if (function_exists($functionname)) {
1202 if ($info = $functionname($rawmods[$seq])) {
1203 if (!empty($info->extra)) {
1204 $mod[$seq]->extra = $info->extra;
1206 if (!empty($info->icon)) {
1207 $mod[$seq]->icon = $info->icon;
1215 return $mod;
1221 function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
1222 // Returns a number of useful structures for course displays
1224 $mods = NULL; // course modules indexed by id
1225 $modnames = NULL; // all course module names (except resource!)
1226 $modnamesplural= NULL; // all course module names (plural form)
1227 $modnamesused = NULL; // course module names used
1229 if ($allmods = get_records("modules")) {
1230 foreach ($allmods as $mod) {
1231 if ($mod->visible) {
1232 $modnames[$mod->name] = get_string("modulename", "$mod->name");
1233 $modnamesplural[$mod->name] = get_string("modulenameplural", "$mod->name");
1236 asort($modnames);
1237 } else {
1238 error("No modules are installed!");
1241 if ($rawmods = get_course_mods($courseid)) {
1242 foreach($rawmods as $mod) { // Index the mods
1243 if (empty($modnames[$mod->modname])) {
1244 continue;
1246 // Check groupings
1247 if (!groups_course_module_visible($mod)) {
1248 continue;
1250 $mods[$mod->id] = $mod;
1251 $mods[$mod->id]->modfullname = $modnames[$mod->modname];
1252 if ($mod->visible or has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_COURSE, $courseid))) {
1253 $modnamesused[$mod->modname] = $modnames[$mod->modname];
1256 if ($modnamesused) {
1257 asort($modnamesused);
1263 function get_all_sections($courseid) {
1265 return get_records("course_sections", "course", "$courseid", "section",
1266 "section, id, course, summary, sequence, visible");
1269 function course_set_display($courseid, $display=0) {
1270 global $USER;
1272 if ($display == "all" or empty($display)) {
1273 $display = 0;
1276 if (empty($USER->id) or $USER->username == 'guest') {
1277 //do not store settings in db for guests
1278 } else if (record_exists("course_display", "userid", $USER->id, "course", $courseid)) {
1279 set_field("course_display", "display", $display, "userid", $USER->id, "course", $courseid);
1280 } else {
1281 $record->userid = $USER->id;
1282 $record->course = $courseid;
1283 $record->display = $display;
1284 if (!insert_record("course_display", $record)) {
1285 notify("Could not save your course display!");
1289 return $USER->display[$courseid] = $display; // Note: = not ==
1292 function set_section_visible($courseid, $sectionnumber, $visibility) {
1293 /// For a given course section, markes it visible or hidden,
1294 /// and does the same for every activity in that section
1296 if ($section = get_record("course_sections", "course", $courseid, "section", $sectionnumber)) {
1297 set_field("course_sections", "visible", "$visibility", "id", $section->id);
1298 if (!empty($section->sequence)) {
1299 $modules = explode(",", $section->sequence);
1300 foreach ($modules as $moduleid) {
1301 set_coursemodule_visible($moduleid, $visibility, true);
1304 rebuild_course_cache($courseid);
1309 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%") {
1310 /// Prints a section full of activity modules
1311 global $CFG, $USER;
1313 static $groupbuttons;
1314 static $groupbuttonslink;
1315 static $isteacher;
1316 static $isediting;
1317 static $ismoving;
1318 static $strmovehere;
1319 static $strmovefull;
1320 static $strunreadpostsone;
1322 static $untracked;
1323 static $usetracking;
1325 $labelformatoptions = New stdClass;
1327 if (!isset($isteacher)) {
1328 $groupbuttons = ($course->groupmode or (!$course->groupmodeforce));
1329 $groupbuttonslink = (!$course->groupmodeforce);
1330 $isediting = isediting($course->id);
1331 $ismoving = $isediting && ismoving($course->id);
1332 if ($ismoving) {
1333 $strmovehere = get_string("movehere");
1334 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1336 include_once($CFG->dirroot.'/mod/forum/lib.php');
1337 if ($usetracking = forum_tp_can_track_forums()) {
1338 $strunreadpostsone = get_string('unreadpostsone', 'forum');
1339 $untracked = forum_tp_get_untracked_forums($USER->id, $course->id);
1342 $labelformatoptions->noclean = true;
1344 /// Casting $course->modinfo to string prevents one notice when the field is null
1345 $modinfo = unserialize((string)$course->modinfo);
1347 $groupings = groups_get_all_groupings($course->id);
1349 //Acccessibility: replace table with list <ul>, but don't output empty list.
1350 if (!empty($section->sequence)) {
1352 // Fix bug #5027, don't want style=\"width:$width\".
1353 echo "<ul class=\"section img-text\">\n";
1354 $sectionmods = explode(",", $section->sequence);
1356 foreach ($sectionmods as $modnumber) {
1357 if (empty($mods[$modnumber])) {
1358 continue;
1360 $mod = $mods[$modnumber];
1362 if (($mod->visible or has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_COURSE, $course->id))) &&
1363 (!$ismoving || $mod->id != $USER->activitycopy) &&
1364 groups_course_module_visible($mod)) {
1365 echo '<li class="activity '.$mod->modname.'" id="module-'.$modnumber.'">'; // Unique ID
1366 if ($ismoving) {
1367 echo '<a title="'.$strmovefull.'"'.
1368 ' href="'.$CFG->wwwroot.'/course/mod.php?moveto='.$mod->id.'&amp;sesskey='.$USER->sesskey.'">'.
1369 '<img class="movetarget" src="'.$CFG->pixpath.'/movehere.gif" '.
1370 ' alt="'.$strmovehere.'" /></a><br />
1373 $instancename = urldecode($modinfo[$modnumber]->name);
1374 $instancename = format_string($instancename, true, $course->id);
1376 if (!empty($modinfo[$modnumber]->extra)) {
1377 $extra = urldecode($modinfo[$modnumber]->extra);
1378 } else {
1379 $extra = "";
1382 if (!empty($modinfo[$modnumber]->icon)) {
1383 $icon = "$CFG->pixpath/".urldecode($modinfo[$modnumber]->icon);
1384 } else {
1385 $icon = "$CFG->modpixpath/$mod->modname/icon.gif";
1388 if ($mod->indent) {
1389 print_spacer(12, 20 * $mod->indent, false);
1392 if ($mod->modname == "label") {
1393 if (!$mod->visible) {
1394 echo "<span class=\"dimmed_text\">";
1396 echo format_text($extra, FORMAT_HTML, $labelformatoptions);
1397 if (!$mod->visible) {
1398 echo "</span>";
1401 } else { // Normal activity
1403 //Accessibility: for files get description via icon.
1404 $altname = '';
1405 if ('resource'==$mod->modname) {
1406 if (!empty($modinfo[$modnumber]->icon)) {
1407 $possaltname = $modinfo[$modnumber]->icon;
1409 $mimetype = mimeinfo_from_icon('type', $possaltname);
1410 $altname = get_mimetype_description($mimetype); //get_string($mimetype, 'mimetypes');
1411 } else {
1412 $altname = $mod->modfullname;
1414 } else {
1415 $altname = $mod->modfullname;
1418 // Avoid unnecessary duplication.
1419 if (false!==stripos($instancename, $altname)) {
1420 $altname = '';
1423 $linkcss = $mod->visible ? "" : " class=\"dimmed\" ";
1424 echo '<a '.$linkcss.' '.$extra. // Title unnecessary!
1425 ' href="'.$CFG->wwwroot.'/mod/'.$mod->modname.'/view.php?id='.$mod->id.'">'.
1426 '<img src="'.$icon.'" title=""'. // Suppress IE tooltip.
1427 ' class="activityicon" alt="'.$altname.'" /> <span>'.
1428 $instancename.'</span></a>';
1429 if (!empty($CFG->enablegroupings) && !empty($mod->groupingid) && has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
1430 echo " <span class=\"groupinglabel\"> - ".format_string($groupings[$mod->groupingid]->name).'</span>';
1433 if ($usetracking && $mod->modname == 'forum') {
1434 $groupmode = groups_get_course_groupmode($course, $mod);
1435 $groupid = ($groupmode == SEPARATEGROUPS && !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) ?
1436 groups_get_course_group($course, true) : false;
1438 if (forum_tp_can_track_forums() && !isset($untracked[$mod->instance])) {
1439 $unread = forum_tp_count_forum_unread_posts($USER->id, $mod->instance, $groupid);
1440 if ($unread) {
1441 echo '<span class="unread"> <a href="'.$CFG->wwwroot.'/mod/forum/view.php?id='.$mod->id.'">';
1442 if ($unread == 1) {
1443 echo $strunreadpostsone;
1444 } else {
1445 print_string('unreadpostsnumber', 'forum', $unread);
1447 echo '</a> </span>';
1452 if ($isediting) {
1453 // TODO: we must define this as mod property!
1454 if ($groupbuttons and $mod->modname != 'label' and $mod->modname != 'resource' and $mod->modname != 'glossary') {
1455 if (! $mod->groupmodelink = $groupbuttonslink) {
1456 $mod->groupmode = $course->groupmode;
1459 } else {
1460 $mod->groupmode = false;
1462 echo '&nbsp;&nbsp;';
1463 echo make_editing_buttons($mod, $absolute, true, $mod->indent, $section->section);
1465 echo "</li>\n";
1468 } elseif ($ismoving) {
1469 echo "<ul class=\"section\">\n";
1471 if ($ismoving) {
1472 echo '<li><a title="'.$strmovefull.'"'.
1473 ' href="'.$CFG->wwwroot.'/course/mod.php?movetosection='.$section->id.'&amp;sesskey='.$USER->sesskey.'">'.
1474 '<img class="movetarget" src="'.$CFG->pixpath.'/movehere.gif" '.
1475 ' alt="'.$strmovehere.'" /></a></li>
1478 if (!empty($section->sequence) || $ismoving) {
1479 echo "</ul><!--class='section'-->\n\n";
1484 * Prints the menus to add activities and resources.
1486 function print_section_add_menus($course, $section, $modnames, $vertical=false, $return=false) {
1487 global $CFG;
1489 // check to see if user can add menus
1490 if (!has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $course->id))) {
1491 return false;
1494 static $resources = false;
1495 static $activities = false;
1497 if ($resources === false) {
1498 $resources = array();
1499 $activities = array();
1501 foreach($modnames as $modname=>$modnamestr) {
1502 if (!course_allowed_module($course, $modname)) {
1503 continue;
1506 require_once("$CFG->dirroot/mod/$modname/lib.php");
1507 $gettypesfunc = $modname.'_get_types';
1508 if (function_exists($gettypesfunc)) {
1509 $types = $gettypesfunc();
1510 foreach($types as $type) {
1511 if ($type->modclass == MOD_CLASS_RESOURCE) {
1512 $resources[$type->type] = $type->typestr;
1513 } else {
1514 $activities[$type->type] = $type->typestr;
1517 } else {
1518 // all mods without type are considered activity
1519 $activities[$modname] = $modnamestr;
1524 $straddactivity = get_string('addactivity');
1525 $straddresource = get_string('addresource');
1527 $output = '<div class="section_add_menus">';
1529 if (!$vertical) {
1530 $output .= '<div class="horizontal">';
1533 if (!empty($resources)) {
1534 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&amp;section=$section&amp;sesskey=".sesskey()."&amp;add=",
1535 $resources, "ressection$section", "", $straddresource, 'resource/types', $straddresource, true);
1538 if (!empty($activities)) {
1539 $output .= ' ';
1540 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&amp;section=$section&amp;sesskey=".sesskey()."&amp;add=",
1541 $activities, "section$section", "", $straddactivity, 'mods', $straddactivity, true);
1544 if (!$vertical) {
1545 $output .= '</div>';
1548 $output .= '</div>';
1550 if ($return) {
1551 return $output;
1552 } else {
1553 echo $output;
1557 function rebuild_course_cache($courseid=0) {
1558 // Rebuilds the cached list of course activities stored in the database
1559 // If a courseid is not specified, then all are rebuilt
1561 if ($courseid) {
1562 $select = "id = '$courseid'";
1563 } else {
1564 $select = "";
1565 @set_time_limit(0); // this could take a while! MDL-10954
1568 if ($courses = get_records_select("course", $select,'','id,fullname')) {
1569 foreach ($courses as $course) {
1570 $modinfo = serialize(get_array_of_activities($course->id));
1571 if (!set_field("course", "modinfo", $modinfo, "id", $course->id)) {
1572 notify("Could not cache module information for course '" . format_string($course->fullname) . "'!");
1580 function make_categories_list(&$list, &$parents, $category=NULL, $path="") {
1581 /// Given an empty array, this function recursively travels the
1582 /// categories, building up a nice list for display. It also makes
1583 /// an array that list all the parents for each category.
1585 // initialize the arrays if needed
1586 if (!is_array($list)) {
1587 $list = array();
1589 if (!is_array($parents)) {
1590 $parents = array();
1593 if ($category) {
1594 if ($path) {
1595 $path = $path.' / '.format_string($category->name);
1596 } else {
1597 $path = format_string($category->name);
1599 $list[$category->id] = $path;
1600 } else {
1601 $category->id = 0;
1604 if ($categories = get_categories($category->id)) { // Print all the children recursively
1605 foreach ($categories as $cat) {
1606 if (!empty($category->id)) {
1607 if (isset($parents[$category->id])) {
1608 $parents[$cat->id] = $parents[$category->id];
1610 $parents[$cat->id][] = $category->id;
1612 make_categories_list($list, $parents, $cat, $path);
1618 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $files = true) {
1619 /// Recursive function to print out all the categories in a nice format
1620 /// with or without courses included
1621 global $CFG;
1623 if (isset($CFG->max_category_depth) && ($depth >= $CFG->max_category_depth)) {
1624 return;
1627 if (!$displaylist) {
1628 make_categories_list($displaylist, $parentslist);
1631 if ($category) {
1632 if ($category->visible or has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
1633 print_category_info($category, $depth, $files);
1634 } else {
1635 return; // Don't bother printing children of invisible categories
1638 } else {
1639 $category->id = "0";
1642 if ($categories = get_categories($category->id)) { // Print all the children recursively
1643 $countcats = count($categories);
1644 $count = 0;
1645 $first = true;
1646 $last = false;
1647 foreach ($categories as $cat) {
1648 $count++;
1649 if ($count == $countcats) {
1650 $last = true;
1652 $up = $first ? false : true;
1653 $down = $last ? false : true;
1654 $first = false;
1656 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1, $files);
1661 // this function will return $options array for choose_from_menu, with whitespace to denote nesting.
1663 function make_categories_options() {
1664 make_categories_list($cats,$parents);
1665 foreach ($cats as $key => $value) {
1666 if (array_key_exists($key,$parents)) {
1667 if ($indent = count($parents[$key])) {
1668 for ($i = 0; $i < $indent; $i++) {
1669 $cats[$key] = '&nbsp;'.$cats[$key];
1674 return $cats;
1677 function print_category_info($category, $depth, $files = false) {
1678 /// Prints the category info in indented fashion
1679 /// This function is only used by print_whole_category_list() above
1681 global $CFG;
1682 static $strallowguests, $strrequireskey, $strsummary;
1684 if (empty($strsummary)) {
1685 $strallowguests = get_string('allowguests');
1686 $strrequireskey = get_string('requireskey');
1687 $strsummary = get_string('summary');
1690 $catlinkcss = $category->visible ? '' : ' class="dimmed" ';
1692 $coursecount = count_records('course') <= FRONTPAGECOURSELIMIT;
1693 if ($files and $coursecount) {
1694 $catimage = '<img src="'.$CFG->pixpath.'/i/course.gif" alt="" />';
1695 } else {
1696 $catimage = "&nbsp;";
1699 echo "\n\n".'<table class="categorylist">';
1701 if ($files and $coursecount) {
1702 $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');
1704 echo '<tr>';
1706 if ($depth) {
1707 $indent = $depth*30;
1708 $rows = count($courses) + 1;
1709 echo '<td rowspan="'.$rows.'" valign="top" width="'.$indent.'">';
1710 print_spacer(10, $indent);
1711 echo '</td>';
1714 echo '<td valign="top" class="category image">'.$catimage.'</td>';
1715 echo '<td valign="top" class="category name">';
1716 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot.'/course/category.php?id='.$category->id.'">'. format_string($category->name).'</a>';
1717 echo '</td>';
1718 echo '<td class="category info">&nbsp;</td>';
1719 echo '</tr>';
1721 if ($courses && !(isset($CFG->max_category_depth)&&($depth>=$CFG->max_category_depth-1))) {
1722 foreach ($courses as $course) {
1723 $linkcss = $course->visible ? '' : ' class="dimmed" ';
1724 echo '<tr><td valign="top">&nbsp;';
1725 echo '</td><td valign="top" class="course name">';
1726 echo '<a '.$linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'. format_string($course->fullname).'</a>';
1727 echo '</td><td align="right" valign="top" class="course info">';
1728 if ($course->guest ) {
1729 echo '<a title="'.$strallowguests.'" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">';
1730 echo '<img alt="'.$strallowguests.'" src="'.$CFG->pixpath.'/i/guest.gif" /></a>';
1731 } else {
1732 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath.'/spacer.gif" />';
1734 if ($course->password) {
1735 echo '<a title="'.$strrequireskey.'" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">';
1736 echo '<img alt="'.$strrequireskey.'" src="'.$CFG->pixpath.'/i/key.gif" /></a>';
1737 } else {
1738 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath.'/spacer.gif" />';
1740 if ($course->summary) {
1741 link_to_popup_window ('/course/info.php?id='.$course->id, 'courseinfo',
1742 '<img alt="'.$strsummary.'" src="'.$CFG->pixpath.'/i/info.gif" />',
1743 400, 500, $strsummary);
1744 } else {
1745 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath.'/spacer.gif" />';
1747 echo '</td></tr>';
1750 } else {
1752 echo '<tr>';
1754 if ($depth) {
1755 $indent = $depth*20;
1756 echo '<td valign="top" width="'.$indent.'">';
1757 print_spacer(10, $indent);
1758 echo '</td>';
1761 echo '<td valign="top" class="category name">';
1762 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot.'/course/category.php?id='.$category->id.'">'. format_string($category->name).'</a>';
1763 echo '</td>';
1764 echo '<td valign="top" class="category number">';
1765 if ($category->coursecount) {
1766 echo $category->coursecount;
1768 echo '</td></tr>';
1770 echo '</table>';
1775 function print_courses($category) {
1776 /// Category is 0 (for all courses) or an object
1778 global $CFG;
1780 if (!is_object($category) && $category==0) {
1781 $categories = get_categories(0); // Parent = 0 ie top-level categories only
1782 if (is_array($categories) && count($categories) == 1) {
1783 $category = array_shift($categories);
1784 $courses = get_courses_wmanagers($category->id,
1785 'c.sortorder ASC',
1786 array('password','summary','currency'));
1787 } else {
1788 $courses = get_courses_wmanagers('all',
1789 'c.sortorder ASC',
1790 array('password','summary','currency'));
1792 unset($categories);
1793 } else {
1794 $courses = get_courses_wmanagers($category->id,
1795 'c.sortorder ASC',
1796 array('password','summary','currency'));
1799 if ($courses) {
1800 foreach ($courses as $course) {
1801 if ($course->visible == 1
1802 || has_capability('moodle/course:viewhidden',$course->context)) {
1803 print_course($course);
1806 } else {
1807 print_heading(get_string("nocoursesyet"));
1808 $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
1809 if (has_capability('moodle/course:create', $context)) {
1810 $options = array();
1811 $options['category'] = $category->id;
1812 echo '<div class="addcoursebutton">';
1813 print_single_button($CFG->wwwroot.'/course/edit.php', $options, get_string("addnewcourse"));
1814 echo '</div>';
1823 function print_course($course) {
1825 global $CFG, $USER;
1827 if (isset($course->context)) {
1828 $context = $course->context;
1829 } else {
1830 $context = get_context_instance(CONTEXT_COURSE, $course->id);
1833 $linkcss = $course->visible ? '' : ' class="dimmed" ';
1835 echo '<div class="coursebox">';
1836 echo '<div class="info">';
1837 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
1838 $linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.
1839 format_string($course->fullname).'</a></div>';
1841 /// first find all roles that are supposed to be displayed
1843 if (!empty($CFG->coursemanager)) {
1844 $managerroles = split(',', $CFG->coursemanager);
1845 $canseehidden = has_capability('moodle/role:viewhiddenassigns', $context);
1846 $namesarray = array();
1847 if (isset($course->managers)) {
1848 if (count($course->managers)) {
1849 $rusers = $course->managers;
1850 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
1851 foreach ($rusers as $ra) {
1852 if ($ra->hidden == 0 || $canseehidden) {
1853 $fullname = fullname($ra->user, $canviewfullnames);
1854 $namesarray[] = format_string($ra->rolename)
1855 . ': <a href="'.$CFG->wwwroot.'/user/view.php?id='.$ra->user->id.'&amp;course='.SITEID.'">'
1856 . $fullname . '</a>';
1860 } else {
1861 $rusers = get_role_users($managerroles, $context,
1862 true, '', 'r.sortorder ASC, u.lastname ASC', $canseehidden);
1863 if (is_array($rusers) && count($rusers)) {
1864 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
1865 foreach ($rusers as $teacher) {
1866 $fullname = fullname($teacher, $canviewfullnames);
1867 $namesarray[] = format_string($teacher->rolename)
1868 . ': <a href="'.$CFG->wwwroot.'/user/view.php?id='.$teacher->id.'&amp;course='.SITEID.'">'
1869 . $fullname . '</a>';
1874 if (!empty($namesarray)) {
1875 echo "<ul class=\"teachers\">\n<li>";
1876 echo implode('</li><li>', $namesarray);
1877 echo "</li></ul>";
1881 require_once("$CFG->dirroot/enrol/enrol.class.php");
1882 $enrol = enrolment_factory::factory($course->enrol);
1883 echo $enrol->get_access_icons($course);
1885 echo '</div><div class="summary">';
1886 $options = NULL;
1887 $options->noclean = true;
1888 $options->para = false;
1889 echo format_text($course->summary, FORMAT_MOODLE, $options, $course->id);
1890 echo '</div>';
1891 echo '</div>';
1892 echo '<div class="clearer"></div>';
1896 function print_my_moodle() {
1897 /// Prints custom user information on the home page.
1898 /// Over time this can include all sorts of information
1900 global $USER, $CFG;
1902 if (empty($USER->id)) {
1903 error("It shouldn't be possible to see My Moodle without being logged in.");
1906 $courses = get_my_courses($USER->id, 'visible DESC,sortorder ASC', array('summary'));
1907 $rhosts = array();
1908 $rcourses = array();
1909 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
1910 $rcourses = get_my_remotecourses($USER->id);
1911 $rhosts = get_my_remotehosts();
1914 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
1916 if (!empty($courses)) {
1917 foreach ($courses as $course) {
1918 if ($course->id == SITEID) {
1919 continue;
1921 print_course($course, "100%");
1925 // MNET
1926 if (!empty($rcourses)) {
1927 // at the IDP, we know of all the remote courses
1928 foreach ($rcourses as $course) {
1929 print_remote_course($course, "100%");
1931 } elseif (!empty($rhosts)) {
1932 // non-IDP, we know of all the remote servers, but not courses
1933 foreach ($rhosts as $host) {
1934 print_remote_host($host, "100%");
1937 unset($course);
1938 unset($host);
1940 if (count_records("course") > (count($courses) + 1) ) { // Some courses not being displayed
1941 echo "<table width=\"100%\"><tr><td align=\"center\">";
1942 print_course_search("", false, "short");
1943 echo "</td><td align=\"center\">";
1944 print_single_button("$CFG->wwwroot/course/index.php", NULL, get_string("fulllistofcourses"), "get");
1945 echo "</td></tr></table>\n";
1948 } else {
1949 if (count_records("course_categories") > 1) {
1950 print_simple_box_start("center", "100%", "#FFFFFF", 5, "categorybox");
1951 print_whole_category_list();
1952 print_simple_box_end();
1953 } else {
1954 print_courses(0);
1960 function print_course_search($value="", $return=false, $format="plain") {
1962 global $CFG;
1963 static $count = 0;
1965 $count++;
1967 $id = 'coursesearch';
1969 if ($count > 1) {
1970 $id .= $count;
1973 $strsearchcourses= get_string("searchcourses");
1975 if ($format == 'plain') {
1976 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
1977 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
1978 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
1979 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
1980 $output .= '<input type="submit" value="'.get_string('go').'" />';
1981 $output .= '</fieldset></form>';
1982 } else if ($format == 'short') {
1983 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
1984 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
1985 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
1986 $output .= '<input type="text" id="coursesearchbox" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
1987 $output .= '<input type="submit" value="'.get_string('go').'" />';
1988 $output .= '</fieldset></form>';
1989 } else if ($format == 'navbar') {
1990 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
1991 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
1992 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
1993 $output .= '<input type="text" id="coursesearchbox" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
1994 $output .= '<input type="submit" value="'.get_string('go').'" />';
1995 $output .= '</fieldset></form>';
1998 if ($return) {
1999 return $output;
2001 echo $output;
2004 function print_remote_course($course, $width="100%") {
2006 global $CFG, $USER;
2008 $linkcss = '';
2010 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&amp;wantsurl=/course/view.php?id={$course->remoteid}";
2012 echo '<div class="coursebox remotecoursebox">';
2013 echo '<div class="info">';
2014 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2015 $linkcss.' href="'.$url.'">'
2016 . format_string($course->fullname) .'</a><br />'
2017 . format_string($course->hostname) . ' : '
2018 . format_string($course->cat_name) . ' : '
2019 . format_string($course->shortname). '</div>';
2020 echo '</div><div class="summary">';
2021 $options = NULL;
2022 $options->noclean = true;
2023 $options->para = false;
2024 echo format_text($course->summary, FORMAT_MOODLE, $options);
2025 echo '</div>';
2026 echo '</div>';
2027 echo '<div class="clearer"></div>';
2030 function print_remote_host($host, $width="100%") {
2032 global $CFG, $USER;
2034 $linkcss = '';
2036 echo '<div class="coursebox">';
2037 echo '<div class="info">';
2038 echo '<div class="name">';
2039 echo '<img src="'.$CFG->pixpath.'/i/mnethost.gif" class="icon" alt="'.get_string('course').'" />';
2040 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2041 . s($host['name']).'</a> - ';
2042 echo $host['count'] . ' ' . get_string('courses');
2043 echo '</div>';
2044 echo '</div>';
2045 echo '</div>';
2046 echo '<div class="clearer"></div>';
2050 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2052 function add_course_module($mod) {
2054 $mod->added = time();
2055 unset($mod->id);
2057 return insert_record("course_modules", $mod);
2061 * Returns course section - creates new if does not exist yet.
2062 * @param int $relative section number
2063 * @param int $courseid
2064 * @return object $course_section object
2066 function get_course_section($section, $courseid) {
2067 if ($cw = get_record("course_sections", "section", $section, "course", $courseid)) {
2068 return $cw;
2070 $cw = new object();
2071 $cw->course = $courseid;
2072 $cw->section = $section;
2073 $cw->summary = "";
2074 $cw->sequence = "";
2075 $id = insert_record("course_sections", $cw);
2076 return get_record("course_sections", "id", $id);
2079 function add_mod_to_section($mod, $beforemod=NULL) {
2080 /// Given a full mod object with section and course already defined
2081 /// If $before is specified, then this is an existing ID which we
2082 /// will insert the new module before
2084 /// Returns the course_sections ID where the mod is inserted
2086 if ($section = get_record("course_sections", "course", "$mod->course", "section", "$mod->section")) {
2088 $section->sequence = trim($section->sequence);
2090 if (empty($section->sequence)) {
2091 $newsequence = "$mod->coursemodule";
2093 } else if ($beforemod) {
2094 $modarray = explode(",", $section->sequence);
2096 if ($key = array_keys ($modarray, $beforemod->id)) {
2097 $insertarray = array($mod->id, $beforemod->id);
2098 array_splice($modarray, $key[0], 1, $insertarray);
2099 $newsequence = implode(",", $modarray);
2101 } else { // Just tack it on the end anyway
2102 $newsequence = "$section->sequence,$mod->coursemodule";
2105 } else {
2106 $newsequence = "$section->sequence,$mod->coursemodule";
2109 if (set_field("course_sections", "sequence", $newsequence, "id", $section->id)) {
2110 return $section->id; // Return course_sections ID that was used.
2111 } else {
2112 return 0;
2115 } else { // Insert a new record
2116 $section->course = $mod->course;
2117 $section->section = $mod->section;
2118 $section->summary = "";
2119 $section->sequence = $mod->coursemodule;
2120 return insert_record("course_sections", $section);
2124 function set_coursemodule_groupmode($id, $groupmode) {
2125 return set_field("course_modules", "groupmode", $groupmode, "id", $id);
2128 function set_coursemodule_groupingid($id, $groupingid) {
2129 return set_field("course_modules", "groupingid", $groupingid, "id", $id);
2132 function set_coursemodule_groupmembersonly($id, $groupmembersonly) {
2133 return set_field("course_modules", "groupmembersonly", $groupmembersonly, "id", $id);
2136 function set_coursemodule_idnumber($id, $idnumber) {
2137 return set_field("course_modules", "idnumber", $idnumber, "id", $id);
2140 * $prevstateoverrides = true will set the visibility of the course module
2141 * to what is defined in visibleold. This enables us to remember the current
2142 * visibility when making a whole section hidden, so that when we toggle
2143 * that section back to visible, we are able to return the visibility of
2144 * the course module back to what it was originally.
2146 function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
2147 if (!$cm = get_record('course_modules', 'id', $id)) {
2148 return false;
2150 if (!$modulename = get_field('modules', 'name', 'id', $cm->module)) {
2151 return false;
2153 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
2154 foreach($events as $event) {
2155 if ($visible) {
2156 show_event($event);
2157 } else {
2158 hide_event($event);
2162 if ($prevstateoverrides) {
2163 if ($visible == '0') {
2164 // Remember the current visible state so we can toggle this back.
2165 set_field('course_modules', 'visibleold', $cm->visible, 'id', $id);
2166 } else {
2167 // Get the previous saved visible states.
2168 return set_field('course_modules', 'visible', $cm->visibleold, 'id', $id);
2171 return set_field("course_modules", "visible", $visible, "id", $id);
2175 * Delete a course module and any associated data at the course level (events)
2176 * Until 1.5 this function simply marked a deleted flag ... now it
2177 * deletes it completely.
2180 function delete_course_module($id) {
2181 global $CFG;
2182 require_once($CFG->libdir.'/gradelib.php');
2184 if (!$cm = get_record('course_modules', 'id', $id)) {
2185 return true;
2187 $modulename = get_field('modules', 'name', 'id', $cm->module);
2188 //delete events from calendar
2189 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
2190 foreach($events as $event) {
2191 delete_event($event->id);
2194 //delete grade items, outcome items and grades attached to modules
2195 if ($grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2196 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course))) {
2197 foreach ($grade_items as $grade_item) {
2198 $grade_item->delete('moddelete');
2202 return delete_records('course_modules', 'id', $cm->id);
2205 function delete_mod_from_section($mod, $section) {
2207 if ($section = get_record("course_sections", "id", "$section") ) {
2209 $modarray = explode(",", $section->sequence);
2211 if ($key = array_keys ($modarray, $mod)) {
2212 array_splice($modarray, $key[0], 1);
2213 $newsequence = implode(",", $modarray);
2214 return set_field("course_sections", "sequence", $newsequence, "id", $section->id);
2215 } else {
2216 return false;
2220 return false;
2223 function move_section($course, $section, $move) {
2224 /// Moves a whole course section up and down within the course
2225 global $USER;
2227 if (!$move) {
2228 return true;
2231 $sectiondest = $section + $move;
2233 if ($sectiondest > $course->numsections or $sectiondest < 1) {
2234 return false;
2237 if (!$sectionrecord = get_record("course_sections", "course", $course->id, "section", $section)) {
2238 return false;
2241 if (!$sectiondestrecord = get_record("course_sections", "course", $course->id, "section", $sectiondest)) {
2242 return false;
2245 if (!set_field("course_sections", "section", $sectiondest, "id", $sectionrecord->id)) {
2246 return false;
2248 if (!set_field("course_sections", "section", $section, "id", $sectiondestrecord->id)) {
2249 return false;
2251 // if the focus is on the section that is being moved, then move the focus along
2252 if (isset($USER->display[$course->id]) and ($USER->display[$course->id] == $section)) {
2253 course_set_display($course->id, $sectiondest);
2256 // Check for duplicates and fix order if needed.
2257 // There is a very rare case that some sections in the same course have the same section id.
2258 $sections = get_records_select('course_sections', "course = $course->id", 'section ASC');
2259 $n = 0;
2260 foreach ($sections as $section) {
2261 if ($section->section != $n) {
2262 if (!set_field('course_sections', 'section', $n, 'id', $section->id)) {
2263 return false;
2266 $n++;
2268 return true;
2272 function moveto_module($mod, $section, $beforemod=NULL) {
2273 /// All parameters are objects
2274 /// Move the module object $mod to the specified $section
2275 /// If $beforemod exists then that is the module
2276 /// before which $modid should be inserted
2278 /// Remove original module from original section
2280 if (! delete_mod_from_section($mod->id, $mod->section)) {
2281 notify("Could not delete module from existing section");
2284 /// Update module itself if necessary
2286 if ($mod->section != $section->id) {
2287 $mod->section = $section->id;
2288 if (!update_record("course_modules", $mod)) {
2289 return false;
2291 // if moving to a hidden section then hide module
2292 if (!$section->visible) {
2293 set_coursemodule_visible($mod->id, 0);
2297 /// Add the module into the new section
2299 $mod->course = $section->course;
2300 $mod->section = $section->section; // need relative reference
2301 $mod->coursemodule = $mod->id;
2303 if (! add_mod_to_section($mod, $beforemod)) {
2304 return false;
2307 return true;
2311 function make_editing_buttons($mod, $absolute=false, $moveselect=true, $indent=-1, $section=-1) {
2312 global $CFG, $USER;
2314 static $str;
2315 static $sesskey;
2317 $modcontext = get_context_instance(CONTEXT_MODULE, $mod->id);
2318 // no permission to edit
2319 if (!has_capability('moodle/course:manageactivities', $modcontext)) {
2320 return false;
2323 if (!isset($str)) {
2324 $str->delete = get_string("delete");
2325 $str->move = get_string("move");
2326 $str->moveup = get_string("moveup");
2327 $str->movedown = get_string("movedown");
2328 $str->moveright = get_string("moveright");
2329 $str->moveleft = get_string("moveleft");
2330 $str->update = get_string("update");
2331 $str->duplicate = get_string("duplicate");
2332 $str->hide = get_string("hide");
2333 $str->show = get_string("show");
2334 $str->clicktochange = get_string("clicktochange");
2335 $str->forcedmode = get_string("forcedmode");
2336 $str->groupsnone = get_string("groupsnone");
2337 $str->groupsseparate = get_string("groupsseparate");
2338 $str->groupsvisible = get_string("groupsvisible");
2339 $sesskey = sesskey();
2342 if ($section >= 0) {
2343 $section = '&amp;sr='.$section; // Section return
2344 } else {
2345 $section = '';
2348 if ($absolute) {
2349 $path = $CFG->wwwroot.'/course';
2350 } else {
2351 $path = '.';
2354 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
2355 if ($mod->visible) {
2356 $hideshow = '<a class="editing_hide" title="'.$str->hide.'" href="'.$path.'/mod.php?hide='.$mod->id.
2357 '&amp;sesskey='.$sesskey.$section.'"><img'.
2358 ' src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" '.
2359 ' alt="'.$str->hide.'" /></a>'."\n";
2360 } else {
2361 $hideshow = '<a class="editing_show" title="'.$str->show.'" href="'.$path.'/mod.php?show='.$mod->id.
2362 '&amp;sesskey='.$sesskey.$section.'"><img'.
2363 ' src="'.$CFG->pixpath.'/t/show.gif" class="iconsmall" '.
2364 ' alt="'.$str->show.'" /></a>'."\n";
2367 if ($mod->groupmode !== false) {
2368 if ($mod->groupmode == SEPARATEGROUPS) {
2369 $grouptitle = $str->groupsseparate;
2370 $groupclass = 'editing_groupsseparate';
2371 $groupimage = $CFG->pixpath.'/t/groups.gif';
2372 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=0&amp;sesskey='.$sesskey;
2373 } else if ($mod->groupmode == VISIBLEGROUPS) {
2374 $grouptitle = $str->groupsvisible;
2375 $groupclass = 'editing_groupsvisible';
2376 $groupimage = $CFG->pixpath.'/t/groupv.gif';
2377 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=1&amp;sesskey='.$sesskey;
2378 } else {
2379 $grouptitle = $str->groupsnone;
2380 $groupclass = 'editing_groupsnone';
2381 $groupimage = $CFG->pixpath.'/t/groupn.gif';
2382 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=2&amp;sesskey='.$sesskey;
2384 if ($mod->groupmodelink) {
2385 $groupmode = '<a class="'.$groupclass.'" title="'.$grouptitle.' ('.$str->clicktochange.')" href="'.$grouplink.'">'.
2386 '<img src="'.$groupimage.'" class="iconsmall" '.
2387 'alt="'.$grouptitle.'" /></a>';
2388 } else {
2389 $groupmode = '<img title="'.$grouptitle.' ('.$str->forcedmode.')" '.
2390 ' src="'.$groupimage.'" class="iconsmall" '.
2391 'alt="'.$grouptitle.'" />';
2393 } else {
2394 $groupmode = "";
2397 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $mod->course))) {
2398 if ($moveselect) {
2399 $move = '<a class="editing_move" title="'.$str->move.'" href="'.$path.'/mod.php?copy='.$mod->id.
2400 '&amp;sesskey='.$sesskey.$section.'"><img'.
2401 ' src="'.$CFG->pixpath.'/t/move.gif" class="iconsmall" '.
2402 ' alt="'.$str->move.'" /></a>'."\n";
2403 } else {
2404 $move = '<a class="editing_moveup" title="'.$str->moveup.'" href="'.$path.'/mod.php?id='.$mod->id.
2405 '&amp;move=-1&amp;sesskey='.$sesskey.$section.'"><img'.
2406 ' src="'.$CFG->pixpath.'/t/up.gif" class="iconsmall" '.
2407 ' alt="'.$str->moveup.'" /></a>'."\n".
2408 '<a class="editing_movedown" title="'.$str->movedown.'" href="'.$path.'/mod.php?id='.$mod->id.
2409 '&amp;move=1&amp;sesskey='.$sesskey.$section.'"><img'.
2410 ' src="'.$CFG->pixpath.'/t/down.gif" class="iconsmall" '.
2411 ' alt="'.$str->movedown.'" /></a>'."\n";
2413 } else {
2414 $move = '';
2417 $leftright = '';
2418 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $mod->course))) {
2420 if (right_to_left()) { // Exchange arrows on RTL
2421 $rightarrow = 'left.gif';
2422 $leftarrow = 'right.gif';
2423 } else {
2424 $rightarrow = 'right.gif';
2425 $leftarrow = 'left.gif';
2428 if ($indent > 0) {
2429 $leftright .= '<a class="editing_moveleft" title="'.$str->moveleft.'" href="'.$path.'/mod.php?id='.$mod->id.
2430 '&amp;indent=-1&amp;sesskey='.$sesskey.$section.'"><img'.
2431 ' src="'.$CFG->pixpath.'/t/'.$leftarrow.'" class="iconsmall" '.
2432 ' alt="'.$str->moveleft.'" /></a>'."\n";
2434 if ($indent >= 0) {
2435 $leftright .= '<a class="editing_moveright" title="'.$str->moveright.'" href="'.$path.'/mod.php?id='.$mod->id.
2436 '&amp;indent=1&amp;sesskey='.$sesskey.$section.'"><img'.
2437 ' src="'.$CFG->pixpath.'/t/'.$rightarrow.'" class="iconsmall" '.
2438 ' alt="'.$str->moveright.'" /></a>'."\n";
2442 return '<span class="commands">'."\n".$leftright.$move.
2443 '<a class="editing_update" title="'.$str->update.'" href="'.$path.'/mod.php?update='.$mod->id.
2444 '&amp;sesskey='.$sesskey.$section.'"><img'.
2445 ' src="'.$CFG->pixpath.'/t/edit.gif" class="iconsmall" '.
2446 ' alt="'.$str->update.'" /></a>'."\n".
2447 '<a class="editing_delete" title="'.$str->delete.'" href="'.$path.'/mod.php?delete='.$mod->id.
2448 '&amp;sesskey='.$sesskey.$section.'"><img'.
2449 ' src="'.$CFG->pixpath.'/t/delete.gif" class="iconsmall" '.
2450 ' alt="'.$str->delete.'" /></a>'."\n".$hideshow.$groupmode."\n".'</span>';
2454 * given a course object with shortname & fullname, this function will
2455 * truncate the the number of chars allowed and add ... if it was too long
2457 function course_format_name ($course,$max=100) {
2459 $str = $course->shortname.': '. $course->fullname;
2460 if (strlen($str) <= $max) {
2461 return $str;
2463 else {
2464 return substr($str,0,$max-3).'...';
2469 * This function will return true if the given course is a child course at all
2471 function course_in_meta ($course) {
2472 return record_exists("course_meta","child_course",$course->id);
2477 * Print standard form elements on module setup forms in mod/.../mod.html
2479 function print_standard_coursemodule_settings($form, $features=null) {
2480 if (! $course = get_record('course', 'id', $form->course)) {
2481 error("This course doesn't exist");
2483 print_groupmode_setting($form, $course);
2484 if (!empty($features->groupings)) {
2485 print_grouping_settings($form, $course);
2487 print_visible_setting($form, $course);
2491 * Print groupmode form element on module setup forms in mod/.../mod.html
2493 function print_groupmode_setting($form, $course=NULL) {
2495 if (empty($course)) {
2496 if (! $course = get_record('course', 'id', $form->course)) {
2497 error("This course doesn't exist");
2500 if ($form->coursemodule) {
2501 if (! $cm = get_record('course_modules', 'id', $form->coursemodule)) {
2502 error("This course module doesn't exist");
2504 $groupmode = groups_get_activity_groupmode($cm);
2505 } else {
2506 $cm = null;
2507 $groupmode = groups_get_course_groupmode($course);
2509 if ($course->groupmode or (!$course->groupmodeforce)) {
2510 echo '<tr valign="top">';
2511 echo '<td align="right"><b>'.get_string('groupmode').':</b></td>';
2512 echo '<td align="left">';
2513 $choices = array();
2514 $choices[NOGROUPS] = get_string('groupsnone');
2515 $choices[SEPARATEGROUPS] = get_string('groupsseparate');
2516 $choices[VISIBLEGROUPS] = get_string('groupsvisible');
2517 choose_from_menu($choices, 'groupmode', $groupmode, '', '', 0, false, $course->groupmodeforce);
2518 helpbutton('groupmode', get_string('groupmode'));
2519 echo '</td></tr>';
2524 * Print groupmode form element on module setup forms in mod/.../mod.html
2526 function print_grouping_settings($form, $course=NULL) {
2528 if (empty($course)) {
2529 if (! $course = get_record('course', 'id', $form->course)) {
2530 error("This course doesn't exist");
2533 if ($form->coursemodule) {
2534 if (! $cm = get_record('course_modules', 'id', $form->coursemodule)) {
2535 error("This course module doesn't exist");
2537 } else {
2538 $cm = null;
2541 $groupings = get_records_menu('groupings', 'courseid', $course->id, 'name', 'id, name');
2542 if (!empty($groupings)) {
2543 echo '<tr valign="top">';
2544 echo '<td align="right"><b>'.get_string('grouping', 'group').':</b></td>';
2545 echo '<td align="left">';
2547 $groupings;
2548 $groupingid = isset($cm->groupingid) ? $cm->groupingid : 0;
2550 choose_from_menu($groupings, 'groupingid', $groupingid, get_string('none'), '', 0, false);
2551 echo '</td></tr>';
2553 $checked = empty($cm->groupmembersonly) ? '':'checked="checked"';
2554 echo '<tr valign="top">';
2555 echo '<td align="right"><b>'.get_string('groupmembersonly', 'group').':</b></td>';
2556 echo '<td align="left">';
2557 echo "<input type=\"checkbox\" name=\"groupmembersonly\" value=\"1\" $checked />";
2558 echo '</td></tr>';
2564 * Print visibility setting form element on module setup forms in mod/.../mod.html
2566 function print_visible_setting($form, $course=NULL) {
2567 if (empty($course)) {
2568 if (! $course = get_record('course', 'id', $form->course)) {
2569 error("This course doesn't exist");
2572 if ($form->coursemodule) {
2573 $visible = get_field('course_modules', 'visible', 'id', $form->coursemodule);
2574 } else {
2575 $visible = true;
2578 if ($form->mode == 'add') { // in this case $form->section is the section number, not the id
2579 $hiddensection = !get_field('course_sections', 'visible', 'section', $form->section, 'course', $form->course);
2580 } else {
2581 $hiddensection = !get_field('course_sections', 'visible', 'id', $form->section);
2583 if ($hiddensection) {
2584 $visible = false;
2587 echo '<tr valign="top">';
2588 echo '<td align="right"><b>'.get_string('visible', '').':</b></td>';
2589 echo '<td align="left">';
2590 unset($choices);
2591 $choices[1] = get_string('show');
2592 $choices[0] = get_string('hide');
2593 choose_from_menu($choices, 'visible', $visible, '', '', 0, false, $hiddensection);
2594 echo '</td></tr>';
2597 function update_restricted_mods($course,$mods) {
2598 delete_records("course_allowed_modules","course",$course->id);
2599 if (empty($course->restrictmodules)) {
2600 return;
2602 else {
2603 foreach ($mods as $mod) {
2604 if ($mod == 0)
2605 continue; // this is the 'allow none' option
2606 $am->course = $course->id;
2607 $am->module = $mod;
2608 insert_record("course_allowed_modules",$am);
2614 * This function will take an int (module id) or a string (module name)
2615 * and return true or false, whether it's allowed in the given course (object)
2616 * $mod is not allowed to be an object, as the field for the module id is inconsistent
2617 * depending on where in the code it's called from (sometimes $mod->id, sometimes $mod->module)
2620 function course_allowed_module($course,$mod) {
2621 if (empty($course->restrictmodules)) {
2622 return true;
2625 // i am not sure this capability is correct
2626 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
2627 return true;
2629 if (is_numeric($mod)) {
2630 $modid = $mod;
2631 } else if (is_string($mod)) {
2632 if ($mod = get_field("modules","id","name",$mod))
2633 $modid = $mod;
2635 if (empty($modid)) {
2636 return false;
2638 return (record_exists("course_allowed_modules","course",$course->id,"module",$modid));
2641 /***
2642 *** Efficiently moves many courses around while maintaining
2643 *** sortorder in order.
2645 *** $courseids is an array of course ids
2649 function move_courses ($courseids, $categoryid) {
2651 global $CFG;
2653 if (!empty($courseids)) {
2655 $courseids = array_reverse($courseids);
2657 foreach ($courseids as $courseid) {
2659 if (! $course = get_record("course", "id", $courseid)) {
2660 notify("Error finding course $courseid");
2661 } else {
2662 // figure out a sortorder that we can use in the destination category
2663 $sortorder = get_field_sql('SELECT MIN(sortorder)-1 AS min
2664 FROM ' . $CFG->prefix . 'course WHERE category=' . $categoryid);
2665 if ($sortorder === false) {
2666 // the category is empty
2667 // rather than let the db default to 0
2668 // set it to > 100 and avoid extra work in fix_coursesortorder()
2669 $sortorder = 200;
2670 } else if ($sortorder < 10) {
2671 fix_course_sortorder($categoryid);
2674 $course->category = $categoryid;
2675 $course->sortorder = $sortorder;
2676 $course->fullname = addslashes($course->fullname);
2677 $course->shortname = addslashes($course->shortname);
2678 $course->summary = addslashes($course->summary);
2679 $course->password = addslashes($course->password);
2680 $course->teacher = addslashes($course->teacher);
2681 $course->teachers = addslashes($course->teachers);
2682 $course->student = addslashes($course->student);
2683 $course->students = addslashes($course->students);
2685 if (!update_record('course', $course)) {
2686 notify("An error occurred - course not moved!");
2689 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2690 $newparent = get_context_instance(CONTEXT_COURSECAT, $course->category);
2691 context_moved($context, $newparent);
2694 fix_course_sortorder();
2696 return true;
2699 /***
2700 *** Efficiently moves a category - NOTE that this can have
2701 *** a huge impact access-control-wise...
2705 function move_category ($category, $newparentcat) {
2707 global $CFG;
2709 if (!set_field('course_categories', 'parent', $newparentcat->id, 'id', $category->id)) {
2710 return false;
2713 $context = get_context_instance(CONTEXT_COURSECAT, $category->id);
2714 $newparent = get_context_instance(CONTEXT_COURSECAT, $newparentcat->id);
2715 context_moved($context, $newparent);
2717 // The most effective thing would be to find the common parent,
2718 // until then, do it sitewide...
2719 fix_course_sortorder();
2722 return true;
2726 * @param string $format Course format ID e.g. 'weeks'
2727 * @return Name that the course format prefers for sections
2729 function get_section_name($format) {
2730 $sectionname = get_string("name$format","format_$format");
2731 if($sectionname == "[[name$format]]") {
2732 $sectionname = get_string("name$format");
2734 return $sectionname;
2738 * Can the current user delete this course?
2739 * @param int $courseid
2740 * @return boolean
2742 * Exception here to fix MDL-7796.
2744 * FIXME
2745 * Course creators who can manage activities in the course
2746 * shoule be allowed to delete the course. We do it this
2747 * way because we need a quick fix to bring the functionality
2748 * in line with what we had pre-roles. We can't give the
2749 * default course creator role moodle/course:delete at
2750 * CONTEXT_SYSTEM level because this will allow them to
2751 * delete any course in the site. So we hard code this here
2752 * for now.
2754 * @author vyshane AT gmail.com
2756 function can_delete_course($courseid) {
2758 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2760 return ( has_capability('moodle/course:delete', $context)
2761 || (has_capability('moodle/legacy:coursecreator', $context)
2762 && has_capability('moodle/course:manageactivities', $context)) );
2767 * Create a course and either return a $course object or false
2769 * @param object $data - all the data needed for an entry in the 'course' table
2771 function create_course($data) {
2772 global $CFG, $USER;
2774 // preprocess allowed mods
2775 $allowedmods = empty($data->allowedmods) ? array() : $data->allowedmods;
2776 unset($data->allowedmods);
2777 if (!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
2778 if ($CFG->restrictmodulesfor == 'all') {
2779 $data->restrictmodules = 1;
2780 } else {
2781 $data->restrictmodules = 0;
2785 $data->timecreated = time();
2787 // place at beginning of category
2788 fix_course_sortorder();
2789 $data->sortorder = get_field_sql("SELECT min(sortorder)-1 FROM {$CFG->prefix}course WHERE category=$data->category");
2790 if (empty($data->sortorder)) {
2791 $data->sortorder = 100;
2794 if ($newcourseid = insert_record('course', $data)) { // Set up new course
2796 $course = get_record('course', 'id', $newcourseid);
2798 // Setup the blocks
2799 $page = page_create_object(PAGE_COURSE_VIEW, $course->id);
2800 blocks_repopulate_page($page); // Return value not checked because you can always edit later
2802 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
2803 update_restricted_mods($course, $allowedmods);
2806 $section = new object();
2807 $section->course = $course->id; // Create a default section.
2808 $section->section = 0;
2809 $section->id = insert_record('course_sections', $section);
2811 fix_course_sortorder();
2813 add_to_log(SITEID, 'course', 'new', 'view.php?id='.$course->id, $data->fullname.' (ID '.$course->id.')');
2815 return $course;
2818 return false; // error
2823 * Update a course and return true or false
2825 * @param object $data - all the data needed for an entry in the 'course' table
2827 function update_course($data) {
2828 global $USER, $CFG;
2830 // preprocess allowed mods
2831 $allowedmods = empty($data->allowedmods) ? array() : $data->allowedmods;
2832 unset($data->allowedmods);
2833 if (!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
2834 unset($data->restrictmodules);
2837 $movecat = false;
2838 $oldcourse = get_record('course', 'id', $data->id); // should not fail, already tested above
2839 if (!has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $oldcourse->category))
2840 or !has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $data->category))) {
2841 // can not move to new category, keep the old one
2842 unset($data->category);
2843 } elseif ($oldcourse->category != $data->category) {
2844 $movecat = true;
2847 // Update with the new data
2848 if (update_record('course', $data)) {
2850 $course = get_record('course', 'id', $data->id);
2852 add_to_log($course->id, "course", "update", "edit.php?id=$course->id", $course->id);
2854 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
2855 update_restricted_mods($course, $allowedmods);
2858 if ($movecat) {
2859 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2860 $newparent = get_context_instance(CONTEXT_COURSECAT, $course->category);
2861 context_moved($context, $newparent);
2864 fix_course_sortorder();
2866 // Test for and remove blocks which aren't appropriate anymore
2867 $page = page_create_object(PAGE_COURSE_VIEW, $course->id);
2868 blocks_remove_inappropriate($page);
2870 // put custom role names into db
2871 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2873 foreach ($data as $dname => $dvalue) {
2875 // is this the right param?
2876 $dvalue = clean_param($dvalue, PARAM_NOTAGS);
2878 if (!strstr($dname, 'role_')) {
2879 continue;
2882 $dt = explode('_', $dname);
2883 $roleid = $dt[1];
2884 // make up our mind whether we want to delete, update or insert
2886 if (empty($dvalue)) {
2888 delete_records('role_names', 'contextid', $context->id, 'roleid', $roleid);
2890 } else if ($t = get_record('role_names', 'contextid', $context->id, 'roleid', $roleid)) {
2892 $t->text = $dvalue;
2893 update_record('role_names', $t);
2895 } else {
2897 $t->contextid = $context->id;
2898 $t->roleid = $roleid;
2899 $t->text = $dvalue;
2900 insert_record('role_names', $t);
2905 return true;
2909 return false;