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