"MDL-17448, fix assignment due time, merged from 1.9"
[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
f36cbf1d 1628/**
1629 * Rebuilds the cached list of course activities stored in the database
1630 * @param int $courseid - id of course to rebuil, empty means all
1631 * @param boolean $clearonly - only clear the modinfo fields, gets rebuild automatically on the fly
1632 */
1633function rebuild_course_cache($courseid=0, $clearonly=false) {
f33e1ed4 1634 global $COURSE, $DB;
f36cbf1d 1635
1636 if ($clearonly) {
1c69b885 1637 if (empty($courseid)) {
1638 $courseselect = array();
1639 } else {
1640 $courseselect = array('id'=>$courseid);
1641 }
1642 $DB->set_field('course', 'modinfo', null, $courseselect);
f36cbf1d 1643 // update cached global COURSE too ;-)
1644 if ($courseid == $COURSE->id) {
238c0dd9 1645 $COURSE->modinfo = null;
f36cbf1d 1646 }
1647 // reset the fast modinfo cache
1648 $reset = 'reset';
1649 get_fast_modinfo($reset);
1650 return;
1651 }
5867bfb5 1652
1653 if ($courseid) {
cb6fec1f 1654 $select = array('id'=>$courseid);
5867bfb5 1655 } else {
cb6fec1f 1656 $select = array();
6cf890e3 1657 @set_time_limit(0); // this could take a while! MDL-10954
5867bfb5 1658 }
1659
cb6fec1f 1660 if ($rs = $DB->get_recordset("course", $select,'','id,fullname')) {
1661 foreach ($rs as $course) {
5867bfb5 1662 $modinfo = serialize(get_array_of_activities($course->id));
cb6fec1f 1663 if (!$DB->set_field("course", "modinfo", $modinfo, array("id"=>$course->id))) {
6ba65fa0 1664 notify("Could not cache module information for course '" . format_string($course->fullname) . "'!");
5867bfb5 1665 }
dd97c328 1666 // update cached global COURSE too ;-)
1667 if ($course->id == $COURSE->id) {
238c0dd9 1668 $COURSE->modinfo = $modinfo;
dd97c328 1669 }
5867bfb5 1670 }
cb6fec1f 1671 $rs->close();
5867bfb5 1672 }
dd97c328 1673 // reset the fast modinfo cache
65a00c97 1674 $reset = 'reset';
1675 get_fast_modinfo($reset);
5867bfb5 1676}
1677
cb6fec1f 1678/**
1679 * Returns an array of the children categories for the given category
1680 * ID by caching all of the categories in a static hash
1681 */
9bb19e58 1682function get_child_categories($parent) {
9bb19e58 1683 static $allcategories = null;
1684
1685 // only fill in this variable the first time
1686 if (null == $allcategories) {
1687 $allcategories = array();
1688
1689 $categories = get_categories();
1690 foreach ($categories as $category) {
1691 if (empty($allcategories[$category->parent])) {
1692 $allcategories[$category->parent] = array();
1693 }
1694 $allcategories[$category->parent][] = $category;
1695 }
1696 }
1697
1698 if (empty($allcategories[$parent])) {
1699 return array();
1700 } else {
1701 return $allcategories[$parent];
1702 }
1703}
1704
cb6fec1f 1705/**
1706 * Given an empty array, this function recursively travels the
1707 * categories, building up a nice list for display. It also makes
1708 * an array that list all the parents for each category.
1709 */
c2cb4545 1710function make_categories_list(&$list, &$parents, $category=NULL, $path="") {
9d866ae0 1711 // initialize the arrays if needed
1712 if (!is_array($list)) {
264867fd 1713 $list = array();
9d866ae0 1714 }
1715 if (!is_array($parents)) {
264867fd 1716 $parents = array();
9d866ae0 1717 }
1718
c2cb4545 1719 if ($category) {
1720 if ($path) {
6ba65fa0 1721 $path = $path.' / '.format_string($category->name);
c2cb4545 1722 } else {
6ba65fa0 1723 $path = format_string($category->name);
c2cb4545 1724 }
1725 $list[$category->id] = $path;
1726 } else {
1727 $category->id = 0;
1728 }
1729
9bb19e58 1730 if ($categories = get_child_categories($category->id)) { // Print all the children recursively
c2cb4545 1731 foreach ($categories as $cat) {
1732 if (!empty($category->id)) {
3bd4de22 1733 if (isset($parents[$category->id])) {
2832badf 1734 $parents[$cat->id] = $parents[$category->id];
1735 }
c2cb4545 1736 $parents[$cat->id][] = $category->id;
1737 }
89adb174 1738 make_categories_list($list, $parents, $cat, $path);
c2cb4545 1739 }
1740 }
1741}
1742
1743
cb6fec1f 1744/**
1745 * Recursive function to print out all the categories in a nice format
1746 * with or without courses included
1747 */
d157bd5b 1748function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $files = true) {
9ff5310a 1749 global $CFG;
e05bcf2f 1750
1751 if (isset($CFG->max_category_depth) && ($depth >= $CFG->max_category_depth)) {
1752 return;
9ff5310a 1753 }
c2cb4545 1754
1755 if (!$displaylist) {
e92fe848 1756 make_categories_list($displaylist, $parentslist);
c2cb4545 1757 }
1758
1759 if ($category) {
8e480396 1760 if ($category->visible or has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM))) {
6f24e48e 1761 print_category_info($category, $depth, $files);
c2cb4545 1762 } else {
1763 return; // Don't bother printing children of invisible categories
1764 }
89adb174 1765
c2cb4545 1766 } else {
c2cb4545 1767 $category->id = "0";
1768 }
1769
9bb19e58 1770 if ($categories = get_child_categories($category->id)) { // Print all the children recursively
c2cb4545 1771 $countcats = count($categories);
1772 $count = 0;
1773 $first = true;
1774 $last = false;
1775 foreach ($categories as $cat) {
1776 $count++;
1777 if ($count == $countcats) {
1778 $last = true;
1779 }
1780 $up = $first ? false : true;
1781 $down = $last ? false : true;
1782 $first = false;
1783
6f24e48e 1784 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1, $files);
c2cb4545 1785 }
1786 }
c2cb4545 1787}
1788
cb6fec1f 1789/**
1790 * This function will return $options array for choose_from_menu, with whitespace to denote nesting.
1791 */
0705ff84 1792function make_categories_options() {
1793 make_categories_list($cats,$parents);
1794 foreach ($cats as $key => $value) {
1795 if (array_key_exists($key,$parents)) {
1796 if ($indent = count($parents[$key])) {
1797 for ($i = 0; $i < $indent; $i++) {
1798 $cats[$key] = '&nbsp;'.$cats[$key];
1799 }
1800 }
1801 }
1802 }
1803 return $cats;
1804}
c2cb4545 1805
cb6fec1f 1806/**
1807 * Prints the category info in indented fashion
1808 * This function is only used by print_whole_category_list() above
1809 */
6f24e48e 1810function print_category_info($category, $depth, $files = false) {
cb6fec1f 1811 global $CFG, $DB;
b48f834c 1812 static $strallowguests, $strrequireskey, $strsummary;
c2cb4545 1813
b48f834c 1814 if (empty($strsummary)) {
e05bcf2f 1815 $strallowguests = get_string('allowguests');
1816 $strrequireskey = get_string('requireskey');
1817 $strsummary = get_string('summary');
b48f834c 1818 }
ba2e5d73 1819
e05bcf2f 1820 $catlinkcss = $category->visible ? '' : ' class="dimmed" ';
d5f26b07 1821
cb6fec1f 1822 $coursecount = $DB->count_records('course') <= FRONTPAGECOURSELIMIT;
6f24e48e 1823 if ($files and $coursecount) {
fcf9577a 1824 $catimage = '<img src="'.$CFG->pixpath.'/i/course.gif" alt="" />';
b48f834c 1825 } else {
7b0b5c14 1826 $catimage = "&nbsp;";
8ef9cb56 1827 }
b48f834c 1828
fcf9577a 1829 echo "\n\n".'<table class="categorylist">';
d2b6ba70 1830
7ffcbfe1 1831 $courses = get_courses($category->id, 'c.sortorder ASC', 'c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.password,c.summary,c.guest,c.cost,c.currency');
6f24e48e 1832 if ($files and $coursecount) {
b48f834c 1833
978abb42 1834 echo '<tr>';
b48f834c 1835
1836 if ($depth) {
1837 $indent = $depth*30;
1838 $rows = count($courses) + 1;
a682f0c2 1839 echo '<td class="category indentation" rowspan="'.$rows.'" valign="top">';
b48f834c 1840 print_spacer(10, $indent);
e05bcf2f 1841 echo '</td>';
b48f834c 1842 }
89adb174 1843
9deaeaa1 1844 echo '<td valign="top" class="category image">'.$catimage.'</td>';
fcf9577a 1845 echo '<td valign="top" class="category name">';
6ba65fa0 1846 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot.'/course/category.php?id='.$category->id.'">'. format_string($category->name).'</a>';
e05bcf2f 1847 echo '</td>';
290130b3 1848 echo '<td class="category info">&nbsp;</td>';
e05bcf2f 1849 echo '</tr>';
b48f834c 1850
9ff5310a 1851 if ($courses && !(isset($CFG->max_category_depth)&&($depth>=$CFG->max_category_depth-1))) {
c2cb4545 1852 foreach ($courses as $course) {
e05bcf2f 1853 $linkcss = $course->visible ? '' : ' class="dimmed" ';
fcf9577a 1854 echo '<tr><td valign="top">&nbsp;';
1855 echo '</td><td valign="top" class="course name">';
6ba65fa0 1856 echo '<a '.$linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'. format_string($course->fullname).'</a>';
fcf9577a 1857 echo '</td><td align="right" valign="top" class="course info">';
c2cb4545 1858 if ($course->guest ) {
e05bcf2f 1859 echo '<a title="'.$strallowguests.'" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">';
fcf9577a 1860 echo '<img alt="'.$strallowguests.'" src="'.$CFG->pixpath.'/i/guest.gif" /></a>';
ebe8ddc1 1861 } else {
fcf9577a 1862 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath.'/spacer.gif" />';
0c656181 1863 }
c2cb4545 1864 if ($course->password) {
e05bcf2f 1865 echo '<a title="'.$strrequireskey.'" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">';
fcf9577a 1866 echo '<img alt="'.$strrequireskey.'" src="'.$CFG->pixpath.'/i/key.gif" /></a>';
ebe8ddc1 1867 } else {
fcf9577a 1868 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath.'/spacer.gif" />';
b48f834c 1869 }
1870 if ($course->summary) {
e05bcf2f 1871 link_to_popup_window ('/course/info.php?id='.$course->id, 'courseinfo',
fcf9577a 1872 '<img alt="'.$strsummary.'" src="'.$CFG->pixpath.'/i/info.gif" />',
b48f834c 1873 400, 500, $strsummary);
ebe8ddc1 1874 } else {
fcf9577a 1875 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath.'/spacer.gif" />';
0c656181 1876 }
e05bcf2f 1877 echo '</td></tr>';
0c656181 1878 }
ba2e5d73 1879 }
d2b6ba70 1880 } else {
b48f834c 1881
e0140f24 1882 echo '<tr>';
1883
b48f834c 1884 if ($depth) {
1885 $indent = $depth*20;
a682f0c2 1886 echo '<td class="category indentation" valign="top">';
b48f834c 1887 print_spacer(10, $indent);
e05bcf2f 1888 echo '</td>';
d2b6ba70 1889 }
89adb174 1890
fcf9577a 1891 echo '<td valign="top" class="category name">';
6ba65fa0 1892 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot.'/course/category.php?id='.$category->id.'">'. format_string($category->name).'</a>';
e05bcf2f 1893 echo '</td>';
290130b3 1894 echo '<td valign="top" class="category number">';
7ffcbfe1 1895 if (count($courses)) {
1896 echo count($courses);
e05bcf2f 1897 }
1898 echo '</td></tr>';
c2cb4545 1899 }
e05bcf2f 1900 echo '</table>';
c2cb4545 1901}
1902
c2cb4545 1903
e0b033d5 1904
cb6fec1f 1905/**
1906 * Category is 0 (for all courses) or an object
1907 */
6c54240a 1908function print_courses($category) {
810393c8 1909 global $CFG;
c2cb4545 1910
4dde1463 1911 if (!is_object($category) && $category==0) {
9bb19e58 1912 $categories = get_child_categories(0); // Parent = 0 ie top-level categories only
4dde1463 1913 if (is_array($categories) && count($categories) == 1) {
90c2ca2e 1914 $category = array_shift($categories);
238c0dd9 1915 $courses = get_courses_wmanagers($category->id,
1916 'c.sortorder ASC',
4dde1463 1917 array('password','summary','currency'));
90c2ca2e 1918 } else {
238c0dd9 1919 $courses = get_courses_wmanagers('all',
1920 'c.sortorder ASC',
4dde1463 1921 array('password','summary','currency'));
90c2ca2e 1922 }
1923 unset($categories);
607809b3 1924 } else {
238c0dd9 1925 $courses = get_courses_wmanagers($category->id,
1926 'c.sortorder ASC',
4dde1463 1927 array('password','summary','currency'));
c2cb4545 1928 }
1929
49cd4d79 1930 if ($courses) {
8fee6c60 1931 echo '<ul class="unlist">';
c2cb4545 1932 foreach ($courses as $course) {
4dde1463 1933 if ($course->visible == 1
003bbcc8 1934 || has_capability('moodle/course:viewhiddencourses',$course->context)) {
8fee6c60 1935 echo '<li>';
4dde1463 1936 print_course($course);
8fee6c60 1937 echo "</li>\n";
4dde1463 1938 }
c2cb4545 1939 }
8fee6c60 1940 echo "</ul>\n";
c2cb4545 1941 } else {
f9667a5a 1942 print_heading(get_string("nocoursesyet"));
8e480396 1943 $context = get_context_instance(CONTEXT_SYSTEM);
0468976c 1944 if (has_capability('moodle/course:create', $context)) {
255d1033 1945 $options = array();
1946 $options['category'] = $category->id;
6b7425d2 1947 echo '<div class="addcoursebutton">';
255d1033 1948 print_single_button($CFG->wwwroot.'/course/edit.php', $options, get_string("addnewcourse"));
1949 echo '</div>';
1950 }
c2cb4545 1951 }
c2cb4545 1952}
1953
1954
35d0244a 1955function print_course($course) {
cb6fec1f 1956 global $CFG, $USER, $DB;
c2cb4545 1957
4dde1463 1958 if (isset($course->context)) {
1959 $context = $course->context;
1960 } else {
1961 $context = get_context_instance(CONTEXT_COURSE, $course->id);
1962 }
146bbb8f 1963
88768091 1964 $linkcss = $course->visible ? '' : ' class="dimmed" ';
22288704 1965
7cd266e9 1966 echo '<div class="coursebox clearfix">';
afba7be1 1967 echo '<div class="info">';
7f9c4fb9 1968 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
e5e81e78 1969 $linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.
238c0dd9 1970 format_string($course->fullname).'</a></div>';
1971
d42c64ba 1972 /// first find all roles that are supposed to be displayed
238c0dd9 1973
6b4d8c4d 1974 if (!empty($CFG->coursemanager)) {
1975 $managerroles = split(',', $CFG->coursemanager);
3bf13d05 1976 $canseehidden = has_capability('moodle/role:viewhiddenassigns', $context);
4dde1463 1977 $namesarray = array();
1978 if (isset($course->managers)) {
1979 if (count($course->managers)) {
1980 $rusers = $course->managers;
1981 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
238c0dd9 1982
b682cee9 1983 /// Rename some of the role names if needed
1984 if (isset($context)) {
cb6fec1f 1985 $aliasnames = $DB->get_records('role_names', array('contextid'=>$context->id), '', 'roleid,contextid,name');
b682cee9 1986 }
1987
9d5a4b23 1988 // keep a note of users displayed to eliminate duplicates
1989 $usersshown = array();
4dde1463 1990 foreach ($rusers as $ra) {
9d5a4b23 1991
1992 // if we've already displayed user don't again
1993 if (in_array($ra->user->id,$usersshown)) {
1994 continue;
1995 }
1996 $usersshown[] = $ra->user->id;
1997
4dde1463 1998 if ($ra->hidden == 0 || $canseehidden) {
238c0dd9 1999 $fullname = fullname($ra->user, $canviewfullnames);
e6924a01 2000 if ($ra->hidden == 1) {
b9837ddf 2001 $status = " <img src=\"{$CFG->pixpath}/t/show.gif\" title=\"".get_string('userhashiddenassignments', 'role')."\" alt=\"".get_string('hiddenassign')."\" class=\"hide-show-image\"/>";
e6924a01 2002 } else {
2003 $status = '';
1780d87b 2004 }
b682cee9 2005
2006 if (isset($aliasnames[$ra->roleid])) {
87486420 2007 $ra->rolename = $aliasnames[$ra->roleid]->name;
b682cee9 2008 }
2009
238c0dd9 2010 $namesarray[] = format_string($ra->rolename)
4dde1463 2011 . ': <a href="'.$CFG->wwwroot.'/user/view.php?id='.$ra->user->id.'&amp;course='.SITEID.'">'
238c0dd9 2012 . $fullname . '</a>' . $status;
4dde1463 2013 }
2014 }
2015 }
2016 } else {
238c0dd9 2017 $rusers = get_role_users($managerroles, $context,
4dde1463 2018 true, '', 'r.sortorder ASC, u.lastname ASC', $canseehidden);
2019 if (is_array($rusers) && count($rusers)) {
2020 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
165d25cc 2021
2022 /// Rename some of the role names if needed
2023 if (isset($context)) {
2024 $aliasnames = $DB->get_records('role_names', array('contextid'=>$context->id), '', 'roleid,contextid,name');
2025 }
2026
4dde1463 2027 foreach ($rusers as $teacher) {
238c0dd9 2028 $fullname = fullname($teacher, $canviewfullnames);
165d25cc 2029
2030 /// Apply role names
2031 if (isset($aliasnames[$teacher->roleid])) {
2032 $teacher->rolename = $aliasnames[$teacher->roleid]->name;
2033 }
2034
238c0dd9 2035 $namesarray[] = format_string($teacher->rolename)
4dde1463 2036 . ': <a href="'.$CFG->wwwroot.'/user/view.php?id='.$teacher->id.'&amp;course='.SITEID.'">'
238c0dd9 2037 . $fullname . '</a>';
4dde1463 2038 }
431cad0d 2039 }
c2cb4545 2040 }
431cad0d 2041
d42c64ba 2042 if (!empty($namesarray)) {
88768091 2043 echo "<ul class=\"teachers\">\n<li>";
2044 echo implode('</li><li>', $namesarray);
2045 echo "</li></ul>";
2046 }
c2cb4545 2047 }
238c0dd9 2048
88768091 2049 require_once("$CFG->dirroot/enrol/enrol.class.php");
2050 $enrol = enrolment_factory::factory($course->enrol);
146bbb8f 2051 echo $enrol->get_access_icons($course);
c2cb4545 2052
afba7be1 2053 echo '</div><div class="summary">';
9f39c190 2054 $options = NULL;
2055 $options->noclean = true;
34b5847a 2056 $options->para = false;
9f39c190 2057 echo format_text($course->summary, FORMAT_MOODLE, $options, $course->id);
afba7be1 2058 echo '</div>';
2059 echo '</div>';
c2cb4545 2060}
2061
cb6fec1f 2062/**
2063 * Prints custom user information on the home page.
2064 * Over time this can include all sorts of information
2065 */
c2cb4545 2066function print_my_moodle() {
cb6fec1f 2067 global $USER, $CFG, $DB;
c2cb4545 2068
86a1ba04 2069 if (empty($USER->id)) {
ba6018a9 2070 print_error('nopermissions', '', '', 'See My Moodle');
c2cb4545 2071 }
2072
5b9e50ca 2073 $courses = get_my_courses($USER->id, 'visible DESC,sortorder ASC', array('summary'));
86dd62a7 2074 $rhosts = array();
2075 $rcourses = array();
36e6379e 2076 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
86dd62a7 2077 $rcourses = get_my_remotecourses($USER->id);
643b67b8 2078 $rhosts = get_my_remotehosts();
86dd62a7 2079 }
2080
2081 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
2082
2083 if (!empty($courses)) {
8fee6c60 2084 echo '<ul class="unlist">';
86dd62a7 2085 foreach ($courses as $course) {
2086 if ($course->id == SITEID) {
2087 continue;
2088 }
8fee6c60 2089 echo '<li>';
86dd62a7 2090 print_course($course, "100%");
8fee6c60 2091 echo "</li>\n";
86dd62a7 2092 }
8fee6c60 2093 echo "</ul>\n";
86dd62a7 2094 }
2095
2096 // MNET
238c0dd9 2097 if (!empty($rcourses)) {
86dd62a7 2098 // at the IDP, we know of all the remote courses
2099 foreach ($rcourses as $course) {
2100 print_remote_course($course, "100%");
2101 }
2102 } elseif (!empty($rhosts)) {
2103 // non-IDP, we know of all the remote servers, but not courses
2104 foreach ($rhosts as $host) {
643b67b8 2105 print_remote_host($host, "100%");
c81696e5 2106 }
c2cb4545 2107 }
86dd62a7 2108 unset($course);
2109 unset($host);
38a10939 2110
cb6fec1f 2111 if ($DB->count_records("course") > (count($courses) + 1) ) { // Some courses not being displayed
7f989948 2112 echo "<table width=\"100%\"><tr><td align=\"center\">";
2113 print_course_search("", false, "short");
2114 echo "</td><td align=\"center\">";
2115 print_single_button("$CFG->wwwroot/course/index.php", NULL, get_string("fulllistofcourses"), "get");
2116 echo "</td></tr></table>\n";
2117 }
86dd62a7 2118
26330001 2119 } else {
cb6fec1f 2120 if ($DB->count_records("course_categories") > 1) {
cb29b020 2121 print_simple_box_start("center", "100%", "#FFFFFF", 5, "categorybox");
26330001 2122 print_whole_category_list();
2123 print_simple_box_end();
2124 } else {
35d0244a 2125 print_courses(0);
26330001 2126 }
607809b3 2127 }
2b8cef80 2128}
2129
11b0c469 2130
a8b56716 2131function print_course_search($value="", $return=false, $format="plain") {
38a10939 2132 global $CFG;
1e0fb105 2133 static $count = 0;
2134
2135 $count++;
2136
2137 $id = 'coursesearch';
2138
2139 if ($count > 1) {
2140 $id .= $count;
2141 }
38a10939 2142
2143 $strsearchcourses= get_string("searchcourses");
2144
1c919752 2145 if ($format == 'plain') {
1e0fb105 2146 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
fcf9577a 2147 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
e42f4d92 2148 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
cb6fec1f 2149 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" value="'.s($value).'" />';
e42f4d92 2150 $output .= '<input type="submit" value="'.get_string('go').'" />';
fcf9577a 2151 $output .= '</fieldset></form>';
1c919752 2152 } else if ($format == 'short') {
1e0fb105 2153 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
fcf9577a 2154 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
b1f97418 2155 $output .= '<label for="shortsearchbox">'.$strsearchcourses.': </label>';
cb6fec1f 2156 $output .= '<input type="text" id="shortsearchbox" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
e42f4d92 2157 $output .= '<input type="submit" value="'.get_string('go').'" />';
fcf9577a 2158 $output .= '</fieldset></form>';
1c919752 2159 } else if ($format == 'navbar') {
fcf9577a 2160 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2161 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
b1f97418 2162 $output .= '<label for="navsearchbox">'.$strsearchcourses.': </label>';
cb6fec1f 2163 $output .= '<input type="text" id="navsearchbox" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
e42f4d92 2164 $output .= '<input type="submit" value="'.get_string('go').'" />';
fcf9577a 2165 $output .= '</fieldset></form>';
a8b56716 2166 }
2167
2168 if ($return) {
2169 return $output;
2170 }
2171 echo $output;
38a10939 2172}
11b0c469 2173
86dd62a7 2174function print_remote_course($course, $width="100%") {
86dd62a7 2175 global $CFG, $USER;
2176
2177 $linkcss = '';
2178
2179 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&amp;wantsurl=/course/view.php?id={$course->remoteid}";
2180
7cd266e9 2181 echo '<div class="coursebox remotecoursebox clearfix">';
86dd62a7 2182 echo '<div class="info">';
2183 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2184 $linkcss.' href="'.$url.'">'
6ba65fa0 2185 . format_string($course->fullname) .'</a><br />'
2186 . format_string($course->hostname) . ' : '
238c0dd9 2187 . format_string($course->cat_name) . ' : '
2188 . format_string($course->shortname). '</div>';
86dd62a7 2189 echo '</div><div class="summary">';
2190 $options = NULL;
2191 $options->noclean = true;
2192 $options->para = false;
2193 echo format_text($course->summary, FORMAT_MOODLE, $options);
2194 echo '</div>';
2195 echo '</div>';
86dd62a7 2196}
2197
643b67b8 2198function print_remote_host($host, $width="100%") {
643b67b8 2199 global $CFG, $USER;
2200
2201 $linkcss = '';
2202
7cd266e9 2203 echo '<div class="coursebox clearfix">';
643b67b8 2204 echo '<div class="info">';
2205 echo '<div class="name">';
2206 echo '<img src="'.$CFG->pixpath.'/i/mnethost.gif" class="icon" alt="'.get_string('course').'" />';
2207 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2208 . s($host['name']).'</a> - ';
1fd80ad3 2209 echo $host['count'] . ' ' . get_string('courses');
643b67b8 2210 echo '</div>';
2211 echo '</div>';
caa90d56 2212 echo '</div>';
643b67b8 2213}
2214
86dd62a7 2215
11b0c469 2216/// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2217
2218function add_course_module($mod) {
cb6fec1f 2219 global $DB;
11b0c469 2220
e5dfd0f3 2221 $mod->added = time();
53f4ad2c 2222 unset($mod->id);
11b0c469 2223
cb6fec1f 2224 return $DB->insert_record("course_modules", $mod);
11b0c469 2225}
2226
97928ddf 2227/**
2228 * Returns course section - creates new if does not exist yet.
2229 * @param int $relative section number
2230 * @param int $courseid
2231 * @return object $course_section object
2232 */
2233function get_course_section($section, $courseid) {
cb6fec1f 2234 global $DB;
2235
2236 if ($cw = $DB->get_record("course_sections", array("section"=>$section, "course"=>$courseid))) {
97928ddf 2237 return $cw;
2238 }
2239 $cw = new object();
cb6fec1f 2240 $cw->course = $courseid;
2241 $cw->section = $section;
2242 $cw->summary = "";
97928ddf 2243 $cw->sequence = "";
cb6fec1f 2244 $id = $DB->insert_record("course_sections", $cw);
dc5af91a 2245 return $DB->get_record("course_sections", array("id"=>$id));
97928ddf 2246}
ece966f0 2247/**
2248 * Given a full mod object with section and course already defined, adds this module to that section.
2249 *
2250 * @param object $mod
2251 * @param int $beforemod An existing ID which we will insert the new module before
2252 * @return int The course_sections ID where the mod is inserted
2253 */
7977cffd 2254function add_mod_to_section($mod, $beforemod=NULL) {
cb6fec1f 2255 global $DB;
11b0c469 2256
cb6fec1f 2257 if ($section = $DB->get_record("course_sections", array("course"=>$mod->course, "section"=>$mod->section))) {
7977cffd 2258
2259 $section->sequence = trim($section->sequence);
2260
2261 if (empty($section->sequence)) {
11b0c469 2262 $newsequence = "$mod->coursemodule";
7977cffd 2263
2264 } else if ($beforemod) {
2265 $modarray = explode(",", $section->sequence);
2266
d857e8b6 2267 if ($key = array_keys($modarray, $beforemod->id)) {
7977cffd 2268 $insertarray = array($mod->id, $beforemod->id);
2269 array_splice($modarray, $key[0], 1, $insertarray);
2270 $newsequence = implode(",", $modarray);
2271
2272 } else { // Just tack it on the end anyway
2273 $newsequence = "$section->sequence,$mod->coursemodule";
2274 }
2275
2276 } else {
2277 $newsequence = "$section->sequence,$mod->coursemodule";
11b0c469 2278 }
89adb174 2279
cb6fec1f 2280 if ($DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id))) {
e5dfd0f3 2281 return $section->id; // Return course_sections ID that was used.
11b0c469 2282 } else {
e5dfd0f3 2283 return 0;
11b0c469 2284 }
89adb174 2285
11b0c469 2286 } else { // Insert a new record
cb6fec1f 2287 $section->course = $mod->course;
2288 $section->section = $mod->section;
2289 $section->summary = "";
e5dfd0f3 2290 $section->sequence = $mod->coursemodule;
cb6fec1f 2291 return $DB->insert_record("course_sections", $section);
11b0c469 2292 }
2293}
2294
48e535bc 2295function set_coursemodule_groupmode($id, $groupmode) {
cb6fec1f 2296 global $DB;
a5d424df 2297 return $DB->set_field("course_modules", "groupmode", $groupmode, array("id"=>$id));
3d575e6f 2298}
2299
177d4abf 2300function set_coursemodule_idnumber($id, $idnumber) {
cb6fec1f 2301 global $DB;
238c0dd9 2302 return $DB->set_field("course_modules", "idnumber", $idnumber, array("id"=>$id));
177d4abf 2303}
4e781c7b 2304
02f66c42 2305/**
2306* $prevstateoverrides = true will set the visibility of the course module
2307* to what is defined in visibleold. This enables us to remember the current
2308* visibility when making a whole section hidden, so that when we toggle
2309* that section back to visible, we are able to return the visibility of
2310* the course module back to what it was originally.
2311*/
2312function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
cb6fec1f 2313 global $DB;
2314 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
978abb42 2315 return false;
2316 }
cb6fec1f 2317 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
978abb42 2318 return false;
2319 }
cb6fec1f 2320 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
dcd338ff 2321 foreach($events as $event) {
48e535bc 2322 if ($visible) {
2323 show_event($event);
2324 } else {
2325 hide_event($event);
2326 }
dcd338ff 2327 }
2328 }
02f66c42 2329 if ($prevstateoverrides) {
2330 if ($visible == '0') {
2331 // Remember the current visible state so we can toggle this back.
cb6fec1f 2332 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id'=>$id));
02f66c42 2333 } else {
2334 // Get the previous saved visible states.
cb6fec1f 2335 return $DB->set_field('course_modules', 'visible', $cm->visibleold, array('id'=>$id));
02f66c42 2336 }
2337 }
cb6fec1f 2338 return $DB->set_field("course_modules", "visible", $visible, array("id"=>$id));
1acfbce5 2339}
2340
cb6fec1f 2341/**
290130b3 2342 * Delete a course module and any associated data at the course level (events)
264867fd 2343 * Until 1.5 this function simply marked a deleted flag ... now it
290130b3 2344 * deletes it completely.
2345 *
2346 */
48e535bc 2347function delete_course_module($id) {
cb6fec1f 2348 global $CFG, $DB;
f615fbab 2349 require_once($CFG->libdir.'/gradelib.php');
2350
cb6fec1f 2351 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
290130b3 2352 return true;
2353 }
cb6fec1f 2354 $modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module));
f615fbab 2355 //delete events from calendar
cb6fec1f 2356 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
dcd338ff 2357 foreach($events as $event) {
0ea03696 2358 delete_event($event->id);
dcd338ff 2359 }
2360 }
f615fbab 2361 //delete grade items, outcome items and grades attached to modules
2362 if ($grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2363 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course))) {
2364 foreach ($grade_items as $grade_item) {
2365 $grade_item->delete('moddelete');
2366 }
238c0dd9 2367
f615fbab 2368 }
cb6fec1f 2369 return $DB->delete_records('course_modules', array('id'=>$cm->id));
11b0c469 2370}
2371
2372function delete_mod_from_section($mod, $section) {
cb6fec1f 2373 global $DB;
11b0c469 2374
cb6fec1f 2375 if ($section = $DB->get_record("course_sections", array("id"=>$section)) ) {
11b0c469 2376
e5dfd0f3 2377 $modarray = explode(",", $section->sequence);
11b0c469 2378
2379 if ($key = array_keys ($modarray, $mod)) {
2380 array_splice($modarray, $key[0], 1);
2381 $newsequence = implode(",", $modarray);
cb6fec1f 2382 return $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
11b0c469 2383 } else {
2384 return false;
2385 }
89adb174 2386
11b0c469 2387 }
7977cffd 2388 return false;
11b0c469 2389}
2390
3440ec12 2391/**
2392 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
2393 *
2394 * @param object $course
2395 * @param int $section
2396 * @param int $move (-1 or 1)
2397 */
12905134 2398function move_section($course, $section, $move) {
2399/// Moves a whole course section up and down within the course
cb6fec1f 2400 global $USER, $DB;
12905134 2401
2402 if (!$move) {
2403 return true;
2404 }
2405
2406 $sectiondest = $section + $move;
2407
2408 if ($sectiondest > $course->numsections or $sectiondest < 1) {
2409 return false;
2410 }
2411
cb6fec1f 2412 if (!$sectionrecord = $DB->get_record("course_sections", array("course"=>$course->id, "section"=>$section))) {
12905134 2413 return false;
2414 }
2415
cb6fec1f 2416 if (!$sectiondestrecord = $DB->get_record("course_sections", array("course"=>$course->id, "section"=>$sectiondest))) {
12905134 2417 return false;
2418 }
2419
cb6fec1f 2420 if (!$DB->set_field("course_sections", "section", $sectiondest, array("id"=>$sectionrecord->id))) {
12905134 2421 return false;
2422 }
cb6fec1f 2423 if (!$DB->set_field("course_sections", "section", $section, array("id"=>$sectiondestrecord->id))) {
12905134 2424 return false;
2425 }
798b70a1 2426 // if the focus is on the section that is being moved, then move the focus along
2427 if (isset($USER->display[$course->id]) and ($USER->display[$course->id] == $section)) {
2428 course_set_display($course->id, $sectiondest);
2429 }
5390cbb7 2430
a987106d 2431 // Check for duplicates and fix order if needed.
5390cbb7 2432 // There is a very rare case that some sections in the same course have the same section id.
cb6fec1f 2433 $sections = $DB->get_records('course_sections', array('course'=>$course->id), 'section ASC');
a987106d 2434 $n = 0;
2435 foreach ($sections as $section) {
2436 if ($section->section != $n) {
cb6fec1f 2437 if (!$DB->set_field('course_sections', 'section', $n, array('id'=>$section->id))) {
5390cbb7 2438 return false;
2439 }
5390cbb7 2440 }
a987106d 2441 $n++;
5390cbb7 2442 }
12905134 2443 return true;
2444}
2445
3440ec12 2446/**
2447 * Moves a section within a course, from a position to another.
2448 * Be very careful: $section and $destination refer to section number,
2449 * not id!.
2450 *
2451 * @param object $course
2452 * @param int $section Section number (not id!!!)
2453 * @param int $destination
2454 * @return boolean Result
2455 */
2456function move_section_to($course, $section, $destination) {
2457/// Moves a whole course section up and down within the course
2458 global $USER, $DB;
2459
ca255392 2460 if (!$destination && $destination != 0) {
3440ec12 2461 return true;
2462 }
2463
ca255392 2464 if ($destination > $course->numsections) {
3440ec12 2465 return false;
2466 }
2467
2468 // Get all sections for this course and re-order them (2 of them should now share the same section number)
2469 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
2470 'section ASC, id ASC', 'id, section')) {
2471 return false;
2472 }
2473
2474 $sections = reorder_sections($sections, $section, $destination);
2475
2476 // Update all sections
2477 foreach ($sections as $id => $position) {
2478 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
2479 }
2480
2481 // if the focus is on the section that is being moved, then move the focus along
2482 if (isset($USER->display[$course->id]) and ($USER->display[$course->id] == $section)) {
2483 course_set_display($course->id, $destination);
2484 }
2485 return true;
2486}
2487
2488/**
2489 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
2490 * an original position number and a target position number, rebuilds the array so that the
2491 * move is made without any duplication of section positions.
2492 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
2493 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
2494 *
2495 * @param array $sections
2496 * @param int $origin_position
2497 * @param int $target_position
2498 * @return array
2499 */
2500function reorder_sections($sections, $origin_position, $target_position) {
2501 if (!is_array($sections)) {
2502 return false;
2503 }
2504
2505 // We can't move section position 0
2506 if ($origin_position < 1) {
2507 echo "We can't move section position 0";
2508 return false;
2509 }
2510
2511 // Locate origin section in sections array
2512 if (!$origin_key = array_search($origin_position, $sections)) {
2513 echo "searched position not in sections array";
2514 return false; // searched position not in sections array
2515 }
2516
2517 // Extract origin section
2518 $origin_section = $sections[$origin_key];
2519 unset($sections[$origin_key]);
2520
2521 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
2522 $found = false;
2523 $append_array = array();
2524 foreach ($sections as $id => $position) {
2525 if ($found) {
2526 $append_array[$id] = $position;
2527 unset($sections[$id]);
2528 }
2529 if ($position == $target_position) {
2530 $found = true;
2531 }
2532 }
2533
2534 // Append moved section
2535 $sections[$origin_key] = $origin_section;
2536
2537 // Append rest of array (if applicable)
2538 if (!empty($append_array)) {
2539 foreach ($append_array as $id => $position) {
2540 $sections[$id] = $position;
2541 }
2542 }
2543
2544 // Renumber positions
2545 $position = 0;
2546 foreach ($sections as $id => $p) {
2547 $sections[$id] = $position;
2548 $position++;
2549 }
2550
2551 return $sections;
2552
2553}
2554
cb6fec1f 2555/**
2556 * Move the module object $mod to the specified $section
2557 * If $beforemod exists then that is the module
2558 * before which $modid should be inserted
2559 * All parameters are objects
2560 */
7977cffd 2561function moveto_module($mod, $section, $beforemod=NULL) {
cb6fec1f 2562 global $DB;
7977cffd 2563
2564/// Remove original module from original section
7977cffd 2565 if (! delete_mod_from_section($mod->id, $mod->section)) {
2566 notify("Could not delete module from existing section");
2567 }
2568
2569/// Update module itself if necessary
2570
2571 if ($mod->section != $section->id) {
89adb174 2572 $mod->section = $section->id;
cb6fec1f 2573 if (!$DB->update_record("course_modules", $mod)) {
7977cffd 2574 return false;
2575 }
48e535bc 2576 // if moving to a hidden section then hide module
2577 if (!$section->visible) {
2578 set_coursemodule_visible($mod->id, 0);
2579 }
7977cffd 2580 }
2581
2582/// Add the module into the new section
2583
2584 $mod->course = $section->course;
2585 $mod->section = $section->section; // need relative reference
2586 $mod->coursemodule = $mod->id;
2587
2588 if (! add_mod_to_section($mod, $beforemod)) {
2589 return false;
2590 }
2591
2592 return true;
7977cffd 2593}
2594
24e1eae4 2595function make_editing_buttons($mod, $absolute=false, $moveselect=true, $indent=-1, $section=-1) {
cb6fec1f 2596 global $CFG, $USER, $DB;
94361e02 2597
3d575e6f 2598 static $str;
37a88449 2599 static $sesskey;
3d575e6f 2600
217a8ee9 2601 $modcontext = get_context_instance(CONTEXT_MODULE, $mod->id);
2602 // no permission to edit
2603 if (!has_capability('moodle/course:manageactivities', $modcontext)) {
e2cd3ed0 2604 return false;
217a8ee9 2605 }
2606
3d575e6f 2607 if (!isset($str)) {
9534a8cb 2608 $str->assign = get_string("assignroles", 'role');
90ebdf65 2609 $str->delete = get_string("delete");
2610 $str->move = get_string("move");
2611 $str->moveup = get_string("moveup");
2612 $str->movedown = get_string("movedown");
2613 $str->moveright = get_string("moveright");
2614 $str->moveleft = get_string("moveleft");
2615 $str->update = get_string("update");
2616 $str->duplicate = get_string("duplicate");
2617 $str->hide = get_string("hide");
2618 $str->show = get_string("show");
3d575e6f 2619 $str->clicktochange = get_string("clicktochange");
32d03b7b 2620 $str->forcedmode = get_string("forcedmode");
3d575e6f 2621 $str->groupsnone = get_string("groupsnone");
2622 $str->groupsseparate = get_string("groupsseparate");
2623 $str->groupsvisible = get_string("groupsvisible");
37a88449 2624 $sesskey = sesskey();
1acfbce5 2625 }
94361e02 2626
24e1eae4 2627 if ($section >= 0) {
75f087b6 2628 $section = '&amp;sr='.$section; // Section return
24e1eae4 2629 } else {
2630 $section = '';
2631 }
2632
94361e02 2633 if ($absolute) {
37a88449 2634 $path = $CFG->wwwroot.'/course';
dc0dc7d5 2635 } else {
37a88449 2636 $path = '.';
dc0dc7d5 2637 }
217a8ee9 2638 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
2639 if ($mod->visible) {
2640 $hideshow = '<a class="editing_hide" title="'.$str->hide.'" href="'.$path.'/mod.php?hide='.$mod->id.
2641 '&amp;sesskey='.$sesskey.$section.'"><img'.
2642 ' src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" '.
2643 ' alt="'.$str->hide.'" /></a>'."\n";
2644 } else {
2645 $hideshow = '<a class="editing_show" title="'.$str->show.'" href="'.$path.'/mod.php?show='.$mod->id.
2646 '&amp;sesskey='.$sesskey.$section.'"><img'.
2647 ' src="'.$CFG->pixpath.'/t/show.gif" class="iconsmall" '.
2648 ' alt="'.$str->show.'" /></a>'."\n";
2649 }
530db4cd 2650 } else {
2651 $hideshow = '';
7977cffd 2652 }
530db4cd 2653
3d575e6f 2654 if ($mod->groupmode !== false) {
2655 if ($mod->groupmode == SEPARATEGROUPS) {
32d03b7b 2656 $grouptitle = $str->groupsseparate;
cddbd5d5 2657 $groupclass = 'editing_groupsseparate';
37a88449 2658 $groupimage = $CFG->pixpath.'/t/groups.gif';
2659 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=0&amp;sesskey='.$sesskey;
3d575e6f 2660 } else if ($mod->groupmode == VISIBLEGROUPS) {
32d03b7b 2661 $grouptitle = $str->groupsvisible;
cddbd5d5 2662 $groupclass = 'editing_groupsvisible';
37a88449 2663 $groupimage = $CFG->pixpath.'/t/groupv.gif';
2664 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=1&amp;sesskey='.$sesskey;
32d03b7b 2665 } else {
2666 $grouptitle = $str->groupsnone;
90ebdf65 2667 $groupclass = 'editing_groupsnone';
37a88449 2668 $groupimage = $CFG->pixpath.'/t/groupn.gif';
2669 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=2&amp;sesskey='.$sesskey;
32d03b7b 2670 }
2671 if ($mod->groupmodelink) {
90ebdf65 2672 $groupmode = '<a class="'.$groupclass.'" title="'.$grouptitle.' ('.$str->clicktochange.')" href="'.$grouplink.'">'.
0d905d9f 2673 '<img src="'.$groupimage.'" class="iconsmall" '.
2674 'alt="'.$grouptitle.'" /></a>';
3d575e6f 2675 } else {
37a88449 2676 $groupmode = '<img title="'.$grouptitle.' ('.$str->forcedmode.')" '.
0d905d9f 2677 ' src="'.$groupimage.'" class="iconsmall" '.
2678 'alt="'.$grouptitle.'" />';
3d575e6f 2679 }
2680 } else {
2681 $groupmode = "";
2682 }
e2cd3ed0 2683
217a8ee9 2684 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $mod->course))) {
2685 if ($moveselect) {
2686 $move = '<a class="editing_move" title="'.$str->move.'" href="'.$path.'/mod.php?copy='.$mod->id.
2687 '&amp;sesskey='.$sesskey.$section.'"><img'.
2688 ' src="'.$CFG->pixpath.'/t/move.gif" class="iconsmall" '.
2689 ' alt="'.$str->move.'" /></a>'."\n";
2690 } else {
2691 $move = '<a class="editing_moveup" title="'.$str->moveup.'" href="'.$path.'/mod.php?id='.$mod->id.
2692 '&amp;move=-1&amp;sesskey='.$sesskey.$section.'"><img'.
2693 ' src="'.$CFG->pixpath.'/t/up.gif" class="iconsmall" '.
2694 ' alt="'.$str->moveup.'" /></a>'."\n".
2695 '<a class="editing_movedown" title="'.$str->movedown.'" href="'.$path.'/mod.php?id='.$mod->id.
2696 '&amp;move=1&amp;sesskey='.$sesskey.$section.'"><img'.
2697 ' src="'.$CFG->pixpath.'/t/down.gif" class="iconsmall" '.
2698 ' alt="'.$str->movedown.'" /></a>'."\n";
2699 }
7b44777e 2700 } else {
238c0dd9 2701 $move = '';
7977cffd 2702 }
2703
932be046 2704 $leftright = '';
217a8ee9 2705 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $mod->course))) {
932be046 2706
8047ab1d 2707 if (right_to_left()) { // Exchange arrows on RTL
932be046 2708 $rightarrow = 'left.gif';
2709 $leftarrow = 'right.gif';
2710 } else {
2711 $rightarrow = 'right.gif';
2712 $leftarrow = 'left.gif';
2713 }
238c0dd9 2714
217a8ee9 2715 if ($indent > 0) {
2716 $leftright .= '<a class="editing_moveleft" title="'.$str->moveleft.'" href="'.$path.'/mod.php?id='.$mod->id.
2717 '&amp;indent=-1&amp;sesskey='.$sesskey.$section.'"><img'.
932be046 2718 ' src="'.$CFG->pixpath.'/t/'.$leftarrow.'" class="iconsmall" '.
217a8ee9 2719 ' alt="'.$str->moveleft.'" /></a>'."\n";
2720 }
2721 if ($indent >= 0) {
2722 $leftright .= '<a class="editing_moveright" title="'.$str->moveright.'" href="'.$path.'/mod.php?id='.$mod->id.
2723 '&amp;indent=1&amp;sesskey='.$sesskey.$section.'"><img'.
932be046 2724 ' src="'.$CFG->pixpath.'/t/'.$rightarrow.'" class="iconsmall" '.
217a8ee9 2725 ' alt="'.$str->moveright.'" /></a>'."\n";
2726 }
37a88449 2727 }
9534a8cb 2728 if (has_capability('moodle/course:managegroups', $modcontext)){
2729 $context = get_context_instance(CONTEXT_MODULE, $mod->id);
7b553c8b 2730 $assign = '<a class="editing_assign" title="'.$str->assign.'" href="'.$CFG->wwwroot.'/admin/roles/assign.php?contextid='.
9534a8cb 2731 $context->id.'"><img src="'.$CFG->pixpath.'/i/roles.gif" alt="'.$str->assign.'" class="iconsmall"/></a>';
8634e001 2732 } else {
2733 $assign = '';
9534a8cb 2734 }
8634e001 2735
90ebdf65 2736 return '<span class="commands">'."\n".$leftright.$move.
2737 '<a class="editing_update" title="'.$str->update.'" href="'.$path.'/mod.php?update='.$mod->id.
37a88449 2738 '&amp;sesskey='.$sesskey.$section.'"><img'.
0d905d9f 2739 ' src="'.$CFG->pixpath.'/t/edit.gif" class="iconsmall" '.
90ebdf65 2740 ' alt="'.$str->update.'" /></a>'."\n".
2741 '<a class="editing_delete" title="'.$str->delete.'" href="'.$path.'/mod.php?delete='.$mod->id.
37a88449 2742 '&amp;sesskey='.$sesskey.$section.'"><img'.
0d905d9f 2743 ' src="'.$CFG->pixpath.'/t/delete.gif" class="iconsmall" '.
9534a8cb 2744 ' alt="'.$str->delete.'" /></a>'."\n".$hideshow.$groupmode."\n".$assign.'</span>';
90845098 2745}
2746
b61efafb 2747/**
264867fd 2748 * given a course object with shortname & fullname, this function will
b61efafb 2749 * truncate the the number of chars allowed and add ... if it was too long
2750 */
2751function course_format_name ($course,$max=100) {
264867fd 2752
6ba65fa0 2753 $str = $course->shortname.': '. $course->fullname;
b61efafb 2754 if (strlen($str) <= $max) {
2755 return $str;
2756 }
2757 else {
2758 return substr($str,0,$max-3).'...';
2759 }
2760}
2761
2762/**
2763 * This function will return true if the given course is a child course at all
2764 */
2765function course_in_meta ($course) {
cb6fec1f 2766 global $DB;
2767 return $DB->record_exists("course_meta", array("child_course"=>$course->id));
b61efafb 2768}
2769
48e535bc 2770
2771/**
7cac0c4b 2772 * Print standard form elements on module setup forms in mod/.../mod_form.php
48e535bc 2773 */
263017bb 2774function print_standard_coursemodule_settings($form, $features=null) {
cb6fec1f 2775 global $DB;
2776 if (!$course = $DB->get_record('course', array('id'=>$form->course))) {
ba6018a9 2777 print_error("invalidcourseid");
da2224f8 2778 }
2779 print_groupmode_setting($form, $course);
263017bb 2780 if (!empty($features->groupings)) {
2781 print_grouping_settings($form, $course);
2782 }
da2224f8 2783 print_visible_setting($form, $course);
48e535bc 2784}
2785
2786/**
7cac0c4b 2787 * Print groupmode form element on module setup forms in mod/.../mod_form.php
48e535bc 2788 */
5ebb746b 2789function print_groupmode_setting($form, $course=NULL) {
cb6fec1f 2790 global $DB;
48e535bc 2791
5ebb746b 2792 if (empty($course)) {
cb6fec1f 2793 if (!$course = $DB->get_record('course', array('id'=>$form->course))) {
ba6018a9 2794 print_error("invalidcourseid");
5ebb746b 2795 }
2796 }
48e535bc 2797 if ($form->coursemodule) {
cb6fec1f 2798 if (!$cm = $DB->get_record('course_modules', array('id'=>$form->coursemodule))) {
d857e8b6 2799 print_error('invalidcoursemodule');
48e535bc 2800 }
ffc536af 2801 $groupmode = groups_get_activity_groupmode($cm);
48e535bc 2802 } else {
2803 $cm = null;
ffc536af 2804 $groupmode = groups_get_course_groupmode($course);
48e535bc 2805 }
48e535bc 2806 if ($course->groupmode or (!$course->groupmodeforce)) {
2807 echo '<tr valign="top">';
2808 echo '<td align="right"><b>'.get_string('groupmode').':</b></td>';
7bbe08a2 2809 echo '<td align="left">';
ffc536af 2810 $choices = array();
48e535bc 2811 $choices[NOGROUPS] = get_string('groupsnone');
2812 $choices[SEPARATEGROUPS] = get_string('groupsseparate');
2813 $choices[VISIBLEGROUPS] = get_string('groupsvisible');
2814 choose_from_menu($choices, 'groupmode', $groupmode, '', '', 0, false, $course->groupmodeforce);
2815 helpbutton('groupmode', get_string('groupmode'));
2816 echo '</td></tr>';
2817 }
2818}
2819
263017bb 2820/**
7cac0c4b 2821 * Print groupmode form element on module setup forms in mod/.../mod_form.php
263017bb 2822 */
2823function print_grouping_settings($form, $course=NULL) {
f33e1ed4 2824 global $DB;
263017bb 2825
2826 if (empty($course)) {
cb6fec1f 2827 if (! $course = $DB->get_record('course', array('id'=>$form->course))) {
ba6018a9 2828 print_error("invalidcourseid");
263017bb 2829 }
2830 }
2831 if ($form->coursemodule) {
cb6fec1f 2832 if (!$cm = $DB->get_record('course_modules', array('id'=>$form->coursemodule))) {
d857e8b6 2833 print_error('invalidcoursemodule');
263017bb 2834 }
2835 } else {
2836 $cm = null;
2837 }
2838
f33e1ed4 2839 $groupings = $DB->get_records_menu('groupings', array('courseid'=>$course->id), 'name', 'id, name');
263017bb 2840 if (!empty($groupings)) {
2841 echo '<tr valign="top">';
2842 echo '<td align="right"><b>'.get_string('grouping', 'group').':</b></td>';
2843 echo '<td align="left">';
238c0dd9 2844
263017bb 2845 $groupingid = isset($cm->groupingid) ? $cm->groupingid : 0;
238c0dd9 2846
263017bb 2847 choose_from_menu($groupings, 'groupingid', $groupingid, get_string('none'), '', 0, false);
2848 echo '</td></tr>';
238c0dd9 2849
263017bb 2850 $checked = empty($cm->groupmembersonly) ? '':'checked="checked"';
2851 echo '<tr valign="top">';
2852 echo '<td align="right"><b>'.get_string('groupmembersonly', 'group').':</b></td>';
2853 echo '<td align="left">';
2854 echo "<input type=\"checkbox\" name=\"groupmembersonly\" value=\"1\" $checked />";
2855 echo '</td></tr>';
2856
2857 }
2858}
2859
48e535bc 2860/**
7cac0c4b 2861 * Print visibility setting form element on module setup forms in mod/.../mod_form.php
48e535bc 2862 */
5ebb746b 2863function print_visible_setting($form, $course=NULL) {
cb6fec1f 2864 global $DB;
1ee55c41 2865 if (empty($course)) {
cb6fec1f 2866 if (!$course = $DB->get_record('course', array('id'=>$form->course))) {
ba6018a9 2867 print_error("invalidcourseid");
1ee55c41 2868 }
2869 }
48e535bc 2870 if ($form->coursemodule) {
cb6fec1f 2871 $visible = $DB->get_field('course_modules', 'visible', array('id'=>$form->coursemodule));
48e535bc 2872 } else {
2873 $visible = true;
2874 }
2875
2876 if ($form->mode == 'add') { // in this case $form->section is the section number, not the id
cb6fec1f 2877 $hiddensection = !$DB->get_field('course_sections', 'visible', array('section'=>$form->section, 'course'=>$form->course));
48e535bc 2878 } else {
cb6fec1f 2879 $hiddensection = !$DB->get_field('course_sections', 'visible', array('id'=>$form->section));
48e535bc 2880 }
2881 if ($hiddensection) {
2882 $visible = false;
2883 }
264867fd 2884
48e535bc 2885 echo '<tr valign="top">';
182311e4 2886 echo '<td align="right"><b>'.get_string('visible', '').':</b></td>';
7bbe08a2 2887 echo '<td align="left">';
dd97c328 2888 $choices = array(1 => get_string('show'), 0 => get_string('hide'));
48e535bc 2889 choose_from_menu($choices, 'visible', $visible, '', '', 0, false, $hiddensection);
2890 echo '</td></tr>';
264867fd 2891}
48e535bc 2892
cb6fec1f 2893function update_restricted_mods($course, $mods) {
2894 global $DB;
ddb0a19f 2895
2896/// Delete all the current restricted list
cb6fec1f 2897 $DB->delete_records('course_allowed_modules', array('course'=>$course->id));
ddb0a19f 2898
0705ff84 2899 if (empty($course->restrictmodules)) {
ddb0a19f 2900 return; // We're done
0705ff84 2901 }
ddb0a19f 2902
2903/// Insert the new list of restricted mods
2904 foreach ($mods as $mod) {
2905 if ($mod == 0) {
2906 continue; // this is the 'allow none' option
0705ff84 2907 }
ddb0a19f 2908 $am = new object();
2909 $am->course = $course->id;
2910 $am->module = $mod;
cb6fec1f 2911 $DB->insert_record('course_allowed_modules',$am);
0705ff84 2912 }
2913}
2914
2915/**
2916 * This function will take an int (module id) or a string (module name)
2917 * and return true or false, whether it's allowed in the given course (object)
264867fd 2918 * $mod is not allowed to be an object, as the field for the module id is inconsistent
0705ff84 2919 * depending on where in the code it's called from (sometimes $mod->id, sometimes $mod->module)
2920 */
2921
2922function course_allowed_module($course,$mod) {
cb6fec1f 2923 global $DB;
238c0dd9 2924
0705ff84 2925 if (empty($course->restrictmodules)) {
2926 return true;
2927 }
264867fd 2928
ddb0a19f 2929 // Admins and admin-like people who can edit everything can also add anything.
2930 // This is a bit wierd, really. I debated taking it out but it's enshrined in help for the setting.
8e480396 2931 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM))) {
0705ff84 2932 return true;
2933 }
ddb0a19f 2934
0705ff84 2935 if (is_numeric($mod)) {
2936 $modid = $mod;
2937 } else if (is_string($mod)) {
cb6fec1f 2938 $modid = $DB->get_field('modules', 'id', array('name'=>$mod));
0705ff84 2939 }
2940 if (empty($modid)) {
2941 return false;
2942 }
238c0dd9 2943
cb6fec1f 2944 return $DB->record_exists('course_allowed_modules', array('course'=>$course->id, 'module'=>$modid));
0705ff84 2945}
2946
e2b347e9 2947/**
2948 * Recursively delete category including all subcategories and courses.
2949 * @param object $ccategory
2950 * @return bool status
2951 */
2952function category_delete_full($category, $showfeedback=true) {
cb6fec1f 2953 global $CFG, $DB;
e2b347e9 2954 require_once($CFG->libdir.'/gradelib.php');
2955 require_once($CFG->libdir.'/questionlib.php');
2956
cb6fec1f 2957 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
e2b347e9 2958 foreach ($children as $childcat) {
2959 if (!category_delete_full($childcat, $showfeedback)) {
238c0dd9 2960 notify("Error deleting category $childcat->name");
e2b347e9 2961 return false;
2962 }
2963 }
2964 }
2965
cb6fec1f 2966 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC')) {
e2b347e9 2967 foreach ($courses as $course) {
2942a5cd 2968 if (!delete_course($course, false)) {
238c0dd9 2969 notify("Error deleting course $course->shortname");
e2b347e9 2970 return false;
2971 }
238c0dd9 2972 notify(get_string('coursedeleted', '', $course->shortname), 'notifysuccess');
e2b347e9 2973 }
2974 }
2975
2976 // now delete anything that may depend on course category context
2977 grade_course_category_delete($category->id, 0, $showfeedback);
2978 if (!question_delete_course_category($category, 0, $showfeedback)) {
238c0dd9 2979 notify(get_string('errordeletingquestionsfromcategory', 'question', $category), 'notifysuccess');
e2b347e9 2980 return false;
2981 }
2982
2983 // finally delete the category and it's context
cb6fec1f 2984 $DB->delete_records('course_categories', array('id'=>$category->id));
e2b347e9 2985 delete_context(CONTEXT_COURSECAT, $category->id);
2986
2942a5cd 2987 events_trigger('course_category_deleted', $category);
e2b347e9 2988
238c0dd9 2989 notify(get_string('coursecategorydeleted', '', format_string($category->name)), 'notifysuccess');
e2b347e9 2990
2991 return true;
2992}
2993
2994/**
2995 * Delete category, but move contents to another category.
2996 * @param object $ccategory
2997 * @param int $newparentid category id
2998 * @return bool status
2999 */
3000function category_delete_move($category, $newparentid, $showfeedback=true) {
cb6fec1f 3001 global $CFG, $DB;
e2b347e9 3002 require_once($CFG->libdir.'/gradelib.php');
3003 require_once($CFG->libdir.'/questionlib.php');
3004
cb6fec1f 3005 if (!$newparentcat = $DB->get_record('course_categories', array('id'=>$newparentid))) {
e2b347e9 3006 return false;
3007 }
3008
cb6fec1f 3009 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
e2b347e9 3010 foreach ($children as $childcat) {
3011 if (!move_category($childcat, $newparentcat)) {
238c0dd9 3012 notify("Error moving category $childcat->name");
e2b347e9 3013 return false;
3014 }
3015 }
3016 }
3017
cb6fec1f 3018 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC', 'id')) {
e2b347e9 3019 if (!move_courses(array_keys($courses), $newparentid)) {
238c0dd9 3020 notify("Error moving courses");
e2b347e9 3021 return false;
3022 }
238c0dd9 3023 notify(get_string('coursesmovedout', '', format_string($category->name)), 'notifysuccess');
e2b347e9 3024 }
3025
3026 // now delete anything that may depend on course category context
3027 grade_course_category_delete($category->id, $newparentid, $showfeedback);
3028 if (!question_delete_course_category($category, $newparentcat, $showfeedback)) {
238c0dd9 3029 notify(get_string('errordeletingquestionsfromcategory', 'question', $category), 'notifysuccess');
e2b347e9 3030 return false;
3031 }
3032
3033 // finally delete the category and it's context
cb6fec1f 3034 $DB->delete_records('course_categories', array('id'=>$category->id));
e2b347e9 3035 delete_context(CONTEXT_COURSECAT, $category->id);
3036
2942a5cd 3037 events_trigger('course_category_deleted', $category);
e2b347e9 3038
238c0dd9 3039 notify(get_string('coursecategorydeleted', '', format_string($category->name)), 'notifysuccess');
e2b347e9 3040
3041 return true;
3042}
3043
cb6fec1f 3044/**
3045 * Efficiently moves many courses around while maintaining
3046 * sortorder in order.
3047 *
3048 * @param $courseids is an array of course ids
3049 */
3050function move_courses($courseids, $categoryid) {
3051 global $CFG, $DB;
861efb19 3052
0cbe8111 3053 if (!empty($courseids) and $category = $DB->get_record('course_categories', array('id'=>$categoryid))) {
3054 $courseids = array_reverse($courseids);
3055 $i = 1;
264867fd 3056
0cbe8111 3057 foreach ($courseids as $courseid) {
3058 if (!$course = $DB->get_record("course", array("id"=>$courseid))) {
3059 notify("Error finding course $courseid");
3060 } else {
3061 $course->category = $categoryid;
3062 $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
19f601d1 3063
0cbe8111 3064 if (!$DB->update_record('course', $course)) {
3065 notify("An error occurred - course not moved!");
861efb19 3066 }
0cbe8111 3067
3068 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3069 $newparent = get_context_instance(CONTEXT_COURSECAT, $course->category);
3070 context_moved($context, $newparent);
861efb19 3071 }
264867fd 3072 }
0cbe8111 3073 fix_course_sortorder();
3074 }
861efb19 3075 return true;
3076}
3077
cb6fec1f 3078/**
3079 * Efficiently moves a category - NOTE that this can have
3080 * a huge impact access-control-wise...
3081 */
19f601d1 3082function move_category ($category, $newparentcat) {
cb6fec1f 3083 global $CFG, $DB;
19f601d1 3084
1f41940f 3085 $context = get_context_instance(CONTEXT_COURSECAT, $category->id);
3086
3087 if (empty($newparentcat->id)) {
cb6fec1f 3088 if (!$DB->set_field('course_categories', 'parent', 0, array('id'=>$category->id))) {
1f41940f 3089 return false;
3090 }
0cbe8111 3091
1f41940f 3092 $newparent = get_context_instance(CONTEXT_SYSTEM);
0cbe8111 3093
1f41940f 3094 } else {
cb6fec1f 3095 if (!$DB->set_field('course_categories', 'parent', $newparentcat->id, array('id'=>$category->id))) {
1f41940f 3096 return false;
3097 }
3098 $newparent = get_context_instance(CONTEXT_COURSECAT, $newparentcat->id);
19f601d1 3099 }
3100
19f601d1 3101 context_moved($context, $newparent);
3102
3440ec12 3103 // now make it last in new category
0cbe8111 3104 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('id'=>$category->id));
3105
3106 // and fix the sortorders
19f601d1 3107 fix_course_sortorder();
238c0dd9 3108
19f601d1 3109 return true;
3110}
3111
ae628043 3112/**
3113 * @param string $format Course format ID e.g. 'weeks'
3114 * @return Name that the course format prefers for sections
3115 */
3116function get_section_name($format) {
3117 $sectionname = get_string("name$format","format_$format");
3118 if($sectionname == "[[name$format]]") {
3119 $sectionname = get_string("name$format");
3120 }
a044c05d 3121 return $sectionname;
ae628043 3122}
3123
2585a68d 3124/**
3125 * Can the current user delete this course?
3126 * @param int $courseid
3127 * @return boolean
3128 *
3129 * Exception here to fix MDL-7796.
3130 *
3131 * FIXME
3132 * Course creators who can manage activities in the course
3133 * shoule be allowed to delete the course. We do it this
3134 * way because we need a quick fix to bring the functionality
3135 * in line with what we had pre-roles. We can't give the
3136 * default course creator role moodle/course:delete at
3137 * CONTEXT_SYSTEM level because this will allow them to
3138 * delete any course in the site. So we hard code this here
3139 * for now.
3140 *