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