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