MDL-10995 eliminated some get course record calls - reused $COURSE instead
[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
89bfeee0 25define('MOD_CLASS_ACTIVITY', 0);
26define('MOD_CLASS_RESOURCE', 1);
27
f9903ed0 28
587510be 29function print_recent_selector_form($course, $advancedfilter=0, $selecteduser=0, $selecteddate="lastlogin",
4581271a 30 $mod="", $modid="activity/All", $modaction="", $selectedgroup="", $selectedsort="default") {
cb83c3cb 31
32 global $USER, $CFG;
33
587510be 34 if ($advancedfilter) {
35
36 // Get all the possible users
37 $users = array();
89adb174 38
65ee9c16 39 if ($courseusers = get_course_users($course->id, '', '', 'u.id, u.firstname, u.lastname')) {
587510be 40 foreach ($courseusers as $courseuser) {
1c45e42e 41 $users[$courseuser->id] = fullname($courseuser, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
587510be 42 }
cb83c3cb 43 }
587510be 44 if ($guest = get_guest()) {
45 $users[$guest->id] = fullname($guest);
46 }
89adb174 47
51792df0 48 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
587510be 49 if ($ccc = get_records("course", "", "", "fullname")) {
50 foreach ($ccc as $cc) {
51 if ($cc->category) {
52 $courses["$cc->id"] = "$cc->fullname";
53 } else {
54 $courses["$cc->id"] = " $cc->fullname (Site)";
89adb174 55 }
587510be 56 }
cb83c3cb 57 }
587510be 58 asort($courses);
59 }
4581271a 60
587510be 61 $activities = array();
cb83c3cb 62
587510be 63 $selectedactivity = $modid;
4581271a 64
fea43a7f 65 /// Casting $course->modinfo to string prevents one notice when the field is null
66 if ($modinfo = unserialize((string)$course->modinfo)) {
587510be 67 $section = 0;
68 if ($course->format == 'weeks') { // Body
69 $strsection = get_string("week");
70 } else {
71 $strsection = get_string("topic");
cb83c3cb 72 }
cb83c3cb 73
587510be 74 $activities["activity/All"] = "All activities";
75 $activities["activity/Assignments"] = "All assignments";
76 $activities["activity/Chats"] = "All chats";
77 $activities["activity/Forums"] = "All forums";
78 $activities["activity/Quizzes"] = "All quizzes";
79 $activities["activity/Workshops"] = "All workshops";
80
81 $activities["section/individual"] = "------------- Individual Activities --------------";
82
83 foreach ($modinfo as $mod) {
84 if ($mod->mod == "label") {
85 continue;
89adb174 86 }
3924b988 87 if (!$mod->visible and !has_capability('moodle/course:viewhiddenactivities',get_context_instance(CONTEXT_MODULE, $mod->cm))) {
9c08ad13 88 continue;
89 }
13534ef7
ML
90 $mod->id = $mod->cm;
91 if (!groups_course_module_visible($mod)) {
92 continue;
93 }
9c08ad13 94
587510be 95 if ($mod->section > 0 and $section <> $mod->section) {
96 $activities["section/$mod->section"] = "-------------- $strsection $mod->section --------------";
97 }
98 $section = $mod->section;
235a4ee8 99 $mod->name = strip_tags(format_string(urldecode($mod->name),true));
587510be 100 if (strlen($mod->name) > 55) {
101 $mod->name = substr($mod->name, 0, 50)."...";
102 }
103 if (!$mod->visible) {
104 $mod->name = "(".$mod->name.")";
105 }
106 $activities["$mod->cm"] = $mod->name;
107
108 if ($mod->cm == $modid) {
109 $selectedactivity = "$mod->cm";
110 }
cb83c3cb 111 }
112 }
cb83c3cb 113
587510be 114 $strftimedate = get_string("strftimedate");
115 $strftimedaydate = get_string("strftimedaydate");
cb83c3cb 116
587510be 117 asort($users);
cb83c3cb 118
587510be 119 // Get all the possible dates
120 // Note that we are keeping track of real (GMT) time and user time
121 // User time is only used in displays - all calcs and passing is GMT
cb83c3cb 122
587510be 123 $timenow = time(); // GMT
cb83c3cb 124
587510be 125 // What day is it now for the user, and when is midnight that day (in GMT).
126 $timemidnight = $today = usergetmidnight($timenow);
cb83c3cb 127
587510be 128 $dates = array();
129 $dates["$USER->lastlogin"] = get_string("lastlogin").", ".userdate($USER->lastlogin, $strftimedate);
130 $dates["$timemidnight"] = get_string("today").", ".userdate($timenow, $strftimedate);
cb83c3cb 131
587510be 132 if (!$course->startdate or ($course->startdate > $timenow)) {
133 $course->startdate = $course->timecreated;
134 }
cb83c3cb 135
587510be 136 $numdates = 1;
137 while ($timemidnight > $course->startdate and $numdates < 365) {
138 $timemidnight = $timemidnight - 86400;
139 $timenow = $timenow - 86400;
140 $dates["$timemidnight"] = userdate($timenow, $strftimedaydate);
141 $numdates++;
142 }
cb83c3cb 143
96dcfb56 144 if ($selecteddate === "lastlogin") {
587510be 145 $selecteddate = $USER->lastlogin;
146 }
147
148 echo '<form action="recent.php" method="get">';
1c919752 149 echo '<input type="hidden" name="chooserecent" value="1" />';
587510be 150 echo "<center>";
151 echo "<table>";
152
51792df0 153 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
587510be 154 echo "<tr><td><b>" . get_string("courses") . "</b></td><td>";
155 choose_from_menu ($courses, "id", $course->id, "");
156 echo "</td></tr>";
157 } else {
1c919752 158 echo '<input type="hidden" name="id" value="'.$course->id.'" />';
587510be 159 }
cb83c3cb 160
f5ffb87d 161 $sortfields = array("default" => get_string("bycourseorder"),"dateasc" => get_string("datemostrecentlast"), "datedesc" => get_string("datemostrecentfirst"));
4581271a 162
587510be 163 echo "<tr><td><b>" . get_string("participants") . "</b></td><td>";
164 choose_from_menu ($users, "user", $selecteduser, get_string("allparticipants") );
165 echo "</td>";
166
1c919752 167 echo '<td align="right"><b>' . get_string("since") . '</b></td><td>';
587510be 168 choose_from_menu ($dates, "date", $selecteddate, get_string("alldays"));
4581271a 169 echo "</td></tr>";
4581271a 170
587510be 171 echo "<tr><td><b>" . get_string("activities") . "</b></td><td>";
172 choose_from_menu ($activities, "modid", $selectedactivity, "");
173 echo "</td>";
4581271a 174
1c919752 175 echo '<td align="right"><b>' . get_string("sortby") . "</b></td><td>";
587510be 176 choose_from_menu ($sortfields, "sortby", $selectedsort, "");
177 echo "</td></tr>";
4581271a 178
587510be 179 echo '<tr>';
4581271a 180
587510be 181 $groupmode = groupmode($course);
4581271a 182
3924b988 183 if ($groupmode == VISIBLEGROUPS or ($groupmode and has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id)))) {
5bf243d1 184 if ($groups = groups_get_all_groups($course->id)) {
185 $group_names = array();
186 foreach($groups as $group) {
187 $group_names[$group->id] = format_string($group->name);
188 }
189 echo '<td><b>';
587510be 190 if ($groupmode == VISIBLEGROUPS) {
191 print_string('groupsvisible');
192 } else {
193 print_string('groupsseparate');
194 }
195 echo ':</b></td><td>';
5bf243d1 196 choose_from_menu($group_names, "selectedgroup", $selectedgroup, get_string("allgroups"), "", "");
587510be 197 echo '</td>';
198 }
199 }
200
201
1c919752 202 echo '<td colspan="2" align="right">';
203 echo '<input type="submit" value="'.get_string('showrecent').'" />';
587510be 204 echo "</td></tr>";
205
206 echo "</table>";
207
839f2456 208 $advancedlink = "<a href=\"$CFG->wwwroot/course/recent.php?id=$course->id&amp;advancedfilter=0\">" . get_string("normalfilter") . "</a>";
587510be 209 print_heading($advancedlink);
210 echo "</center>";
211 echo "</form>";
212
213 } else {
214
215 $day_list = array("1","7","14","21","30");
216 $strsince = get_string("since");
217 $strlastlogin = get_string("lastlogin");
218 $strday = get_string("day");
219 $strdays = get_string("days");
220
221 $heading = "";
222 foreach ($day_list as $count) {
223 if ($count == "1") {
224 $day = $strday;
4581271a 225 } else {
587510be 226 $day = $strdays;
4581271a 227 }
3819ed31 228 $tmpdate = time() - ($count * 3600 * 24);
587510be 229 $heading = $heading .
839f2456 230 "<a href=\"$CFG->wwwroot/course/recent.php?id=$course->id&amp;date=$tmpdate\"> $count $day</a> | ";
4581271a 231 }
4581271a 232
587510be 233 $heading = $strsince . ": <a href=\"$CFG->wwwroot/course/recent.php?id=$course->id\">$strlastlogin</a>" . " | " . $heading;
234 print_heading($heading);
4581271a 235
839f2456 236 $advancedlink = "<a href=\"$CFG->wwwroot/course/recent.php?id=$course->id&amp;advancedfilter=1\">" . get_string("advancedfilter") . "</a>";
587510be 237 print_heading($advancedlink);
238
239 }
4581271a 240
cb83c3cb 241}
9ae687af 242
f9903ed0 243
600149be 244function make_log_url($module, $url) {
245 switch ($module) {
bd7be234 246 case 'user':
247 case 'course':
248 case 'file':
249 case 'login':
250 case 'lib':
251 case 'admin':
252 case 'message':
253 case 'calendar':
bd5d0ce5 254 case 'mnet course':
255 return "/course/$url";
256 break;
bd7be234 257 case 'blog':
600149be 258 return "/$module/$url";
259 break;
bd7be234 260 case 'upload':
261 return $url;
c80b7585 262 break;
bd7be234 263 case 'library':
264 case '':
265 return '/';
de2dfe68 266 break;
600149be 267 default:
268 return "/mod/$module/$url";
269 break;
270 }
271}
272
92890025 273
c215b32b 274function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
275 $modname="", $modid=0, $modaction="", $groupid=0) {
276
277 global $CFG;
278
279 // It is assumed that $date is the GMT time of midnight for that day,
280 // and so the next 86400 seconds worth of logs are printed.
281
282 /// Setup for group handling.
283
284 // TODO: I don't understand group/context/etc. enough to be able to do
285 // something interesting with it here
286 // What is the context of a remote course?
287
288 /// If the group mode is separate, and this user does not have editing privileges,
289 /// then only the user's group can be viewed.
290 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
291 // $groupid = get_current_group($course->id);
292 //}
293 /// If this course doesn't have groups, no groupid can be specified.
294 //else if (!$course->groupmode) {
295 // $groupid = 0;
296 //}
297 $groupid = 0;
298
299 $joins = array();
300
301 $qry = "
302 SELECT
303 l.*,
304 u.firstname,
305 u.lastname,
306 u.picture
307 FROM
308 {$CFG->prefix}mnet_log l
309 LEFT JOIN
310 {$CFG->prefix}user u
311 ON
312 l.userid = u.id
313 WHERE
314 ";
315
316 $where .= "l.hostid = '$hostid'";
317
318 // TODO: Is 1 really a magic number referring to the sitename?
319 if ($course != 1 || $modid != 0) {
320 $where .= " AND\n l.course='$course'";
321 }
322
323 if ($modname) {
324 $where .= " AND\n l.module = '$modname'";
325 }
326
327 if ('site_errors' === $modid) {
328 $where .= " AND\n ( l.action='error' OR l.action='infected' )";
329 } else if ($modid) {
330 //TODO: This assumes that modids are the same across sites... probably
331 //not true
332 $where .= " AND\n l.cmid = '$modid'";
333 }
334
335 if ($modaction) {
336 $firstletter = substr($modaction, 0, 1);
337 if (ctype_alpha($firstletter)) {
338 $where .= " AND\n lower(l.action) LIKE '%" . strtolower($modaction) . "%'";
339 } else if ($firstletter == '-') {
340 $where .= " AND\n lower(l.action) NOT LIKE '%" . strtolower(substr($modaction, 1)) . "%'";
341 }
342 }
343
344 if ($user) {
345 $where .= " AND\n l.userid = '$user'";
346 }
347
348 if ($date) {
349 $enddate = $date + 86400;
350 $where .= " AND\n l.time > '$date' AND l.time < '$enddate'";
351 }
352
353 $result = array();
354 $result['totalcount'] = count_records_sql("SELECT COUNT(*) FROM {$CFG->prefix}mnet_log l WHERE $where");
355 if(!empty($result['totalcount'])) {
356 $where .= "\n ORDER BY\n $order";
357 $result['logs'] = get_records_sql($qry.$where, $limitfrom, $limitnum);
358 } else {
359 $result['logs'] = array();
360 }
361 return $result;
362}
363
92890025 364function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
365 $modname="", $modid=0, $modaction="", $groupid=0) {
f24cffb9 366
e0161bff 367 // It is assumed that $date is the GMT time of midnight for that day,
368 // and so the next 86400 seconds worth of logs are printed.
f9903ed0 369
69c76405 370 /// Setup for group handling.
264867fd 371
69c76405 372 /// If the group mode is separate, and this user does not have editing privileges,
373 /// then only the user's group can be viewed.
3924b988 374 if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
69c76405 375 $groupid = get_current_group($course->id);
376 }
377 /// If this course doesn't have groups, no groupid can be specified.
378 else if (!$course->groupmode) {
379 $groupid = 0;
380 }
381
e0161bff 382 $joins = array();
a2ab3b05 383
e15ef260 384 if ($course->id != SITEID || $modid != 0) {
8f0cd6ef 385 $joins[] = "l.course='$course->id'";
e15ef260 386 }
f9903ed0 387
c469a7ef 388 if ($modname) {
e0161bff 389 $joins[] = "l.module = '$modname'";
f24cffb9 390 }
391
e21922f0 392 if ('site_errors' === $modid) {
bf35eb15 393 $joins[] = "( l.action='error' OR l.action='infected' )";
e21922f0 394 } else if ($modid) {
395 $joins[] = "l.cmid = '$modid'";
69d79bc3 396 }
397
398 if ($modaction) {
ee35e0b8 399 $firstletter = substr($modaction, 0, 1);
400 if (ctype_alpha($firstletter)) {
401 $joins[] = "lower(l.action) LIKE '%" . strtolower($modaction) . "%'";
402 } else if ($firstletter == '-') {
403 $joins[] = "lower(l.action) NOT LIKE '%" . strtolower(substr($modaction, 1)) . "%'";
404 }
f24cffb9 405 }
406
69c76405 407 /// Getting all members of a group.
408 if ($groupid and !$user) {
62d63838 409 if ($gusers = groups_get_members($groupid)) {
410 $gusers = array_keys($gusers);
1e95d7b7 411 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
412 } else {
413 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always by false.
69c76405 414 }
415 }
416 else if ($user) {
e0161bff 417 $joins[] = "l.userid = '$user'";
f9903ed0 418 }
419
420 if ($date) {
421 $enddate = $date + 86400;
e0161bff 422 $joins[] = "l.time > '$date' AND l.time < '$enddate'";
f9903ed0 423 }
424
1e95d7b7 425 $selector = implode(' AND ', $joins);
e0161bff 426
d09f3c80 427 $totalcount = 0; // Initialise
92890025 428 $result = array();
429 $result['logs'] = get_logs($selector, $order, $limitfrom, $limitnum, $totalcount);
430 $result['totalcount'] = $totalcount;
431 return $result;
432}
264867fd 433
434
92890025 435function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
436 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
264867fd 437
92890025 438 global $CFG;
264867fd 439
92890025 440 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
441 $modname, $modid, $modaction, $groupid)) {
f9903ed0 442 notify("No logs found!");
443 print_footer($course);
444 exit;
445 }
264867fd 446
ea49a66c 447 $courses = array();
448
92890025 449 if ($course->id == SITEID) {
450 $courses[0] = '';
ea49a66c 451 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
92890025 452 foreach ($ccc as $cc) {
453 $courses[$cc->id] = $cc->shortname;
454 }
455 }
ea49a66c 456 } else {
457 $courses[$course->id] = $course->shortname;
92890025 458 }
264867fd 459
92890025 460 $totalcount = $logs['totalcount'];
f9903ed0 461 $count=0;
2eb68e6f 462 $ldcache = array();
f9903ed0 463 $tt = getdate(time());
464 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
1c0200e0 465
dcde9f02 466 $strftimedatetime = get_string("strftimedatetime");
467
5577ceb3 468 echo "<div class=\"info\">\n";
519d369f 469 print_string("displayingrecords", "", $totalcount);
5577ceb3 470 echo "</div>\n";
1c0200e0 471
8f0cd6ef 472 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
519d369f 473
56595370 474 echo '<table class="logtable genearlbox boxaligncenter" summary="">'."\n";
475 // echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\" summary=\"\">\n";
21283ddc 476 echo "<tr>";
1548978d 477 if ($course->id == SITEID) {
54926e78 478 echo "<th class=\"c0 header\" scope=\"col\">".get_string('course')."</th>\n";
1548978d 479 }
54926e78 480 echo "<th class=\"c1 header\" scope=\"col\">".get_string('time')."</th>\n";
481 echo "<th class=\"c2 header\" scope=\"col\">".get_string('ip_address')."</th>\n";
482 echo "<th class=\"c3 header\" scope=\"col\">".get_string('fullname')."</th>\n";
483 echo "<th class=\"c4 header\" scope=\"col\">".get_string('action')."</th>\n";
484 echo "<th class=\"c5 header\" scope=\"col\">".get_string('info')."</th>\n";
21283ddc 485 echo "</tr>\n";
1548978d 486
1e95d7b7 487 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
2b2d182a 488 if (empty($logs['logs'])) {
1e95d7b7 489 $logs['logs'] = array();
2b2d182a 490 }
1e95d7b7 491
1548978d 492 $row = 1;
92890025 493 foreach ($logs['logs'] as $log) {
600149be 494
1548978d 495 $row = ($row + 1) % 2;
496
2eb68e6f 497 if (isset($ldcache[$log->module][$log->action])) {
498 $ld = $ldcache[$log->module][$log->action];
499 } else {
1548978d 500 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
2eb68e6f 501 $ldcache[$log->module][$log->action] = $ld;
502 }
edf3ef00 503 if ($ld && is_numeric($log->info)) {
181b888e 504 // ugly hack to make sure fullname is shown correctly
4068bedb 505 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
181b888e 506 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
507 } else {
508 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
509 }
600149be 510 }
511
264867fd 512 //Filter log->info
c8b0a50b 513 $log->info = format_string($log->info);
514
d7d145b1 515 $log->url = strip_tags(urldecode($log->url)); // Some XSS protection
516 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
6ac98433 517 $log->url = str_replace('&', '&amp;', $log->url); /// XHTML compatibility
d7d145b1 518
1548978d 519 echo '<tr class="r'.$row.'">';
520 if ($course->id == SITEID) {
56595370 521 echo "<td class=\"cell c0\">\n";
bd5d0ce5 522 if (empty($log->course)) {
523 echo format_string($log->info)."\n";
524 } else {
525 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course])."</a>\n";
526 }
21283ddc 527 echo "</td>\n";
720a43ce 528 }
56595370 529 echo "<td class=\"cell c1\" align=\"right\">".userdate($log->time, '%a').
21283ddc 530 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
56595370 531 echo "<td class=\"cell c2\">\n";
7eca967c 532 link_to_popup_window("/iplookup/index.php?ip=$log->ip&amp;user=$log->userid", 'iplookup',$log->ip, 400, 700);
21283ddc 533 echo "</td>\n";
1c45e42e 534 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
56595370 535 echo "<td class=\"cell c3\">\n";
d3a75287 536 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}&amp;course={$log->course}\">$fullname</a>\n";
21283ddc 537 echo "</td>\n";
56595370 538 echo "<td class=\"cell c4\">\n";
2eb68e6f 539 link_to_popup_window( make_log_url($log->module,$log->url), 'fromloglive',"$log->module $log->action", 400, 600);
21283ddc 540 echo "</td>\n";;
56595370 541 echo "<td class=\"cell c5\">{$log->info}</td>\n";
21283ddc 542 echo "</tr>\n";
f9903ed0 543 }
21283ddc 544 echo "</table>\n";
519d369f 545
8f0cd6ef 546 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
f9903ed0 547}
548
549
c215b32b 550function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
551 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
552
553 global $CFG;
554
555 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
556 $modname, $modid, $modaction, $groupid)) {
557 notify("No logs found!");
558 print_footer($course);
559 exit;
560 }
561
562 if ($course->id == SITEID) {
563 $courses[0] = '';
564 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
565 foreach ($ccc as $cc) {
566 $courses[$cc->id] = $cc->shortname;
567 }
568 }
569 }
570
571 $totalcount = $logs['totalcount'];
572 $count=0;
573 $ldcache = array();
574 $tt = getdate(time());
575 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
576
577 $strftimedatetime = get_string("strftimedatetime");
578
5577ceb3 579 echo "<div class=\"info\">\n";
c215b32b 580 print_string("displayingrecords", "", $totalcount);
5577ceb3 581 echo "</div>\n";
c215b32b 582
583 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
584
5577ceb3 585 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
c215b32b 586 echo "<tr>";
587 if ($course->id == SITEID) {
588 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
589 }
590 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
591 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
592 echo "<th class=\"c3 header\">".get_string('fullname')."</th>\n";
593 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
594 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
595 echo "</tr>\n";
596
597 if (empty($logs['logs'])) {
598 echo "</table>\n";
599 return;
600 }
601
602 $row = 1;
603 foreach ($logs['logs'] as $log) {
604
605 $log->info = $log->coursename;
606 $row = ($row + 1) % 2;
607
608 if (isset($ldcache[$log->module][$log->action])) {
609 $ld = $ldcache[$log->module][$log->action];
610 } else {
611 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
612 $ldcache[$log->module][$log->action] = $ld;
613 }
614 if (0 && $ld && !empty($log->info)) {
615 // ugly hack to make sure fullname is shown correctly
616 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
617 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
618 } else {
619 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
620 }
621 }
622
623 //Filter log->info
624 $log->info = format_string($log->info);
625
626 $log->url = strip_tags(urldecode($log->url)); // Some XSS protection
627 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
628 $log->url = str_replace('&', '&amp;', $log->url); /// XHTML compatibility
629
630 echo '<tr class="r'.$row.'">';
631 if ($course->id == SITEID) {
5577ceb3 632 echo "<td class=\"r$row c0\" >\n";
c215b32b 633 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courses[$log->course]."</a>\n";
634 echo "</td>\n";
635 }
5577ceb3 636 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time, '%a').
c215b32b 637 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
5577ceb3 638 echo "<td class=\"r$row c2\" >\n";
c215b32b 639 link_to_popup_window("/iplookup/index.php?ip=$log->ip&amp;user=$log->userid", 'iplookup',$log->ip, 400, 700);
640 echo "</td>\n";
641 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
5577ceb3 642 echo "<td class=\"r$row c3\" >\n";
c215b32b 643 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
644 echo "</td>\n";
5577ceb3 645 echo "<td class=\"r$row c4\">\n";
c215b32b 646 echo $log->action .': '.$log->module;
647 echo "</td>\n";;
5577ceb3 648 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
c215b32b 649 echo "</tr>\n";
650 }
651 echo "</table>\n";
652
653 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
654}
655
656
92890025 657function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
658 $modid, $modaction, $groupid) {
4068bedb 659
954fdb42 660 $text = get_string('course')."\t".get_string('time')."\t".get_string('ip_address')."\t".
661 get_string('fullname')."\t".get_string('action')."\t".get_string('info');
264867fd 662
954fdb42 663 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
92890025 664 $modname, $modid, $modaction, $groupid)) {
665 return false;
666 }
264867fd 667
ea49a66c 668 $courses = array();
669
92890025 670 if ($course->id == SITEID) {
671 $courses[0] = '';
672 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
673 foreach ($ccc as $cc) {
674 $courses[$cc->id] = $cc->shortname;
675 }
676 }
ea49a66c 677 } else {
678 $courses[$course->id] = $course->shortname;
92890025 679 }
264867fd 680
92890025 681 $count=0;
682 $ldcache = array();
683 $tt = getdate(time());
684 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
685
686 $strftimedatetime = get_string("strftimedatetime");
92890025 687
954fdb42 688 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
689 $filename .= '.txt';
264867fd 690 header("Content-Type: application/download\n");
954fdb42 691 header("Content-Disposition: attachment; filename=$filename");
692 header("Expires: 0");
693 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
694 header("Pragma: public");
695
696 echo get_string('savedat').userdate(time(), $strftimedatetime)."\n";
697 echo $text;
698
2b2d182a 699 if (empty($logs['logs'])) {
700 return true;
701 }
702
954fdb42 703 foreach ($logs['logs'] as $log) {
704 if (isset($ldcache[$log->module][$log->action])) {
705 $ld = $ldcache[$log->module][$log->action];
706 } else {
707 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
708 $ldcache[$log->module][$log->action] = $ld;
709 }
710 if ($ld && !empty($log->info)) {
711 // ugly hack to make sure fullname is shown correctly
4068bedb 712 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
954fdb42 713 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
714 } else {
715 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
716 }
717 }
718
264867fd 719 //Filter log->info
954fdb42 720 $log->info = format_string($log->info);
721
722 $log->url = strip_tags(urldecode($log->url)); // Some XSS protection
723 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
724 $log->url = str_replace('&', '&amp;', $log->url); // XHTML compatibility
725
726 $firstField = $courses[$log->course];
1c45e42e 727 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
954fdb42 728 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action, $log->info);
729 $text = implode("\t", $row);
730 echo $text." \n";
731 }
732 return true;
92890025 733}
734
735
736function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
737 $modid, $modaction, $groupid) {
264867fd 738
92890025 739 global $CFG;
740
954fdb42 741 require_once("$CFG->libdir/excellib.class.php");
264867fd 742
954fdb42 743 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
92890025 744 $modname, $modid, $modaction, $groupid)) {
745 return false;
746 }
264867fd 747
ea49a66c 748 $courses = array();
749
92890025 750 if ($course->id == SITEID) {
751 $courses[0] = '';
752 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
753 foreach ($ccc as $cc) {
754 $courses[$cc->id] = $cc->shortname;
755 }
756 }
ea49a66c 757 } else {
758 $courses[$course->id] = $course->shortname;
92890025 759 }
264867fd 760
92890025 761 $count=0;
762 $ldcache = array();
763 $tt = getdate(time());
764 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
765
766 $strftimedatetime = get_string("strftimedatetime");
92890025 767
954fdb42 768 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
769 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
770 $filename .= '.xls';
264867fd 771
92890025 772 $workbook = new MoodleExcelWorkbook('-');
773 $workbook->send($filename);
264867fd 774
954fdb42 775 $worksheet = array();
776 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
777 get_string('fullname'), get_string('action'), get_string('info'));
264867fd 778
954fdb42 779 // Creating worksheets
780 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
781 $sheettitle = get_string('excel_sheettitle', 'logs', $wsnumber).$nroPages;
782 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
783 $worksheet[$wsnumber]->set_column(1, 1, 30);
784 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
785 userdate(time(), $strftimedatetime));
786 $col = 0;
787 foreach ($headers as $item) {
788 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
789 $col++;
790 }
791 }
792
2b2d182a 793 if (empty($logs['logs'])) {
794 $workbook->close();
795 return true;
796 }
797
954fdb42 798 $formatDate =& $workbook->add_format();
799 $formatDate->set_num_format(get_string('log_excel_date_format'));
800
801 $row = FIRSTUSEDEXCELROW;
802 $wsnumber = 1;
803 $myxls =& $worksheet[$wsnumber];
804 foreach ($logs['logs'] as $log) {
805 if (isset($ldcache[$log->module][$log->action])) {
806 $ld = $ldcache[$log->module][$log->action];
807 } else {
808 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
809 $ldcache[$log->module][$log->action] = $ld;
810 }
811 if ($ld && !empty($log->info)) {
812 // ugly hack to make sure fullname is shown correctly
4068bedb 813 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
954fdb42 814 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
815 } else {
816 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
817 }
818 }
819
820 // Filter log->info
821 $log->info = format_string($log->info);
822 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
823
824 if ($nroPages>1) {
825 if ($row > EXCELROWS) {
826 $wsnumber++;
827 $myxls =& $worksheet[$wsnumber];
828 $row = FIRSTUSEDEXCELROW;
829 }
830 }
264867fd 831
954fdb42 832 $myxls->write($row, 0, $courses[$log->course], '');
833 // Excel counts from 1/1/1900
834 $excelTime=25569+$log->time/(3600*24);
835 $myxls->write($row, 1, $excelTime, $formatDate);
836 $myxls->write($row, 2, $log->ip, '');
1c45e42e 837 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
954fdb42 838 $myxls->write($row, 3, $fullname, '');
839 $myxls->write($row, 4, $log->module.' '.$log->action, '');
840 $myxls->write($row, 5, $log->info, '');
264867fd 841
954fdb42 842 $row++;
843 }
844
845 $workbook->close();
ea49a66c 846 return true;
847}
848
849function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
850 $modid, $modaction, $groupid) {
851
852 global $CFG;
853
854 require_once("$CFG->libdir/odslib.class.php");
855
856 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
857 $modname, $modid, $modaction, $groupid)) {
858 return false;
859 }
860
861 $courses = array();
862
863 if ($course->id == SITEID) {
864 $courses[0] = '';
865 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
866 foreach ($ccc as $cc) {
867 $courses[$cc->id] = $cc->shortname;
868 }
869 }
870 } else {
871 $courses[$course->id] = $course->shortname;
872 }
873
874 $count=0;
875 $ldcache = array();
876 $tt = getdate(time());
877 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
878
879 $strftimedatetime = get_string("strftimedatetime");
880
881 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
882 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
883 $filename .= '.ods';
884
885 $workbook = new MoodleODSWorkbook('-');
886 $workbook->send($filename);
887
888 $worksheet = array();
889 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
890 get_string('fullname'), get_string('action'), get_string('info'));
891
892 // Creating worksheets
893 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
894 $sheettitle = get_string('excel_sheettitle', 'logs', $wsnumber).$nroPages;
895 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
896 $worksheet[$wsnumber]->set_column(1, 1, 30);
897 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
898 userdate(time(), $strftimedatetime));
899 $col = 0;
900 foreach ($headers as $item) {
901 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
902 $col++;
903 }
904 }
905
906 if (empty($logs['logs'])) {
907 $workbook->close();
908 return true;
909 }
910
911 $formatDate =& $workbook->add_format();
912 $formatDate->set_num_format(get_string('log_excel_date_format'));
913
914 $row = FIRSTUSEDEXCELROW;
915 $wsnumber = 1;
916 $myxls =& $worksheet[$wsnumber];
917 foreach ($logs['logs'] as $log) {
918 if (isset($ldcache[$log->module][$log->action])) {
919 $ld = $ldcache[$log->module][$log->action];
920 } else {
921 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
922 $ldcache[$log->module][$log->action] = $ld;
923 }
924 if ($ld && !empty($log->info)) {
925 // ugly hack to make sure fullname is shown correctly
926 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
927 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
928 } else {
929 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
930 }
931 }
932
933 // Filter log->info
934 $log->info = format_string($log->info);
935 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
936
937 if ($nroPages>1) {
938 if ($row > EXCELROWS) {
939 $wsnumber++;
940 $myxls =& $worksheet[$wsnumber];
941 $row = FIRSTUSEDEXCELROW;
942 }
943 }
944
d81b7ffb 945 $myxls->write_string($row, 0, $courses[$log->course]);
946 $myxls->write_date($row, 1, $log->time);
947 $myxls->write_string($row, 2, $log->ip);
ea49a66c 948 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
d81b7ffb 949 $myxls->write_string($row, 3, $fullname);
950 $myxls->write_string($row, 4, $log->module.' '.$log->action);
951 $myxls->write_string($row, 5, $log->info);
ea49a66c 952
953 $row++;
954 }
955
956 $workbook->close();
954fdb42 957 return true;
92890025 958}
959
92890025 960
c2cb4545 961function print_log_graph($course, $userid=0, $type="course.png", $date=0) {
962 global $CFG;
963 if (empty($CFG->gdversion)) {
964 echo "(".get_string("gdneed").")";
d887b5a7 965 } else {
980a5b3a 966 echo '<img src="'.$CFG->wwwroot.'/course/report/log/graph.php?id='.$course->id.
29b59206 967 '&amp;user='.$userid.'&amp;type='.$type.'&amp;date='.$date.'" alt="" />';
d887b5a7 968 }
969}
970
971
185cfb09 972function print_overview($courses) {
0d6b9d4f 973
974 global $CFG, $USER;
975
185cfb09 976 $htmlarray = array();
f8716988 977 if ($modules = get_records('modules')) {
978 foreach ($modules as $mod) {
979 if (file_exists(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php')) {
980 require_once(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php');
981 $fname = $mod->name.'_print_overview';
0d6b9d4f 982 if (function_exists($fname)) {
185cfb09 983 $fname($courses,$htmlarray);
0d6b9d4f 984 }
985 }
986 }
987 }
185cfb09 988 foreach ($courses as $course) {
fe5a1e23 989 print_simple_box_start('center', '100%', '', 5, "coursebox");
185cfb09 990 $linkcss = '';
991 if (empty($course->visible)) {
992 $linkcss = 'class="dimmed"';
993 }
6ba65fa0 994 print_heading('<a title="'. format_string($course->fullname).'" '.$linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'. format_string($course->fullname).'</a>');
185cfb09 995 if (array_key_exists($course->id,$htmlarray)) {
996 foreach ($htmlarray[$course->id] as $modname => $html) {
997 echo $html;
998 }
999 }
1000 print_simple_box_end();
1001 }
0d6b9d4f 1002}
1003
1004
600149be 1005function print_recent_activity($course) {
1006 // $course is an object
89adb174 1007 // This function trawls through the logs looking for
600149be 1008 // anything new since the user's last login
1009
810393c8 1010 global $CFG, $USER, $SESSION;
600149be 1011
e2a3a0e7 1012 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2ac64806 1013
6f80940b 1014 $timestart = time() - COURSE_MAX_RECENT_PERIOD;
0f87cb1d 1015
e2a3a0e7 1016 if (!has_capability('moodle/legacy:guest', $context, NULL, false)) {
1017 if (!empty($USER->lastcourseaccess[$course->id])) {
1018 if ($USER->lastcourseaccess[$course->id] > $timestart) {
1019 $timestart = $USER->lastcourseaccess[$course->id];
1020 }
9e51847a 1021 }
3d891989 1022 }
0f87cb1d 1023
de785682 1024 echo '<div class="activitydate">';
27bf9e20 1025 echo get_string('activitysince', '', userdate($timestart));
de785682 1026 echo '</div>';
1027 echo '<div class="activityhead">';
0f87cb1d 1028
de785682 1029 echo '<a href="'.$CFG->wwwroot.'/course/recent.php?id='.$course->id.'">'.get_string('recentactivityreport').'</a>';
0f87cb1d 1030
5fc835a5 1031 echo "</div>\n";
0f87cb1d 1032
600149be 1033
1034 // Firstly, have there been any new enrolments?
1035
1036 $heading = false;
1037 $content = false;
1b5910c4 1038
6c38b7e0 1039 $users = get_recent_enrolments($course->id, $timestart);
1b5910c4 1040
5fc835a5 1041 //Accessibility: new users now appear in an <OL> list.
6c38b7e0 1042 if ($users) {
27bf9e20 1043 echo '<div class="newusers">';
5fc835a5 1044 if (! $heading) {
264867fd 1045 print_headline(get_string("newusers").':', 3);
5fc835a5 1046 $heading = true;
1047 $content = true;
1048 }
1049 echo "<ol class=\"list\">\n";
6c38b7e0 1050 foreach ($users as $user) {
264867fd 1051
1c45e42e 1052 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
5fc835a5 1053 echo '<li class="name"><a href="'.$CFG->wwwroot."/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a></li>\n";
600149be 1054 }
5fc835a5 1055 echo "</ol>\n</div>\n";
600149be 1056 }
1057
1b5910c4 1058 // Next, have there been any modifications to the course structure?
1059
27bf9e20 1060 $logs = get_records_select('log', "time > '$timestart' AND course = '$course->id' AND
1b5910c4 1061 module = 'course' AND action LIKE '% mod'", "time ASC");
1062
1063 if ($logs) {
1064 foreach ($logs as $key => $log) {
27bf9e20 1065 $info = split(' ', $log->info);
c9f6251e 1066
27bf9e20 1067 if ($info[0] == 'label') { // Labels are special activities
c9f6251e 1068 continue;
1069 }
1070
27bf9e20 1071 $modname = get_field($info[0], 'name', 'id', $info[1]);
1b5910c4 1072 //Create a temp valid module structure (course,id)
1073 $tempmod->course = $log->course;
1074 $tempmod->id = $info[1];
1075 //Obtain the visible property from the instance
1076 $modvisible = instance_is_visible($info[0],$tempmod);
89adb174 1077
1b5910c4 1078 //Only if the mod is visible
1079 if ($modvisible) {
1080 switch ($log->action) {
27bf9e20 1081 case 'add mod':
1082 $stradded = get_string('added', 'moodle', get_string('modulename', $info[0]));
5847b267 1083 $changelist[$log->info] = array ('operation' => 'add', 'text' => "$stradded:<br /><a href=\"$CFG->wwwroot/course/$log->url\">".format_string($modname,true)."</a>");
1b5910c4 1084 break;
27bf9e20 1085 case 'update mod':
1086 $strupdated = get_string('updated', 'moodle', get_string('modulename', $info[0]));
1087 if (empty($changelist[$log->info])) {
5847b267 1088 $changelist[$log->info] = array ('operation' => 'update', 'text' => "$strupdated:<br /><a href=\"$CFG->wwwroot/course/$log->url\">".format_string($modname,true)."</a>");
1b5910c4 1089 }
1090 break;
27bf9e20 1091 case 'delete mod':
1092 if (!empty($changelist[$log->info]['operation']) and
1093 $changelist[$log->info]['operation'] == 'add') {
1094 $changelist[$log->info] = NULL;
1b5910c4 1095 } else {
27bf9e20 1096 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $info[0]));
1097 $changelist[$log->info] = array ('operation' => 'delete', 'text' => $strdeleted);
1b5910c4 1098 }
1099 break;
600149be 1100 }
ef25340c 1101 }
1102 }
1103 }
1104
9c9f7d77 1105 if (!empty($changelist)) {
ef25340c 1106 foreach ($changelist as $changeinfo => $change) {
1107 if ($change) {
1108 $changes[$changeinfo] = $change;
1109 }
1110 }
8a59942e 1111 if (isset($changes)){
1112 if (count($changes) > 0) {
27bf9e20 1113 print_headline(get_string('courseupdates').':', 3);
8a59942e 1114 $content = true;
1115 foreach ($changes as $changeinfo => $change) {
27bf9e20 1116 echo '<p class="activity">'.$change['text'].'</p>';
8a59942e 1117 }
600149be 1118 }
1119 }
89adb174 1120 }
bf40f9c1 1121
3869a2ac 1122 // Now display new things from each module
600149be 1123
27bf9e20 1124 $mods = get_records('modules', 'visible', '1', 'name', 'id, name');
0fd7da81 1125
e2a3a0e7 1126 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
1127
1b5910c4 1128 foreach ($mods as $mod) { // Each module gets it's own logs and prints them
27bf9e20 1129 include_once($CFG->dirroot.'/mod/'.$mod->name.'/lib.php');
1130 $print_recent_activity = $mod->name.'_print_recent_activity';
1b5910c4 1131 if (function_exists($print_recent_activity)) {
66b0b104 1132 //
1133 // NOTE:
e2a3a0e7 1134 // $isteacher (second parameter below) is to be deprecated!
66b0b104 1135 //
1136 // TODO:
1172e5db 1137 // 1) Make sure that all _print_recent_activity functions are
1138 // not using the $isteacher value.
1139 // 2) Eventually, remove the $isteacher parameter from the
1140 // function calls.
66b0b104 1141 //
e2a3a0e7 1142 $modcontent = $print_recent_activity($course, $viewfullnames, $timestart);
3869a2ac 1143 if ($modcontent) {
1144 $content = true;
600149be 1145 }
600149be 1146 }
1147 }
1148
1149 if (! $content) {
27bf9e20 1150 echo '<p class="message">'.get_string('nothingnew').'</p>';
600149be 1151 }
600149be 1152}
1153
e1360728 1154
d897cae4 1155function get_array_of_activities($courseid) {
89adb174 1156// For a given course, returns an array of course activity objects
d897cae4 1157// Each item in the array contains he following properties:
1158// cm - course module id
1159// mod - name of the module (eg forum)
1160// section - the number of the section (eg week or topic)
1161// name - the name of the instance
5867bfb5 1162// visible - is the instance visible or not
13534ef7
ML
1163// groupingid - grouping id
1164// groupmembersonly - is this instance visible to group members only
86aa7ccf 1165// extra - contains extra string to include in any link
d897cae4 1166
8dddba42 1167 global $CFG;
1168
d897cae4 1169 $mod = array();
1170
9fa49e22 1171 if (!$rawmods = get_course_mods($courseid)) {
d897cae4 1172 return NULL;
1173 }
1174
1175 if ($sections = get_records("course_sections", "course", $courseid, "section ASC")) {
1176 foreach ($sections as $section) {
74666583 1177 if (!empty($section->sequence)) {
d897cae4 1178 $sequence = explode(",", $section->sequence);
1179 foreach ($sequence as $seq) {
7af6281f 1180 if (empty($rawmods[$seq])) {
1181 continue;
1182 }
d897cae4 1183 $mod[$seq]->cm = $rawmods[$seq]->id;
1184 $mod[$seq]->mod = $rawmods[$seq]->modname;
1185 $mod[$seq]->section = $section->section;
1186 $mod[$seq]->name = urlencode(get_field($rawmods[$seq]->modname, "name", "id", $rawmods[$seq]->instance));
fec5a6a6 1187 $mod[$seq]->visible = $rawmods[$seq]->visible;
13534ef7
ML
1188 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
1189 $mod[$seq]->groupmembersonly = $rawmods[$seq]->groupmembersonly;
86aa7ccf 1190 $mod[$seq]->extra = "";
8dddba42 1191
1192 $modname = $mod[$seq]->mod;
1193 $functionname = $modname."_get_coursemodule_info";
1194
1195 include_once("$CFG->dirroot/mod/$modname/lib.php");
1196
1197 if (function_exists($functionname)) {
9d361034 1198 if ($info = $functionname($rawmods[$seq])) {
1199 if (!empty($info->extra)) {
1200 $mod[$seq]->extra = $info->extra;
1201 }
1202 if (!empty($info->icon)) {
1203 $mod[$seq]->icon = $info->icon;
1204 }
c9f6251e 1205 }
1206 }
d897cae4 1207 }
1208 }
1209 }
1210 }
1211 return $mod;
1212}
1213
1214
1215
e1360728 1216
90845098 1217function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
1218// Returns a number of useful structures for course displays
7468bf01 1219
90845098 1220 $mods = NULL; // course modules indexed by id
e0161bff 1221 $modnames = NULL; // all course module names (except resource!)
94361e02 1222 $modnamesplural= NULL; // all course module names (plural form)
90845098 1223 $modnamesused = NULL; // course module names used
7468bf01 1224
9fa49e22 1225 if ($allmods = get_records("modules")) {
90845098 1226 foreach ($allmods as $mod) {
5867bfb5 1227 if ($mod->visible) {
1228 $modnames[$mod->name] = get_string("modulename", "$mod->name");
1229 $modnamesplural[$mod->name] = get_string("modulenameplural", "$mod->name");
1230 }
90845098 1231 }
1232 asort($modnames);
1233 } else {
1234 error("No modules are installed!");
1235 }
1236
9fa49e22 1237 if ($rawmods = get_course_mods($courseid)) {
7468bf01 1238 foreach($rawmods as $mod) { // Index the mods
959ae824 1239 if (empty($modnames[$mod->modname])) {
1240 continue;
1241 }
13534ef7
ML
1242 // Check groupings
1243 if (!groups_course_module_visible($mod)) {
1244 continue;
1245 }
7468bf01 1246 $mods[$mod->id] = $mod;
959ae824 1247 $mods[$mod->id]->modfullname = $modnames[$mod->modname];
3924b988 1248 if ($mod->visible or has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_COURSE, $courseid))) {
959ae824 1249 $modnamesused[$mod->modname] = $modnames[$mod->modname];
1acfbce5 1250 }
7468bf01 1251 }
c7da6f7a 1252 if ($modnamesused) {
1253 asort($modnamesused);
1254 }
7468bf01 1255 }
7468bf01 1256}
1257
9fa49e22 1258
7468bf01 1259function get_all_sections($courseid) {
89adb174 1260
1261 return get_records("course_sections", "course", "$courseid", "section",
7d99d695 1262 "section, id, course, summary, sequence, visible");
7468bf01 1263}
1264
b86fc0e2 1265function course_set_display($courseid, $display=0) {
1266 global $USER;
1267
b86fc0e2 1268 if ($display == "all" or empty($display)) {
1269 $display = 0;
1270 }
1271
7b678e0a 1272 if (empty($USER->id) or $USER->username == 'guest') {
1273 //do not store settings in db for guests
1274 } else if (record_exists("course_display", "userid", $USER->id, "course", $courseid)) {
b86fc0e2 1275 set_field("course_display", "display", $display, "userid", $USER->id, "course", $courseid);
1276 } else {
1277 $record->userid = $USER->id;
1278 $record->course = $courseid;
1279 $record->display = $display;
1280 if (!insert_record("course_display", $record)) {
1281 notify("Could not save your course display!");
1282 }
1283 }
1284
1285 return $USER->display[$courseid] = $display; // Note: = not ==
1286}
1287
7d99d695 1288function set_section_visible($courseid, $sectionnumber, $visibility) {
1289/// For a given course section, markes it visible or hidden,
1290/// and does the same for every activity in that section
1291
1292 if ($section = get_record("course_sections", "course", $courseid, "section", $sectionnumber)) {
1293 set_field("course_sections", "visible", "$visibility", "id", $section->id);
1294 if (!empty($section->sequence)) {
1295 $modules = explode(",", $section->sequence);
1296 foreach ($modules as $moduleid) {
02f66c42 1297 set_coursemodule_visible($moduleid, $visibility, true);
7d99d695 1298 }
1299 }
5867bfb5 1300 rebuild_course_cache($courseid);
7d99d695 1301 }
1302}
ba2e5d73 1303
5e367a2d 1304
d897cae4 1305function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%") {
52dcc2f9 1306/// Prints a section full of activity modules
7977cffd 1307 global $CFG, $USER;
1308
3d575e6f 1309 static $groupbuttons;
32d03b7b 1310 static $groupbuttonslink;
52dcc2f9 1311 static $isteacher;
1312 static $isediting;
7977cffd 1313 static $ismoving;
1314 static $strmovehere;
1315 static $strmovefull;
54669989 1316 static $strunreadpostsone;
52dcc2f9 1317
4877707e 1318 static $untracked;
a2d71d8e 1319 static $usetracking;
4877707e 1320
a22f8313 1321 $labelformatoptions = New stdClass;
110a32e2 1322
52dcc2f9 1323 if (!isset($isteacher)) {
9fd9c29b 1324 $groupbuttons = ($course->groupmode or (!$course->groupmodeforce));
32d03b7b 1325 $groupbuttonslink = (!$course->groupmodeforce);
52dcc2f9 1326 $isediting = isediting($course->id);
ff0c7de0 1327 $ismoving = $isediting && ismoving($course->id);
3d575e6f 1328 if ($ismoving) {
1329 $strmovehere = get_string("movehere");
1330 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1331 }
94a6a70f 1332 include_once($CFG->dirroot.'/mod/forum/lib.php');
1333 if ($usetracking = forum_tp_can_track_forums()) {
a2d71d8e 1334 $strunreadpostsone = get_string('unreadpostsone', 'forum');
94a6a70f 1335 $untracked = forum_tp_get_untracked_forums($USER->id, $course->id);
a2d71d8e 1336 }
7977cffd 1337 }
60bd11cf 1338 $labelformatoptions->noclean = true;
94361e02 1339
fea43a7f 1340/// Casting $course->modinfo to string prevents one notice when the field is null
1341 $modinfo = unserialize((string)$course->modinfo);
94361e02 1342
c6a55371 1343 //Acccessibility: replace table with list <ul>, but don't output empty list.
74666583 1344 if (!empty($section->sequence)) {
94361e02 1345
f2d660dc 1346 // Fix bug #5027, don't want style=\"width:$width\".
1347 echo "<ul class=\"section\">\n";
94361e02 1348 $sectionmods = explode(",", $section->sequence);
1349
1350 foreach ($sectionmods as $modnumber) {
9ae687af 1351 if (empty($mods[$modnumber])) {
1352 continue;
1353 }
94361e02 1354 $mod = $mods[$modnumber];
c9f6251e 1355
07996c8e 1356 if (($mod->visible or has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_COURSE, $course->id))) &&
13534ef7
ML
1357 (!$ismoving || $mod->id != $USER->activitycopy) &&
1358 groups_course_module_visible($mod)) {
954fdb42 1359 echo '<li class="activity '.$mod->modname.'" id="module-'.$modnumber.'">'; // Unique ID
7977cffd 1360 if ($ismoving) {
1c919752 1361 echo '<a title="'.$strmovefull.'"'.
8b92f5bb 1362 ' href="'.$CFG->wwwroot.'/course/mod.php?moveto='.$mod->id.'&amp;sesskey='.$USER->sesskey.'">'.
446390fb 1363 '<img class="movetarget" src="'.$CFG->pixpath.'/movehere.gif" '.
1364 ' alt="'.$strmovehere.'" /></a><br />
1c919752 1365 ';
1acfbce5 1366 }
7977cffd 1367 $instancename = urldecode($modinfo[$modnumber]->name);
954fdb42 1368 $instancename = format_string($instancename, true, $course->id);
c9f6251e 1369
86aa7ccf 1370 if (!empty($modinfo[$modnumber]->extra)) {
1371 $extra = urldecode($modinfo[$modnumber]->extra);
1372 } else {
1373 $extra = "";
1374 }
c9f6251e 1375
9d361034 1376 if (!empty($modinfo[$modnumber]->icon)) {
1377 $icon = "$CFG->pixpath/".urldecode($modinfo[$modnumber]->icon);
1378 } else {
1379 $icon = "$CFG->modpixpath/$mod->modname/icon.gif";
1380 }
1381
aac94fd0 1382 if ($mod->indent) {
1383 print_spacer(12, 20 * $mod->indent, false);
1384 }
1385
c9f6251e 1386 if ($mod->modname == "label") {
aac94fd0 1387 if (!$mod->visible) {
1388 echo "<span class=\"dimmed_text\">";
1389 }
179c9a50 1390 echo format_text($extra, FORMAT_HTML, $labelformatoptions);
aac94fd0 1391 if (!$mod->visible) {
1392 echo "</span>";
1393 }
c9f6251e 1394
1395 } else { // Normal activity
78e4f30a 1396
ccffd412 1397 if (!empty($USER->screenreader)) {
78e4f30a 1398 $typestring = '('.get_string('modulename',$mod->modname).') ';
1399 } else {
1400 $typestring = '';
1401 }
1402
c9f6251e 1403 $linkcss = $mod->visible ? "" : " class=\"dimmed\" ";
1c919752 1404 echo '<img src="'.$icon.'"'.
446390fb 1405 ' class="activityicon" alt="'.$mod->modfullname.'" />'.
1406 ' <a title="'.$mod->modfullname.'" '.$linkcss.' '.$extra.
1c919752 1407 ' href="'.$CFG->wwwroot.'/mod/'.$mod->modname.'/view.php?id='.$mod->id.'">'.
78e4f30a 1408 $typestring.$instancename.'</a>';
c9f6251e 1409 }
a2d71d8e 1410 if ($usetracking && $mod->modname == 'forum') {
f37da850 1411 $groupmode = groupmode($course, $mod);
3924b988 1412 $groupid = ($groupmode == SEPARATEGROUPS && !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) ?
a2d71d8e 1413 get_current_group($course->id) : false;
4877707e 1414
94a6a70f 1415 if (forum_tp_can_track_forums() && !isset($untracked[$mod->instance])) {
4877707e 1416 $unread = forum_tp_count_forum_unread_posts($USER->id, $mod->instance, $groupid);
1417 if ($unread) {
1418 echo '<span class="unread"> <a href="'.$CFG->wwwroot.'/mod/forum/view.php?id='.$mod->id.'">';
1419 if ($unread == 1) {
1420 echo $strunreadpostsone;
1421 } else {
1422 print_string('unreadpostsnumber', 'forum', $unread);
1423 }
1424 echo '</a> </span>';
d0388ebe 1425 }
54669989 1426 }
f37da850 1427 }
1428
c9f6251e 1429 if ($isediting) {
edf3ef00 1430 // TODO: we must define this as mod property!
1431 if ($groupbuttons and $mod->modname != 'label' and $mod->modname != 'resource' and $mod->modname != 'glossary') {
32d03b7b 1432 if (! $mod->groupmodelink = $groupbuttonslink) {
1433 $mod->groupmode = $course->groupmode;
1434 }
1435
1436 } else {
3d575e6f 1437 $mod->groupmode = false;
1438 }
37a88449 1439 echo '&nbsp;&nbsp;';
24e1eae4 1440 echo make_editing_buttons($mod, $absolute, true, $mod->indent, $section->section);
c9f6251e 1441 }
c6a55371 1442 echo "</li>\n";
94361e02 1443 }
94361e02 1444 }
f2d660dc 1445 } elseif ($ismoving) {
1446 echo "<ul class=\"section\">\n";
264867fd 1447 }
7977cffd 1448 if ($ismoving) {
64fdc686 1449 echo '<li><a title="'.$strmovefull.'"'.
8b92f5bb 1450 ' href="'.$CFG->wwwroot.'/course/mod.php?movetosection='.$section->id.'&amp;sesskey='.$USER->sesskey.'">'.
446390fb 1451 '<img class="movetarget" src="'.$CFG->pixpath.'/movehere.gif" '.
c6a55371 1452 ' alt="'.$strmovehere.'" /></a></li>
1c919752 1453 ';
7977cffd 1454 }
c6a55371 1455 if (!empty($section->sequence) || $ismoving) {
1456 echo "</ul><!--class='section'-->\n\n";
1457 }
a7ad3ea6 1458}
1459
89bfeee0 1460/**
1461 * Prints the menus to add activities and resources.
1462 */
cb57e6f4 1463function print_section_add_menus($course, $section, $modnames, $vertical=false, $return=false) {
89bfeee0 1464 global $CFG;
e0161bff 1465
217a8ee9 1466 // check to see if user can add menus
1467 if (!has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $course->id))) {
e2cd3ed0 1468 return false;
217a8ee9 1469 }
1470
89bfeee0 1471 static $resources = false;
1472 static $activities = false;
e0161bff 1473
89bfeee0 1474 if ($resources === false) {
1475 $resources = array();
1476 $activities = array();
6da4b261 1477
89bfeee0 1478 foreach($modnames as $modname=>$modnamestr) {
1479 if (!course_allowed_module($course, $modname)) {
1480 continue;
1481 }
6da4b261 1482
89bfeee0 1483 require_once("$CFG->dirroot/mod/$modname/lib.php");
1484 $gettypesfunc = $modname.'_get_types';
1485 if (function_exists($gettypesfunc)) {
1486 $types = $gettypesfunc();
1487 foreach($types as $type) {
1488 if ($type->modclass == MOD_CLASS_RESOURCE) {
1489 $resources[$type->type] = $type->typestr;
1490 } else {
1491 $activities[$type->type] = $type->typestr;
1492 }
1493 }
1494 } else {
1495 // all mods without type are considered activity
1496 $activities[$modname] = $modnamestr;
1497 }
0705ff84 1498 }
e0161bff 1499 }
1500
89bfeee0 1501 $straddactivity = get_string('addactivity');
1502 $straddresource = get_string('addresource');
1503
4f24b3e3 1504 $output = '<div class="section_add_menus">';
1505
1506 if (!$vertical) {
1507 $output .= '<div class="horizontal">';
1508 }
89bfeee0 1509
1510 if (!empty($resources)) {
1511 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&amp;section=$section&amp;sesskey=".sesskey()."&amp;add=",
0705ff84 1512 $resources, "ressection$section", "", $straddresource, 'resource/types', $straddresource, true);
1513 }
cb57e6f4 1514
89bfeee0 1515 if (!empty($activities)) {
1516 $output .= ' ';
1517 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&amp;section=$section&amp;sesskey=".sesskey()."&amp;add=",
1518 $activities, "section$section", "", $straddactivity, 'mods', $straddactivity, true);
0705ff84 1519 }
1520
4f24b3e3 1521 if (!$vertical) {
d33d0cda 1522 $output .= '</div>';
1523 }
1524
cb57e6f4 1525 $output .= '</div>';
1526
1527 if ($return) {
1528 return $output;
1529 } else {
1530 echo $output;
1531 }
e0161bff 1532}
1533
5867bfb5 1534function rebuild_course_cache($courseid=0) {
1535// Rebuilds the cached list of course activities stored in the database
1536// If a courseid is not specified, then all are rebuilt
1537
1538 if ($courseid) {
1539 $select = "id = '$courseid'";
1540 } else {
1541 $select = "";
6cf890e3 1542 @set_time_limit(0); // this could take a while! MDL-10954
5867bfb5 1543 }
1544
1a31c2b3 1545 if ($courses = get_records_select("course", $select,'','id,fullname')) {
5867bfb5 1546 foreach ($courses as $course) {
1547 $modinfo = serialize(get_array_of_activities($course->id));
1548 if (!set_field("course", "modinfo", $modinfo, "id", $course->id)) {
6ba65fa0 1549 notify("Could not cache module information for course '" . format_string($course->fullname) . "'!");
5867bfb5 1550 }
1551 }
1552 }
1553}
1554
1555
c2cb4545 1556
1557function make_categories_list(&$list, &$parents, $category=NULL, $path="") {
89adb174 1558/// Given an empty array, this function recursively travels the
c2cb4545 1559/// categories, building up a nice list for display. It also makes
1560/// an array that list all the parents for each category.
1561
9d866ae0 1562 // initialize the arrays if needed
1563 if (!is_array($list)) {
264867fd 1564 $list = array();
9d866ae0 1565 }
1566 if (!is_array($parents)) {
264867fd 1567 $parents = array();
9d866ae0 1568 }
1569
c2cb4545 1570 if ($category) {
1571 if ($path) {
6ba65fa0 1572 $path = $path.' / '.format_string($category->name);
c2cb4545 1573 } else {
6ba65fa0 1574 $path = format_string($category->name);
c2cb4545 1575 }
1576 $list[$category->id] = $path;
1577 } else {
1578 $category->id = 0;
1579 }
1580
e05bcf2f 1581 if ($categories = get_categories($category->id)) { // Print all the children recursively
c2cb4545 1582 foreach ($categories as $cat) {
1583 if (!empty($category->id)) {
3bd4de22 1584 if (isset($parents[$category->id])) {
2832badf 1585 $parents[$cat->id] = $parents[$category->id];
1586 }
c2cb4545 1587 $parents[$cat->id][] = $category->id;
1588 }
89adb174 1589 make_categories_list($list, $parents, $cat, $path);
c2cb4545 1590 }
1591 }
1592}
1593
1594
d157bd5b 1595function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $files = true) {
89adb174 1596/// Recursive function to print out all the categories in a nice format
c2cb4545 1597/// with or without courses included
9ff5310a 1598 global $CFG;
e05bcf2f 1599
1600 if (isset($CFG->max_category_depth) && ($depth >= $CFG->max_category_depth)) {
1601 return;
9ff5310a 1602 }
c2cb4545 1603
1604 if (!$displaylist) {
e92fe848 1605 make_categories_list($displaylist, $parentslist);
c2cb4545 1606 }
1607
1608 if ($category) {
ec7a8b79 1609 if ($category->visible or has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
6f24e48e 1610 print_category_info($category, $depth, $files);
c2cb4545 1611 } else {
1612 return; // Don't bother printing children of invisible categories
1613 }
89adb174 1614
c2cb4545 1615 } else {
c2cb4545 1616 $category->id = "0";
1617 }
1618
1619 if ($categories = get_categories($category->id)) { // Print all the children recursively
1620 $countcats = count($categories);
1621 $count = 0;
1622 $first = true;
1623 $last = false;
1624 foreach ($categories as $cat) {
1625 $count++;
1626 if ($count == $countcats) {
1627 $last = true;
1628 }
1629 $up = $first ? false : true;
1630 $down = $last ? false : true;
1631 $first = false;
1632
6f24e48e 1633 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1, $files);
c2cb4545 1634 }
1635 }
c2cb4545 1636}
1637
0705ff84 1638// this function will return $options array for choose_from_menu, with whitespace to denote nesting.
1639
1640function make_categories_options() {
1641 make_categories_list($cats,$parents);
1642 foreach ($cats as $key => $value) {
1643 if (array_key_exists($key,$parents)) {
1644 if ($indent = count($parents[$key])) {
1645 for ($i = 0; $i < $indent; $i++) {
1646 $cats[$key] = '&nbsp;'.$cats[$key];
1647 }
1648 }
1649 }
1650 }
1651 return $cats;
1652}
c2cb4545 1653
6f24e48e 1654function print_category_info($category, $depth, $files = false) {
d2b6ba70 1655/// Prints the category info in indented fashion
1656/// This function is only used by print_whole_category_list() above
c2cb4545 1657
1658 global $CFG;
b48f834c 1659 static $strallowguests, $strrequireskey, $strsummary;
c2cb4545 1660
b48f834c 1661 if (empty($strsummary)) {
e05bcf2f 1662 $strallowguests = get_string('allowguests');
1663 $strrequireskey = get_string('requireskey');
1664 $strsummary = get_string('summary');
b48f834c 1665 }
ba2e5d73 1666
e05bcf2f 1667 $catlinkcss = $category->visible ? '' : ' class="dimmed" ';
d5f26b07 1668
6f24e48e 1669 $coursecount = count_records('course') <= FRONTPAGECOURSELIMIT;
1670 if ($files and $coursecount) {
fcf9577a 1671 $catimage = '<img src="'.$CFG->pixpath.'/i/course.gif" alt="" />';
b48f834c 1672 } else {
7b0b5c14 1673 $catimage = "&nbsp;";
8ef9cb56 1674 }
b48f834c 1675
fcf9577a 1676 echo "\n\n".'<table class="categorylist">';
d2b6ba70 1677
6f24e48e 1678 if ($files and $coursecount) {
19374e76 1679 $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 1680
978abb42 1681 echo '<tr>';
b48f834c 1682
1683 if ($depth) {
1684 $indent = $depth*30;
1685 $rows = count($courses) + 1;
1c919752 1686 echo '<td rowspan="'.$rows.'" valign="top" width="'.$indent.'">';
b48f834c 1687 print_spacer(10, $indent);
e05bcf2f 1688 echo '</td>';
b48f834c 1689 }
89adb174 1690
9deaeaa1 1691 echo '<td valign="top" class="category image">'.$catimage.'</td>';
fcf9577a 1692 echo '<td valign="top" class="category name">';
6ba65fa0 1693 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot.'/course/category.php?id='.$category->id.'">'. format_string($category->name).'</a>';
e05bcf2f 1694 echo '</td>';
290130b3 1695 echo '<td class="category info">&nbsp;</td>';
e05bcf2f 1696 echo '</tr>';
b48f834c 1697
9ff5310a 1698 if ($courses && !(isset($CFG->max_category_depth)&&($depth>=$CFG->max_category_depth-1))) {
c2cb4545 1699 foreach ($courses as $course) {
e05bcf2f 1700 $linkcss = $course->visible ? '' : ' class="dimmed" ';
fcf9577a 1701 echo '<tr><td valign="top">&nbsp;';
1702 echo '</td><td valign="top" class="course name">';
6ba65fa0 1703 echo '<a '.$linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'. format_string($course->fullname).'</a>';
fcf9577a 1704 echo '</td><td align="right" valign="top" class="course info">';
c2cb4545 1705 if ($course->guest ) {
e05bcf2f 1706 echo '<a title="'.$strallowguests.'" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">';
fcf9577a 1707 echo '<img alt="'.$strallowguests.'" src="'.$CFG->pixpath.'/i/guest.gif" /></a>';
ebe8ddc1 1708 } else {
fcf9577a 1709 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath.'/spacer.gif" />';
0c656181 1710 }
c2cb4545 1711 if ($course->password) {
e05bcf2f 1712 echo '<a title="'.$strrequireskey.'" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">';
fcf9577a 1713 echo '<img alt="'.$strrequireskey.'" src="'.$CFG->pixpath.'/i/key.gif" /></a>';
ebe8ddc1 1714 } else {
fcf9577a 1715 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath.'/spacer.gif" />';
b48f834c 1716 }
1717 if ($course->summary) {
e05bcf2f 1718 link_to_popup_window ('/course/info.php?id='.$course->id, 'courseinfo',
fcf9577a 1719 '<img alt="'.$strsummary.'" src="'.$CFG->pixpath.'/i/info.gif" />',
b48f834c 1720 400, 500, $strsummary);
ebe8ddc1 1721 } else {
fcf9577a 1722 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath.'/spacer.gif" />';
0c656181 1723 }
e05bcf2f 1724 echo '</td></tr>';
0c656181 1725 }
ba2e5d73 1726 }
d2b6ba70 1727 } else {
b48f834c 1728
e0140f24 1729 echo '<tr>';
1730
b48f834c 1731 if ($depth) {
1732 $indent = $depth*20;
e05bcf2f 1733 echo '<td valign="top" width="'.$indent.'">';
b48f834c 1734 print_spacer(10, $indent);
e05bcf2f 1735 echo '</td>';
d2b6ba70 1736 }
89adb174 1737
fcf9577a 1738 echo '<td valign="top" class="category name">';
6ba65fa0 1739 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot.'/course/category.php?id='.$category->id.'">'. format_string($category->name).'</a>';
e05bcf2f 1740 echo '</td>';
290130b3 1741 echo '<td valign="top" class="category number">';
e05bcf2f 1742 if ($category->coursecount) {
1743 echo $category->coursecount;
1744 }
1745 echo '</td></tr>';
c2cb4545 1746 }
e05bcf2f 1747 echo '</table>';
c2cb4545 1748}
1749
c2cb4545 1750
35d0244a 1751function print_courses($category, $hidesitecourse = false) {
c2cb4545 1752/// Category is 0 (for all courses) or an object
1753
810393c8 1754 global $CFG;
c2cb4545 1755
1756 if (empty($category)) {
90c2ca2e 1757 $categories = get_categories(0); // Parent = 0 ie top-level categories only
650408a3 1758 if ($categories != null and count($categories) == 1) {
90c2ca2e 1759 $category = array_shift($categories);
32b9a983 1760 $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 1761 } else {
32b9a983 1762 $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 1763 }
1764 unset($categories);
607809b3 1765 } else {
c2cb4545 1766 $categories = get_categories($category->id); // sub categories
32b9a983 1767 $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 1768 }
1769
c2cb4545 1770 if ($courses) {
1771 foreach ($courses as $course) {
1936c10e 1772 if ($hidesitecourse and ($course->id == SITEID)) {
8e227aa7 1773 continue;
1774 }
35d0244a 1775 print_course($course);
c2cb4545 1776 }
1777 } else {
f9667a5a 1778 print_heading(get_string("nocoursesyet"));
954fdb42 1779 $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
0468976c 1780 if (has_capability('moodle/course:create', $context)) {
255d1033 1781 $options = array();
1782 $options['category'] = $category->id;
6b7425d2 1783 echo '<div class="addcoursebutton">';
255d1033 1784 print_single_button($CFG->wwwroot.'/course/edit.php', $options, get_string("addnewcourse"));
1785 echo '</div>';
1786 }
c2cb4545 1787 }
86dd62a7 1788
1789
1790
c2cb4545 1791}
1792
1793
35d0244a 1794function print_course($course) {
c2cb4545 1795
861efb19 1796 global $CFG, $USER;
c2cb4545 1797
88768091 1798 $context = get_context_instance(CONTEXT_COURSE, $course->id);
146bbb8f 1799
88768091 1800 $linkcss = $course->visible ? '' : ' class="dimmed" ';
22288704 1801
afba7be1 1802 echo '<div class="coursebox">';
1803 echo '<div class="info">';
1804 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
e5e81e78 1805 $linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.
6ba65fa0 1806 format_string($course->fullname).'</a></div>';
b06334e8 1807
d42c64ba 1808 /// first find all roles that are supposed to be displayed
1809 if ($managerroles = get_config('', 'coursemanager')) {
6480b0da 1810 $coursemanagerroles = split(',', $managerroles);
e8513d2c 1811 $roles = get_records_select( 'role', '', 'sortorder' );
1812 foreach ($roles as $role) {
1813 if (in_array( $role->id, $coursemanagerroles )) {
1814 if ($users = get_role_users($role->id, $context, true, '', 'u.lastname ASC', true)) {
1815 foreach ($users as $teacher) {
1816 $fullname = fullname($teacher, has_capability('moodle/site:viewfullnames', $context));
1817 $namesarray[] = role_get_name($role, $context).': <a href="'.$CFG->wwwroot.'/user/view.php?id='.
b06334e8 1818 $teacher->id.'&amp;course='.SITEID.'">'.$fullname.'</a>';
e8513d2c 1819 }
1820 }
1821 }
c2cb4545 1822 }
d42c64ba 1823
1824 if (!empty($namesarray)) {
88768091 1825 echo "<ul class=\"teachers\">\n<li>";
1826 echo implode('</li><li>', $namesarray);
1827 echo "</li></ul>";
1828 }
c2cb4545 1829 }
d42c64ba 1830
88768091 1831 require_once("$CFG->dirroot/enrol/enrol.class.php");
1832 $enrol = enrolment_factory::factory($course->enrol);
146bbb8f 1833 echo $enrol->get_access_icons($course);
c2cb4545 1834
afba7be1 1835 echo '</div><div class="summary">';
9f39c190 1836 $options = NULL;
1837 $options->noclean = true;
34b5847a 1838 $options->para = false;
9f39c190 1839 echo format_text($course->summary, FORMAT_MOODLE, $options, $course->id);
afba7be1 1840 echo '</div>';
1841 echo '</div>';
1842 echo '<div class="clearer"></div>';
c2cb4545 1843}
1844
1845
1846function print_my_moodle() {
1847/// Prints custom user information on the home page.
1848/// Over time this can include all sorts of information
1849
1850 global $USER, $CFG;
1851
86a1ba04 1852 if (empty($USER->id)) {
c2cb4545 1853 error("It shouldn't be possible to see My Moodle without being logged in.");
1854 }
1855
86dd62a7 1856 $courses = get_my_courses($USER->id);
1857 $rhosts = array();
1858 $rcourses = array();
36e6379e 1859 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
86dd62a7 1860 $rcourses = get_my_remotecourses($USER->id);
643b67b8 1861 $rhosts = get_my_remotehosts();
86dd62a7 1862 }
1863
1864 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
1865
1866 if (!empty($courses)) {
1867 foreach ($courses as $course) {
1868 if ($course->id == SITEID) {
1869 continue;
1870 }
1871 print_course($course, "100%");
1872 }
1873 }
1874
1875 // MNET
1876 if (!empty($rcourses)) {
1877 // at the IDP, we know of all the remote courses
1878 foreach ($rcourses as $course) {
1879 print_remote_course($course, "100%");
1880 }
1881 } elseif (!empty($rhosts)) {
1882 // non-IDP, we know of all the remote servers, but not courses
1883 foreach ($rhosts as $host) {
643b67b8 1884 print_remote_host($host, "100%");
c81696e5 1885 }
c2cb4545 1886 }
86dd62a7 1887 unset($course);
1888 unset($host);
38a10939 1889
7f989948 1890 if (count_records("course") > (count($courses) + 1) ) { // Some courses not being displayed
1891 echo "<table width=\"100%\"><tr><td align=\"center\">";
1892 print_course_search("", false, "short");
1893 echo "</td><td align=\"center\">";
1894 print_single_button("$CFG->wwwroot/course/index.php", NULL, get_string("fulllistofcourses"), "get");
1895 echo "</td></tr></table>\n";
1896 }
86dd62a7 1897
26330001 1898 } else {
1899 if (count_records("course_categories") > 1) {
cb29b020 1900 print_simple_box_start("center", "100%", "#FFFFFF", 5, "categorybox");
26330001 1901 print_whole_category_list();
1902 print_simple_box_end();
1903 } else {
35d0244a 1904 print_courses(0);
26330001 1905 }
607809b3 1906 }
2b8cef80 1907}
1908
11b0c469 1909
a8b56716 1910function print_course_search($value="", $return=false, $format="plain") {
38a10939 1911
1912 global $CFG;
1e0fb105 1913 static $count = 0;
1914
1915 $count++;
1916
1917 $id = 'coursesearch';
1918
1919 if ($count > 1) {
1920 $id .= $count;
1921 }
38a10939 1922
1923 $strsearchcourses= get_string("searchcourses");
1924
1c919752 1925 if ($format == 'plain') {
1e0fb105 1926 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
fcf9577a 1927 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
e42f4d92 1928 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
1929 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
1930 $output .= '<input type="submit" value="'.get_string('go').'" />';
fcf9577a 1931 $output .= '</fieldset></form>';
1c919752 1932 } else if ($format == 'short') {
1e0fb105 1933 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
fcf9577a 1934 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
e42f4d92 1935 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
1936 $output .= '<input type="text" id="coursesearchbox" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
1937 $output .= '<input type="submit" value="'.get_string('go').'" />';
fcf9577a 1938 $output .= '</fieldset></form>';
1c919752 1939 } else if ($format == 'navbar') {
fcf9577a 1940 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
1941 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
e42f4d92 1942 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
1943 $output .= '<input type="text" id="coursesearchbox" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
1944 $output .= '<input type="submit" value="'.get_string('go').'" />';
fcf9577a 1945 $output .= '</fieldset></form>';
a8b56716 1946 }
1947
1948 if ($return) {
1949 return $output;
1950 }
1951 echo $output;
38a10939 1952}
11b0c469 1953
86dd62a7 1954function print_remote_course($course, $width="100%") {
1955
1956 global $CFG, $USER;
1957
1958 $linkcss = '';
1959
1960 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&amp;wantsurl=/course/view.php?id={$course->remoteid}";
1961
643b67b8 1962 echo '<div class="coursebox remotecoursebox">';
86dd62a7 1963 echo '<div class="info">';
1964 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
1965 $linkcss.' href="'.$url.'">'
6ba65fa0 1966 . format_string($course->fullname) .'</a><br />'
1967 . format_string($course->hostname) . ' : '
1968 . format_string($course->cat_name) . ' : '
1969 . format_string($course->shortname). '</div>';
86dd62a7 1970 echo '</div><div class="summary">';
1971 $options = NULL;
1972 $options->noclean = true;
1973 $options->para = false;
1974 echo format_text($course->summary, FORMAT_MOODLE, $options);
1975 echo '</div>';
1976 echo '</div>';
1977 echo '<div class="clearer"></div>';
1978}
1979
643b67b8 1980function print_remote_host($host, $width="100%") {
1981
1982 global $CFG, $USER;
1983
1984 $linkcss = '';
1985
1986 echo '<div class="coursebox">';
1987 echo '<div class="info">';
1988 echo '<div class="name">';
1989 echo '<img src="'.$CFG->pixpath.'/i/mnethost.gif" class="icon" alt="'.get_string('course').'" />';
1990 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
1991 . s($host['name']).'</a> - ';
1fd80ad3 1992 echo $host['count'] . ' ' . get_string('courses');
643b67b8 1993 echo '</div>';
1994 echo '</div>';
caa90d56 1995 echo '</div>';
643b67b8 1996 echo '<div class="clearer"></div>';
1997}
1998
86dd62a7 1999
11b0c469 2000/// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2001
2002function add_course_module($mod) {
11b0c469 2003
e5dfd0f3 2004 $mod->added = time();
53f4ad2c 2005 unset($mod->id);
11b0c469 2006
e5dfd0f3 2007 return insert_record("course_modules", $mod);
11b0c469 2008}
2009
7977cffd 2010function add_mod_to_section($mod, $beforemod=NULL) {
2011/// Given a full mod object with section and course already defined
2012/// If $before is specified, then this is an existing ID which we
2013/// will insert the new module before
2014///
2015/// Returns the course_sections ID where the mod is inserted
11b0c469 2016
9fa49e22 2017 if ($section = get_record("course_sections", "course", "$mod->course", "section", "$mod->section")) {
7977cffd 2018
2019 $section->sequence = trim($section->sequence);
2020
2021 if (empty($section->sequence)) {
11b0c469 2022 $newsequence = "$mod->coursemodule";
7977cffd 2023
2024 } else if ($beforemod) {
2025 $modarray = explode(",", $section->sequence);
2026
2027 if ($key = array_keys ($modarray, $beforemod->id)) {
2028 $insertarray = array($mod->id, $beforemod->id);
2029 array_splice($modarray, $key[0], 1, $insertarray);
2030 $newsequence = implode(",", $modarray);
2031
2032 } else { // Just tack it on the end anyway
2033 $newsequence = "$section->sequence,$mod->coursemodule";
2034 }
2035
2036 } else {
2037 $newsequence = "$section->sequence,$mod->coursemodule";
11b0c469 2038 }
89adb174 2039
e5dfd0f3 2040 if (set_field("course_sections", "sequence", $newsequence, "id", $section->id)) {
2041 return $section->id; // Return course_sections ID that was used.
11b0c469 2042 } else {
e5dfd0f3 2043 return 0;
11b0c469 2044 }
89adb174 2045
11b0c469 2046 } else { // Insert a new record
e5dfd0f3 2047 $section->course = $mod->course;
2048 $section->section = $mod->section;
2049 $section->summary = "";
2050 $section->sequence = $mod->coursemodule;
2051 return insert_record("course_sections", $section);
11b0c469 2052 }
2053}
2054
48e535bc 2055function set_coursemodule_groupmode($id, $groupmode) {
3d575e6f 2056 return set_field("course_modules", "groupmode", $groupmode, "id", $id);
2057}
2058
24f41672 2059function set_coursemodule_groupingid($id, $groupingid) {
2060 return set_field("course_modules", "groupingid", $groupingid, "id", $id);
2061}
2062
2063function set_coursemodule_groupmembersonly($id, $groupmembersonly) {
2064 return set_field("course_modules", "groupmembersonly", $groupmembersonly, "id", $id);
2065}
2066
177d4abf 2067function set_coursemodule_idnumber($id, $idnumber) {
2068 return set_field("course_modules", "idnumber", $idnumber, "id", $id);
2069}
02f66c42 2070/**
2071* $prevstateoverrides = true will set the visibility of the course module
2072* to what is defined in visibleold. This enables us to remember the current
2073* visibility when making a whole section hidden, so that when we toggle
2074* that section back to visible, we are able to return the visibility of
2075* the course module back to what it was originally.
2076*/
2077function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
978abb42 2078 if (!$cm = get_record('course_modules', 'id', $id)) {
2079 return false;
2080 }
2081 if (!$modulename = get_field('modules', 'name', 'id', $cm->module)) {
2082 return false;
2083 }
dcd338ff 2084 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
2085 foreach($events as $event) {
48e535bc 2086 if ($visible) {
2087 show_event($event);
2088 } else {
2089 hide_event($event);
2090 }
dcd338ff 2091 }
2092 }
02f66c42 2093 if ($prevstateoverrides) {
2094 if ($visible == '0') {
2095 // Remember the current visible state so we can toggle this back.
2096 set_field('course_modules', 'visibleold', $cm->visible, 'id', $id);
2097 } else {
2098 // Get the previous saved visible states.
2099 return set_field('course_modules', 'visible', $cm->visibleold, 'id', $id);
2100 }
2101 }
48e535bc 2102 return set_field("course_modules", "visible", $visible, "id", $id);
1acfbce5 2103}
2104
290130b3 2105/*
2106 * Delete a course module and any associated data at the course level (events)
264867fd 2107 * Until 1.5 this function simply marked a deleted flag ... now it
290130b3 2108 * deletes it completely.
2109 *
2110 */
48e535bc 2111function delete_course_module($id) {
f615fbab 2112 global $CFG;
2113 require_once($CFG->libdir.'/gradelib.php');
2114
290130b3 2115 if (!$cm = get_record('course_modules', 'id', $id)) {
2116 return true;
2117 }
dcd338ff 2118 $modulename = get_field('modules', 'name', 'id', $cm->module);
f615fbab 2119 //delete events from calendar
dcd338ff 2120 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
2121 foreach($events as $event) {
0ea03696 2122 delete_event($event->id);
dcd338ff 2123 }
2124 }
f615fbab 2125 //delete grade items, outcome items and grades attached to modules
2126 if ($grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2127 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course))) {
2128 foreach ($grade_items as $grade_item) {
2129 $grade_item->delete('moddelete');
2130 }
2131
2132 }
290130b3 2133 return delete_records('course_modules', 'id', $cm->id);
11b0c469 2134}
2135
2136function delete_mod_from_section($mod, $section) {
11b0c469 2137
e5dfd0f3 2138 if ($section = get_record("course_sections", "id", "$section") ) {
11b0c469 2139
e5dfd0f3 2140 $modarray = explode(",", $section->sequence);
11b0c469 2141
2142 if ($key = array_keys ($modarray, $mod)) {
2143 array_splice($modarray, $key[0], 1);
2144 $newsequence = implode(",", $modarray);
e5dfd0f3 2145 return set_field("course_sections", "sequence", $newsequence, "id", $section->id);
11b0c469 2146 } else {
2147 return false;
2148 }
89adb174 2149
11b0c469 2150 }
7977cffd 2151 return false;
11b0c469 2152}
2153
12905134 2154function move_section($course, $section, $move) {
2155/// Moves a whole course section up and down within the course
798b70a1 2156 global $USER;
12905134 2157
2158 if (!$move) {
2159 return true;
2160 }
2161
2162 $sectiondest = $section + $move;
2163
2164 if ($sectiondest > $course->numsections or $sectiondest < 1) {
2165 return false;
2166 }
2167
2168 if (!$sectionrecord = get_record("course_sections", "course", $course->id, "section", $section)) {
2169 return false;
2170 }
2171
2172 if (!$sectiondestrecord = get_record("course_sections", "course", $course->id, "section", $sectiondest)) {
2173 return false;
2174 }
2175
56e34ee4 2176 if (!set_field("course_sections", "section", $sectiondest, "id", $sectionrecord->id)) {
12905134 2177 return false;
2178 }
56e34ee4 2179 if (!set_field("course_sections", "section", $section, "id", $sectiondestrecord->id)) {
12905134 2180 return false;
2181 }
798b70a1 2182 // if the focus is on the section that is being moved, then move the focus along
2183 if (isset($USER->display[$course->id]) and ($USER->display[$course->id] == $section)) {
2184 course_set_display($course->id, $sectiondest);
2185 }
5390cbb7 2186
a987106d 2187 // Check for duplicates and fix order if needed.
5390cbb7 2188 // There is a very rare case that some sections in the same course have the same section id.
a987106d 2189 $sections = get_records_select('course_sections', "course = $course->id", 'section ASC');
2190 $n = 0;
2191 foreach ($sections as $section) {
2192 if ($section->section != $n) {
5390cbb7 2193 if (!set_field('course_sections', 'section', $n, 'id', $section->id)) {
2194 return false;
2195 }
5390cbb7 2196 }
a987106d 2197 $n++;
5390cbb7 2198 }
12905134 2199 return true;
2200}
2201
2202
7977cffd 2203function moveto_module($mod, $section, $beforemod=NULL) {
2204/// All parameters are objects
2205/// Move the module object $mod to the specified $section
2206/// If $beforemod exists then that is the module
2207/// before which $modid should be inserted
2208
2209/// Remove original module from original section
2210
2211 if (! delete_mod_from_section($mod->id, $mod->section)) {
2212 notify("Could not delete module from existing section");
2213 }
2214
2215/// Update module itself if necessary
2216
2217 if ($mod->section != $section->id) {
89adb174 2218 $mod->section = $section->id;
7977cffd 2219 if (!update_record("course_modules", $mod)) {
2220 return false;
2221 }
48e535bc 2222 // if moving to a hidden section then hide module
2223 if (!$section->visible) {
2224 set_coursemodule_visible($mod->id, 0);
2225 }
7977cffd 2226 }
2227
2228/// Add the module into the new section
2229
2230 $mod->course = $section->course;
2231 $mod->section = $section->section; // need relative reference
2232 $mod->coursemodule = $mod->id;
2233
2234 if (! add_mod_to_section($mod, $beforemod)) {
2235 return false;
2236 }
2237
2238 return true;
2239
2240}
2241
24e1eae4 2242function make_editing_buttons($mod, $absolute=false, $moveselect=true, $indent=-1, $section=-1) {
810393c8 2243 global $CFG, $USER;
94361e02 2244
3d575e6f 2245 static $str;
37a88449 2246 static $sesskey;
3d575e6f 2247
217a8ee9 2248 $modcontext = get_context_instance(CONTEXT_MODULE, $mod->id);
2249 // no permission to edit
2250 if (!has_capability('moodle/course:manageactivities', $modcontext)) {
e2cd3ed0 2251 return false;
217a8ee9 2252 }
2253
3d575e6f 2254 if (!isset($str)) {
90ebdf65 2255 $str->delete = get_string("delete");
2256 $str->move = get_string("move");
2257 $str->moveup = get_string("moveup");
2258 $str->movedown = get_string("movedown");
2259 $str->moveright = get_string("moveright");
2260 $str->moveleft = get_string("moveleft");
2261 $str->update = get_string("update");
2262 $str->duplicate = get_string("duplicate");
2263 $str->hide = get_string("hide");
2264 $str->show = get_string("show");
3d575e6f 2265 $str->clicktochange = get_string("clicktochange");
32d03b7b 2266 $str->forcedmode = get_string("forcedmode");
3d575e6f 2267 $str->groupsnone = get_string("groupsnone");
2268 $str->groupsseparate = get_string("groupsseparate");
2269 $str->groupsvisible = get_string("groupsvisible");
37a88449 2270 $sesskey = sesskey();
1acfbce5 2271 }
94361e02 2272
24e1eae4 2273 if ($section >= 0) {
75f087b6 2274 $section = '&amp;sr='.$section; // Section return
24e1eae4 2275 } else {
2276 $section = '';
2277 }
2278
94361e02 2279 if ($absolute) {
37a88449 2280 $path = $CFG->wwwroot.'/course';
dc0dc7d5 2281 } else {
37a88449 2282 $path = '.';
dc0dc7d5 2283 }
2284
217a8ee9 2285 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
2286 if ($mod->visible) {
2287 $hideshow = '<a class="editing_hide" title="'.$str->hide.'" href="'.$path.'/mod.php?hide='.$mod->id.
2288 '&amp;sesskey='.$sesskey.$section.'"><img'.
2289 ' src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" '.
2290 ' alt="'.$str->hide.'" /></a>'."\n";
2291 } else {
2292 $hideshow = '<a class="editing_show" title="'.$str->show.'" href="'.$path.'/mod.php?show='.$mod->id.
2293 '&amp;sesskey='.$sesskey.$section.'"><img'.
2294 ' src="'.$CFG->pixpath.'/t/show.gif" class="iconsmall" '.
2295 ' alt="'.$str->show.'" /></a>'."\n";
2296 }
7977cffd 2297 }
3d575e6f 2298 if ($mod->groupmode !== false) {
2299 if ($mod->groupmode == SEPARATEGROUPS) {
32d03b7b 2300 $grouptitle = $str->groupsseparate;
cddbd5d5 2301 $groupclass = 'editing_groupsseparate';
37a88449 2302 $groupimage = $CFG->pixpath.'/t/groups.gif';
2303 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=0&amp;sesskey='.$sesskey;
3d575e6f 2304 } else if ($mod->groupmode == VISIBLEGROUPS) {
32d03b7b 2305 $grouptitle = $str->groupsvisible;
cddbd5d5 2306 $groupclass = 'editing_groupsvisible';
37a88449 2307 $groupimage = $CFG->pixpath.'/t/groupv.gif';
2308 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=1&amp;sesskey='.$sesskey;
32d03b7b 2309 } else {
2310 $grouptitle = $str->groupsnone;
90ebdf65 2311 $groupclass = 'editing_groupsnone';
37a88449 2312 $groupimage = $CFG->pixpath.'/t/groupn.gif';
2313 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=2&amp;sesskey='.$sesskey;
32d03b7b 2314 }
2315 if ($mod->groupmodelink) {
90ebdf65 2316 $groupmode = '<a class="'.$groupclass.'" title="'.$grouptitle.' ('.$str->clicktochange.')" href="'.$grouplink.'">'.
0d905d9f 2317 '<img src="'.$groupimage.'" class="iconsmall" '.
2318 'alt="'.$grouptitle.'" /></a>';
3d575e6f 2319 } else {
37a88449 2320 $groupmode = '<img title="'.$grouptitle.' ('.$str->forcedmode.')" '.
0d905d9f 2321 ' src="'.$groupimage.'" class="iconsmall" '.
2322 'alt="'.$grouptitle.'" />';
3d575e6f 2323 }
2324 } else {
2325 $groupmode = "";
2326 }
e2cd3ed0 2327
217a8ee9 2328 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $mod->course))) {
2329 if ($moveselect) {
2330 $move = '<a class="editing_move" title="'.$str->move.'" href="'.$path.'/mod.php?copy='.$mod->id.
2331 '&amp;sesskey='.$sesskey.$section.'"><img'.
2332 ' src="'.$CFG->pixpath.'/t/move.gif" class="iconsmall" '.
2333 ' alt="'.$str->move.'" /></a>'."\n";
2334 } else {
2335 $move = '<a class="editing_moveup" title="'.$str->moveup.'" href="'.$path.'/mod.php?id='.$mod->id.
2336 '&amp;move=-1&amp;sesskey='.$sesskey.$section.'"><img'.
2337 ' src="'.$CFG->pixpath.'/t/up.gif" class="iconsmall" '.
2338 ' alt="'.$str->moveup.'" /></a>'."\n".
2339 '<a class="editing_movedown" title="'.$str->movedown.'" href="'.$path.'/mod.php?id='.$mod->id.
2340 '&amp;move=1&amp;sesskey='.$sesskey.$section.'"><img'.
2341 ' src="'.$CFG->pixpath.'/t/down.gif" class="iconsmall" '.
2342 ' alt="'.$str->movedown.'" /></a>'."\n";
2343 }
7b44777e 2344 } else {
2345 $move = '';
7977cffd 2346 }
2347
932be046 2348 $leftright = '';
217a8ee9 2349 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $mod->course))) {
932be046 2350
8047ab1d 2351 if (right_to_left()) { // Exchange arrows on RTL
932be046 2352 $rightarrow = 'left.gif';
2353 $leftarrow = 'right.gif';
2354 } else {
2355 $rightarrow = 'right.gif';
2356 $leftarrow = 'left.gif';
2357 }
2358
217a8ee9 2359 if ($indent > 0) {
2360 $leftright .= '<a class="editing_moveleft" title="'.$str->moveleft.'" href="'.$path.'/mod.php?id='.$mod->id.
2361 '&amp;indent=-1&amp;sesskey='.$sesskey.$section.'"><img'.
932be046 2362 ' src="'.$CFG->pixpath.'/t/'.$leftarrow.'" class="iconsmall" '.
217a8ee9 2363 ' alt="'.$str->moveleft.'" /></a>'."\n";
2364 }
2365 if ($indent >= 0) {
2366 $leftright .= '<a class="editing_moveright" title="'.$str->moveright.'" href="'.$path.'/mod.php?id='.$mod->id.
2367 '&amp;indent=1&amp;sesskey='.$sesskey.$section.'"><img'.
932be046 2368 ' src="'.$CFG->pixpath.'/t/'.$rightarrow.'" class="iconsmall" '.
217a8ee9 2369 ' alt="'.$str->moveright.'" /></a>'."\n";
2370 }
37a88449 2371 }
2372
90ebdf65 2373 return '<span class="commands">'."\n".$leftright.$move.
2374 '<a class="editing_update" title="'.$str->update.'" href="'.$path.'/mod.php?update='.$mod->id.
37a88449 2375 '&amp;sesskey='.$sesskey.$section.'"><img'.
0d905d9f 2376 ' src="'.$CFG->pixpath.'/t/edit.gif" class="iconsmall" '.
90ebdf65 2377 ' alt="'.$str->update.'" /></a>'."\n".
2378 '<a class="editing_delete" title="'.$str->delete.'" href="'.$path.'/mod.php?delete='.$mod->id.
37a88449 2379 '&amp;sesskey='.$sesskey.$section.'"><img'.
0d905d9f 2380 ' src="'.$CFG->pixpath.'/t/delete.gif" class="iconsmall" '.
90ebdf65 2381 ' alt="'.$str->delete.'" /></a>'."\n".$hideshow.$groupmode."\n".'</span>';
90845098 2382}
2383
b61efafb 2384/**
264867fd 2385 * given a course object with shortname & fullname, this function will
b61efafb 2386 * truncate the the number of chars allowed and add ... if it was too long
2387 */
2388function course_format_name ($course,$max=100) {
264867fd 2389
6ba65fa0 2390 $str = $course->shortname.': '. $course->fullname;
b61efafb 2391 if (strlen($str) <= $max) {
2392 return $str;
2393 }
2394 else {
2395 return substr($str,0,$max-3).'...';
2396 }
2397}
2398
2399/**
2400 * This function will return true if the given course is a child course at all
2401 */
2402function course_in_meta ($course) {
5f37b628 2403 return record_exists("course_meta","child_course",$course->id);
b61efafb 2404}
2405
48e535bc 2406
2407/**
2408 * Print standard form elements on module setup forms in mod/.../mod.html
2409 */
2410function print_standard_coursemodule_settings($form) {
da2224f8 2411 if (! $course = get_record('course', 'id', $form->course)) {
2412 error("This course doesn't exist");
2413 }
2414 print_groupmode_setting($form, $course);
2415 print_visible_setting($form, $course);
48e535bc 2416}
2417
2418/**
2419 * Print groupmode form element on module setup forms in mod/.../mod.html
2420 */
5ebb746b 2421function print_groupmode_setting($form, $course=NULL) {
48e535bc 2422
5ebb746b 2423 if (empty($course)) {
2424 if (! $course = get_record('course', 'id', $form->course)) {
2425 error("This course doesn't exist");
2426 }
2427 }
48e535bc 2428 if ($form->coursemodule) {
2429 if (! $cm = get_record('course_modules', 'id', $form->coursemodule)) {
2430 error("This course module doesn't exist");
2431 }
2432 } else {
2433 $cm = null;
2434 }
2435 $groupmode = groupmode($course, $cm);
2436 if ($course->groupmode or (!$course->groupmodeforce)) {
2437 echo '<tr valign="top">';
2438 echo '<td align="right"><b>'.get_string('groupmode').':</b></td>';
7bbe08a2 2439 echo '<td align="left">';
48e535bc 2440 unset($choices);
2441 $choices[NOGROUPS] = get_string('groupsnone');
2442 $choices[SEPARATEGROUPS] = get_string('groupsseparate');
2443 $choices[VISIBLEGROUPS] = get_string('groupsvisible');
2444 choose_from_menu($choices, 'groupmode', $groupmode, '', '', 0, false, $course->groupmodeforce);
2445 helpbutton('groupmode', get_string('groupmode'));
2446 echo '</td></tr>';
2447 }
2448}
2449
2450/**
2451 * Print visibility setting form element on module setup forms in mod/.../mod.html
2452 */
5ebb746b 2453function print_visible_setting($form, $course=NULL) {
1ee55c41 2454 if (empty($course)) {
2455 if (! $course = get_record('course', 'id', $form->course)) {
2456 error("This course doesn't exist");
2457 }
2458 }
48e535bc 2459 if ($form->coursemodule) {
2460 $visible = get_field('course_modules', 'visible', 'id', $form->coursemodule);
2461 } else {
2462 $visible = true;
2463 }
2464
2465 if ($form->mode == 'add') { // in this case $form->section is the section number, not the id
2466 $hiddensection = !get_field('course_sections', 'visible', 'section', $form->section, 'course', $form->course);
2467 } else {
2468 $hiddensection = !get_field('course_sections', 'visible', 'id', $form->section);
2469 }
2470 if ($hiddensection) {
2471 $visible = false;
2472 }
264867fd 2473
48e535bc 2474 echo '<tr valign="top">';
182311e4 2475 echo '<td align="right"><b>'.get_string('visible', '').':</b></td>';
7bbe08a2 2476 echo '<td align="left">';
48e535bc 2477 unset($choices);
1f15db9d 2478 $choices[1] = get_string('show');
2479 $choices[0] = get_string('hide');
48e535bc 2480 choose_from_menu($choices, 'visible', $visible, '', '', 0, false, $hiddensection);
2481 echo '</td></tr>';
264867fd 2482}
48e535bc 2483
0705ff84 2484function update_restricted_mods($course,$mods) {
2485 delete_records("course_allowed_modules","course",$course->id);
2486 if (empty($course->restrictmodules)) {
2487 return;
2488 }
2489 else {
2490 foreach ($mods as $mod) {
2491 if ($mod == 0)
2492 continue; // this is the 'allow none' option
2493 $am->course = $course->id;
2494 $am->module = $mod;
2495 insert_record("course_allowed_modules",$am);
2496 }
2497 }
2498}
2499
2500/**
2501 * This function will take an int (module id) or a string (module name)
2502 * and return true or false, whether it's allowed in the given course (object)
264867fd 2503 * $mod is not allowed to be an object, as the field for the module id is inconsistent
0705ff84 2504 * depending on where in the code it's called from (sometimes $mod->id, sometimes $mod->module)
2505 */
2506
2507function course_allowed_module($course,$mod) {
2508 if (empty($course->restrictmodules)) {
2509 return true;
2510 }
264867fd 2511
51792df0 2512 // i am not sure this capability is correct
2513 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
0705ff84 2514 return true;
2515 }
2516 if (is_numeric($mod)) {
2517 $modid = $mod;
2518 } else if (is_string($mod)) {
cb77cf12 2519 if ($mod = get_field("modules","id","name",$mod))
0705ff84 2520 $modid = $mod;
2521 }
2522 if (empty($modid)) {
2523 return false;
2524 }
2525 return (record_exists("course_allowed_modules","course",$course->id,"module",$modid));
2526}
2527
861efb19 2528/***
2529 *** Efficiently moves many courses around while maintaining
2530 *** sortorder in order.
264867fd 2531 ***
861efb19 2532 *** $courseids is an array of course ids
2533 ***
2534 **/
2535
2536function move_courses ($courseids, $categoryid) {
2537
2538 global $CFG;
2539
2540 if (!empty($courseids)) {
264867fd 2541
2542 $courseids = array_reverse($courseids);
861efb19 2543
2544 foreach ($courseids as $courseid) {
264867fd 2545
861efb19 2546 if (! $course = get_record("course", "id", $courseid)) {
2547 notify("Error finding course $courseid");
2548 } else {
2549 // figure out a sortorder that we can use in the destination category
2550 $sortorder = get_field_sql('SELECT MIN(sortorder)-1 AS min
2551 FROM ' . $CFG->prefix . 'course WHERE category=' . $categoryid);
2552 if ($sortorder === false) {
2553 // the category is empty
2554 // rather than let the db default to 0
264867fd 2555 // set it to > 100 and avoid extra work in fix_coursesortorder()
861efb19 2556 $sortorder = 200;
2557 } else if ($sortorder < 10) {
2558 fix_course_sortorder($categoryid);
2559 }
2560
2561 $course->category = $categoryid;
2562 $course->sortorder = $sortorder;
2563 $course->fullname = addslashes($course->fullname);
2564 $course->shortname = addslashes($course->shortname);
2565 $course->summary = addslashes($course->summary);
2566 $course->password = addslashes($course->password);
2567 $course->teacher = addslashes($course->teacher);
2568 $course->teachers = addslashes($course->teachers);
2569 $course->student = addslashes($course->student);
2570 $course->students = addslashes($course->students);
264867fd 2571
861efb19 2572 if (!update_record('course', $course)) {
2573 notify("An error occurred - course not moved!");
2574 }
c345bb58 2575 // parents changed (course category)
2576 // rebuild this context and all children
2577 rebuild_context_rel(get_context_instance(CONTEXT_COURSE, $course->id));
861efb19 2578 }
2579 }
2580 fix_course_sortorder();
264867fd 2581 }
861efb19 2582 return true;
2583}
2584
ae628043 2585/**
2586 * @param string $format Course format ID e.g. 'weeks'
2587 * @return Name that the course format prefers for sections
2588 */
2589function get_section_name($format) {
2590 $sectionname = get_string("name$format","format_$format");
2591 if($sectionname == "[[name$format]]") {
2592 $sectionname = get_string("name$format");
2593 }
a044c05d 2594 return $sectionname;
ae628043 2595}
2596
2585a68d 2597/**
2598 * Can the current user delete this course?
2599 * @param int $courseid
2600 * @return boolean
2601 *
2602 * Exception here to fix MDL-7796.
2603 *
2604 * FIXME
2605 * Course creators who can manage activities in the course
2606 * shoule be allowed to delete the course. We do it this
2607 * way because we need a quick fix to bring the functionality
2608 * in line with what we had pre-roles. We can't give the
2609 * default course creator role moodle/course:delete at
2610 * CONTEXT_SYSTEM level because this will allow them to
2611 * delete any course in the site. So we hard code this here
2612 * for now.
2613 *
2614 * @author vyshane AT gmail.com
2615 */
2616function can_delete_course($courseid) {
2617
2618 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2619
2620 return ( has_capability('moodle/course:delete', $context)
2621 || (has_capability('moodle/legacy:coursecreator', $context)
2622 && has_capability('moodle/course:manageactivities', $context)) );
2623}
2624
2625
bfefa87e 2626/*
2627 * Create a course and either return a $course object or false
2628 *
2629 * @param object $data - all the data needed for an entry in the 'course' table
2630 */
2631function create_course($data) {
2632 global $CFG, $USER;
2633
2634 // preprocess allowed mods
2635 $allowedmods = empty($data->allowedmods) ? array() : $data->allowedmods;
2636 unset($data->allowedmods);
2637 if (!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
2638 if ($CFG->restrictmodulesfor == 'all') {
2639 $data->restrictmodules = 1;
2640 } else {
2641 $data->restrictmodules = 0;
2642 }
2643 }
2585a68d 2644
bfefa87e 2645 $data->timecreated = time();
2646
2647 // place at beginning of category
2648 fix_course_sortorder();
2649 $data->sortorder = get_field_sql("SELECT min(sortorder)-1 FROM {$CFG->prefix}course WHERE category=$data->category");
2650 if (empty($data->sortorder)) {
2651 $data->sortorder = 100;
2652 }
2653
2654 if ($newcourseid = insert_record('course', $data)) { // Set up new course
2655
2656 $course = get_record('course', 'id', $newcourseid);
2657
2658 // Setup the blocks
2659 $page = page_create_object(PAGE_COURSE_VIEW, $course->id);
2660 blocks_repopulate_page($page); // Return value not checked because you can always edit later
2661
2662 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
2663 update_restricted_mods($course, $allowedmods);
2664 }
2665
2666 $section = new object();
2667 $section->course = $course->id; // Create a default section.
2668 $section->section = 0;
2669 $section->id = insert_record('course_sections', $section);
2670
2671 fix_course_sortorder();
2672
2673 add_to_log(SITEID, 'course', 'new', 'view.php?id='.$course->id, $data->fullname.' (ID '.$course->id.')');
2674
2675 return $course;
2676 }
2677
2678 return false; // error
2679}
2680
2681
2682/*
2683 * Update a course and return true or false
2684 *
2685 * @param object $data - all the data needed for an entry in the 'course' table
2686 */
2687function update_course($data) {
2688 global $USER, $CFG;
2689
2690 // preprocess allowed mods
2691 $allowedmods = empty($data->allowedmods) ? array() : $data->allowedmods;
2692 unset($data->allowedmods);
2693 if (!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
2694 unset($data->restrictmodules);
2695 }
2696
2697 $oldcourse = get_record('course', 'id', $data->id); // should not fail, already tested above
2698 if (!has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $oldcourse->category))
2699 or !has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $data->category))) {
2700 // can not move to new category, keep the old one
2701 unset($data->category);
2702 }
2703
2704 // Update with the new data
2705 if (update_record('course', $data)) {
2706
2707 $course = get_record('course', 'id', $data->id);
2708
0be70104 2709 add_to_log($course->id, "course", "update", "edit.php?id=$course->id", $course->id);
bfefa87e 2710
2711 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
2712 update_restricted_mods($course, $allowedmods);
2713 }
2714
2715 fix_course_sortorder();
2716
2717 // Test for and remove blocks which aren't appropriate anymore
2718 $page = page_create_object(PAGE_COURSE_VIEW, $course->id);
2719 blocks_remove_inappropriate($page);
2720
2721 // put custom role names into db
2722 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2723
2724 foreach ($data as $dname => $dvalue) {
2725
2726 // is this the right param?
2727 $dvalue = clean_param($dvalue, PARAM_NOTAGS);
2728
2729 if (!strstr($dname, 'role_')) {
2730 continue;
2731 }
2732
2733 $dt = explode('_', $dname);
2734 $roleid = $dt[1];
2735 // make up our mind whether we want to delete, update or insert
2736
2737 if (empty($dvalue)) {
2738
2739 delete_records('role_names', 'contextid', $context->id, 'roleid', $roleid);
2740
2741 } else if ($t = get_record('role_names', 'contextid', $context->id, 'roleid', $roleid)) {
2742
2743 $t->text = $dvalue;
2744 update_record('role_names', $t);
2745
2746 } else {
2747
2748 $t->contextid = $context->id;
2749 $t->roleid = $roleid;
2750 $t->text = $dvalue;
2751 insert_record('role_names', $t);
2752 }
2753
2754 }
2755
2756 return true;
2757
2758 }
2759
2760 return false;
2761}
2585a68d 2762
9deaeaa1 2763?>