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