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