(Manual capture settings: cron=enabled, an_review=checked, an_capture_day=0)
[moodle.git] / course / lib.php
CommitLineData
e4027ac9 1<?php // $Id$
97c270e9 2 // Library of useful functions
f9903ed0 3
f9903ed0 4
3d891989 5if (defined('COURSE_MAX_LOG_DISPLAY')) { // Being included again - should never happen!!
9ae687af 6 return;
7}
8
92890025 9define('COURSE_MAX_LOG_DISPLAY', 150); // days
10define('COURSE_MAX_LOGS_PER_PAGE', 1000); // records
11define('COURSE_LIVELOG_REFRESH', 60); // Seconds
12define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds
13define('COURSE_MAX_SUMMARIES_PER_PAGE', 10); // courses
950c35a9 14define('COURSE_MAX_COURSES_PER_DROPDOWN',1000); // max courses in log dropdown before switching to optional
92890025 15define('COURSE_MAX_USERS_PER_DROPDOWN',1000); // max users in log dropdown before switching to optional
16define('FRONTPAGENEWS', 0);
17define('FRONTPAGECOURSELIST', 1);
18define('FRONTPAGECATEGORYNAMES', 2);
19define('FRONTPAGETOPICONLY', 3);
20define("EXCELROWS", 65535);
21define("FIRSTUSEDEXCELROW", 3);
60fdc714 22
f9903ed0 23
587510be 24function print_recent_selector_form($course, $advancedfilter=0, $selecteduser=0, $selecteddate="lastlogin",
4581271a 25 $mod="", $modid="activity/All", $modaction="", $selectedgroup="", $selectedsort="default") {
cb83c3cb 26
27 global $USER, $CFG;
28
cb83c3cb 29 $isteacher = isteacher($course->id);
587510be 30 if ($advancedfilter) {
31
32 // Get all the possible users
33 $users = array();
89adb174 34
65ee9c16 35 if ($courseusers = get_course_users($course->id, '', '', 'u.id, u.firstname, u.lastname')) {
587510be 36 foreach ($courseusers as $courseuser) {
37 $users[$courseuser->id] = fullname($courseuser, $isteacher);
38 }
cb83c3cb 39 }
587510be 40 if ($guest = get_guest()) {
41 $users[$guest->id] = fullname($guest);
42 }
89adb174 43
587510be 44 if (isadmin()) {
45 if ($ccc = get_records("course", "", "", "fullname")) {
46 foreach ($ccc as $cc) {
47 if ($cc->category) {
48 $courses["$cc->id"] = "$cc->fullname";
49 } else {
50 $courses["$cc->id"] = " $cc->fullname (Site)";
89adb174 51 }
587510be 52 }
cb83c3cb 53 }
587510be 54 asort($courses);
55 }
4581271a 56
587510be 57 $activities = array();
cb83c3cb 58
587510be 59 $selectedactivity = $modid;
4581271a 60
587510be 61 if ($modinfo = unserialize($course->modinfo)) {
62 $section = 0;
63 if ($course->format == 'weeks') { // Body
64 $strsection = get_string("week");
65 } else {
66 $strsection = get_string("topic");
cb83c3cb 67 }
cb83c3cb 68
587510be 69 $activities["activity/All"] = "All activities";
70 $activities["activity/Assignments"] = "All assignments";
71 $activities["activity/Chats"] = "All chats";
72 $activities["activity/Forums"] = "All forums";
73 $activities["activity/Quizzes"] = "All quizzes";
74 $activities["activity/Workshops"] = "All workshops";
75
76 $activities["section/individual"] = "------------- Individual Activities --------------";
77
78 foreach ($modinfo as $mod) {
79 if ($mod->mod == "label") {
80 continue;
89adb174 81 }
9c08ad13 82 if (!$mod->visible and !$isteacher) {
83 continue;
84 }
85
587510be 86 if ($mod->section > 0 and $section <> $mod->section) {
87 $activities["section/$mod->section"] = "-------------- $strsection $mod->section --------------";
88 }
89 $section = $mod->section;
235a4ee8 90 $mod->name = strip_tags(format_string(urldecode($mod->name),true));
587510be 91 if (strlen($mod->name) > 55) {
92 $mod->name = substr($mod->name, 0, 50)."...";
93 }
94 if (!$mod->visible) {
95 $mod->name = "(".$mod->name.")";
96 }
97 $activities["$mod->cm"] = $mod->name;
98
99 if ($mod->cm == $modid) {
100 $selectedactivity = "$mod->cm";
101 }
cb83c3cb 102 }
103 }
cb83c3cb 104
587510be 105 $strftimedate = get_string("strftimedate");
106 $strftimedaydate = get_string("strftimedaydate");
cb83c3cb 107
587510be 108 asort($users);
cb83c3cb 109
587510be 110 // Get all the possible dates
111 // Note that we are keeping track of real (GMT) time and user time
112 // User time is only used in displays - all calcs and passing is GMT
cb83c3cb 113
587510be 114 $timenow = time(); // GMT
cb83c3cb 115
587510be 116 // What day is it now for the user, and when is midnight that day (in GMT).
117 $timemidnight = $today = usergetmidnight($timenow);
cb83c3cb 118
587510be 119 $dates = array();
120 $dates["$USER->lastlogin"] = get_string("lastlogin").", ".userdate($USER->lastlogin, $strftimedate);
121 $dates["$timemidnight"] = get_string("today").", ".userdate($timenow, $strftimedate);
cb83c3cb 122
587510be 123 if (!$course->startdate or ($course->startdate > $timenow)) {
124 $course->startdate = $course->timecreated;
125 }
cb83c3cb 126
587510be 127 $numdates = 1;
128 while ($timemidnight > $course->startdate and $numdates < 365) {
129 $timemidnight = $timemidnight - 86400;
130 $timenow = $timenow - 86400;
131 $dates["$timemidnight"] = userdate($timenow, $strftimedaydate);
132 $numdates++;
133 }
cb83c3cb 134
96dcfb56 135 if ($selecteddate === "lastlogin") {
587510be 136 $selecteddate = $USER->lastlogin;
137 }
138
139 echo '<form action="recent.php" method="get">';
1c919752 140 echo '<input type="hidden" name="chooserecent" value="1" />';
587510be 141 echo "<center>";
142 echo "<table>";
143
144 if (isadmin()) {
145 echo "<tr><td><b>" . get_string("courses") . "</b></td><td>";
146 choose_from_menu ($courses, "id", $course->id, "");
147 echo "</td></tr>";
148 } else {
1c919752 149 echo '<input type="hidden" name="id" value="'.$course->id.'" />';
587510be 150 }
cb83c3cb 151
f5ffb87d 152 $sortfields = array("default" => get_string("bycourseorder"),"dateasc" => get_string("datemostrecentlast"), "datedesc" => get_string("datemostrecentfirst"));
4581271a 153
587510be 154 echo "<tr><td><b>" . get_string("participants") . "</b></td><td>";
155 choose_from_menu ($users, "user", $selecteduser, get_string("allparticipants") );
156 echo "</td>";
157
1c919752 158 echo '<td align="right"><b>' . get_string("since") . '</b></td><td>';
587510be 159 choose_from_menu ($dates, "date", $selecteddate, get_string("alldays"));
4581271a 160 echo "</td></tr>";
4581271a 161
587510be 162 echo "<tr><td><b>" . get_string("activities") . "</b></td><td>";
163 choose_from_menu ($activities, "modid", $selectedactivity, "");
164 echo "</td>";
4581271a 165
1c919752 166 echo '<td align="right"><b>' . get_string("sortby") . "</b></td><td>";
587510be 167 choose_from_menu ($sortfields, "sortby", $selectedsort, "");
168 echo "</td></tr>";
4581271a 169
587510be 170 echo '<tr>';
4581271a 171
587510be 172 $groupmode = groupmode($course);
4581271a 173
587510be 174 if ($groupmode == VISIBLEGROUPS or ($groupmode and isteacheredit($course->id))) {
175 if ($groups = get_records_menu("groups", "courseid", $course->id, "name ASC", "id,name")) {
4581271a 176 echo '<td><b>';
587510be 177 if ($groupmode == VISIBLEGROUPS) {
178 print_string('groupsvisible');
179 } else {
180 print_string('groupsseparate');
181 }
182 echo ':</b></td><td>';
183 choose_from_menu($groups, "selectedgroup", $selectedgroup, get_string("allgroups"), "", "");
184 echo '</td>';
185 }
186 }
187
188
1c919752 189 echo '<td colspan="2" align="right">';
190 echo '<input type="submit" value="'.get_string('showrecent').'" />';
587510be 191 echo "</td></tr>";
192
193 echo "</table>";
194
839f2456 195 $advancedlink = "<a href=\"$CFG->wwwroot/course/recent.php?id=$course->id&amp;advancedfilter=0\">" . get_string("normalfilter") . "</a>";
587510be 196 print_heading($advancedlink);
197 echo "</center>";
198 echo "</form>";
199
200 } else {
201
202 $day_list = array("1","7","14","21","30");
203 $strsince = get_string("since");
204 $strlastlogin = get_string("lastlogin");
205 $strday = get_string("day");
206 $strdays = get_string("days");
207
208 $heading = "";
209 foreach ($day_list as $count) {
210 if ($count == "1") {
211 $day = $strday;
4581271a 212 } else {
587510be 213 $day = $strdays;
4581271a 214 }
3819ed31 215 $tmpdate = time() - ($count * 3600 * 24);
587510be 216 $heading = $heading .
839f2456 217 "<a href=\"$CFG->wwwroot/course/recent.php?id=$course->id&amp;date=$tmpdate\"> $count $day</a> | ";
4581271a 218 }
4581271a 219
587510be 220 $heading = $strsince . ": <a href=\"$CFG->wwwroot/course/recent.php?id=$course->id\">$strlastlogin</a>" . " | " . $heading;
221 print_heading($heading);
4581271a 222
839f2456 223 $advancedlink = "<a href=\"$CFG->wwwroot/course/recent.php?id=$course->id&amp;advancedfilter=1\">" . get_string("advancedfilter") . "</a>";
587510be 224 print_heading($advancedlink);
225
226 }
4581271a 227
cb83c3cb 228}
9ae687af 229
f9903ed0 230
600149be 231function make_log_url($module, $url) {
232 switch ($module) {
bd7be234 233 case 'user':
234 case 'course':
235 case 'file':
236 case 'login':
237 case 'lib':
238 case 'admin':
239 case 'message':
240 case 'calendar':
241 case 'blog':
600149be 242 return "/$module/$url";
243 break;
bd7be234 244 case 'upload':
245 return $url;
c80b7585 246 break;
bd7be234 247 case 'library':
248 case '':
249 return '/';
de2dfe68 250 break;
600149be 251 default:
252 return "/mod/$module/$url";
253 break;
254 }
255}
256
92890025 257
258function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
259 $modname="", $modid=0, $modaction="", $groupid=0) {
f24cffb9 260
e0161bff 261 // It is assumed that $date is the GMT time of midnight for that day,
262 // and so the next 86400 seconds worth of logs are printed.
f9903ed0 263
92890025 264 global $db;
47f1da80 265
69c76405 266 /// Setup for group handling.
267 $isteacher = isteacher($course->id);
268 $isteacheredit = isteacheredit($course->id);
269
270 /// If the group mode is separate, and this user does not have editing privileges,
271 /// then only the user's group can be viewed.
272 if ($course->groupmode == SEPARATEGROUPS and !$isteacheredit) {
273 $groupid = get_current_group($course->id);
274 }
275 /// If this course doesn't have groups, no groupid can be specified.
276 else if (!$course->groupmode) {
277 $groupid = 0;
278 }
279
e0161bff 280 $joins = array();
a2ab3b05 281
e15ef260 282 if ($course->id != SITEID || $modid != 0) {
8f0cd6ef 283 $joins[] = "l.course='$course->id'";
e15ef260 284 }
f9903ed0 285
c469a7ef 286 if ($modname) {
e0161bff 287 $joins[] = "l.module = '$modname'";
f24cffb9 288 }
289
e21922f0 290 if ('site_errors' === $modid) {
bf35eb15 291 $joins[] = "( l.action='error' OR l.action='infected' )";
e21922f0 292 } else if ($modid) {
293 $joins[] = "l.cmid = '$modid'";
69d79bc3 294 }
295
296 if ($modaction) {
ee35e0b8 297 $firstletter = substr($modaction, 0, 1);
298 if (ctype_alpha($firstletter)) {
299 $joins[] = "lower(l.action) LIKE '%" . strtolower($modaction) . "%'";
300 } else if ($firstletter == '-') {
301 $joins[] = "lower(l.action) NOT LIKE '%" . strtolower(substr($modaction, 1)) . "%'";
302 }
f24cffb9 303 }
304
69c76405 305 /// Getting all members of a group.
306 if ($groupid and !$user) {
307 if ($gusers = get_records('groups_members', 'groupid', $groupid)) {
308 $first = true;
309 foreach($gusers as $guser) {
310 if ($first) {
311 $gselect = '(l.userid='.$guser->userid;
312 $first = false;
313 }
314 else {
315 $gselect .= ' OR l.userid='.$guser->userid;
316 }
317 }
318 if (!$first) $gselect .= ')';
319 $joins[] = $gselect;
320 }
321 }
322 else if ($user) {
e0161bff 323 $joins[] = "l.userid = '$user'";
f9903ed0 324 }
325
326 if ($date) {
327 $enddate = $date + 86400;
e0161bff 328 $joins[] = "l.time > '$date' AND l.time < '$enddate'";
f9903ed0 329 }
330
2828ff51 331 $selector = '';
e0161bff 332 for ($i = 0; $i < count($joins); $i++) {
333 $selector .= $joins[$i] . (($i == count($joins)-1) ? " " : " AND ");
334 }
335
d09f3c80 336 $totalcount = 0; // Initialise
92890025 337
338 $result = array();
339 $result['logs'] = get_logs($selector, $order, $limitfrom, $limitnum, $totalcount);
340 $result['totalcount'] = $totalcount;
341 return $result;
342}
343
344
345function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
346 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
347
348 global $CFG;
349
350 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
351 $modname, $modid, $modaction, $groupid)) {
f9903ed0 352 notify("No logs found!");
353 print_footer($course);
354 exit;
355 }
92890025 356
357 if ($course->id == SITEID) {
358 $courses[0] = '';
359 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
360 foreach ($ccc as $cc) {
361 $courses[$cc->id] = $cc->shortname;
362 }
363 }
364 }
365
366 $totalcount = $logs['totalcount'];
f9903ed0 367 $count=0;
2eb68e6f 368 $ldcache = array();
f9903ed0 369 $tt = getdate(time());
370 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
1c0200e0 371
dcde9f02 372 $strftimedatetime = get_string("strftimedatetime");
2ac64806 373 $isteacher = isteacher($course->id);
dcde9f02 374
21283ddc 375 echo "<p align=\"center\">\n";
519d369f 376 print_string("displayingrecords", "", $totalcount);
21283ddc 377 echo "</p>\n";
1c0200e0 378
8f0cd6ef 379 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
519d369f 380
21283ddc 381 echo "<table class=\"logtable\" border=\"0\" align=\"center\" cellpadding=\"3\" cellspacing=\"0\">\n";
382 echo "<tr>";
1548978d 383 if ($course->id == SITEID) {
21283ddc 384 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
1548978d 385 }
21283ddc 386 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
387 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
388 echo "<th class=\"c3 header\">".get_string('fullname')."</th>\n";
389 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
390 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
391 echo "</tr>\n";
1548978d 392
393 $row = 1;
92890025 394 foreach ($logs['logs'] as $log) {
600149be 395
1548978d 396 $row = ($row + 1) % 2;
397
2eb68e6f 398 if (isset($ldcache[$log->module][$log->action])) {
399 $ld = $ldcache[$log->module][$log->action];
400 } else {
1548978d 401 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
2eb68e6f 402 $ldcache[$log->module][$log->action] = $ld;
403 }
76feee3f 404 if ($ld && !empty($log->info)) {
181b888e 405 // ugly hack to make sure fullname is shown correctly
406 if (($ld->mtable == 'user') and ($ld->field == 'CONCAT(firstname," ",lastname)')) {
407 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
408 } else {
409 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
410 }
600149be 411 }
412
c8b0a50b 413 //Filter log->info
414 $log->info = format_string($log->info);
415
d7d145b1 416 $log->url = strip_tags(urldecode($log->url)); // Some XSS protection
417 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
6ac98433 418 $log->url = str_replace('&', '&amp;', $log->url); /// XHTML compatibility
d7d145b1 419
1548978d 420 echo '<tr class="r'.$row.'">';
421 if ($course->id == SITEID) {
21283ddc 422 echo "<td class=\"r$row c0\" nowrap=\"nowrap\">\n";
423 echo " <a href=\"view.php?id={$log->course}\">".$courses[$log->course]."</a>\n";
424 echo "</td>\n";
720a43ce 425 }
21283ddc 426 echo "<td class=\"r$row c1\" nowrap=\"nowrap\" align=\"right\">".userdate($log->time, '%a').
427 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
428 echo "<td class=\"r$row c2\" nowrap=\"nowrap\">\n";
7eca967c 429 link_to_popup_window("/iplookup/index.php?ip=$log->ip&amp;user=$log->userid", 'iplookup',$log->ip, 400, 700);
21283ddc 430 echo "</td>\n";
2ac64806 431 $fullname = fullname($log, $isteacher);
21283ddc 432 echo "<td class=\"r$row c3\" nowrap=\"nowrap\">\n";
d3a75287 433 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}&amp;course={$log->course}\">$fullname</a>\n";
21283ddc 434 echo "</td>\n";
435 echo "<td class=\"r$row c4\" nowrap=\"nowrap\">\n";
2eb68e6f 436 link_to_popup_window( make_log_url($log->module,$log->url), 'fromloglive',"$log->module $log->action", 400, 600);
21283ddc 437 echo "</td>\n";;
438 echo "<td class=\"r$row c5\" nowrap=\"nowrap\">{$log->info}</td>\n";
439 echo "</tr>\n";
f9903ed0 440 }
21283ddc 441 echo "</table>\n";
519d369f 442
8f0cd6ef 443 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
f9903ed0 444}
445
446
92890025 447function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
448 $modid, $modaction, $groupid) {
449
450 $text = get_string('course')."\t".get_string('time')."\t".get_string('ip_address')."\t".
451 get_string('fullname')."\t".get_string('action')."\t".get_string('info');
452
453 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
454 $modname, $modid, $modaction, $groupid)) {
455 return false;
456 }
457
458 if ($course->id == SITEID) {
459 $courses[0] = '';
460 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
461 foreach ($ccc as $cc) {
462 $courses[$cc->id] = $cc->shortname;
463 }
464 }
465 }
466
467 $count=0;
468 $ldcache = array();
469 $tt = getdate(time());
470 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
471
472 $strftimedatetime = get_string("strftimedatetime");
473 $isteacher = isteacher($course->id);
474
475 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
476 $filename .= '.txt';
477 header("Content-Type: application/download\n");
478 header("Content-Disposition: attachment; filename=$filename");
479 header("Expires: 0");
480 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
481 header("Pragma: public");
482
483 echo get_string('savedat').userdate(time(), $strftimedatetime)."\n";
484 echo $text;
485
486 foreach ($logs['logs'] as $log) {
487 if (isset($ldcache[$log->module][$log->action])) {
488 $ld = $ldcache[$log->module][$log->action];
489 } else {
490 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
491 $ldcache[$log->module][$log->action] = $ld;
492 }
493 if ($ld && !empty($log->info)) {
494 // ugly hack to make sure fullname is shown correctly
495 if (($ld->mtable == 'user') and ($ld->field == 'CONCAT(firstname," ",lastname)')) {
496 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
497 } else {
498 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
499 }
500 }
501
502 //Filter log->info
503 $log->info = format_string($log->info);
504
505 $log->url = strip_tags(urldecode($log->url)); // Some XSS protection
506 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
507 $log->url = str_replace('&', '&amp;', $log->url); // XHTML compatibility
508
509 $firstField = $courses[$log->course];
510 $fullname = fullname($log, $isteacher);
511 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action, $log->info);
512 $text = implode("\t", $row);
513 echo $text." \n";
514 }
515 return true;
516}
517
518
519function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
520 $modid, $modaction, $groupid) {
521
522 global $CFG;
523
524 require_once("$CFG->libdir/excellib.class.php");
525
526 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
527 $modname, $modid, $modaction, $groupid)) {
528 return false;
529 }
530
531 if ($course->id == SITEID) {
532 $courses[0] = '';
533 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
534 foreach ($ccc as $cc) {
535 $courses[$cc->id] = $cc->shortname;
536 }
537 }
538 }
539
540 $count=0;
541 $ldcache = array();
542 $tt = getdate(time());
543 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
544
545 $strftimedatetime = get_string("strftimedatetime");
546 $isteacher = isteacher($course->id);
547
548 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
549 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
550 $filename .= '.xls';
551
552 $workbook = new MoodleExcelWorkbook('-');
553 $workbook->send($filename);
554
555 $worksheet = array();
556 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
557 get_string('fullname'), get_string('action'), get_string('info'));
558
559 // Creating worksheets
560 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
561 $sheettitle = get_string('excel_sheettitle', 'logs', $wsnumber).$nroPages;
562 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
563 $worksheet[$wsnumber]->set_column(1, 1, 30);
564 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
565 userdate(time(), $strftimedatetime));
566 $col = 0;
567 foreach ($headers as $item) {
568 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
569 $col++;
570 }
571 }
572
573 $formatDate =& $workbook->add_format();
574 $formatDate->set_num_format(get_string('log_excel_date_format'));
575
576 $row = FIRSTUSEDEXCELROW;
577 $wsnumber = 1;
578 $myxls =& $worksheet[$wsnumber];
579 foreach ($logs['logs'] as $log) {
580 if (isset($ldcache[$log->module][$log->action])) {
581 $ld = $ldcache[$log->module][$log->action];
582 } else {
583 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
584 $ldcache[$log->module][$log->action] = $ld;
585 }
586 if ($ld && !empty($log->info)) {
587 // ugly hack to make sure fullname is shown correctly
588 if (($ld->mtable == 'user') and ($ld->field == 'CONCAT(firstname," ",lastname)')) {
589 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
590 } else {
591 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
592 }
593 }
594
595 // Filter log->info
596 $log->info = format_string($log->info);
597 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
598
599 if ($nroPages>1) {
600 if ($row > EXCELROWS) {
601 $wsnumber++;
602 $myxls =& $worksheet[$wsnumber];
603 $row = FIRSTUSEDEXCELROW;
604 }
605 }
606
607 $myxls->write($row, 0, $courses[$log->course], '');
608 // Excel counts from 1/1/1900
609 $excelTime=25569+$log->time/(3600*24);
610 $myxls->write($row, 1, $excelTime, $formatDate);
611 $myxls->write($row, 2, $log->ip, '');
612 $fullname = fullname($log, $isteacher);
613 $myxls->write($row, 3, $fullname, '');
614 $myxls->write($row, 4, $log->module.' '.$log->action, '');
615 $myxls->write($row, 5, $log->info, '');
616
617 $row++;
618 }
619
620 $workbook->close();
621 return true;
622}
623
624/*
625// Relies on $CFG->libdir.'/phpdocwriter/lib/include.php', which is not
626// included in the default Moodle distribution.
627
628function print_log_ooo($course, $user, $date, $order='l.time DESC', $modname,
629 $modid, $modaction, $groupid) { global $CFG;
630
631 require_once($CFG->libdir.'/phpdocwriter/lib/include.php');
632
633 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
634 $modname, $modid, $modaction, $groupid)) {
635 return false;
636 }
637
638 if ($course->id == SITEID) {
639 $courses[0] = '';
640 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
641 foreach ($ccc as $cc) {
642 $courses[$cc->id] = $cc->shortname;
643 }
644 }
645 }
646
647 $count=0;
648 $ldcache = array();
649 $tt = getdate(time());
650 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
651
652 $strftimedatetime = get_string("strftimedatetime");
653 $isteacher = isteacher($course->id);
654
655 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
656 $filename .= '.sxw';
657 import('phpdocwriter.pdw_document');
658 header("Content-Type: application/download\n");
659 header("Content-Disposition: attachment; filename=$filename");
660 header("Expires: 0");
661 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
662 header("Pragma: public");
663 header("Content-Transfer-Encoding: binary");
664
665 $sxw = new pdw_document;
666 $sxw->SetFileName($filename);
667 $sxw->SetAuthor('Moodle');
668 $sxw->SetTitle('logs');
669 $sxw->SetDescription('logs'.' - '.$filename);
670 $sxw->SetLanguage('es','ES');
671 $sxw->SetStdFont("Times New Roman",12);
672 $sxw->AddPageDef(array('name'=>'Standard', 'margins'=>'1,1,1,1', 'w'=>'29.7', 'h'=>'21'));
673 $sxw->Write(get_string('savedat').userdate(time(), $strftimedatetime));
674 $sxw->Ln(3);
675
676 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
677 get_string('fullname'), get_string('action'), get_string('info'));
678
679 foreach($headers as $key=>$header){
680 $headers[$key] = eregi_replace ("<br?>", " ",$header);
681 }
682
683 foreach ($logs['logs'] as $log) {
684 if (isset($ldcache[$log->module][$log->action])) {
685 $ld = $ldcache[$log->module][$log->action];
686 } else {
687 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
688 $ldcache[$log->module][$log->action] = $ld;
689 }
690 if ($ld && !empty($log->info)) {
691 // ugly hack to make sure fullname is shown correctly
692 if (($ld->mtable == 'user') and ($ld->field == 'CONCAT(firstname," ",lastname)')) {
693 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
694 } else {
695 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
696 }
697 }
698
699 // Filter log->info
700 $log->info = format_string($log->info);
701
702 $log->url = strip_tags(urldecode($log->url)); // Some XSS protection
703 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
704 $log->url = str_replace('&', '&amp;', $log->url); // XHTML compatibility
705
706 $firstField = $courses[$log->course];
707 $fullname = fullname($log, $isteacher);
708 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action, $log->info);
709
710 $data[] = $row;
711 }
712 $sxw->Table($headers,$data);
713 $sxw->Output();
714
715 return true;
716}
717*/
718
c2cb4545 719function print_log_graph($course, $userid=0, $type="course.png", $date=0) {
720 global $CFG;
721 if (empty($CFG->gdversion)) {
722 echo "(".get_string("gdneed").")";
d887b5a7 723 } else {
980a5b3a 724 echo '<img src="'.$CFG->wwwroot.'/course/report/log/graph.php?id='.$course->id.
29b59206 725 '&amp;user='.$userid.'&amp;type='.$type.'&amp;date='.$date.'" alt="" />';
d887b5a7 726 }
727}
728
729
185cfb09 730function print_overview($courses) {
0d6b9d4f 731
732 global $CFG, $USER;
733
185cfb09 734 $htmlarray = array();
f8716988 735 if ($modules = get_records('modules')) {
736 foreach ($modules as $mod) {
737 if (file_exists(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php')) {
738 require_once(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php');
739 $fname = $mod->name.'_print_overview';
0d6b9d4f 740 if (function_exists($fname)) {
185cfb09 741 $fname($courses,$htmlarray);
0d6b9d4f 742 }
743 }
744 }
745 }
185cfb09 746 foreach ($courses as $course) {
fe5a1e23 747 print_simple_box_start('center', '100%', '', 5, "coursebox");
185cfb09 748 $linkcss = '';
749 if (empty($course->visible)) {
750 $linkcss = 'class="dimmed"';
751 }
752 print_heading('<a title="'.$course->fullname.'" '.$linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.$course->fullname.'</a>');
753 if (array_key_exists($course->id,$htmlarray)) {
754 foreach ($htmlarray[$course->id] as $modname => $html) {
755 echo $html;
756 }
757 }
758 print_simple_box_end();
759 }
0d6b9d4f 760}
761
762
600149be 763function print_recent_activity($course) {
764 // $course is an object
89adb174 765 // This function trawls through the logs looking for
600149be 766 // anything new since the user's last login
767
810393c8 768 global $CFG, $USER, $SESSION;
600149be 769
2ac64806 770 $isteacher = isteacher($course->id);
771
6f80940b 772 $timestart = time() - COURSE_MAX_RECENT_PERIOD;
0f87cb1d 773
9e51847a 774 if (!empty($USER->timeaccess[$course->id])) {
6f80940b 775 if ($USER->timeaccess[$course->id] > $timestart) {
9e51847a 776 $timestart = $USER->timeaccess[$course->id];
777 }
3d891989 778 }
0f87cb1d 779
de785682 780 echo '<div class="activitydate">';
27bf9e20 781 echo get_string('activitysince', '', userdate($timestart));
de785682 782 echo '</div>';
783 echo '<div class="activityhead">';
0f87cb1d 784
de785682 785 echo '<a href="'.$CFG->wwwroot.'/course/recent.php?id='.$course->id.'">'.get_string('recentactivityreport').'</a>';
0f87cb1d 786
de785682 787 echo '</div>';
0f87cb1d 788
600149be 789
790 // Firstly, have there been any new enrolments?
791
792 $heading = false;
793 $content = false;
1b5910c4 794
6c38b7e0 795 $users = get_recent_enrolments($course->id, $timestart);
1b5910c4 796
6c38b7e0 797 if ($users) {
27bf9e20 798 echo '<div class="newusers">';
6c38b7e0 799 foreach ($users as $user) {
600149be 800 if (! $heading) {
27bf9e20 801 print_headline(get_string("newusers").':', 3);
600149be 802 $heading = true;
803 $content = true;
804 }
2ac64806 805 $fullname = fullname($user, $isteacher);
27bf9e20 806 echo '<span class="name"><a href="'.$CFG->wwwroot."/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a></span><br />";
600149be 807 }
27bf9e20 808 echo '</div>';
600149be 809 }
810
1b5910c4 811 // Next, have there been any modifications to the course structure?
812
27bf9e20 813 $logs = get_records_select('log', "time > '$timestart' AND course = '$course->id' AND
1b5910c4 814 module = 'course' AND action LIKE '% mod'", "time ASC");
815
816 if ($logs) {
817 foreach ($logs as $key => $log) {
27bf9e20 818 $info = split(' ', $log->info);
c9f6251e 819
27bf9e20 820 if ($info[0] == 'label') { // Labels are special activities
c9f6251e 821 continue;
822 }
823
27bf9e20 824 $modname = get_field($info[0], 'name', 'id', $info[1]);
1b5910c4 825 //Create a temp valid module structure (course,id)
826 $tempmod->course = $log->course;
827 $tempmod->id = $info[1];
828 //Obtain the visible property from the instance
829 $modvisible = instance_is_visible($info[0],$tempmod);
89adb174 830
1b5910c4 831 //Only if the mod is visible
832 if ($modvisible) {
833 switch ($log->action) {
27bf9e20 834 case 'add mod':
835 $stradded = get_string('added', 'moodle', get_string('modulename', $info[0]));
5847b267 836 $changelist[$log->info] = array ('operation' => 'add', 'text' => "$stradded:<br /><a href=\"$CFG->wwwroot/course/$log->url\">".format_string($modname,true)."</a>");
1b5910c4 837 break;
27bf9e20 838 case 'update mod':
839 $strupdated = get_string('updated', 'moodle', get_string('modulename', $info[0]));
840 if (empty($changelist[$log->info])) {
5847b267 841 $changelist[$log->info] = array ('operation' => 'update', 'text' => "$strupdated:<br /><a href=\"$CFG->wwwroot/course/$log->url\">".format_string($modname,true)."</a>");
1b5910c4 842 }
843 break;
27bf9e20 844 case 'delete mod':
845 if (!empty($changelist[$log->info]['operation']) and
846 $changelist[$log->info]['operation'] == 'add') {
847 $changelist[$log->info] = NULL;
1b5910c4 848 } else {
27bf9e20 849 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $info[0]));
850 $changelist[$log->info] = array ('operation' => 'delete', 'text' => $strdeleted);
1b5910c4 851 }
852 break;
600149be 853 }
ef25340c 854 }
855 }
856 }
857
9c9f7d77 858 if (!empty($changelist)) {
ef25340c 859 foreach ($changelist as $changeinfo => $change) {
860 if ($change) {
861 $changes[$changeinfo] = $change;
862 }
863 }
8a59942e 864 if (isset($changes)){
865 if (count($changes) > 0) {
27bf9e20 866 print_headline(get_string('courseupdates').':', 3);
8a59942e 867 $content = true;
868 foreach ($changes as $changeinfo => $change) {
27bf9e20 869 echo '<p class="activity">'.$change['text'].'</p>';
8a59942e 870 }
600149be 871 }
872 }
89adb174 873 }
bf40f9c1 874
3869a2ac 875 // Now display new things from each module
600149be 876
27bf9e20 877 $mods = get_records('modules', 'visible', '1', 'name', 'id, name');
0fd7da81 878
1b5910c4 879 foreach ($mods as $mod) { // Each module gets it's own logs and prints them
27bf9e20 880 include_once($CFG->dirroot.'/mod/'.$mod->name.'/lib.php');
881 $print_recent_activity = $mod->name.'_print_recent_activity';
1b5910c4 882 if (function_exists($print_recent_activity)) {
883 $modcontent = $print_recent_activity($course, $isteacher, $timestart);
3869a2ac 884 if ($modcontent) {
885 $content = true;
600149be 886 }
600149be 887 }
888 }
889
890 if (! $content) {
27bf9e20 891 echo '<p class="message">'.get_string('nothingnew').'</p>';
600149be 892 }
600149be 893}
894
e1360728 895
d897cae4 896function get_array_of_activities($courseid) {
89adb174 897// For a given course, returns an array of course activity objects
d897cae4 898// Each item in the array contains he following properties:
899// cm - course module id
900// mod - name of the module (eg forum)
901// section - the number of the section (eg week or topic)
902// name - the name of the instance
5867bfb5 903// visible - is the instance visible or not
86aa7ccf 904// extra - contains extra string to include in any link
d897cae4 905
8dddba42 906 global $CFG;
907
d897cae4 908 $mod = array();
909
9fa49e22 910 if (!$rawmods = get_course_mods($courseid)) {
d897cae4 911 return NULL;
912 }
913
914 if ($sections = get_records("course_sections", "course", $courseid, "section ASC")) {
915 foreach ($sections as $section) {
74666583 916 if (!empty($section->sequence)) {
d897cae4 917 $sequence = explode(",", $section->sequence);
918 foreach ($sequence as $seq) {
7af6281f 919 if (empty($rawmods[$seq])) {
920 continue;
921 }
d897cae4 922 $mod[$seq]->cm = $rawmods[$seq]->id;
923 $mod[$seq]->mod = $rawmods[$seq]->modname;
924 $mod[$seq]->section = $section->section;
925 $mod[$seq]->name = urlencode(get_field($rawmods[$seq]->modname, "name", "id", $rawmods[$seq]->instance));
fec5a6a6 926 $mod[$seq]->visible = $rawmods[$seq]->visible;
86aa7ccf 927 $mod[$seq]->extra = "";
8dddba42 928
929 $modname = $mod[$seq]->mod;
930 $functionname = $modname."_get_coursemodule_info";
931
932 include_once("$CFG->dirroot/mod/$modname/lib.php");
933
934 if (function_exists($functionname)) {
9d361034 935 if ($info = $functionname($rawmods[$seq])) {
936 if (!empty($info->extra)) {
937 $mod[$seq]->extra = $info->extra;
938 }
939 if (!empty($info->icon)) {
940 $mod[$seq]->icon = $info->icon;
941 }
c9f6251e 942 }
943 }
d897cae4 944 }
945 }
946 }
947 }
948 return $mod;
949}
950
951
952
e1360728 953
90845098 954function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
955// Returns a number of useful structures for course displays
7468bf01 956
90845098 957 $mods = NULL; // course modules indexed by id
e0161bff 958 $modnames = NULL; // all course module names (except resource!)
94361e02 959 $modnamesplural= NULL; // all course module names (plural form)
90845098 960 $modnamesused = NULL; // course module names used
7468bf01 961
9fa49e22 962 if ($allmods = get_records("modules")) {
90845098 963 foreach ($allmods as $mod) {
5867bfb5 964 if ($mod->visible) {
965 $modnames[$mod->name] = get_string("modulename", "$mod->name");
966 $modnamesplural[$mod->name] = get_string("modulenameplural", "$mod->name");
967 }
90845098 968 }
969 asort($modnames);
970 } else {
971 error("No modules are installed!");
972 }
973
9fa49e22 974 if ($rawmods = get_course_mods($courseid)) {
7468bf01 975 foreach($rawmods as $mod) { // Index the mods
959ae824 976 if (empty($modnames[$mod->modname])) {
977 continue;
978 }
7468bf01 979 $mods[$mod->id] = $mod;
959ae824 980 $mods[$mod->id]->modfullname = $modnames[$mod->modname];
981 if ($mod->visible or isteacher($courseid)) {
982 $modnamesused[$mod->modname] = $modnames[$mod->modname];
1acfbce5 983 }
7468bf01 984 }
c7da6f7a 985 if ($modnamesused) {
986 asort($modnamesused);
987 }
7468bf01 988 }
e0161bff 989
990 unset($modnames['resource']);
991 unset($modnames['label']);
7468bf01 992}
993
9fa49e22 994
7468bf01 995function get_all_sections($courseid) {
89adb174 996
997 return get_records("course_sections", "course", "$courseid", "section",
7d99d695 998 "section, id, course, summary, sequence, visible");
7468bf01 999}
1000
b86fc0e2 1001function course_set_display($courseid, $display=0) {
1002 global $USER;
1003
1066e0dc 1004 if (empty($USER->id)) {
b86fc0e2 1005 return false;
1006 }
1007
1008 if ($display == "all" or empty($display)) {
1009 $display = 0;
1010 }
1011
1012 if (record_exists("course_display", "userid", $USER->id, "course", $courseid)) {
1013 set_field("course_display", "display", $display, "userid", $USER->id, "course", $courseid);
1014 } else {
1015 $record->userid = $USER->id;
1016 $record->course = $courseid;
1017 $record->display = $display;
1018 if (!insert_record("course_display", $record)) {
1019 notify("Could not save your course display!");
1020 }
1021 }
1022
1023 return $USER->display[$courseid] = $display; // Note: = not ==
1024}
1025
7d99d695 1026function set_section_visible($courseid, $sectionnumber, $visibility) {
1027/// For a given course section, markes it visible or hidden,
1028/// and does the same for every activity in that section
1029
1030 if ($section = get_record("course_sections", "course", $courseid, "section", $sectionnumber)) {
1031 set_field("course_sections", "visible", "$visibility", "id", $section->id);
1032 if (!empty($section->sequence)) {
1033 $modules = explode(",", $section->sequence);
1034 foreach ($modules as $moduleid) {
02f66c42 1035 set_coursemodule_visible($moduleid, $visibility, true);
7d99d695 1036 }
1037 }
5867bfb5 1038 rebuild_course_cache($courseid);
7d99d695 1039 }
1040}
ba2e5d73 1041
5e367a2d 1042
d897cae4 1043function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%") {
52dcc2f9 1044/// Prints a section full of activity modules
7977cffd 1045 global $CFG, $USER;
1046
3d575e6f 1047 static $groupbuttons;
32d03b7b 1048 static $groupbuttonslink;
52dcc2f9 1049 static $isteacher;
1050 static $isediting;
7977cffd 1051 static $ismoving;
1052 static $strmovehere;
1053 static $strmovefull;
54669989 1054 static $strunreadpostsone;
52dcc2f9 1055
4877707e 1056 static $untracked;
a2d71d8e 1057 static $usetracking;
4877707e 1058
a22f8313 1059 $labelformatoptions = New stdClass;
110a32e2 1060
52dcc2f9 1061 if (!isset($isteacher)) {
9fd9c29b 1062 $groupbuttons = ($course->groupmode or (!$course->groupmodeforce));
32d03b7b 1063 $groupbuttonslink = (!$course->groupmodeforce);
52dcc2f9 1064 $isteacher = isteacher($course->id);
52dcc2f9 1065 $isediting = isediting($course->id);
ff0c7de0 1066 $ismoving = $isediting && ismoving($course->id);
3d575e6f 1067 if ($ismoving) {
1068 $strmovehere = get_string("movehere");
1069 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1070 }
94a6a70f 1071 include_once($CFG->dirroot.'/mod/forum/lib.php');
1072 if ($usetracking = forum_tp_can_track_forums()) {
a2d71d8e 1073 $strunreadpostsone = get_string('unreadpostsone', 'forum');
94a6a70f 1074 $untracked = forum_tp_get_untracked_forums($USER->id, $course->id);
a2d71d8e 1075 }
7977cffd 1076 }
60bd11cf 1077 $labelformatoptions->noclean = true;
94361e02 1078
c408b0c4 1079 $modinfo = unserialize($course->modinfo);
94361e02 1080
c6a55371 1081 //Acccessibility: replace table with list <ul>, but don't output empty list.
74666583 1082 if (!empty($section->sequence)) {
94361e02 1083
f2d660dc 1084 // Fix bug #5027, don't want style=\"width:$width\".
1085 echo "<ul class=\"section\">\n";
94361e02 1086 $sectionmods = explode(",", $section->sequence);
1087
1088 foreach ($sectionmods as $modnumber) {
9ae687af 1089 if (empty($mods[$modnumber])) {
1090 continue;
1091 }
94361e02 1092 $mod = $mods[$modnumber];
c9f6251e 1093
52dcc2f9 1094 if ($mod->visible or $isteacher) {
64fdc686 1095 echo '<li class="activity '.$mod->modname.'">';
7977cffd 1096 if ($ismoving) {
1097 if ($mod->id == $USER->activitycopy) {
1098 continue;
1099 }
1c919752 1100 echo '<a title="'.$strmovefull.'"'.
8b92f5bb 1101 ' href="'.$CFG->wwwroot.'/course/mod.php?moveto='.$mod->id.'&amp;sesskey='.$USER->sesskey.'">'.
446390fb 1102 '<img class="movetarget" src="'.$CFG->pixpath.'/movehere.gif" '.
1103 ' alt="'.$strmovehere.'" /></a><br />
1c919752 1104 ';
1acfbce5 1105 }
7977cffd 1106 $instancename = urldecode($modinfo[$modnumber]->name);
a92d95b1 1107 $instancename = format_string($instancename, true, $course->id);
c9f6251e 1108
86aa7ccf 1109 if (!empty($modinfo[$modnumber]->extra)) {
1110 $extra = urldecode($modinfo[$modnumber]->extra);
1111 } else {
1112 $extra = "";
1113 }
c9f6251e 1114
9d361034 1115 if (!empty($modinfo[$modnumber]->icon)) {
1116 $icon = "$CFG->pixpath/".urldecode($modinfo[$modnumber]->icon);
1117 } else {
1118 $icon = "$CFG->modpixpath/$mod->modname/icon.gif";
1119 }
1120
aac94fd0 1121 if ($mod->indent) {
1122 print_spacer(12, 20 * $mod->indent, false);
1123 }
1124
c9f6251e 1125 if ($mod->modname == "label") {
aac94fd0 1126 if (!$mod->visible) {
1127 echo "<span class=\"dimmed_text\">";
1128 }
179c9a50 1129 echo format_text($extra, FORMAT_HTML, $labelformatoptions);
aac94fd0 1130 if (!$mod->visible) {
1131 echo "</span>";
1132 }
c9f6251e 1133
1134 } else { // Normal activity
1135 $linkcss = $mod->visible ? "" : " class=\"dimmed\" ";
1c919752 1136 echo '<img src="'.$icon.'"'.
446390fb 1137 ' class="activityicon" alt="'.$mod->modfullname.'" />'.
1138 ' <a title="'.$mod->modfullname.'" '.$linkcss.' '.$extra.
1c919752 1139 ' href="'.$CFG->wwwroot.'/mod/'.$mod->modname.'/view.php?id='.$mod->id.'">'.
446390fb 1140 $instancename.'</a>';
c9f6251e 1141 }
a2d71d8e 1142 if ($usetracking && $mod->modname == 'forum') {
f37da850 1143 $groupmode = groupmode($course, $mod);
1144 $groupid = ($groupmode == SEPARATEGROUPS && !isteacheredit($course->id)) ?
a2d71d8e 1145 get_current_group($course->id) : false;
4877707e 1146
94a6a70f 1147 if (forum_tp_can_track_forums() && !isset($untracked[$mod->instance])) {
4877707e 1148 $unread = forum_tp_count_forum_unread_posts($USER->id, $mod->instance, $groupid);
1149 if ($unread) {
1150 echo '<span class="unread"> <a href="'.$CFG->wwwroot.'/mod/forum/view.php?id='.$mod->id.'">';
1151 if ($unread == 1) {
1152 echo $strunreadpostsone;
1153 } else {
1154 print_string('unreadpostsnumber', 'forum', $unread);
1155 }
1156 echo '</a> </span>';
d0388ebe 1157 }
54669989 1158 }
f37da850 1159 }
1160
c9f6251e 1161 if ($isediting) {
5f390342 1162 if ($groupbuttons and $mod->modname != 'label' and $mod->modname != 'resource') {
32d03b7b 1163 if (! $mod->groupmodelink = $groupbuttonslink) {
1164 $mod->groupmode = $course->groupmode;
1165 }
1166
1167 } else {
3d575e6f 1168 $mod->groupmode = false;
1169 }
37a88449 1170 echo '&nbsp;&nbsp;';
24e1eae4 1171 echo make_editing_buttons($mod, $absolute, true, $mod->indent, $section->section);
c9f6251e 1172 }
c6a55371 1173 echo "</li>\n";
94361e02 1174 }
94361e02 1175 }
f2d660dc 1176 } elseif ($ismoving) {
1177 echo "<ul class=\"section\">\n";
1178 }
7977cffd 1179 if ($ismoving) {
64fdc686 1180 echo '<li><a title="'.$strmovefull.'"'.
8b92f5bb 1181 ' href="'.$CFG->wwwroot.'/course/mod.php?movetosection='.$section->id.'&amp;sesskey='.$USER->sesskey.'">'.
446390fb 1182 '<img class="movetarget" src="'.$CFG->pixpath.'/movehere.gif" '.
c6a55371 1183 ' alt="'.$strmovehere.'" /></a></li>
1c919752 1184 ';
7977cffd 1185 }
c6a55371 1186 if (!empty($section->sequence) || $ismoving) {
1187 echo "</ul><!--class='section'-->\n\n";
1188 }
a7ad3ea6 1189}
1190
5867bfb5 1191
cb57e6f4 1192function print_section_add_menus($course, $section, $modnames, $vertical=false, $return=false) {
e0161bff 1193// Prints the menus to add activities and resources
1194
8b92f5bb 1195 global $CFG, $USER;
6da4b261 1196 static $straddactivity, $stractivities, $straddresource, $resources;
e0161bff 1197
1198 if (!isset($straddactivity)) {
1199 $straddactivity = get_string('addactivity');
1200 $straddresource = get_string('addresource');
6da4b261 1201
1202 /// Standard resource types
1203 require_once("$CFG->dirroot/mod/resource/lib.php");
1204 $resourceraw = resource_get_resource_types();
1205
1206 foreach ($resourceraw as $type => $name) {
839f2456 1207 $resources["resource&amp;type=$type"] = $name;
e0161bff 1208 }
0705ff84 1209 if (course_allowed_module($course,'label')) {
1210 $resources['label'] = get_string('resourcetypelabel', 'resource');
1211 }
e0161bff 1212 }
1213
d33d0cda 1214 $output = '<div style="text-align: right">';
0705ff84 1215 if (course_allowed_module($course,'resource')) {
81a5d9ca 1216 $resourceallowed = true;
0705ff84 1217 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&amp;section=$section&amp;sesskey=$USER->sesskey&amp;add=",
1218 $resources, "ressection$section", "", $straddresource, 'resource/types', $straddresource, true);
1219 }
cb57e6f4 1220
1221 if ($vertical) {
d33d0cda 1222 $output .= '<div>';
cb57e6f4 1223 }
1224
0705ff84 1225 // we need to loop through the forms and check to see if we can add them.
1226 foreach ($modnames as $key) {
1227 if (!course_allowed_module($course,$key))
1228 unset($modnames[strtolower($key)]);
1229 }
1230
1231 // this is stupid but labels get put into resource, so if resource is hidden and label is not, we're in trouble.
1232 if (course_allowed_module($course,'label') && empty($resourceallowed)) {
1233 $modnames['label'] = get_string('modulename', 'label');
1234 }
1235
1c46eb03 1236 $output .= ' ';
8b92f5bb 1237 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&amp;section=$section&amp;sesskey=$USER->sesskey&amp;add=",
6da4b261 1238 $modnames, "section$section", "", $straddactivity, 'mods', $straddactivity, true);
d33d0cda 1239
1240 if ($vertical) {
1241 $output .= '</div>';
1242 }
1243
cb57e6f4 1244 $output .= '</div>';
1245
1246 if ($return) {
1247 return $output;
1248 } else {
1249 echo $output;
1250 }
e0161bff 1251}
1252
5867bfb5 1253function rebuild_course_cache($courseid=0) {
1254// Rebuilds the cached list of course activities stored in the database
1255// If a courseid is not specified, then all are rebuilt
1256
1257 if ($courseid) {
1258 $select = "id = '$courseid'";
1259 } else {
1260 $select = "";
1261 }
1262
1a31c2b3 1263 if ($courses = get_records_select("course", $select,'','id,fullname')) {
5867bfb5 1264 foreach ($courses as $course) {
1265 $modinfo = serialize(get_array_of_activities($course->id));
1266 if (!set_field("course", "modinfo", $modinfo, "id", $course->id)) {
1267 notify("Could not cache module information for course '$course->fullname'!");
1268 }
1269 }
1270 }
1271}
1272
1273
c2cb4545 1274
1275function make_categories_list(&$list, &$parents, $category=NULL, $path="") {
89adb174 1276/// Given an empty array, this function recursively travels the
c2cb4545 1277/// categories, building up a nice list for display. It also makes
1278/// an array that list all the parents for each category.
1279
9d866ae0 1280 // initialize the arrays if needed
1281 if (!is_array($list)) {
1282 $list = array();
1283 }
1284 if (!is_array($parents)) {
1285 $parents = array();
1286 }
1287
c2cb4545 1288 if ($category) {
1289 if ($path) {
e05bcf2f 1290 $path = $path.' / '.$category->name;
c2cb4545 1291 } else {
e05bcf2f 1292 $path = $category->name;
c2cb4545 1293 }
1294 $list[$category->id] = $path;
1295 } else {
1296 $category->id = 0;
1297 }
1298
e05bcf2f 1299 if ($categories = get_categories($category->id)) { // Print all the children recursively
c2cb4545 1300 foreach ($categories as $cat) {
1301 if (!empty($category->id)) {
3bd4de22 1302 if (isset($parents[$category->id])) {
2832badf 1303 $parents[$cat->id] = $parents[$category->id];
1304 }
c2cb4545 1305 $parents[$cat->id][] = $category->id;
1306 }
89adb174 1307 make_categories_list($list, $parents, $cat, $path);
c2cb4545 1308 }
1309 }
1310}
1311
1312
c2cb4545 1313function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1) {
89adb174 1314/// Recursive function to print out all the categories in a nice format
c2cb4545 1315/// with or without courses included
9ff5310a 1316 global $CFG;
e05bcf2f 1317
1318 if (isset($CFG->max_category_depth) && ($depth >= $CFG->max_category_depth)) {
1319 return;
9ff5310a 1320 }
c2cb4545 1321
1322 if (!$displaylist) {
e92fe848 1323 make_categories_list($displaylist, $parentslist);
c2cb4545 1324 }
1325
1326 if ($category) {
3af6e1db 1327 if ($category->visible or iscreator()) {
d2b6ba70 1328 print_category_info($category, $depth);
c2cb4545 1329 } else {
1330 return; // Don't bother printing children of invisible categories
1331 }
89adb174 1332
c2cb4545 1333 } else {
c2cb4545 1334 $category->id = "0";
1335 }
1336
1337 if ($categories = get_categories($category->id)) { // Print all the children recursively
1338 $countcats = count($categories);
1339 $count = 0;
1340 $first = true;
1341 $last = false;
1342 foreach ($categories as $cat) {
1343 $count++;
1344 if ($count == $countcats) {
1345 $last = true;
1346 }
1347 $up = $first ? false : true;
1348 $down = $last ? false : true;
1349 $first = false;
1350
814f88c0 1351 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1);
c2cb4545 1352 }
1353 }
c2cb4545 1354}
1355
0705ff84 1356// this function will return $options array for choose_from_menu, with whitespace to denote nesting.
1357
1358function make_categories_options() {
1359 make_categories_list($cats,$parents);
1360 foreach ($cats as $key => $value) {
1361 if (array_key_exists($key,$parents)) {
1362 if ($indent = count($parents[$key])) {
1363 for ($i = 0; $i < $indent; $i++) {
1364 $cats[$key] = '&nbsp;'.$cats[$key];
1365 }
1366 }
1367 }
1368 }
1369 return $cats;
1370}
c2cb4545 1371
d2b6ba70 1372function print_category_info($category, $depth) {
1373/// Prints the category info in indented fashion
1374/// This function is only used by print_whole_category_list() above
c2cb4545 1375
1376 global $CFG;
b48f834c 1377 static $strallowguests, $strrequireskey, $strsummary;
c2cb4545 1378
b48f834c 1379 if (empty($strsummary)) {
e05bcf2f 1380 $strallowguests = get_string('allowguests');
1381 $strrequireskey = get_string('requireskey');
1382 $strsummary = get_string('summary');
b48f834c 1383 }
ba2e5d73 1384
e05bcf2f 1385 $catlinkcss = $category->visible ? '' : ' class="dimmed" ';
d5f26b07 1386
e1638d61 1387 $frontpage = explode(',', $CFG->frontpage);
1388 $frontpage = $frontpage?array_flip($frontpage):array();
48643b49 1389 $coursecount = count_records('course') <= 200;
1390 if (isset($frontpage[FRONTPAGECATEGORYNAMES]) && !isset($frontpage[FRONTPAGECOURSELIST]) && $coursecount) {
839f2456 1391 $catimage = '<img src="'.$CFG->pixpath.'/i/course.gif" width="16" height="16" border="0" alt="" />';
b48f834c 1392 } else {
7b0b5c14 1393 $catimage = "&nbsp;";
8ef9cb56 1394 }
b48f834c 1395
87d32352 1396 echo "\n\n".'<table border="0" cellpadding="3" cellspacing="0" width="100%">';
d2b6ba70 1397
48643b49 1398 if (isset($frontpage[FRONTPAGECATEGORYNAMES]) && !isset($frontpage[FRONTPAGECOURSELIST]) && $coursecount) {
19374e76 1399 $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');
b48f834c 1400
1401 echo "<tr>";
1402
1403 if ($depth) {
1404 $indent = $depth*30;
1405 $rows = count($courses) + 1;
1c919752 1406 echo '<td rowspan="'.$rows.'" valign="top" width="'.$indent.'">';
b48f834c 1407 print_spacer(10, $indent);
e05bcf2f 1408 echo '</td>';
b48f834c 1409 }
89adb174 1410
e05bcf2f 1411 echo '<td valign="top">'.$catimage.'</td>';
290130b3 1412 echo '<td valign="top" width="100%" class="category name">';
e05bcf2f 1413 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot.'/course/category.php?id='.$category->id.'">'.$category->name.'</a>';
1414 echo '</td>';
290130b3 1415 echo '<td class="category info">&nbsp;</td>';
e05bcf2f 1416 echo '</tr>';
b48f834c 1417
9ff5310a 1418 if ($courses && !(isset($CFG->max_category_depth)&&($depth>=$CFG->max_category_depth-1))) {
c2cb4545 1419 foreach ($courses as $course) {
e05bcf2f 1420 $linkcss = $course->visible ? '' : ' class="dimmed" ';
1421 echo '<tr><td valign="top" width="30">&nbsp;';
290130b3 1422 echo '</td><td valign="top" width="100%" class="course name">';
e05bcf2f 1423 echo '<a '.$linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.$course->fullname.'</a>';
290130b3 1424 echo '</td><td align="right" valign="top" nowrap="nowrap" class="course info">';
c2cb4545 1425 if ($course->guest ) {
e05bcf2f 1426 echo '<a title="'.$strallowguests.'" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">';
1427 echo '<img hspace="1" alt="'.$strallowguests.'" height="16" width="16" border="0" src="'.$CFG->pixpath.'/i/guest.gif" /></a>';
ebe8ddc1 1428 } else {
e05bcf2f 1429 echo '<img alt="" height="16" width="18" border="0" src="'.$CFG->pixpath.'/spacer.gif" />';
0c656181 1430 }
c2cb4545 1431 if ($course->password) {
e05bcf2f 1432 echo '<a title="'.$strrequireskey.'" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">';
1433 echo '<img hspace="1" alt="'.$strrequireskey.'" height="16" width="16" border="0" src="'.$CFG->pixpath.'/i/key.gif" /></a>';
ebe8ddc1 1434 } else {
e05bcf2f 1435 echo '<img alt="" height="16" width="18" border="0" src="'.$CFG->pixpath.'/spacer.gif" />';
b48f834c 1436 }
1437 if ($course->summary) {
e05bcf2f 1438 link_to_popup_window ('/course/info.php?id='.$course->id, 'courseinfo',
1439 '<img hspace="1" alt="'.$strsummary.'" height="16" width="16" border="0" src="'.$CFG->pixpath.'/i/info.gif" />',
b48f834c 1440 400, 500, $strsummary);
ebe8ddc1 1441 } else {
e05bcf2f 1442 echo '<img alt="" height="16" width="18" border="0" src="'.$CFG->pixpath.'/spacer.gif" />';
0c656181 1443 }
e05bcf2f 1444 echo '</td></tr>';
0c656181 1445 }
ba2e5d73 1446 }
d2b6ba70 1447 } else {
b48f834c 1448
e0140f24 1449 echo '<tr>';
1450
b48f834c 1451 if ($depth) {
1452 $indent = $depth*20;
e05bcf2f 1453 echo '<td valign="top" width="'.$indent.'">';
b48f834c 1454 print_spacer(10, $indent);
e05bcf2f 1455 echo '</td>';
d2b6ba70 1456 }
89adb174 1457
290130b3 1458 echo '<td valign="top" width="100%" class="category name">';
e05bcf2f 1459 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot.'/course/category.php?id='.$category->id.'">'.$category->name.'</a>';
1460 echo '</td>';
290130b3 1461 echo '<td valign="top" class="category number">';
e05bcf2f 1462 if ($category->coursecount) {
1463 echo $category->coursecount;
1464 }
1465 echo '</td></tr>';
c2cb4545 1466 }
e05bcf2f 1467 echo '</table>';
c2cb4545 1468}
1469
c2cb4545 1470
8e227aa7 1471function print_courses($category, $width="100%", $hidesitecourse = false) {
c2cb4545 1472/// Category is 0 (for all courses) or an object
1473
810393c8 1474 global $CFG;
c2cb4545 1475
1476 if (empty($category)) {
90c2ca2e 1477 $categories = get_categories(0); // Parent = 0 ie top-level categories only
1478 if (count($categories) == 1) {
1479 $category = array_shift($categories);
0cb9ec10 1480 $courses = get_courses($category->id, 'c.sortorder ASC', 'c.id,c.category,c.sortorder,c.visible,c.fullname,c.shortname,c.password,c.summary,c.teacher,c.cost,c.currency,c.enrol');
90c2ca2e 1481 } else {
0cb9ec10 1482 $courses = get_courses('all', 'c.sortorder ASC', 'c.id,c.category,c.sortorder,c.visible,c.fullname,c.shortname,c.password,c.summary,c.teacher,c.cost,c.currency,c.enrol');
90c2ca2e 1483 }
1484 unset($categories);
607809b3 1485 } else {
c2cb4545 1486 $categories = get_categories($category->id); // sub categories
0cb9ec10 1487 $courses = get_courses($category->id, 'c.sortorder ASC', 'c.id,c.category,c.sortorder,c.visible,c.fullname,c.shortname,c.password,c.summary,c.teacher,c.cost,c.currency,c.enrol');
c2cb4545 1488 }
1489
c2cb4545 1490 if ($courses) {
1491 foreach ($courses as $course) {
8e227aa7 1492 if ($hidesitecourse && !$course->category) {
1493 continue;
1494 }
c2cb4545 1495 print_course($course, $width);
c2cb4545 1496 }
1497 } else {
f9667a5a 1498 print_heading(get_string("nocoursesyet"));
255d1033 1499 if (iscreator()) { // Make it obvious for newbies on new sites how to add a course
1500 $options = array();
1501 $options['category'] = $category->id;
1502 echo '<div class="addcoursebutton" align="center">';
1503 print_single_button($CFG->wwwroot.'/course/edit.php', $options, get_string("addnewcourse"));
1504 echo '</div>';
1505 }
c2cb4545 1506 }
1507
1508}
1509
1510
1511function print_course($course, $width="100%") {
1512
861efb19 1513 global $CFG, $USER;
c2cb4545 1514
f9667a5a 1515 require_once("$CFG->dirroot/enrol/enrol.class.php");
146bbb8f 1516
f9667a5a 1517 $enrol = enrolment_factory::factory($course->enrol);
146bbb8f 1518
810393c8 1519 print_simple_box_start("center", "$width", '', 5, "coursebox");
c2cb4545 1520
22288704 1521 $linkcss = $course->visible ? "" : " class=\"dimmed\" ";
1522
c2cb4545 1523 echo "<table width=\"100%\">";
e5e81e78 1524 echo '<tr valign="top">';
290130b3 1525 echo '<td valign="top" width="50%" class="info">';
34b5847a 1526 echo '<b><a title="'.get_string('entercourse').'"'.
e5e81e78 1527 $linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.
34b5847a 1528 $course->fullname.'</a></b><br />';
c2cb4545 1529 if ($teachers = get_course_teachers($course->id)) {
290130b3 1530 echo "<span class=\"teachers\">\n";
c2cb4545 1531 foreach ($teachers as $teacher) {
1532 if ($teacher->authority > 0) {
1533 if (!$teacher->role) {
1534 $teacher->role = $course->teacher;
1535 }
2ac64806 1536 $fullname = fullname($teacher, isteacher($course->id)); // is the USER a teacher of that course
8bd84b4d 1537 echo $teacher->role.': <a href="'.$CFG->wwwroot.'/user/view.php?id='.$teacher->id.
1538 '&amp;course='.SITEID.'">'.$fullname.'</a><br />';
c2cb4545 1539 }
1540 }
34b5847a 1541 echo "</span>\n";
c2cb4545 1542 }
c2cb4545 1543
146bbb8f 1544 echo $enrol->get_access_icons($course);
c2cb4545 1545
290130b3 1546 echo '</td><td valign="top" width="50%" class="summary">';
9f39c190 1547 $options = NULL;
1548 $options->noclean = true;
34b5847a 1549 $options->para = false;
9f39c190 1550 echo format_text($course->summary, FORMAT_MOODLE, $options, $course->id);
c2cb4545 1551 echo "</td></tr>";
1552 echo "</table>";
1553
1554 print_simple_box_end();
1555}
1556
1557
1558function print_my_moodle() {
1559/// Prints custom user information on the home page.
1560/// Over time this can include all sorts of information
1561
1562 global $USER, $CFG;
1563
1564 if (!isset($USER->id)) {
1565 error("It shouldn't be possible to see My Moodle without being logged in.");
1566 }
1567
1568 if ($courses = get_my_courses($USER->id)) {
1569 foreach ($courses as $course) {
c81696e5 1570 if (!$course->category) {
1571 continue;
1572 }
c2cb4545 1573 print_course($course, "100%");
c2cb4545 1574 }
38a10939 1575
7f989948 1576 if (count_records("course") > (count($courses) + 1) ) { // Some courses not being displayed
1577 echo "<table width=\"100%\"><tr><td align=\"center\">";
1578 print_course_search("", false, "short");
1579 echo "</td><td align=\"center\">";
1580 print_single_button("$CFG->wwwroot/course/index.php", NULL, get_string("fulllistofcourses"), "get");
1581 echo "</td></tr></table>\n";
1582 }
26330001 1583 } else {
1584 if (count_records("course_categories") > 1) {
cb29b020 1585 print_simple_box_start("center", "100%", "#FFFFFF", 5, "categorybox");
26330001 1586 print_whole_category_list();
1587 print_simple_box_end();
1588 } else {
1589 print_courses(0, "100%");
1590 }
607809b3 1591 }
2b8cef80 1592}
1593
11b0c469 1594
a8b56716 1595function print_course_search($value="", $return=false, $format="plain") {
38a10939 1596
1597 global $CFG;
1598
1599 $strsearchcourses= get_string("searchcourses");
1600
1c919752 1601 if ($format == 'plain') {
87d32352 1602 $output = '<form name="coursesearch" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
1603 $output .= '<center><p align="center" class="coursesearchbox">';
f8a5159a 1604 $output .= '<input type="text" size="30" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
9cc78ee1 1605 $output .= '<input type="submit" value="'.s($strsearchcourses).'" />';
87d32352 1606 $output .= '</p></center></form>';
1c919752 1607 } else if ($format == 'short') {
87d32352 1608 $output = '<form name="coursesearch" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
1609 $output .= '<center><p align="center" class="coursesearchbox">';
f8a5159a 1610 $output .= '<input type="text" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
9cc78ee1 1611 $output .= '<input type="submit" value="'.s($strsearchcourses).'" />';
87d32352 1612 $output .= '</p></center></form>';
1c919752 1613 } else if ($format == 'navbar') {
87d32352 1614 $output = '<form name="coursesearch" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
1615 $output .= '<table border="0" cellpadding="0" cellspacing="0"><tr><td nowrap="nowrap">';
f8a5159a 1616 $output .= '<input type="text" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
9cc78ee1 1617 $output .= '<input type="submit" value="'.s($strsearchcourses).'" />';
1c919752 1618 $output .= '</td></tr></table>';
87d32352 1619 $output .= '</form>';
a8b56716 1620 }
1621
1622 if ($return) {
1623 return $output;
1624 }
1625 echo $output;
38a10939 1626}
11b0c469 1627
1628/// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
1629
1630function add_course_module($mod) {
11b0c469 1631
e5dfd0f3 1632 $mod->added = time();
53f4ad2c 1633 unset($mod->id);
11b0c469 1634
e5dfd0f3 1635 return insert_record("course_modules", $mod);
11b0c469 1636}
1637
7977cffd 1638function add_mod_to_section($mod, $beforemod=NULL) {
1639/// Given a full mod object with section and course already defined
1640/// If $before is specified, then this is an existing ID which we
1641/// will insert the new module before
1642///
1643/// Returns the course_sections ID where the mod is inserted
11b0c469 1644
9fa49e22 1645 if ($section = get_record("course_sections", "course", "$mod->course", "section", "$mod->section")) {
7977cffd 1646
1647 $section->sequence = trim($section->sequence);
1648
1649 if (empty($section->sequence)) {
11b0c469 1650 $newsequence = "$mod->coursemodule";
7977cffd 1651
1652 } else if ($beforemod) {
1653 $modarray = explode(",", $section->sequence);
1654
1655 if ($key = array_keys ($modarray, $beforemod->id)) {
1656 $insertarray = array($mod->id, $beforemod->id);
1657 array_splice($modarray, $key[0], 1, $insertarray);
1658 $newsequence = implode(",", $modarray);
1659
1660 } else { // Just tack it on the end anyway
1661 $newsequence = "$section->sequence,$mod->coursemodule";
1662 }
1663
1664 } else {
1665 $newsequence = "$section->sequence,$mod->coursemodule";
11b0c469 1666 }
89adb174 1667
e5dfd0f3 1668 if (set_field("course_sections", "sequence", $newsequence, "id", $section->id)) {
1669 return $section->id; // Return course_sections ID that was used.
11b0c469 1670 } else {
e5dfd0f3 1671 return 0;
11b0c469 1672 }
89adb174 1673
11b0c469 1674 } else { // Insert a new record
e5dfd0f3 1675 $section->course = $mod->course;
1676 $section->section = $mod->section;
1677 $section->summary = "";
1678 $section->sequence = $mod->coursemodule;
1679 return insert_record("course_sections", $section);
11b0c469 1680 }
1681}
1682
48e535bc 1683function set_coursemodule_groupmode($id, $groupmode) {
3d575e6f 1684 return set_field("course_modules", "groupmode", $groupmode, "id", $id);
1685}
1686
02f66c42 1687/**
1688* $prevstateoverrides = true will set the visibility of the course module
1689* to what is defined in visibleold. This enables us to remember the current
1690* visibility when making a whole section hidden, so that when we toggle
1691* that section back to visible, we are able to return the visibility of
1692* the course module back to what it was originally.
1693*/
1694function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
48e535bc 1695 $cm = get_record('course_modules', 'id', $id);
dcd338ff 1696 $modulename = get_field('modules', 'name', 'id', $cm->module);
1697 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
1698 foreach($events as $event) {
48e535bc 1699 if ($visible) {
1700 show_event($event);
1701 } else {
1702 hide_event($event);
1703 }
dcd338ff 1704 }
1705 }
02f66c42 1706 if ($prevstateoverrides) {
1707 if ($visible == '0') {
1708 // Remember the current visible state so we can toggle this back.
1709 set_field('course_modules', 'visibleold', $cm->visible, 'id', $id);
1710 } else {
1711 // Get the previous saved visible states.
1712 return set_field('course_modules', 'visible', $cm->visibleold, 'id', $id);
1713 }
1714 }
48e535bc 1715 return set_field("course_modules", "visible", $visible, "id", $id);
1acfbce5 1716}
1717
290130b3 1718/*
1719 * Delete a course module and any associated data at the course level (events)
1720 * Until 1.5 this function simply marked a deleted flag ... now it
1721 * deletes it completely.
1722 *
1723 */
48e535bc 1724function delete_course_module($id) {
290130b3 1725 if (!$cm = get_record('course_modules', 'id', $id)) {
1726 return true;
1727 }
dcd338ff 1728 $modulename = get_field('modules', 'name', 'id', $cm->module);
1729 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
1730 foreach($events as $event) {
48e535bc 1731 delete_event($event);
dcd338ff 1732 }
1733 }
290130b3 1734 return delete_records('course_modules', 'id', $cm->id);
11b0c469 1735}
1736
1737function delete_mod_from_section($mod, $section) {
11b0c469 1738
e5dfd0f3 1739 if ($section = get_record("course_sections", "id", "$section") ) {
11b0c469 1740
e5dfd0f3 1741 $modarray = explode(",", $section->sequence);
11b0c469 1742
1743 if ($key = array_keys ($modarray, $mod)) {
1744 array_splice($modarray, $key[0], 1);
1745 $newsequence = implode(",", $modarray);
e5dfd0f3 1746 return set_field("course_sections", "sequence", $newsequence, "id", $section->id);
11b0c469 1747 } else {
1748 return false;
1749 }
89adb174 1750
11b0c469 1751 }
7977cffd 1752 return false;
11b0c469 1753}
1754
12905134 1755function move_section($course, $section, $move) {
1756/// Moves a whole course section up and down within the course
798b70a1 1757 global $USER;
12905134 1758
1759 if (!$move) {
1760 return true;
1761 }
1762
1763 $sectiondest = $section + $move;
1764
1765 if ($sectiondest > $course->numsections or $sectiondest < 1) {
1766 return false;
1767 }
1768
1769 if (!$sectionrecord = get_record("course_sections", "course", $course->id, "section", $section)) {
1770 return false;
1771 }
1772
1773 if (!$sectiondestrecord = get_record("course_sections", "course", $course->id, "section", $sectiondest)) {
1774 return false;
1775 }
1776
56e34ee4 1777 if (!set_field("course_sections", "section", $sectiondest, "id", $sectionrecord->id)) {
12905134 1778 return false;
1779 }
56e34ee4 1780 if (!set_field("course_sections", "section", $section, "id", $sectiondestrecord->id)) {
12905134 1781 return false;
1782 }
798b70a1 1783 // if the focus is on the section that is being moved, then move the focus along
1784 if (isset($USER->display[$course->id]) and ($USER->display[$course->id] == $section)) {
1785 course_set_display($course->id, $sectiondest);
1786 }
5390cbb7 1787
1788 // Check for duplicates.
1789 // There is a very rare case that some sections in the same course have the same section id.
1790 if (($count_section = count_records('course_sections', 'course', $course->id) - 1) != $course->numsections) {
1791 $sections = get_records_select('course_sections', "course = $course->id AND section > 0", 'section ASC');
1792 $n = 1;
1793 foreach ($sections as $section) {
1794 if (!set_field('course_sections', 'section', $n, 'id', $section->id)) {
1795 return false;
1796 }
1797 $n++;
1798 }
1799 if (!set_field('course', 'numsections', $count_section, 'id', $course->id)) {
1800 return false;
1801 }
1802 }
12905134 1803 return true;
1804}
1805
1806
7977cffd 1807function moveto_module($mod, $section, $beforemod=NULL) {
1808/// All parameters are objects
1809/// Move the module object $mod to the specified $section
1810/// If $beforemod exists then that is the module
1811/// before which $modid should be inserted
1812
1813/// Remove original module from original section
1814
1815 if (! delete_mod_from_section($mod->id, $mod->section)) {
1816 notify("Could not delete module from existing section");
1817 }
1818
1819/// Update module itself if necessary
1820
1821 if ($mod->section != $section->id) {
89adb174 1822 $mod->section = $section->id;
7977cffd 1823 if (!update_record("course_modules", $mod)) {
1824 return false;
1825 }
48e535bc 1826 // if moving to a hidden section then hide module
1827 if (!$section->visible) {
1828 set_coursemodule_visible($mod->id, 0);
1829 }
7977cffd 1830 }
1831
1832/// Add the module into the new section
1833
1834 $mod->course = $section->course;
1835 $mod->section = $section->section; // need relative reference
1836 $mod->coursemodule = $mod->id;
1837
1838 if (! add_mod_to_section($mod, $beforemod)) {
1839 return false;
1840 }
1841
1842 return true;
1843
1844}
1845
24e1eae4 1846function make_editing_buttons($mod, $absolute=false, $moveselect=true, $indent=-1, $section=-1) {
810393c8 1847 global $CFG, $USER;
94361e02 1848
3d575e6f 1849 static $str;
37a88449 1850 static $sesskey;
3d575e6f 1851
1852 if (!isset($str)) {
1853 $str->delete = get_string("delete");
1854 $str->move = get_string("move");
1855 $str->moveup = get_string("moveup");
1856 $str->movedown = get_string("movedown");
1857 $str->moveright = get_string("moveright");
1858 $str->moveleft = get_string("moveleft");
1859 $str->update = get_string("update");
d33a2a6f 1860 $str->duplicate = get_string("duplicate");
3d575e6f 1861 $str->hide = get_string("hide");
1862 $str->show = get_string("show");
1863 $str->clicktochange = get_string("clicktochange");
32d03b7b 1864 $str->forcedmode = get_string("forcedmode");
3d575e6f 1865 $str->groupsnone = get_string("groupsnone");
1866 $str->groupsseparate = get_string("groupsseparate");
1867 $str->groupsvisible = get_string("groupsvisible");
37a88449 1868 $sesskey = sesskey();
1acfbce5 1869 }
94361e02 1870
24e1eae4 1871 if ($section >= 0) {
75f087b6 1872 $section = '&amp;sr='.$section; // Section return
24e1eae4 1873 } else {
1874 $section = '';
1875 }
1876
94361e02 1877 if ($absolute) {
37a88449 1878 $path = $CFG->wwwroot.'/course';
dc0dc7d5 1879 } else {
37a88449 1880 $path = '.';
dc0dc7d5 1881 }
1882
3d575e6f 1883 if ($mod->visible) {
37a88449 1884 $hideshow = '<a title="'.$str->hide.'" href="'.$path.'/mod.php?hide='.$mod->id.
1885 '&amp;sesskey='.$sesskey.$section.'"><img'.
1886 ' src="'.$CFG->pixpath.'/t/hide.gif" hspace="2" height="11" width="11" '.
1887 ' border="0" alt="'.$str->hide.'" /></a> ';
1acfbce5 1888 } else {
37a88449 1889 $hideshow = '<a title="'.$str->show.'" href="'.$path.'/mod.php?show='.$mod->id.
1890 '&amp;sesskey='.$sesskey.$section.'"><img'.
1891 ' src="'.$CFG->pixpath.'/t/show.gif" hspace="2" height="11" width="11" '.
1892 ' border="0" alt="'.$str->show.'" /></a> ';
7977cffd 1893 }
3d575e6f 1894 if ($mod->groupmode !== false) {
1895 if ($mod->groupmode == SEPARATEGROUPS) {
32d03b7b 1896 $grouptitle = $str->groupsseparate;
37a88449 1897 $groupimage = $CFG->pixpath.'/t/groups.gif';
1898 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=0&amp;sesskey='.$sesskey;
3d575e6f 1899 } else if ($mod->groupmode == VISIBLEGROUPS) {
32d03b7b 1900 $grouptitle = $str->groupsvisible;
37a88449 1901 $groupimage = $CFG->pixpath.'/t/groupv.gif';
1902 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=1&amp;sesskey='.$sesskey;
32d03b7b 1903 } else {
1904 $grouptitle = $str->groupsnone;
37a88449 1905 $groupimage = $CFG->pixpath.'/t/groupn.gif';
1906 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=2&amp;sesskey='.$sesskey;
32d03b7b 1907 }
1908 if ($mod->groupmodelink) {
37a88449 1909 $groupmode = '<a title="'.$grouptitle.' ('.$str->clicktochange.')" href="'.$grouplink.'">'.
1910 '<img src="'.$groupimage.'" hspace="2" height="11" width="11" '.
1911 'border="0" alt="'.$grouptitle.'" /></a>';
3d575e6f 1912 } else {
37a88449 1913 $groupmode = '<img title="'.$grouptitle.' ('.$str->forcedmode.')" '.
1914 ' src="'.$groupimage.'" hspace="2" height="11" width="11" '.
1915 'border="0" alt="'.$grouptitle.'" />';
3d575e6f 1916 }
1917 } else {
1918 $groupmode = "";
1919 }
7977cffd 1920
1921 if ($moveselect) {
37a88449 1922 $move = '<a title="'.$str->move.'" href="'.$path.'/mod.php?copy='.$mod->id.
1923 '&amp;sesskey='.$sesskey.$section.'"><img'.
1924 ' src="'.$CFG->pixpath.'/t/move.gif" hspace="2" height="11" width="11" '.
1925 ' border="0" alt="'.$str->move.'" /></a>';
493486c4 1926 } else {
37a88449 1927 $move = '<a title="'.$str->moveup.'" href="'.$path.'/mod.php?id='.$mod->id.
1928 '&amp;move=-1&amp;sesskey='.$sesskey.$section.'"><img'.
1929 ' src="'.$CFG->pixpath.'/t/up.gif" hspace="2" height="11" width="11" '.
1930 ' border="0" alt="'.$str->moveup.'" /></a>'.
1931 '<a title="'.$str->movedown.'" href="'.$path.'/mod.php?id='.$mod->id.
1932 '&amp;move=1&amp;sesskey='.$sesskey.$section.'"><img'.
1933 ' src="'.$CFG->pixpath.'/t/down.gif" hspace="2" height="11" width="11" '.
1934 ' border="0" alt="'.$str->movedown.'" /></a>';
7977cffd 1935 }
1936
aac94fd0 1937 $leftright = "";
1938 if ($indent > 0) {
37a88449 1939 $leftright .= '<a title="'.$str->moveleft.'" href="'.$path.'/mod.php?id='.$mod->id.
1940 '&amp;indent=-1&amp;sesskey='.$sesskey.$section.'"><img'.
1941 ' src="'.$CFG->pixpath.'/t/left.gif" hspace="2" height="11" width="11" '.
1942 ' border="0" alt="'.$str->moveleft.'" /></a>';
aac94fd0 1943 }
1944 if ($indent >= 0) {
37a88449 1945 $leftright .= '<a title="'.$str->moveright.'" href="'.$path.'/mod.php?id='.$mod->id.
1946 '&amp;indent=1&amp;sesskey='.$sesskey.$section.'"><img'.
1947 ' src="'.$CFG->pixpath.'/t/right.gif" hspace="2" height="11" width="11" '.
1948 ' border="0" alt="'.$str->moveright.'" /></a>';
1949 }
1950
1951 return '<span class="commands">'.$leftright.$move.
1952 '<a title="'.$str->update.'" href="'.$path.'/mod.php?update='.$mod->id.
1953 '&amp;sesskey='.$sesskey.$section.'"><img'.
1954 ' src="'.$CFG->pixpath.'/t/edit.gif" hspace="2" height="11" width="11" border="0" '.
1955 ' alt="'.$str->update.'" /></a>'.
1956 '<a title="'.$str->delete.'" href="'.$path.'/mod.php?delete='.$mod->id.
1957 '&amp;sesskey='.$sesskey.$section.'"><img'.
1958 ' src="'.$CFG->pixpath.'/t/delete.gif" hspace="2" height="11" width="11" border="0" '.
1959 ' alt="'.$str->delete.'" /></a>'.$hideshow.$groupmode.'</span>';
90845098 1960}
1961
b61efafb 1962/**
1963 * given a course object with shortname & fullname, this function will
1964 * truncate the the number of chars allowed and add ... if it was too long
1965 */
1966function course_format_name ($course,$max=100) {
1967
1968 $str = $course->shortname.': '.$course->fullname;
1969 if (strlen($str) <= $max) {
1970 return $str;
1971 }
1972 else {
1973 return substr($str,0,$max-3).'...';
1974 }
1975}
1976
1977/**
1978 * This function will return true if the given course is a child course at all
1979 */
1980function course_in_meta ($course) {
5f37b628 1981 return record_exists("course_meta","child_course",$course->id);
b61efafb 1982}
1983
48e535bc 1984
1985/**
1986 * Print standard form elements on module setup forms in mod/.../mod.html
1987 */
1988function print_standard_coursemodule_settings($form) {
da2224f8 1989 if (! $course = get_record('course', 'id', $form->course)) {
1990 error("This course doesn't exist");
1991 }
1992 print_groupmode_setting($form, $course);
1993 print_visible_setting($form, $course);
48e535bc 1994}
1995
1996/**
1997 * Print groupmode form element on module setup forms in mod/.../mod.html
1998 */
5ebb746b 1999function print_groupmode_setting($form, $course=NULL) {
48e535bc 2000
5ebb746b 2001 if (empty($course)) {
2002 if (! $course = get_record('course', 'id', $form->course)) {
2003 error("This course doesn't exist");
2004 }
2005 }
48e535bc 2006 if ($form->coursemodule) {
2007 if (! $cm = get_record('course_modules', 'id', $form->coursemodule)) {
2008 error("This course module doesn't exist");
2009 }
2010 } else {
2011 $cm = null;
2012 }
2013 $groupmode = groupmode($course, $cm);
2014 if ($course->groupmode or (!$course->groupmodeforce)) {
2015 echo '<tr valign="top">';
2016 echo '<td align="right"><b>'.get_string('groupmode').':</b></td>';
7bbe08a2 2017 echo '<td align="left">';
48e535bc 2018 unset($choices);
2019 $choices[NOGROUPS] = get_string('groupsnone');
2020 $choices[SEPARATEGROUPS] = get_string('groupsseparate');
2021 $choices[VISIBLEGROUPS] = get_string('groupsvisible');
2022 choose_from_menu($choices, 'groupmode', $groupmode, '', '', 0, false, $course->groupmodeforce);
2023 helpbutton('groupmode', get_string('groupmode'));
2024 echo '</td></tr>';
2025 }
2026}
2027
2028/**
2029 * Print visibility setting form element on module setup forms in mod/.../mod.html
2030 */
5ebb746b 2031function print_visible_setting($form, $course=NULL) {
1ee55c41 2032 if (empty($course)) {
2033 if (! $course = get_record('course', 'id', $form->course)) {
2034 error("This course doesn't exist");
2035 }
2036 }
48e535bc 2037 if ($form->coursemodule) {
2038 $visible = get_field('course_modules', 'visible', 'id', $form->coursemodule);
2039 } else {
2040 $visible = true;
2041 }
2042
2043 if ($form->mode == 'add') { // in this case $form->section is the section number, not the id
2044 $hiddensection = !get_field('course_sections', 'visible', 'section', $form->section, 'course', $form->course);
2045 } else {
2046 $hiddensection = !get_field('course_sections', 'visible', 'id', $form->section);
2047 }
2048 if ($hiddensection) {
2049 $visible = false;
2050 }
2051
2052 echo '<tr valign="top">';
1f15db9d 2053 echo '<td align="right"><b>'.get_string('visibletostudents','',moodle_strtolower($course->students)).':</b></td>';
7bbe08a2 2054 echo '<td align="left">';
48e535bc 2055 unset($choices);
1f15db9d 2056 $choices[1] = get_string('show');
2057 $choices[0] = get_string('hide');
48e535bc 2058 choose_from_menu($choices, 'visible', $visible, '', '', 0, false, $hiddensection);
2059 echo '</td></tr>';
2060}
2061
0705ff84 2062function update_restricted_mods($course,$mods) {
2063 delete_records("course_allowed_modules","course",$course->id);
2064 if (empty($course->restrictmodules)) {
2065 return;
2066 }
2067 else {
2068 foreach ($mods as $mod) {
2069 if ($mod == 0)
2070 continue; // this is the 'allow none' option
2071 $am->course = $course->id;
2072 $am->module = $mod;
2073 insert_record("course_allowed_modules",$am);
2074 }
2075 }
2076}
2077
2078/**
2079 * This function will take an int (module id) or a string (module name)
2080 * and return true or false, whether it's allowed in the given course (object)
2081 * $mod is not allowed to be an object, as the field for the module id is inconsistent
2082 * depending on where in the code it's called from (sometimes $mod->id, sometimes $mod->module)
2083 */
2084
2085function course_allowed_module($course,$mod) {
2086 if (empty($course->restrictmodules)) {
2087 return true;
2088 }
2089 if (isadmin()) {
2090 return true;
2091 }
2092 if (is_numeric($mod)) {
2093 $modid = $mod;
2094 } else if (is_string($mod)) {
2095 if ($mod = get_field("modules","id","name",strtolower($mod)))
2096 $modid = $mod;
2097 }
2098 if (empty($modid)) {
2099 return false;
2100 }
2101 return (record_exists("course_allowed_modules","course",$course->id,"module",$modid));
2102}
2103
861efb19 2104/***
2105 *** Efficiently moves many courses around while maintaining
2106 *** sortorder in order.
2107 ***
2108 *** $courseids is an array of course ids
2109 ***
2110 **/
2111
2112function move_courses ($courseids, $categoryid) {
2113
2114 global $CFG;
2115
2116 if (!empty($courseids)) {
2117
2118 $courseids = array_reverse($courseids);
2119
2120 foreach ($courseids as $courseid) {
2121
2122 if (! $course = get_record("course", "id", $courseid)) {
2123 notify("Error finding course $courseid");
2124 } else {
2125 // figure out a sortorder that we can use in the destination category
2126 $sortorder = get_field_sql('SELECT MIN(sortorder)-1 AS min
2127 FROM ' . $CFG->prefix . 'course WHERE category=' . $categoryid);
2128 if ($sortorder === false) {
2129 // the category is empty
2130 // rather than let the db default to 0
2131 // set it to > 100 and avoid extra work in fix_coursesortorder()
2132 $sortorder = 200;
2133 } else if ($sortorder < 10) {
2134 fix_course_sortorder($categoryid);
2135 }
2136
2137 $course->category = $categoryid;
2138 $course->sortorder = $sortorder;
2139 $course->fullname = addslashes($course->fullname);
2140 $course->shortname = addslashes($course->shortname);
2141 $course->summary = addslashes($course->summary);
2142 $course->password = addslashes($course->password);
2143 $course->teacher = addslashes($course->teacher);
2144 $course->teachers = addslashes($course->teachers);
2145 $course->student = addslashes($course->student);
2146 $course->students = addslashes($course->students);
2147
2148 if (!update_record('course', $course)) {
2149 notify("An error occurred - course not moved!");
2150 }
2151 }
2152 }
2153 fix_course_sortorder();
2154 }
2155 return true;
2156}
2157
92890025 2158?>