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