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