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