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