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