Merged fixes from stable
[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";
81e10e95 423 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courses[$log->course]."</a>\n";
21283ddc 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,
0adf53f6 629 $modid, $modaction, $groupid) {
630
631 global $CFG;
92890025 632 require_once($CFG->libdir.'/phpdocwriter/lib/include.php');
633
634 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
635 $modname, $modid, $modaction, $groupid)) {
636 return false;
637 }
638
639 if ($course->id == SITEID) {
640 $courses[0] = '';
641 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
642 foreach ($ccc as $cc) {
643 $courses[$cc->id] = $cc->shortname;
644 }
645 }
646 }
647
648 $count=0;
649 $ldcache = array();
650 $tt = getdate(time());
651 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
652
653 $strftimedatetime = get_string("strftimedatetime");
654 $isteacher = isteacher($course->id);
655
656 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
657 $filename .= '.sxw';
658 import('phpdocwriter.pdw_document');
659 header("Content-Type: application/download\n");
660 header("Content-Disposition: attachment; filename=$filename");
661 header("Expires: 0");
662 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
663 header("Pragma: public");
664 header("Content-Transfer-Encoding: binary");
665
666 $sxw = new pdw_document;
667 $sxw->SetFileName($filename);
668 $sxw->SetAuthor('Moodle');
669 $sxw->SetTitle('logs');
670 $sxw->SetDescription('logs'.' - '.$filename);
671 $sxw->SetLanguage('es','ES');
672 $sxw->SetStdFont("Times New Roman",12);
673 $sxw->AddPageDef(array('name'=>'Standard', 'margins'=>'1,1,1,1', 'w'=>'29.7', 'h'=>'21'));
674 $sxw->Write(get_string('savedat').userdate(time(), $strftimedatetime));
675 $sxw->Ln(3);
676
677 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
678 get_string('fullname'), get_string('action'), get_string('info'));
679
680 foreach($headers as $key=>$header){
681 $headers[$key] = eregi_replace ("<br?>", " ",$header);
682 }
683
684 foreach ($logs['logs'] as $log) {
685 if (isset($ldcache[$log->module][$log->action])) {
686 $ld = $ldcache[$log->module][$log->action];
687 } else {
688 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
689 $ldcache[$log->module][$log->action] = $ld;
690 }
691 if ($ld && !empty($log->info)) {
692 // ugly hack to make sure fullname is shown correctly
693 if (($ld->mtable == 'user') and ($ld->field == 'CONCAT(firstname," ",lastname)')) {
694 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
695 } else {
696 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
697 }
698 }
699
700 // Filter log->info
701 $log->info = format_string($log->info);
702
703 $log->url = strip_tags(urldecode($log->url)); // Some XSS protection
704 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
705 $log->url = str_replace('&', '&amp;', $log->url); // XHTML compatibility
706
707 $firstField = $courses[$log->course];
708 $fullname = fullname($log, $isteacher);
709 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action, $log->info);
710
711 $data[] = $row;
712 }
713 $sxw->Table($headers,$data);
714 $sxw->Output();
715
716 return true;
717}
718*/
719
c2cb4545 720function print_log_graph($course, $userid=0, $type="course.png", $date=0) {
721 global $CFG;
722 if (empty($CFG->gdversion)) {
723 echo "(".get_string("gdneed").")";
d887b5a7 724 } else {
980a5b3a 725 echo '<img src="'.$CFG->wwwroot.'/course/report/log/graph.php?id='.$course->id.
29b59206 726 '&amp;user='.$userid.'&amp;type='.$type.'&amp;date='.$date.'" alt="" />';
d887b5a7 727 }
728}
729
730
185cfb09 731function print_overview($courses) {
0d6b9d4f 732
733 global $CFG, $USER;
734
185cfb09 735 $htmlarray = array();
f8716988 736 if ($modules = get_records('modules')) {
737 foreach ($modules as $mod) {
738 if (file_exists(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php')) {
739 require_once(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php');
740 $fname = $mod->name.'_print_overview';
0d6b9d4f 741 if (function_exists($fname)) {
185cfb09 742 $fname($courses,$htmlarray);
0d6b9d4f 743 }
744 }
745 }
746 }
185cfb09 747 foreach ($courses as $course) {
fe5a1e23 748 print_simple_box_start('center', '100%', '', 5, "coursebox");
185cfb09 749 $linkcss = '';
750 if (empty($course->visible)) {
751 $linkcss = 'class="dimmed"';
752 }
753 print_heading('<a title="'.$course->fullname.'" '.$linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.$course->fullname.'</a>');
754 if (array_key_exists($course->id,$htmlarray)) {
755 foreach ($htmlarray[$course->id] as $modname => $html) {
756 echo $html;
757 }
758 }
759 print_simple_box_end();
760 }
0d6b9d4f 761}
762
763
600149be 764function print_recent_activity($course) {
765 // $course is an object
89adb174 766 // This function trawls through the logs looking for
600149be 767 // anything new since the user's last login
768
810393c8 769 global $CFG, $USER, $SESSION;
600149be 770
2ac64806 771 $isteacher = isteacher($course->id);
772
6f80940b 773 $timestart = time() - COURSE_MAX_RECENT_PERIOD;
0f87cb1d 774
9e51847a 775 if (!empty($USER->timeaccess[$course->id])) {
6f80940b 776 if ($USER->timeaccess[$course->id] > $timestart) {
9e51847a 777 $timestart = $USER->timeaccess[$course->id];
778 }
3d891989 779 }
0f87cb1d 780
de785682 781 echo '<div class="activitydate">';
27bf9e20 782 echo get_string('activitysince', '', userdate($timestart));
de785682 783 echo '</div>';
784 echo '<div class="activityhead">';
0f87cb1d 785
de785682 786 echo '<a href="'.$CFG->wwwroot.'/course/recent.php?id='.$course->id.'">'.get_string('recentactivityreport').'</a>';
0f87cb1d 787
5fc835a5 788 echo "</div>\n";
0f87cb1d 789
600149be 790
791 // Firstly, have there been any new enrolments?
792
793 $heading = false;
794 $content = false;
1b5910c4 795
6c38b7e0 796 $users = get_recent_enrolments($course->id, $timestart);
1b5910c4 797
5fc835a5 798 //Accessibility: new users now appear in an <OL> list.
6c38b7e0 799 if ($users) {
27bf9e20 800 echo '<div class="newusers">';
5fc835a5 801 if (! $heading) {
802 print_headline(get_string("newusers").':', 3);
803 $heading = true;
804 $content = true;
805 }
806 echo "<ol class=\"list\">\n";
6c38b7e0 807 foreach ($users as $user) {
5fc835a5 808
2ac64806 809 $fullname = fullname($user, $isteacher);
5fc835a5 810 echo '<li class="name"><a href="'.$CFG->wwwroot."/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a></li>\n";
600149be 811 }
5fc835a5 812 echo "</ol>\n</div>\n";
600149be 813 }
814
1b5910c4 815 // Next, have there been any modifications to the course structure?
816
27bf9e20 817 $logs = get_records_select('log', "time > '$timestart' AND course = '$course->id' AND
1b5910c4 818 module = 'course' AND action LIKE '% mod'", "time ASC");
819
820 if ($logs) {
821 foreach ($logs as $key => $log) {
27bf9e20 822 $info = split(' ', $log->info);
c9f6251e 823
27bf9e20 824 if ($info[0] == 'label') { // Labels are special activities
c9f6251e 825 continue;
826 }
827
27bf9e20 828 $modname = get_field($info[0], 'name', 'id', $info[1]);
1b5910c4 829 //Create a temp valid module structure (course,id)
830 $tempmod->course = $log->course;
831 $tempmod->id = $info[1];
832 //Obtain the visible property from the instance
833 $modvisible = instance_is_visible($info[0],$tempmod);
89adb174 834
1b5910c4 835 //Only if the mod is visible
836 if ($modvisible) {
837 switch ($log->action) {
27bf9e20 838 case 'add mod':
839 $stradded = get_string('added', 'moodle', get_string('modulename', $info[0]));
5847b267 840 $changelist[$log->info] = array ('operation' => 'add', 'text' => "$stradded:<br /><a href=\"$CFG->wwwroot/course/$log->url\">".format_string($modname,true)."</a>");
1b5910c4 841 break;
27bf9e20 842 case 'update mod':
843 $strupdated = get_string('updated', 'moodle', get_string('modulename', $info[0]));
844 if (empty($changelist[$log->info])) {
5847b267 845 $changelist[$log->info] = array ('operation' => 'update', 'text' => "$strupdated:<br /><a href=\"$CFG->wwwroot/course/$log->url\">".format_string($modname,true)."</a>");
1b5910c4 846 }
847 break;
27bf9e20 848 case 'delete mod':
849 if (!empty($changelist[$log->info]['operation']) and
850 $changelist[$log->info]['operation'] == 'add') {
851 $changelist[$log->info] = NULL;
1b5910c4 852 } else {
27bf9e20 853 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $info[0]));
854 $changelist[$log->info] = array ('operation' => 'delete', 'text' => $strdeleted);
1b5910c4 855 }
856 break;
600149be 857 }
ef25340c 858 }
859 }
860 }
861
9c9f7d77 862 if (!empty($changelist)) {
ef25340c 863 foreach ($changelist as $changeinfo => $change) {
864 if ($change) {
865 $changes[$changeinfo] = $change;
866 }
867 }
8a59942e 868 if (isset($changes)){
869 if (count($changes) > 0) {
27bf9e20 870 print_headline(get_string('courseupdates').':', 3);
8a59942e 871 $content = true;
872 foreach ($changes as $changeinfo => $change) {
27bf9e20 873 echo '<p class="activity">'.$change['text'].'</p>';
8a59942e 874 }
600149be 875 }
876 }
89adb174 877 }
bf40f9c1 878
3869a2ac 879 // Now display new things from each module
600149be 880
27bf9e20 881 $mods = get_records('modules', 'visible', '1', 'name', 'id, name');
0fd7da81 882
1b5910c4 883 foreach ($mods as $mod) { // Each module gets it's own logs and prints them
27bf9e20 884 include_once($CFG->dirroot.'/mod/'.$mod->name.'/lib.php');
885 $print_recent_activity = $mod->name.'_print_recent_activity';
1b5910c4 886 if (function_exists($print_recent_activity)) {
887 $modcontent = $print_recent_activity($course, $isteacher, $timestart);
3869a2ac 888 if ($modcontent) {
889 $content = true;
600149be 890 }
600149be 891 }
892 }
893
894 if (! $content) {
27bf9e20 895 echo '<p class="message">'.get_string('nothingnew').'</p>';
600149be 896 }
600149be 897}
898
e1360728 899
d897cae4 900function get_array_of_activities($courseid) {
89adb174 901// For a given course, returns an array of course activity objects
d897cae4 902// Each item in the array contains he following properties:
903// cm - course module id
904// mod - name of the module (eg forum)
905// section - the number of the section (eg week or topic)
906// name - the name of the instance
5867bfb5 907// visible - is the instance visible or not
86aa7ccf 908// extra - contains extra string to include in any link
d897cae4 909
8dddba42 910 global $CFG;
911
d897cae4 912 $mod = array();
913
9fa49e22 914 if (!$rawmods = get_course_mods($courseid)) {
d897cae4 915 return NULL;
916 }
917
918 if ($sections = get_records("course_sections", "course", $courseid, "section ASC")) {
919 foreach ($sections as $section) {
74666583 920 if (!empty($section->sequence)) {
d897cae4 921 $sequence = explode(",", $section->sequence);
922 foreach ($sequence as $seq) {
7af6281f 923 if (empty($rawmods[$seq])) {
924 continue;
925 }
d897cae4 926 $mod[$seq]->cm = $rawmods[$seq]->id;
927 $mod[$seq]->mod = $rawmods[$seq]->modname;
928 $mod[$seq]->section = $section->section;
929 $mod[$seq]->name = urlencode(get_field($rawmods[$seq]->modname, "name", "id", $rawmods[$seq]->instance));
fec5a6a6 930 $mod[$seq]->visible = $rawmods[$seq]->visible;
86aa7ccf 931 $mod[$seq]->extra = "";
8dddba42 932
933 $modname = $mod[$seq]->mod;
934 $functionname = $modname."_get_coursemodule_info";
935
936 include_once("$CFG->dirroot/mod/$modname/lib.php");
937
938 if (function_exists($functionname)) {
9d361034 939 if ($info = $functionname($rawmods[$seq])) {
940 if (!empty($info->extra)) {
941 $mod[$seq]->extra = $info->extra;
942 }
943 if (!empty($info->icon)) {
944 $mod[$seq]->icon = $info->icon;
945 }
c9f6251e 946 }
947 }
d897cae4 948 }
949 }
950 }
951 }
952 return $mod;
953}
954
955
956
e1360728 957
90845098 958function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
959// Returns a number of useful structures for course displays
7468bf01 960
90845098 961 $mods = NULL; // course modules indexed by id
e0161bff 962 $modnames = NULL; // all course module names (except resource!)
94361e02 963 $modnamesplural= NULL; // all course module names (plural form)
90845098 964 $modnamesused = NULL; // course module names used
7468bf01 965
9fa49e22 966 if ($allmods = get_records("modules")) {
90845098 967 foreach ($allmods as $mod) {
5867bfb5 968 if ($mod->visible) {
969 $modnames[$mod->name] = get_string("modulename", "$mod->name");
970 $modnamesplural[$mod->name] = get_string("modulenameplural", "$mod->name");
971 }
90845098 972 }
973 asort($modnames);
974 } else {
975 error("No modules are installed!");
976 }
977
9fa49e22 978 if ($rawmods = get_course_mods($courseid)) {
7468bf01 979 foreach($rawmods as $mod) { // Index the mods
959ae824 980 if (empty($modnames[$mod->modname])) {
981 continue;
982 }
7468bf01 983 $mods[$mod->id] = $mod;
959ae824 984 $mods[$mod->id]->modfullname = $modnames[$mod->modname];
985 if ($mod->visible or isteacher($courseid)) {
986 $modnamesused[$mod->modname] = $modnames[$mod->modname];
1acfbce5 987 }
7468bf01 988 }
c7da6f7a 989 if ($modnamesused) {
990 asort($modnamesused);
991 }
7468bf01 992 }
e0161bff 993
994 unset($modnames['resource']);
995 unset($modnames['label']);
7468bf01 996}
997
9fa49e22 998
7468bf01 999function get_all_sections($courseid) {
89adb174 1000
1001 return get_records("course_sections", "course", "$courseid", "section",
7d99d695 1002 "section, id, course, summary, sequence, visible");
7468bf01 1003}
1004
b86fc0e2 1005function course_set_display($courseid, $display=0) {
1006 global $USER;
1007
1066e0dc 1008 if (empty($USER->id)) {
b86fc0e2 1009 return false;
1010 }
1011
1012 if ($display == "all" or empty($display)) {
1013 $display = 0;
1014 }
1015
1016 if (record_exists("course_display", "userid", $USER->id, "course", $courseid)) {
1017 set_field("course_display", "display", $display, "userid", $USER->id, "course", $courseid);
1018 } else {
1019 $record->userid = $USER->id;
1020 $record->course = $courseid;
1021 $record->display = $display;
1022 if (!insert_record("course_display", $record)) {
1023 notify("Could not save your course display!");
1024 }
1025 }
1026
1027 return $USER->display[$courseid] = $display; // Note: = not ==
1028}
1029
7d99d695 1030function set_section_visible($courseid, $sectionnumber, $visibility) {
1031/// For a given course section, markes it visible or hidden,
1032/// and does the same for every activity in that section
1033
1034 if ($section = get_record("course_sections", "course", $courseid, "section", $sectionnumber)) {
1035 set_field("course_sections", "visible", "$visibility", "id", $section->id);
1036 if (!empty($section->sequence)) {
1037 $modules = explode(",", $section->sequence);
1038 foreach ($modules as $moduleid) {
02f66c42 1039 set_coursemodule_visible($moduleid, $visibility, true);
7d99d695 1040 }
1041 }
5867bfb5 1042 rebuild_course_cache($courseid);
7d99d695 1043 }
1044}
ba2e5d73 1045
5e367a2d 1046
d897cae4 1047function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%") {
52dcc2f9 1048/// Prints a section full of activity modules
7977cffd 1049 global $CFG, $USER;
1050
3d575e6f 1051 static $groupbuttons;
32d03b7b 1052 static $groupbuttonslink;
52dcc2f9 1053 static $isteacher;
1054 static $isediting;
7977cffd 1055 static $ismoving;
1056 static $strmovehere;
1057 static $strmovefull;
54669989 1058 static $strunreadpostsone;
52dcc2f9 1059
4877707e 1060 static $untracked;
a2d71d8e 1061 static $usetracking;
4877707e 1062
a22f8313 1063 $labelformatoptions = New stdClass;
110a32e2 1064
52dcc2f9 1065 if (!isset($isteacher)) {
9fd9c29b 1066 $groupbuttons = ($course->groupmode or (!$course->groupmodeforce));
32d03b7b 1067 $groupbuttonslink = (!$course->groupmodeforce);
52dcc2f9 1068 $isteacher = isteacher($course->id);
52dcc2f9 1069 $isediting = isediting($course->id);
ff0c7de0 1070 $ismoving = $isediting && ismoving($course->id);
3d575e6f 1071 if ($ismoving) {
1072 $strmovehere = get_string("movehere");
1073 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1074 }
94a6a70f 1075 include_once($CFG->dirroot.'/mod/forum/lib.php');
1076 if ($usetracking = forum_tp_can_track_forums()) {
a2d71d8e 1077 $strunreadpostsone = get_string('unreadpostsone', 'forum');
94a6a70f 1078 $untracked = forum_tp_get_untracked_forums($USER->id, $course->id);
a2d71d8e 1079 }
7977cffd 1080 }
60bd11cf 1081 $labelformatoptions->noclean = true;
94361e02 1082
c408b0c4 1083 $modinfo = unserialize($course->modinfo);
94361e02 1084
c6a55371 1085 //Acccessibility: replace table with list <ul>, but don't output empty list.
74666583 1086 if (!empty($section->sequence)) {
94361e02 1087
f2d660dc 1088 // Fix bug #5027, don't want style=\"width:$width\".
1089 echo "<ul class=\"section\">\n";
94361e02 1090 $sectionmods = explode(",", $section->sequence);
1091
1092 foreach ($sectionmods as $modnumber) {
9ae687af 1093 if (empty($mods[$modnumber])) {
1094 continue;
1095 }
94361e02 1096 $mod = $mods[$modnumber];
c9f6251e 1097
52dcc2f9 1098 if ($mod->visible or $isteacher) {
64fdc686 1099 echo '<li class="activity '.$mod->modname.'">';
7977cffd 1100 if ($ismoving) {
1101 if ($mod->id == $USER->activitycopy) {
1102 continue;
1103 }
1c919752 1104 echo '<a title="'.$strmovefull.'"'.
8b92f5bb 1105 ' href="'.$CFG->wwwroot.'/course/mod.php?moveto='.$mod->id.'&amp;sesskey='.$USER->sesskey.'">'.
446390fb 1106 '<img class="movetarget" src="'.$CFG->pixpath.'/movehere.gif" '.
1107 ' alt="'.$strmovehere.'" /></a><br />
1c919752 1108 ';
1acfbce5 1109 }
7977cffd 1110 $instancename = urldecode($modinfo[$modnumber]->name);
a92d95b1 1111 $instancename = format_string($instancename, true, $course->id);
c9f6251e 1112
86aa7ccf 1113 if (!empty($modinfo[$modnumber]->extra)) {
1114 $extra = urldecode($modinfo[$modnumber]->extra);
1115 } else {
1116 $extra = "";
1117 }
c9f6251e 1118
9d361034 1119 if (!empty($modinfo[$modnumber]->icon)) {
1120 $icon = "$CFG->pixpath/".urldecode($modinfo[$modnumber]->icon);
1121 } else {
1122 $icon = "$CFG->modpixpath/$mod->modname/icon.gif";
1123 }
1124
aac94fd0 1125 if ($mod->indent) {
1126 print_spacer(12, 20 * $mod->indent, false);
1127 }
1128
c9f6251e 1129 if ($mod->modname == "label") {
aac94fd0 1130 if (!$mod->visible) {
1131 echo "<span class=\"dimmed_text\">";
1132 }
179c9a50 1133 echo format_text($extra, FORMAT_HTML, $labelformatoptions);
aac94fd0 1134 if (!$mod->visible) {
1135 echo "</span>";
1136 }
c9f6251e 1137
1138 } else { // Normal activity
1139 $linkcss = $mod->visible ? "" : " class=\"dimmed\" ";
1c919752 1140 echo '<img src="'.$icon.'"'.
446390fb 1141 ' class="activityicon" alt="'.$mod->modfullname.'" />'.
1142 ' <a title="'.$mod->modfullname.'" '.$linkcss.' '.$extra.
1c919752 1143 ' href="'.$CFG->wwwroot.'/mod/'.$mod->modname.'/view.php?id='.$mod->id.'">'.
446390fb 1144 $instancename.'</a>';
c9f6251e 1145 }
a2d71d8e 1146 if ($usetracking && $mod->modname == 'forum') {
f37da850 1147 $groupmode = groupmode($course, $mod);
1148 $groupid = ($groupmode == SEPARATEGROUPS && !isteacheredit($course->id)) ?
a2d71d8e 1149 get_current_group($course->id) : false;
4877707e 1150
94a6a70f 1151 if (forum_tp_can_track_forums() && !isset($untracked[$mod->instance])) {
4877707e 1152 $unread = forum_tp_count_forum_unread_posts($USER->id, $mod->instance, $groupid);
1153 if ($unread) {
1154 echo '<span class="unread"> <a href="'.$CFG->wwwroot.'/mod/forum/view.php?id='.$mod->id.'">';
1155 if ($unread == 1) {
1156 echo $strunreadpostsone;
1157 } else {
1158 print_string('unreadpostsnumber', 'forum', $unread);
1159 }
1160 echo '</a> </span>';
d0388ebe 1161 }
54669989 1162 }
f37da850 1163 }
1164
c9f6251e 1165 if ($isediting) {
5f390342 1166 if ($groupbuttons and $mod->modname != 'label' and $mod->modname != 'resource') {
32d03b7b 1167 if (! $mod->groupmodelink = $groupbuttonslink) {
1168 $mod->groupmode = $course->groupmode;
1169 }
1170
1171 } else {
3d575e6f 1172 $mod->groupmode = false;
1173 }
37a88449 1174 echo '&nbsp;&nbsp;';
24e1eae4 1175 echo make_editing_buttons($mod, $absolute, true, $mod->indent, $section->section);
c9f6251e 1176 }
c6a55371 1177 echo "</li>\n";
94361e02 1178 }
94361e02 1179 }
f2d660dc 1180 } elseif ($ismoving) {
1181 echo "<ul class=\"section\">\n";
1182 }
7977cffd 1183 if ($ismoving) {
64fdc686 1184 echo '<li><a title="'.$strmovefull.'"'.
8b92f5bb 1185 ' href="'.$CFG->wwwroot.'/course/mod.php?movetosection='.$section->id.'&amp;sesskey='.$USER->sesskey.'">'.
446390fb 1186 '<img class="movetarget" src="'.$CFG->pixpath.'/movehere.gif" '.
c6a55371 1187 ' alt="'.$strmovehere.'" /></a></li>
1c919752 1188 ';
7977cffd 1189 }
c6a55371 1190 if (!empty($section->sequence) || $ismoving) {
1191 echo "</ul><!--class='section'-->\n\n";
1192 }
a7ad3ea6 1193}
1194
5867bfb5 1195
cb57e6f4 1196function print_section_add_menus($course, $section, $modnames, $vertical=false, $return=false) {
e0161bff 1197// Prints the menus to add activities and resources
1198
8b92f5bb 1199 global $CFG, $USER;
6da4b261 1200 static $straddactivity, $stractivities, $straddresource, $resources;
e0161bff 1201
1202 if (!isset($straddactivity)) {
1203 $straddactivity = get_string('addactivity');
1204 $straddresource = get_string('addresource');
6da4b261 1205
1206 /// Standard resource types
1207 require_once("$CFG->dirroot/mod/resource/lib.php");
1208 $resourceraw = resource_get_resource_types();
1209
1210 foreach ($resourceraw as $type => $name) {
839f2456 1211 $resources["resource&amp;type=$type"] = $name;
e0161bff 1212 }
0705ff84 1213 if (course_allowed_module($course,'label')) {
1214 $resources['label'] = get_string('resourcetypelabel', 'resource');
1215 }
e0161bff 1216 }
1217
d33d0cda 1218 $output = '<div style="text-align: right">';
0705ff84 1219 if (course_allowed_module($course,'resource')) {
81a5d9ca 1220 $resourceallowed = true;
0705ff84 1221 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&amp;section=$section&amp;sesskey=$USER->sesskey&amp;add=",
1222 $resources, "ressection$section", "", $straddresource, 'resource/types', $straddresource, true);
1223 }
cb57e6f4 1224
1225 if ($vertical) {
d33d0cda 1226 $output .= '<div>';
cb57e6f4 1227 }
1228
0705ff84 1229 // we need to loop through the forms and check to see if we can add them.
cb77cf12 1230 foreach ($modnames as $key=>$value) {
0705ff84 1231 if (!course_allowed_module($course,$key))
cb77cf12 1232 unset($modnames[$key]);
0705ff84 1233 }
1234
1235 // this is stupid but labels get put into resource, so if resource is hidden and label is not, we're in trouble.
1236 if (course_allowed_module($course,'label') && empty($resourceallowed)) {
1237 $modnames['label'] = get_string('modulename', 'label');
1238 }
1239
1c46eb03 1240 $output .= ' ';
8b92f5bb 1241 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&amp;section=$section&amp;sesskey=$USER->sesskey&amp;add=",
6da4b261 1242 $modnames, "section$section", "", $straddactivity, 'mods', $straddactivity, true);
d33d0cda 1243
1244 if ($vertical) {
1245 $output .= '</div>';
1246 }
1247
cb57e6f4 1248 $output .= '</div>';
1249
1250 if ($return) {
1251 return $output;
1252 } else {
1253 echo $output;
1254 }
e0161bff 1255}
1256
5867bfb5 1257function rebuild_course_cache($courseid=0) {
1258// Rebuilds the cached list of course activities stored in the database
1259// If a courseid is not specified, then all are rebuilt
1260
1261 if ($courseid) {
1262 $select = "id = '$courseid'";
1263 } else {
1264 $select = "";
1265 }
1266
1a31c2b3 1267 if ($courses = get_records_select("course", $select,'','id,fullname')) {
5867bfb5 1268 foreach ($courses as $course) {
1269 $modinfo = serialize(get_array_of_activities($course->id));
1270 if (!set_field("course", "modinfo", $modinfo, "id", $course->id)) {
1271 notify("Could not cache module information for course '$course->fullname'!");
1272 }
1273 }
1274 }
1275}
1276
1277
c2cb4545 1278
1279function make_categories_list(&$list, &$parents, $category=NULL, $path="") {
89adb174 1280/// Given an empty array, this function recursively travels the
c2cb4545 1281/// categories, building up a nice list for display. It also makes
1282/// an array that list all the parents for each category.
1283
9d866ae0 1284 // initialize the arrays if needed
1285 if (!is_array($list)) {
1286 $list = array();
1287 }
1288 if (!is_array($parents)) {
1289 $parents = array();
1290 }
1291
c2cb4545 1292 if ($category) {
1293 if ($path) {
e05bcf2f 1294 $path = $path.' / '.$category->name;
c2cb4545 1295 } else {
e05bcf2f 1296 $path = $category->name;
c2cb4545 1297 }
1298 $list[$category->id] = $path;
1299 } else {
1300 $category->id = 0;
1301 }
1302
e05bcf2f 1303 if ($categories = get_categories($category->id)) { // Print all the children recursively
c2cb4545 1304 foreach ($categories as $cat) {
1305 if (!empty($category->id)) {
3bd4de22 1306 if (isset($parents[$category->id])) {
2832badf 1307 $parents[$cat->id] = $parents[$category->id];
1308 }
c2cb4545 1309 $parents[$cat->id][] = $category->id;
1310 }
89adb174 1311 make_categories_list($list, $parents, $cat, $path);
c2cb4545 1312 }
1313 }
1314}
1315
1316
c2cb4545 1317function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1) {
89adb174 1318/// Recursive function to print out all the categories in a nice format
c2cb4545 1319/// with or without courses included
9ff5310a 1320 global $CFG;
e05bcf2f 1321
1322 if (isset($CFG->max_category_depth) && ($depth >= $CFG->max_category_depth)) {
1323 return;
9ff5310a 1324 }
c2cb4545 1325
1326 if (!$displaylist) {
e92fe848 1327 make_categories_list($displaylist, $parentslist);
c2cb4545 1328 }
1329
1330 if ($category) {
3af6e1db 1331 if ($category->visible or iscreator()) {
d2b6ba70 1332 print_category_info($category, $depth);
c2cb4545 1333 } else {
1334 return; // Don't bother printing children of invisible categories
1335 }
89adb174 1336
c2cb4545 1337 } else {
c2cb4545 1338 $category->id = "0";
1339 }
1340
1341 if ($categories = get_categories($category->id)) { // Print all the children recursively
1342 $countcats = count($categories);
1343 $count = 0;
1344 $first = true;
1345 $last = false;
1346 foreach ($categories as $cat) {
1347 $count++;
1348 if ($count == $countcats) {
1349 $last = true;
1350 }
1351 $up = $first ? false : true;
1352 $down = $last ? false : true;
1353 $first = false;
1354
814f88c0 1355 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1);
c2cb4545 1356 }
1357 }
c2cb4545 1358}
1359
0705ff84 1360// this function will return $options array for choose_from_menu, with whitespace to denote nesting.
1361
1362function make_categories_options() {
1363 make_categories_list($cats,$parents);
1364 foreach ($cats as $key => $value) {
1365 if (array_key_exists($key,$parents)) {
1366 if ($indent = count($parents[$key])) {
1367 for ($i = 0; $i < $indent; $i++) {
1368 $cats[$key] = '&nbsp;'.$cats[$key];
1369 }
1370 }
1371 }
1372 }
1373 return $cats;
1374}
c2cb4545 1375
d2b6ba70 1376function print_category_info($category, $depth) {
1377/// Prints the category info in indented fashion
1378/// This function is only used by print_whole_category_list() above
c2cb4545 1379
1380 global $CFG;
b48f834c 1381 static $strallowguests, $strrequireskey, $strsummary;
c2cb4545 1382
b48f834c 1383 if (empty($strsummary)) {
e05bcf2f 1384 $strallowguests = get_string('allowguests');
1385 $strrequireskey = get_string('requireskey');
1386 $strsummary = get_string('summary');
b48f834c 1387 }
ba2e5d73 1388
e05bcf2f 1389 $catlinkcss = $category->visible ? '' : ' class="dimmed" ';
d5f26b07 1390
e1638d61 1391 $frontpage = explode(',', $CFG->frontpage);
1392 $frontpage = $frontpage?array_flip($frontpage):array();
48643b49 1393 $coursecount = count_records('course') <= 200;
1394 if (isset($frontpage[FRONTPAGECATEGORYNAMES]) && !isset($frontpage[FRONTPAGECOURSELIST]) && $coursecount) {
839f2456 1395 $catimage = '<img src="'.$CFG->pixpath.'/i/course.gif" width="16" height="16" border="0" alt="" />';
b48f834c 1396 } else {
7b0b5c14 1397 $catimage = "&nbsp;";
8ef9cb56 1398 }
b48f834c 1399
87d32352 1400 echo "\n\n".'<table border="0" cellpadding="3" cellspacing="0" width="100%">';
d2b6ba70 1401
48643b49 1402 if (isset($frontpage[FRONTPAGECATEGORYNAMES]) && !isset($frontpage[FRONTPAGECOURSELIST]) && $coursecount) {
19374e76 1403 $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 1404
1405 echo "<tr>";
1406
1407 if ($depth) {
1408 $indent = $depth*30;
1409 $rows = count($courses) + 1;
1c919752 1410 echo '<td rowspan="'.$rows.'" valign="top" width="'.$indent.'">';
b48f834c 1411 print_spacer(10, $indent);
e05bcf2f 1412 echo '</td>';
b48f834c 1413 }
89adb174 1414
e05bcf2f 1415 echo '<td valign="top">'.$catimage.'</td>';
290130b3 1416 echo '<td valign="top" width="100%" class="category name">';
e05bcf2f 1417 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot.'/course/category.php?id='.$category->id.'">'.$category->name.'</a>';
1418 echo '</td>';
290130b3 1419 echo '<td class="category info">&nbsp;</td>';
e05bcf2f 1420 echo '</tr>';
b48f834c 1421
9ff5310a 1422 if ($courses && !(isset($CFG->max_category_depth)&&($depth>=$CFG->max_category_depth-1))) {
c2cb4545 1423 foreach ($courses as $course) {
e05bcf2f 1424 $linkcss = $course->visible ? '' : ' class="dimmed" ';
1425 echo '<tr><td valign="top" width="30">&nbsp;';
290130b3 1426 echo '</td><td valign="top" width="100%" class="course name">';
e05bcf2f 1427 echo '<a '.$linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.$course->fullname.'</a>';
290130b3 1428 echo '</td><td align="right" valign="top" nowrap="nowrap" class="course info">';
c2cb4545 1429 if ($course->guest ) {
e05bcf2f 1430 echo '<a title="'.$strallowguests.'" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">';
1431 echo '<img hspace="1" alt="'.$strallowguests.'" height="16" width="16" border="0" src="'.$CFG->pixpath.'/i/guest.gif" /></a>';
ebe8ddc1 1432 } else {
e05bcf2f 1433 echo '<img alt="" height="16" width="18" border="0" src="'.$CFG->pixpath.'/spacer.gif" />';
0c656181 1434 }
c2cb4545 1435 if ($course->password) {
e05bcf2f 1436 echo '<a title="'.$strrequireskey.'" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">';
1437 echo '<img hspace="1" alt="'.$strrequireskey.'" height="16" width="16" border="0" src="'.$CFG->pixpath.'/i/key.gif" /></a>';
ebe8ddc1 1438 } else {
e05bcf2f 1439 echo '<img alt="" height="16" width="18" border="0" src="'.$CFG->pixpath.'/spacer.gif" />';
b48f834c 1440 }
1441 if ($course->summary) {
e05bcf2f 1442 link_to_popup_window ('/course/info.php?id='.$course->id, 'courseinfo',
1443 '<img hspace="1" alt="'.$strsummary.'" height="16" width="16" border="0" src="'.$CFG->pixpath.'/i/info.gif" />',
b48f834c 1444 400, 500, $strsummary);
ebe8ddc1 1445 } else {
e05bcf2f 1446 echo '<img alt="" height="16" width="18" border="0" src="'.$CFG->pixpath.'/spacer.gif" />';
0c656181 1447 }
e05bcf2f 1448 echo '</td></tr>';
0c656181 1449 }
ba2e5d73 1450 }
d2b6ba70 1451 } else {
b48f834c 1452
e0140f24 1453 echo '<tr>';
1454
b48f834c 1455 if ($depth) {
1456 $indent = $depth*20;
e05bcf2f 1457 echo '<td valign="top" width="'.$indent.'">';
b48f834c 1458 print_spacer(10, $indent);
e05bcf2f 1459 echo '</td>';
d2b6ba70 1460 }
89adb174 1461
290130b3 1462 echo '<td valign="top" width="100%" class="category name">';
e05bcf2f 1463 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot.'/course/category.php?id='.$category->id.'">'.$category->name.'</a>';
1464 echo '</td>';
290130b3 1465 echo '<td valign="top" class="category number">';
e05bcf2f 1466 if ($category->coursecount) {
1467 echo $category->coursecount;
1468 }
1469 echo '</td></tr>';
c2cb4545 1470 }
e05bcf2f 1471 echo '</table>';
c2cb4545 1472}
1473
c2cb4545 1474
8e227aa7 1475function print_courses($category, $width="100%", $hidesitecourse = false) {
c2cb4545 1476/// Category is 0 (for all courses) or an object
1477
810393c8 1478 global $CFG;
c2cb4545 1479
1480 if (empty($category)) {
90c2ca2e 1481 $categories = get_categories(0); // Parent = 0 ie top-level categories only
1482 if (count($categories) == 1) {
1483 $category = array_shift($categories);
0cb9ec10 1484 $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 1485 } else {
0cb9ec10 1486 $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 1487 }
1488 unset($categories);
607809b3 1489 } else {
c2cb4545 1490 $categories = get_categories($category->id); // sub categories
0cb9ec10 1491 $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 1492 }
1493
c2cb4545 1494 if ($courses) {
1495 foreach ($courses as $course) {
8e227aa7 1496 if ($hidesitecourse && !$course->category) {
1497 continue;
1498 }
c2cb4545 1499 print_course($course, $width);
c2cb4545 1500 }
1501 } else {
f9667a5a 1502 print_heading(get_string("nocoursesyet"));
255d1033 1503 if (iscreator()) { // Make it obvious for newbies on new sites how to add a course
1504 $options = array();
1505 $options['category'] = $category->id;
1506 echo '<div class="addcoursebutton" align="center">';
1507 print_single_button($CFG->wwwroot.'/course/edit.php', $options, get_string("addnewcourse"));
1508 echo '</div>';
1509 }
c2cb4545 1510 }
1511
1512}
1513
1514
1515function print_course($course, $width="100%") {
1516
861efb19 1517 global $CFG, $USER;
c2cb4545 1518
f9667a5a 1519 require_once("$CFG->dirroot/enrol/enrol.class.php");
146bbb8f 1520
f9667a5a 1521 $enrol = enrolment_factory::factory($course->enrol);
146bbb8f 1522
810393c8 1523 print_simple_box_start("center", "$width", '', 5, "coursebox");
c2cb4545 1524
22288704 1525 $linkcss = $course->visible ? "" : " class=\"dimmed\" ";
1526
c2cb4545 1527 echo "<table width=\"100%\">";
e5e81e78 1528 echo '<tr valign="top">';
290130b3 1529 echo '<td valign="top" width="50%" class="info">';
34b5847a 1530 echo '<b><a title="'.get_string('entercourse').'"'.
e5e81e78 1531 $linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.
34b5847a 1532 $course->fullname.'</a></b><br />';
c2cb4545 1533 if ($teachers = get_course_teachers($course->id)) {
290130b3 1534 echo "<span class=\"teachers\">\n";
c2cb4545 1535 foreach ($teachers as $teacher) {
1536 if ($teacher->authority > 0) {
1537 if (!$teacher->role) {
1538 $teacher->role = $course->teacher;
1539 }
2ac64806 1540 $fullname = fullname($teacher, isteacher($course->id)); // is the USER a teacher of that course
8bd84b4d 1541 echo $teacher->role.': <a href="'.$CFG->wwwroot.'/user/view.php?id='.$teacher->id.
1542 '&amp;course='.SITEID.'">'.$fullname.'</a><br />';
c2cb4545 1543 }
1544 }
34b5847a 1545 echo "</span>\n";
c2cb4545 1546 }
c2cb4545 1547
146bbb8f 1548 echo $enrol->get_access_icons($course);
c2cb4545 1549
290130b3 1550 echo '</td><td valign="top" width="50%" class="summary">';
9f39c190 1551 $options = NULL;
1552 $options->noclean = true;
34b5847a 1553 $options->para = false;
9f39c190 1554 echo format_text($course->summary, FORMAT_MOODLE, $options, $course->id);
c2cb4545 1555 echo "</td></tr>";
1556 echo "</table>";
1557
1558 print_simple_box_end();
1559}
1560
1561
1562function print_my_moodle() {
1563/// Prints custom user information on the home page.
1564/// Over time this can include all sorts of information
1565
1566 global $USER, $CFG;
1567
1568 if (!isset($USER->id)) {
1569 error("It shouldn't be possible to see My Moodle without being logged in.");
1570 }
1571
1572 if ($courses = get_my_courses($USER->id)) {
1573 foreach ($courses as $course) {
c81696e5 1574 if (!$course->category) {
1575 continue;
1576 }
c2cb4545 1577 print_course($course, "100%");
c2cb4545 1578 }
38a10939 1579
7f989948 1580 if (count_records("course") > (count($courses) + 1) ) { // Some courses not being displayed
1581 echo "<table width=\"100%\"><tr><td align=\"center\">";
1582 print_course_search("", false, "short");
1583 echo "</td><td align=\"center\">";
1584 print_single_button("$CFG->wwwroot/course/index.php", NULL, get_string("fulllistofcourses"), "get");
1585 echo "</td></tr></table>\n";
1586 }
26330001 1587 } else {
1588 if (count_records("course_categories") > 1) {
cb29b020 1589 print_simple_box_start("center", "100%", "#FFFFFF", 5, "categorybox");
26330001 1590 print_whole_category_list();
1591 print_simple_box_end();
1592 } else {
1593 print_courses(0, "100%");
1594 }
607809b3 1595 }
2b8cef80 1596}
1597
11b0c469 1598
a8b56716 1599function print_course_search($value="", $return=false, $format="plain") {
38a10939 1600
1601 global $CFG;
1602
1603 $strsearchcourses= get_string("searchcourses");
1604
1c919752 1605 if ($format == 'plain') {
87d32352 1606 $output = '<form name="coursesearch" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
1607 $output .= '<center><p align="center" class="coursesearchbox">';
f8a5159a 1608 $output .= '<input type="text" size="30" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
9cc78ee1 1609 $output .= '<input type="submit" value="'.s($strsearchcourses).'" />';
87d32352 1610 $output .= '</p></center></form>';
1c919752 1611 } else if ($format == 'short') {
87d32352 1612 $output = '<form name="coursesearch" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
1613 $output .= '<center><p align="center" class="coursesearchbox">';
f8a5159a 1614 $output .= '<input type="text" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
9cc78ee1 1615 $output .= '<input type="submit" value="'.s($strsearchcourses).'" />';
87d32352 1616 $output .= '</p></center></form>';
1c919752 1617 } else if ($format == 'navbar') {
87d32352 1618 $output = '<form name="coursesearch" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
1619 $output .= '<table border="0" cellpadding="0" cellspacing="0"><tr><td nowrap="nowrap">';
f8a5159a 1620 $output .= '<input type="text" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
9cc78ee1 1621 $output .= '<input type="submit" value="'.s($strsearchcourses).'" />';
1c919752 1622 $output .= '</td></tr></table>';
87d32352 1623 $output .= '</form>';
a8b56716 1624 }
1625
1626 if ($return) {
1627 return $output;
1628 }
1629 echo $output;
38a10939 1630}
11b0c469 1631
1632/// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
1633
1634function add_course_module($mod) {
11b0c469 1635
e5dfd0f3 1636 $mod->added = time();
53f4ad2c 1637 unset($mod->id);
11b0c469 1638
e5dfd0f3 1639 return insert_record("course_modules", $mod);
11b0c469 1640}
1641
7977cffd 1642function add_mod_to_section($mod, $beforemod=NULL) {
1643/// Given a full mod object with section and course already defined
1644/// If $before is specified, then this is an existing ID which we
1645/// will insert the new module before
1646///
1647/// Returns the course_sections ID where the mod is inserted
11b0c469 1648
9fa49e22 1649 if ($section = get_record("course_sections", "course", "$mod->course", "section", "$mod->section")) {
7977cffd 1650
1651 $section->sequence = trim($section->sequence);
1652
1653 if (empty($section->sequence)) {
11b0c469 1654 $newsequence = "$mod->coursemodule";
7977cffd 1655
1656 } else if ($beforemod) {
1657 $modarray = explode(",", $section->sequence);
1658
1659 if ($key = array_keys ($modarray, $beforemod->id)) {
1660 $insertarray = array($mod->id, $beforemod->id);
1661 array_splice($modarray, $key[0], 1, $insertarray);
1662 $newsequence = implode(",", $modarray);
1663
1664 } else { // Just tack it on the end anyway
1665 $newsequence = "$section->sequence,$mod->coursemodule";
1666 }
1667
1668 } else {
1669 $newsequence = "$section->sequence,$mod->coursemodule";
11b0c469 1670 }
89adb174 1671
e5dfd0f3 1672 if (set_field("course_sections", "sequence", $newsequence, "id", $section->id)) {
1673 return $section->id; // Return course_sections ID that was used.
11b0c469 1674 } else {
e5dfd0f3 1675 return 0;
11b0c469 1676 }
89adb174 1677
11b0c469 1678 } else { // Insert a new record
e5dfd0f3 1679 $section->course = $mod->course;
1680 $section->section = $mod->section;
1681 $section->summary = "";
1682 $section->sequence = $mod->coursemodule;
1683 return insert_record("course_sections", $section);
11b0c469 1684 }
1685}
1686
48e535bc 1687function set_coursemodule_groupmode($id, $groupmode) {
3d575e6f 1688 return set_field("course_modules", "groupmode", $groupmode, "id", $id);
1689}
1690
02f66c42 1691/**
1692* $prevstateoverrides = true will set the visibility of the course module
1693* to what is defined in visibleold. This enables us to remember the current
1694* visibility when making a whole section hidden, so that when we toggle
1695* that section back to visible, we are able to return the visibility of
1696* the course module back to what it was originally.
1697*/
1698function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
48e535bc 1699 $cm = get_record('course_modules', 'id', $id);
dcd338ff 1700 $modulename = get_field('modules', 'name', 'id', $cm->module);
1701 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
1702 foreach($events as $event) {
48e535bc 1703 if ($visible) {
1704 show_event($event);
1705 } else {
1706 hide_event($event);
1707 }
dcd338ff 1708 }
1709 }
02f66c42 1710 if ($prevstateoverrides) {
1711 if ($visible == '0') {
1712 // Remember the current visible state so we can toggle this back.
1713 set_field('course_modules', 'visibleold', $cm->visible, 'id', $id);
1714 } else {
1715 // Get the previous saved visible states.
1716 return set_field('course_modules', 'visible', $cm->visibleold, 'id', $id);
1717 }
1718 }
48e535bc 1719 return set_field("course_modules", "visible", $visible, "id", $id);
1acfbce5 1720}
1721
290130b3 1722/*
1723 * Delete a course module and any associated data at the course level (events)
1724 * Until 1.5 this function simply marked a deleted flag ... now it
1725 * deletes it completely.
1726 *
1727 */
48e535bc 1728function delete_course_module($id) {
290130b3 1729 if (!$cm = get_record('course_modules', 'id', $id)) {
1730 return true;
1731 }
dcd338ff 1732 $modulename = get_field('modules', 'name', 'id', $cm->module);
1733 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
1734 foreach($events as $event) {
48e535bc 1735 delete_event($event);
dcd338ff 1736 }
1737 }
290130b3 1738 return delete_records('course_modules', 'id', $cm->id);
11b0c469 1739}
1740
1741function delete_mod_from_section($mod, $section) {
11b0c469 1742
e5dfd0f3 1743 if ($section = get_record("course_sections", "id", "$section") ) {
11b0c469 1744
e5dfd0f3 1745 $modarray = explode(",", $section->sequence);
11b0c469 1746
1747 if ($key = array_keys ($modarray, $mod)) {
1748 array_splice($modarray, $key[0], 1);
1749 $newsequence = implode(",", $modarray);
e5dfd0f3 1750 return set_field("course_sections", "sequence", $newsequence, "id", $section->id);
11b0c469 1751 } else {
1752 return false;
1753 }
89adb174 1754
11b0c469 1755 }
7977cffd 1756 return false;
11b0c469 1757}
1758
12905134 1759function move_section($course, $section, $move) {
1760/// Moves a whole course section up and down within the course
798b70a1 1761 global $USER;
12905134 1762
1763 if (!$move) {
1764 return true;
1765 }
1766
1767 $sectiondest = $section + $move;
1768
1769 if ($sectiondest > $course->numsections or $sectiondest < 1) {
1770 return false;
1771 }
1772
1773 if (!$sectionrecord = get_record("course_sections", "course", $course->id, "section", $section)) {
1774 return false;
1775 }
1776
1777 if (!$sectiondestrecord = get_record("course_sections", "course", $course->id, "section", $sectiondest)) {
1778 return false;
1779 }
1780
56e34ee4 1781 if (!set_field("course_sections", "section", $sectiondest, "id", $sectionrecord->id)) {
12905134 1782 return false;
1783 }
56e34ee4 1784 if (!set_field("course_sections", "section", $section, "id", $sectiondestrecord->id)) {
12905134 1785 return false;
1786 }
798b70a1 1787 // if the focus is on the section that is being moved, then move the focus along
1788 if (isset($USER->display[$course->id]) and ($USER->display[$course->id] == $section)) {
1789 course_set_display($course->id, $sectiondest);
1790 }
5390cbb7 1791
1792 // Check for duplicates.
1793 // There is a very rare case that some sections in the same course have the same section id.
1794 if (($count_section = count_records('course_sections', 'course', $course->id) - 1) != $course->numsections) {
1795 $sections = get_records_select('course_sections', "course = $course->id AND section > 0", 'section ASC');
1796 $n = 1;
1797 foreach ($sections as $section) {
1798 if (!set_field('course_sections', 'section', $n, 'id', $section->id)) {
1799 return false;
1800 }
1801 $n++;
1802 }
1803 if (!set_field('course', 'numsections', $count_section, 'id', $course->id)) {
1804 return false;
1805 }
1806 }
12905134 1807 return true;
1808}
1809
1810
7977cffd 1811function moveto_module($mod, $section, $beforemod=NULL) {
1812/// All parameters are objects
1813/// Move the module object $mod to the specified $section
1814/// If $beforemod exists then that is the module
1815/// before which $modid should be inserted
1816
1817/// Remove original module from original section
1818
1819 if (! delete_mod_from_section($mod->id, $mod->section)) {
1820 notify("Could not delete module from existing section");
1821 }
1822
1823/// Update module itself if necessary
1824
1825 if ($mod->section != $section->id) {
89adb174 1826 $mod->section = $section->id;
7977cffd 1827 if (!update_record("course_modules", $mod)) {
1828 return false;
1829 }
48e535bc 1830 // if moving to a hidden section then hide module
1831 if (!$section->visible) {
1832 set_coursemodule_visible($mod->id, 0);
1833 }
7977cffd 1834 }
1835
1836/// Add the module into the new section
1837
1838 $mod->course = $section->course;
1839 $mod->section = $section->section; // need relative reference
1840 $mod->coursemodule = $mod->id;
1841
1842 if (! add_mod_to_section($mod, $beforemod)) {
1843 return false;
1844 }
1845
1846 return true;
1847
1848}
1849
24e1eae4 1850function make_editing_buttons($mod, $absolute=false, $moveselect=true, $indent=-1, $section=-1) {
810393c8 1851 global $CFG, $USER;
94361e02 1852
3d575e6f 1853 static $str;
37a88449 1854 static $sesskey;
3d575e6f 1855
1856 if (!isset($str)) {
1857 $str->delete = get_string("delete");
1858 $str->move = get_string("move");
1859 $str->moveup = get_string("moveup");
1860 $str->movedown = get_string("movedown");
1861 $str->moveright = get_string("moveright");
1862 $str->moveleft = get_string("moveleft");
1863 $str->update = get_string("update");
d33a2a6f 1864 $str->duplicate = get_string("duplicate");
3d575e6f 1865 $str->hide = get_string("hide");
1866 $str->show = get_string("show");
1867 $str->clicktochange = get_string("clicktochange");
32d03b7b 1868 $str->forcedmode = get_string("forcedmode");
3d575e6f 1869 $str->groupsnone = get_string("groupsnone");
1870 $str->groupsseparate = get_string("groupsseparate");
1871 $str->groupsvisible = get_string("groupsvisible");
37a88449 1872 $sesskey = sesskey();
1acfbce5 1873 }
94361e02 1874
24e1eae4 1875 if ($section >= 0) {
75f087b6 1876 $section = '&amp;sr='.$section; // Section return
24e1eae4 1877 } else {
1878 $section = '';
1879 }
1880
94361e02 1881 if ($absolute) {
37a88449 1882 $path = $CFG->wwwroot.'/course';
dc0dc7d5 1883 } else {
37a88449 1884 $path = '.';
dc0dc7d5 1885 }
1886
3d575e6f 1887 if ($mod->visible) {
37a88449 1888 $hideshow = '<a title="'.$str->hide.'" href="'.$path.'/mod.php?hide='.$mod->id.
1889 '&amp;sesskey='.$sesskey.$section.'"><img'.
1890 ' src="'.$CFG->pixpath.'/t/hide.gif" hspace="2" height="11" width="11" '.
1891 ' border="0" alt="'.$str->hide.'" /></a> ';
1acfbce5 1892 } else {
37a88449 1893 $hideshow = '<a title="'.$str->show.'" href="'.$path.'/mod.php?show='.$mod->id.
1894 '&amp;sesskey='.$sesskey.$section.'"><img'.
1895 ' src="'.$CFG->pixpath.'/t/show.gif" hspace="2" height="11" width="11" '.
1896 ' border="0" alt="'.$str->show.'" /></a> ';
7977cffd 1897 }
3d575e6f 1898 if ($mod->groupmode !== false) {
1899 if ($mod->groupmode == SEPARATEGROUPS) {
32d03b7b 1900 $grouptitle = $str->groupsseparate;
37a88449 1901 $groupimage = $CFG->pixpath.'/t/groups.gif';
1902 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=0&amp;sesskey='.$sesskey;
3d575e6f 1903 } else if ($mod->groupmode == VISIBLEGROUPS) {
32d03b7b 1904 $grouptitle = $str->groupsvisible;
37a88449 1905 $groupimage = $CFG->pixpath.'/t/groupv.gif';
1906 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=1&amp;sesskey='.$sesskey;
32d03b7b 1907 } else {
1908 $grouptitle = $str->groupsnone;
37a88449 1909 $groupimage = $CFG->pixpath.'/t/groupn.gif';
1910 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=2&amp;sesskey='.$sesskey;
32d03b7b 1911 }
1912 if ($mod->groupmodelink) {
37a88449 1913 $groupmode = '<a title="'.$grouptitle.' ('.$str->clicktochange.')" href="'.$grouplink.'">'.
1914 '<img src="'.$groupimage.'" hspace="2" height="11" width="11" '.
1915 'border="0" alt="'.$grouptitle.'" /></a>';
3d575e6f 1916 } else {
37a88449 1917 $groupmode = '<img title="'.$grouptitle.' ('.$str->forcedmode.')" '.
1918 ' src="'.$groupimage.'" hspace="2" height="11" width="11" '.
1919 'border="0" alt="'.$grouptitle.'" />';
3d575e6f 1920 }
1921 } else {
1922 $groupmode = "";
1923 }
7977cffd 1924
1925 if ($moveselect) {
37a88449 1926 $move = '<a title="'.$str->move.'" href="'.$path.'/mod.php?copy='.$mod->id.
1927 '&amp;sesskey='.$sesskey.$section.'"><img'.
1928 ' src="'.$CFG->pixpath.'/t/move.gif" hspace="2" height="11" width="11" '.
1929 ' border="0" alt="'.$str->move.'" /></a>';
493486c4 1930 } else {
37a88449 1931 $move = '<a title="'.$str->moveup.'" href="'.$path.'/mod.php?id='.$mod->id.
1932 '&amp;move=-1&amp;sesskey='.$sesskey.$section.'"><img'.
1933 ' src="'.$CFG->pixpath.'/t/up.gif" hspace="2" height="11" width="11" '.
1934 ' border="0" alt="'.$str->moveup.'" /></a>'.
1935 '<a title="'.$str->movedown.'" href="'.$path.'/mod.php?id='.$mod->id.
1936 '&amp;move=1&amp;sesskey='.$sesskey.$section.'"><img'.
1937 ' src="'.$CFG->pixpath.'/t/down.gif" hspace="2" height="11" width="11" '.
1938 ' border="0" alt="'.$str->movedown.'" /></a>';
7977cffd 1939 }
1940
aac94fd0 1941 $leftright = "";
1942 if ($indent > 0) {
37a88449 1943 $leftright .= '<a title="'.$str->moveleft.'" href="'.$path.'/mod.php?id='.$mod->id.
1944 '&amp;indent=-1&amp;sesskey='.$sesskey.$section.'"><img'.
1945 ' src="'.$CFG->pixpath.'/t/left.gif" hspace="2" height="11" width="11" '.
1946 ' border="0" alt="'.$str->moveleft.'" /></a>';
aac94fd0 1947 }
1948 if ($indent >= 0) {
37a88449 1949 $leftright .= '<a title="'.$str->moveright.'" href="'.$path.'/mod.php?id='.$mod->id.
1950 '&amp;indent=1&amp;sesskey='.$sesskey.$section.'"><img'.
1951 ' src="'.$CFG->pixpath.'/t/right.gif" hspace="2" height="11" width="11" '.
1952 ' border="0" alt="'.$str->moveright.'" /></a>';
1953 }
1954
1955 return '<span class="commands">'.$leftright.$move.
1956 '<a title="'.$str->update.'" href="'.$path.'/mod.php?update='.$mod->id.
1957 '&amp;sesskey='.$sesskey.$section.'"><img'.
1958 ' src="'.$CFG->pixpath.'/t/edit.gif" hspace="2" height="11" width="11" border="0" '.
1959 ' alt="'.$str->update.'" /></a>'.
1960 '<a title="'.$str->delete.'" href="'.$path.'/mod.php?delete='.$mod->id.
1961 '&amp;sesskey='.$sesskey.$section.'"><img'.
1962 ' src="'.$CFG->pixpath.'/t/delete.gif" hspace="2" height="11" width="11" border="0" '.
1963 ' alt="'.$str->delete.'" /></a>'.$hideshow.$groupmode.'</span>';
90845098 1964}
1965
b61efafb 1966/**
1967 * given a course object with shortname & fullname, this function will
1968 * truncate the the number of chars allowed and add ... if it was too long
1969 */
1970function course_format_name ($course,$max=100) {
1971
1972 $str = $course->shortname.': '.$course->fullname;
1973 if (strlen($str) <= $max) {
1974 return $str;
1975 }
1976 else {
1977 return substr($str,0,$max-3).'...';
1978 }
1979}
1980
1981/**
1982 * This function will return true if the given course is a child course at all
1983 */
1984function course_in_meta ($course) {
5f37b628 1985 return record_exists("course_meta","child_course",$course->id);
b61efafb 1986}
1987
48e535bc 1988
1989/**
1990 * Print standard form elements on module setup forms in mod/.../mod.html
1991 */
1992function print_standard_coursemodule_settings($form) {
da2224f8 1993 if (! $course = get_record('course', 'id', $form->course)) {
1994 error("This course doesn't exist");
1995 }
1996 print_groupmode_setting($form, $course);
1997 print_visible_setting($form, $course);
48e535bc 1998}
1999
2000/**
2001 * Print groupmode form element on module setup forms in mod/.../mod.html
2002 */
5ebb746b 2003function print_groupmode_setting($form, $course=NULL) {
48e535bc 2004
5ebb746b 2005 if (empty($course)) {
2006 if (! $course = get_record('course', 'id', $form->course)) {
2007 error("This course doesn't exist");
2008 }
2009 }
48e535bc 2010 if ($form->coursemodule) {
2011 if (! $cm = get_record('course_modules', 'id', $form->coursemodule)) {
2012 error("This course module doesn't exist");
2013 }
2014 } else {
2015 $cm = null;
2016 }
2017 $groupmode = groupmode($course, $cm);
2018 if ($course->groupmode or (!$course->groupmodeforce)) {
2019 echo '<tr valign="top">';
2020 echo '<td align="right"><b>'.get_string('groupmode').':</b></td>';
7bbe08a2 2021 echo '<td align="left">';
48e535bc 2022 unset($choices);
2023 $choices[NOGROUPS] = get_string('groupsnone');
2024 $choices[SEPARATEGROUPS] = get_string('groupsseparate');
2025 $choices[VISIBLEGROUPS] = get_string('groupsvisible');
2026 choose_from_menu($choices, 'groupmode', $groupmode, '', '', 0, false, $course->groupmodeforce);
2027 helpbutton('groupmode', get_string('groupmode'));
2028 echo '</td></tr>';
2029 }
2030}
2031
2032/**
2033 * Print visibility setting form element on module setup forms in mod/.../mod.html
2034 */
5ebb746b 2035function print_visible_setting($form, $course=NULL) {
1ee55c41 2036 if (empty($course)) {
2037 if (! $course = get_record('course', 'id', $form->course)) {
2038 error("This course doesn't exist");
2039 }
2040 }
48e535bc 2041 if ($form->coursemodule) {
2042 $visible = get_field('course_modules', 'visible', 'id', $form->coursemodule);
2043 } else {
2044 $visible = true;
2045 }
2046
2047 if ($form->mode == 'add') { // in this case $form->section is the section number, not the id
2048 $hiddensection = !get_field('course_sections', 'visible', 'section', $form->section, 'course', $form->course);
2049 } else {
2050 $hiddensection = !get_field('course_sections', 'visible', 'id', $form->section);
2051 }
2052 if ($hiddensection) {
2053 $visible = false;
2054 }
2055
2056 echo '<tr valign="top">';
1f15db9d 2057 echo '<td align="right"><b>'.get_string('visibletostudents','',moodle_strtolower($course->students)).':</b></td>';
7bbe08a2 2058 echo '<td align="left">';
48e535bc 2059 unset($choices);
1f15db9d 2060 $choices[1] = get_string('show');
2061 $choices[0] = get_string('hide');
48e535bc 2062 choose_from_menu($choices, 'visible', $visible, '', '', 0, false, $hiddensection);
2063 echo '</td></tr>';
2064}
2065
0705ff84 2066function update_restricted_mods($course,$mods) {
2067 delete_records("course_allowed_modules","course",$course->id);
2068 if (empty($course->restrictmodules)) {
2069 return;
2070 }
2071 else {
2072 foreach ($mods as $mod) {
2073 if ($mod == 0)
2074 continue; // this is the 'allow none' option
2075 $am->course = $course->id;
2076 $am->module = $mod;
2077 insert_record("course_allowed_modules",$am);
2078 }
2079 }
2080}
2081
2082/**
2083 * This function will take an int (module id) or a string (module name)
2084 * and return true or false, whether it's allowed in the given course (object)
2085 * $mod is not allowed to be an object, as the field for the module id is inconsistent
2086 * depending on where in the code it's called from (sometimes $mod->id, sometimes $mod->module)
2087 */
2088
2089function course_allowed_module($course,$mod) {
2090 if (empty($course->restrictmodules)) {
2091 return true;
2092 }
2093 if (isadmin()) {
2094 return true;
2095 }
2096 if (is_numeric($mod)) {
2097 $modid = $mod;
2098 } else if (is_string($mod)) {
cb77cf12 2099 if ($mod = get_field("modules","id","name",$mod))
0705ff84 2100 $modid = $mod;
2101 }
2102 if (empty($modid)) {
2103 return false;
2104 }
2105 return (record_exists("course_allowed_modules","course",$course->id,"module",$modid));
2106}
2107
861efb19 2108/***
2109 *** Efficiently moves many courses around while maintaining
2110 *** sortorder in order.
2111 ***
2112 *** $courseids is an array of course ids
2113 ***
2114 **/
2115
2116function move_courses ($courseids, $categoryid) {
2117
2118 global $CFG;
2119
2120 if (!empty($courseids)) {
2121
2122 $courseids = array_reverse($courseids);
2123
2124 foreach ($courseids as $courseid) {
2125
2126 if (! $course = get_record("course", "id", $courseid)) {
2127 notify("Error finding course $courseid");
2128 } else {
2129 // figure out a sortorder that we can use in the destination category
2130 $sortorder = get_field_sql('SELECT MIN(sortorder)-1 AS min
2131 FROM ' . $CFG->prefix . 'course WHERE category=' . $categoryid);
2132 if ($sortorder === false) {
2133 // the category is empty
2134 // rather than let the db default to 0
2135 // set it to > 100 and avoid extra work in fix_coursesortorder()
2136 $sortorder = 200;
2137 } else if ($sortorder < 10) {
2138 fix_course_sortorder($categoryid);
2139 }
2140
2141 $course->category = $categoryid;
2142 $course->sortorder = $sortorder;
2143 $course->fullname = addslashes($course->fullname);
2144 $course->shortname = addslashes($course->shortname);
2145 $course->summary = addslashes($course->summary);
2146 $course->password = addslashes($course->password);
2147 $course->teacher = addslashes($course->teacher);
2148 $course->teachers = addslashes($course->teachers);
2149 $course->student = addslashes($course->student);
2150 $course->students = addslashes($course->students);
2151
2152 if (!update_record('course', $course)) {
2153 notify("An error occurred - course not moved!");
2154 }
2155 }
2156 }
2157 fix_course_sortorder();
2158 }
2159 return true;
2160}
2161
92890025 2162?>