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