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