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