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