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