MDL-17816: Minor whitespace fixes before I work on the actual bug
[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
dd97c328 1087/**
1088 * Returns reference to full info about modules in course (including visibility).
1089 * Cached and as fast as possible (0 or 1 db query).
65a00c97 1090 * @param $course object or 'reset' string to reset caches, modinfo may be updated in db
dd97c328 1091 * @return mixed courseinfo object or nothing if resetting
1092 */
65a00c97 1093function &get_fast_modinfo(&$course, $userid=0) {
cb6fec1f 1094 global $CFG, $USER, $DB;
d91a4be0 1095 if (!empty($CFG->enableavailability)) {
82bd6a5e 1096 require_once($CFG->libdir.'/conditionlib.php');
1097 }
dd97c328 1098
1099 static $cache = array();
1100
1101 if ($course === 'reset') {
1102 $cache = array();
1103 $nothing = null;
1104 return $nothing; // we must return some reference
1105 }
1106
1107 if (empty($userid)) {
1108 $userid = $USER->id;
1109 }
1110
1111 if (array_key_exists($course->id, $cache) and $cache[$course->id]->userid == $userid) {
1112 return $cache[$course->id];
1113 }
1114
1115 if (empty($course->modinfo)) {
1116 // no modinfo yet - load it
1117 rebuild_course_cache($course->id);
cb6fec1f 1118 $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
dd97c328 1119 }
1120
1121 $modinfo = new object();
1122 $modinfo->courseid = $course->id;
1123 $modinfo->userid = $userid;
1124 $modinfo->sections = array();
1125 $modinfo->cms = array();
1126 $modinfo->instances = array();
1127 $modinfo->groups = null; // loaded only when really needed - the only one db query
1128
1129 $info = unserialize($course->modinfo);
1130 if (!is_array($info)) {
1131 // hmm, something is wrong - lets try to fix it
1132 rebuild_course_cache($course->id);
cb6fec1f 1133 $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
dd97c328 1134 $info = unserialize($course->modinfo);
1135 if (!is_array($info)) {
1136 return $modinfo;
1137 }
1138 }
1139
1140 if ($info) {
1141 // detect if upgrade required
1142 $first = reset($info);
1143 if (!isset($first->id)) {
1144 rebuild_course_cache($course->id);
cb6fec1f 1145 $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
dd97c328 1146 $info = unserialize($course->modinfo);
1147 if (!is_array($info)) {
1148 return $modinfo;
1149 }
1150 }
1151 }
1152
1153 $modlurals = array();
1154
00653161 1155 // If we haven't already preloaded contexts for the course, do it now
1156 preload_course_contexts($course->id);
65bcf17b 1157
dd97c328 1158 foreach ($info as $mod) {
7c3b032e 1159 if (empty($mod->name)) {
1160 // something is wrong here
1161 continue;
1162 }
dd97c328 1163 // reconstruct minimalistic $cm
1164 $cm = new object();
1165 $cm->id = $mod->cm;
1166 $cm->instance = $mod->id;
1167 $cm->course = $course->id;
1168 $cm->modname = $mod->mod;
1169 $cm->name = urldecode($mod->name);
1170 $cm->visible = $mod->visible;
76cbde41 1171 $cm->sectionnum = $mod->section;
dd97c328 1172 $cm->groupmode = $mod->groupmode;
1173 $cm->groupingid = $mod->groupingid;
1174 $cm->groupmembersonly = $mod->groupmembersonly;
82bd6a5e 1175 $cm->indent = $mod->indent;
1176 $cm->completion = $mod->completion;
dd97c328 1177 $cm->extra = isset($mod->extra) ? urldecode($mod->extra) : '';
1178 $cm->icon = isset($mod->icon) ? $mod->icon : '';
1179 $cm->uservisible = true;
82bd6a5e 1180 if(!empty($CFG->enableavailability)) {
1181 // We must have completion information from modinfo. If it's not
1182 // there, cache needs rebuilding
1183 if(!isset($mod->availablefrom)) {
1184 debugging('enableavailability option was changed; rebuilding '.
1185 'cache for course '.$course->id);
1186 rebuild_course_cache($course->id,true);
1187 // Re-enter this routine to do it all properly
1188 return get_fast_modinfo($course,$userid);
1189 }
1190 $cm->availablefrom = $mod->availablefrom;
1191 $cm->availableuntil = $mod->availableuntil;
1192 $cm->showavailability = $mod->showavailability;
1193 $cm->conditionscompletion = $mod->conditionscompletion;
1194 $cm->conditionsgrade = $mod->conditionsgrade;
1195 }
dd97c328 1196
7c3b032e 1197 // preload long names plurals and also check module is installed properly
dd97c328 1198 if (!isset($modlurals[$cm->modname])) {
7c3b032e 1199 if (!file_exists("$CFG->dirroot/mod/$cm->modname/lib.php")) {
1200 continue;
1201 }
dd97c328 1202 $modlurals[$cm->modname] = get_string('modulenameplural', $cm->modname);
1203 }
1204 $cm->modplural = $modlurals[$cm->modname];
00653161 1205 $modcontext = get_context_instance(CONTEXT_MODULE,$cm->id);
1206
82bd6a5e 1207 if(!empty($CFG->enableavailability)) {
1208 // Unfortunately the next call really wants to call
1209 // get_fast_modinfo, but that would be recursive, so we fake up a
1210 // modinfo for it already
1211 if(empty($minimalmodinfo)) {
1212 $minimalmodinfo=new stdClass();
1213 $minimalmodinfo->cms=array();
1214 foreach($info as $mod) {
1215 $minimalcm=new stdClass();
1216 $minimalcm->id=$mod->cm;
1217 $minimalcm->name=urldecode($mod->name);
1218 $minimalmodinfo->cms[$minimalcm->id]=$minimalcm;
1219 }
1220 }
1221
1222 // Get availability information
1223 $ci = new condition_info($cm);
1224 $cm->available=$ci->is_available($cm->availableinfo,true,$userid,
1225 $minimalmodinfo);
1226 } else {
1227 $cm->available=true;
1228 }
00653161 1229 if ((!$cm->visible or !$cm->available) and !has_capability('moodle/course:viewhiddenactivities', $modcontext, $userid)) {
dd97c328 1230 $cm->uservisible = false;
1231
1232 } else if (!empty($CFG->enablegroupings) and !empty($cm->groupmembersonly)
00653161 1233 and !has_capability('moodle/site:accessallgroups', $modcontext, $userid)) {
dd97c328 1234 if (is_null($modinfo->groups)) {
1235 $modinfo->groups = groups_get_user_groups($course->id, $userid);
1236 }
1237 if (empty($modinfo->groups[$cm->groupingid])) {
1238 $cm->uservisible = false;
1239 }
1240 }
1241
1242 if (!isset($modinfo->instances[$cm->modname])) {
1243 $modinfo->instances[$cm->modname] = array();
1244 }
1245 $modinfo->instances[$cm->modname][$cm->instance] =& $cm;
1246 $modinfo->cms[$cm->id] =& $cm;
1247
1248 // reconstruct sections
76cbde41 1249 if (!isset($modinfo->sections[$cm->sectionnum])) {
1250 $modinfo->sections[$cm->sectionnum] = array();
dd97c328 1251 }
76cbde41 1252 $modinfo->sections[$cm->sectionnum][] = $cm->id;
dd97c328 1253
1254 unset($cm);
1255 }
1256
76cbde41 1257 unset($cache[$course->id]); // prevent potential reference problems when switching users
dd97c328 1258 $cache[$course->id] = $modinfo;
1259
4d10247f 1260 // Ensure cache does not use too much RAM
1261 if (count($cache) > MAX_MODINFO_CACHE_SIZE) {
1262 array_shift($cache);
1263 }
1264
dd97c328 1265 return $cache[$course->id];
1266}
d897cae4 1267
cb6fec1f 1268/**
1269 * Returns a number of useful structures for course displays
1270 */
90845098 1271function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
82bd6a5e 1272 global $DB,$COURSE;
7468bf01 1273
dd97c328 1274 $mods = array(); // course modules indexed by id
1275 $modnames = array(); // all course module names (except resource!)
1276 $modnamesplural= array(); // all course module names (plural form)
1277 $modnamesused = array(); // course module names used
7468bf01 1278
cb6fec1f 1279 if ($allmods = $DB->get_records("modules")) {
90845098 1280 foreach ($allmods as $mod) {
5867bfb5 1281 if ($mod->visible) {
1282 $modnames[$mod->name] = get_string("modulename", "$mod->name");
1283 $modnamesplural[$mod->name] = get_string("modulenameplural", "$mod->name");
1284 }
90845098 1285 }
91374f3e 1286 asort($modnames, SORT_LOCALE_STRING);
90845098 1287 } else {
ba6018a9 1288 print_error("nomodules", 'debug');
90845098 1289 }
1290
82bd6a5e 1291 $course = ($courseid==$COURSE->id) ? $COURSE : $DB->get_record('course',array('id'=>$courseid));
1292 $modinfo = get_fast_modinfo($course);
1293
1294 if ($rawmods=$modinfo->cms) {
7468bf01 1295 foreach($rawmods as $mod) { // Index the mods
959ae824 1296 if (empty($modnames[$mod->modname])) {
1297 continue;
1298 }
dd97c328 1299 $mods[$mod->id] = $mod;
1300 $mods[$mod->id]->modfullname = $modnames[$mod->modname];
1301 if (!$mod->visible and !has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_COURSE, $courseid))) {
1302 continue;
1303 }
13534ef7
ML
1304 // Check groupings
1305 if (!groups_course_module_visible($mod)) {
1306 continue;
1307 }
dd97c328 1308 $modnamesused[$mod->modname] = $modnames[$mod->modname];
7468bf01 1309 }
c7da6f7a 1310 if ($modnamesused) {
dba21d4a 1311 asort($modnamesused, SORT_LOCALE_STRING);
c7da6f7a 1312 }
7468bf01 1313 }
7468bf01 1314}
1315
9fa49e22 1316
7468bf01 1317function get_all_sections($courseid) {
cb6fec1f 1318 global $DB;
1319 return $DB->get_records("course_sections", array("course"=>"$courseid"), "section",
7d99d695 1320 "section, id, course, summary, sequence, visible");
7468bf01 1321}
1322
b86fc0e2 1323function course_set_display($courseid, $display=0) {
cb6fec1f 1324 global $USER, $DB;
b86fc0e2 1325
b86fc0e2 1326 if ($display == "all" or empty($display)) {
1327 $display = 0;
1328 }
1329
7b678e0a 1330 if (empty($USER->id) or $USER->username == 'guest') {
1331 //do not store settings in db for guests
238c0dd9 1332 } else if ($DB->record_exists("course_display", array("userid" => $USER->id, "course"=>$courseid))) {
cb6fec1f 1333 $DB->set_field("course_display", "display", $display, array("userid"=>$USER->id, "course"=>$courseid));
b86fc0e2 1334 } else {
dd97c328 1335 $record = new object();
b86fc0e2 1336 $record->userid = $USER->id;
1337 $record->course = $courseid;
1338 $record->display = $display;
cb6fec1f 1339 if (!$DB->insert_record("course_display", $record)) {
b86fc0e2 1340 notify("Could not save your course display!");
1341 }
1342 }
1343
1344 return $USER->display[$courseid] = $display; // Note: = not ==
1345}
1346
cb6fec1f 1347/**
1348 * For a given course section, markes it visible or hidden,
1349 * and does the same for every activity in that section
1350 */
7d99d695 1351function set_section_visible($courseid, $sectionnumber, $visibility) {
cb6fec1f 1352 global $DB;
7d99d695 1353
cb6fec1f 1354 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
1355 $DB->set_field("course_sections", "visible", "$visibility", array("id"=>$section->id));
7d99d695 1356 if (!empty($section->sequence)) {
1357 $modules = explode(",", $section->sequence);
1358 foreach ($modules as $moduleid) {
02f66c42 1359 set_coursemodule_visible($moduleid, $visibility, true);
7d99d695 1360 }
1361 }
5867bfb5 1362 rebuild_course_cache($courseid);
7d99d695 1363 }
1364}
ba2e5d73 1365
cb6fec1f 1366/**
1367 * Prints a section full of activity modules
1368 */
4e781c7b 1369function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%", $hidecompletion=false) {
cb6fec1f 1370 global $CFG, $USER, $DB;
7977cffd 1371
dd97c328 1372 static $initialised;
1373
3d575e6f 1374 static $groupbuttons;
32d03b7b 1375 static $groupbuttonslink;
52dcc2f9 1376 static $isediting;
7977cffd 1377 static $ismoving;
1378 static $strmovehere;
1379 static $strmovefull;
54669989 1380 static $strunreadpostsone;
a2d71d8e 1381 static $usetracking;
dd97c328 1382 static $groupings;
4877707e 1383
110a32e2 1384
dd97c328 1385 if (!isset($initialised)) {
9fd9c29b 1386 $groupbuttons = ($course->groupmode or (!$course->groupmodeforce));
32d03b7b 1387 $groupbuttonslink = (!$course->groupmodeforce);
dd97c328 1388 $isediting = isediting($course->id);
1389 $ismoving = $isediting && ismoving($course->id);
3d575e6f 1390 if ($ismoving) {
dd97c328 1391 $strmovehere = get_string("movehere");
1392 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
3d575e6f 1393 }
94a6a70f 1394 include_once($CFG->dirroot.'/mod/forum/lib.php');
1395 if ($usetracking = forum_tp_can_track_forums()) {
dd97c328 1396 $strunreadpostsone = get_string('unreadpostsone', 'forum');
a2d71d8e 1397 }
dd97c328 1398 $initialised = true;
7977cffd 1399 }
dd97c328 1400
1401 $labelformatoptions = new object();
60bd11cf 1402 $labelformatoptions->noclean = true;
94361e02 1403
fea43a7f 1404/// Casting $course->modinfo to string prevents one notice when the field is null
dd97c328 1405 $modinfo = get_fast_modinfo($course);
238c0dd9 1406
94361e02 1407
c6a55371 1408 //Acccessibility: replace table with list <ul>, but don't output empty list.
74666583 1409 if (!empty($section->sequence)) {
94361e02 1410
f2d660dc 1411 // Fix bug #5027, don't want style=\"width:$width\".
6285f8a8 1412 echo "<ul class=\"section img-text\">\n";
94361e02 1413 $sectionmods = explode(",", $section->sequence);
1414
1415 foreach ($sectionmods as $modnumber) {
9ae687af 1416 if (empty($mods[$modnumber])) {
1417 continue;
1418 }
dd97c328 1419
94361e02 1420 $mod = $mods[$modnumber];
c9f6251e 1421
dd97c328 1422 if ($ismoving and $mod->id == $USER->activitycopy) {
1423 // do not display moving mod
1424 continue;
1425 }
c9f6251e 1426
dd97c328 1427 if (isset($modinfo->cms[$modnumber])) {
85f55ba2 1428 // We can continue (because it will not be displayed at all)
1429 // if:
1430 // 1) The activity is not visible to users
1431 // and
1432 // 2a) The 'showavailability' option is not set (if that is set,
1433 // we need to display the activity so we can show
1434 // availability info)
1435 // or
1436 // 2b) The 'availableinfo' is empty, i.e. the activity was
1437 // hidden in a way that leaves no info, such as using the
1438 // eye icon.
82bd6a5e 1439 if (!$modinfo->cms[$modnumber]->uservisible &&
85f55ba2 1440 (empty($modinfo->cms[$modnumber]->showavailability) ||
1441 empty($modinfo->cms[$modnumber]->availableinfo))) {
dd97c328 1442 // visibility shortcut
1443 continue;
86aa7ccf 1444 }
dd97c328 1445 } else {
0f56c9da 1446 if (!file_exists("$CFG->dirroot/mod/$mod->modname/lib.php")) {
1447 // module not installed
1448 continue;
1449 }
82bd6a5e 1450 if (!coursemodule_visible_for_user($mod) &&
1451 empty($mod->showavailability)) {
dd97c328 1452 // full visibility check
1453 continue;
9d361034 1454 }
dd97c328 1455 }
1456
1457 echo '<li class="activity '.$mod->modname.'" id="module-'.$modnumber.'">'; // Unique ID
1458 if ($ismoving) {
1459 echo '<a title="'.$strmovefull.'"'.
d4a1fcaf 1460 ' href="'.$CFG->wwwroot.'/course/mod.php?moveto='.$mod->id.'&amp;sesskey='.sesskey().'">'.
dd97c328 1461 '<img class="movetarget" src="'.$CFG->pixpath.'/movehere.gif" '.
1462 ' alt="'.$strmovehere.'" /></a><br />
1463 ';
1464 }
9d361034 1465
dd97c328 1466 if ($mod->indent) {
1467 print_spacer(12, 20 * $mod->indent, false);
1468 }
1469
554606c7 1470 $extra = '';
1471 if (!empty($modinfo->cms[$modnumber]->extra)) {
82bd6a5e 1472 $extra = $modinfo->cms[$modnumber]->extra;
554606c7 1473 }
dd97c328 1474
1475 if ($mod->modname == "label") {
82bd6a5e 1476 if (!$mod->visible || !$mod->uservisible) {
85f55ba2 1477 echo '<div class="dimmed_text"><span class="accesshide">'.
4a087123 1478 get_string('hiddenfromstudents').'</span>';
dd97c328 1479 }
1480 echo format_text($extra, FORMAT_HTML, $labelformatoptions);
4a087123 1481 if (!$mod->visible || !$mod->uservisible) {
9009a990 1482 echo "</div>";
aac94fd0 1483 }
c4d989a1 1484 if (!empty($CFG->enablegroupings) && !empty($mod->groupingid) && has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
1485 if (!isset($groupings)) {
1486 $groupings = groups_get_all_groupings($course->id);
1487 }
1470825e 1488 echo " <span class=\"groupinglabel\">(".format_string($groupings[$mod->groupingid]->name).')</span>';
c4d989a1 1489 }
aac94fd0 1490
dd97c328 1491 } else { // Normal activity
1492 $instancename = format_string($modinfo->cms[$modnumber]->name, true, $course->id);
c9f6251e 1493
c93dae38 1494 $customicon = $modinfo->cms[$modnumber]->icon;
1495 if (!empty($customicon)) {
1496 if (substr($customicon, 0, 4) === 'mod/') {
1497 $icon = "$CFG->modpixpath/".substr($customicon, 4);
1498 } else {
1499 $icon = "$CFG->pixpath/".$customicon;
1500 }
dd97c328 1501 } else {
1502 $icon = "$CFG->modpixpath/$mod->modname/icon.gif";
1503 }
e0b033d5 1504
dd97c328 1505 //Accessibility: for files get description via icon.
1506 $altname = '';
1507 if ('resource'==$mod->modname) {
c93dae38 1508 if (!empty($customicon)) {
1509 $possaltname = $customicon;
6285f8a8 1510
dd97c328 1511 $mimetype = mimeinfo_from_icon('type', $possaltname);
1512 $altname = get_mimetype_description($mimetype);
6285f8a8 1513 } else {
1514 $altname = $mod->modfullname;
1515 }
dd97c328 1516 } else {
1517 $altname = $mod->modfullname;
1518 }
1519 // Avoid unnecessary duplication.
1520 if (false!==stripos($instancename, $altname)) {
1521 $altname = '';
1522 }
1523 // File type after name, for alphabetic lists (screen reader).
1524 if ($altname) {
1525 $altname = get_accesshide(' '.$altname);
1526 }
6285f8a8 1527
82bd6a5e 1528 // We may be displaying this just in order to show information
1529 // about visibility, without the actual link
52dbbcf6 1530 if ($mod->uservisible) {
82bd6a5e 1531 // Display normal module link
52dbbcf6 1532 if ($mod->visible) {
1533 $linkcss = '';
1534 $accesstext ='';
85f55ba2 1535 } else {
1536 $linkcss = ' class="dimmed" ';
52dbbcf6 1537 $accesstext = '<span class="accesshide">'.
85f55ba2 1538 get_string('hiddenfromstudents').': </span>';
1539 }
52dbbcf6 1540
85f55ba2 1541 echo '<a '.$linkcss.' '.$extra.
1542 ' href="'.$CFG->wwwroot.'/mod/'.$mod->modname.'/view.php?id='.$mod->id.'">'.
1543 '<img src="'.$icon.'" class="activityicon" alt="" /> '.
1544 $accesstext.'<span>'.$instancename.$altname.'</span></a>';
82bd6a5e 1545
1546 if (!empty($CFG->enablegroupings) && !empty($mod->groupingid) && has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
1547 if (!isset($groupings)) {
1548 $groupings = groups_get_all_groupings($course->id);
1549 }
1550 echo " <span class=\"groupinglabel\">(".format_string($groupings[$mod->groupingid]->name).')</span>';
acf000b0 1551 }
82bd6a5e 1552 } else {
1553 // Display greyed-out text of link
85f55ba2 1554 echo '<span class="dimmed_text" '.$extra.' ><span class="accesshide">'.
1555 get_string('notavailableyet','condition').': </span>'.
1556 '<img src="'.$icon.'" class="activityicon" alt="" /> <span>'.
1557 $instancename.$altname.'</span></span>';
c9f6251e 1558 }
dd97c328 1559 }
1560 if ($usetracking && $mod->modname == 'forum') {
90f4745c 1561 if ($unread = forum_tp_count_forum_unread_posts($mod, $course)) {
1562 echo '<span class="unread"> <a href="'.$CFG->wwwroot.'/mod/forum/view.php?id='.$mod->id.'">';
1563 if ($unread == 1) {
1564 echo $strunreadpostsone;
1565 } else {
1566 print_string('unreadpostsnumber', 'forum', $unread);
54669989 1567 }
90f4745c 1568 echo '</a></span>';
f37da850 1569 }
dd97c328 1570 }
f37da850 1571
dd97c328 1572 if ($isediting) {
1573 // TODO: we must define this as mod property!
1574 if ($groupbuttons and $mod->modname != 'label' and $mod->modname != 'resource' and $mod->modname != 'glossary') {
1575 if (! $mod->groupmodelink = $groupbuttonslink) {
1576 $mod->groupmode = $course->groupmode;
3d575e6f 1577 }
dd97c328 1578
1579 } else {
1580 $mod->groupmode = false;
c9f6251e 1581 }
dd97c328 1582 echo '&nbsp;&nbsp;';
1583 echo make_editing_buttons($mod, $absolute, true, $mod->indent, $section->section);
94361e02 1584 }
4e781c7b 1585
1586 // Completion
1587 $completioninfo=new completion_info($course);
1588 $completion=$hidecompletion
1589 ? COMPLETION_TRACKING_NONE
1590 : $completioninfo->is_enabled($mod);
82bd6a5e 1591 if($completion!=COMPLETION_TRACKING_NONE && isloggedin() &&
1592 !isguestuser() && $mod->uservisible) {
4e781c7b 1593 $completiondata=$completioninfo->get_data($mod,true);
1594 $completionicon='';
1595 if($isediting) {
1596 switch($completion) {
ca255392 1597 case COMPLETION_TRACKING_MANUAL :
4e781c7b 1598 $completionicon='manual-enabled'; break;
ca255392 1599 case COMPLETION_TRACKING_AUTOMATIC :
4e781c7b 1600 $completionicon='auto-enabled'; break;
1601 default: // wtf
1602 }
1603 } else if($completion==COMPLETION_TRACKING_MANUAL) {
1604 switch($completiondata->completionstate) {
1605 case COMPLETION_INCOMPLETE:
1606 $completionicon='manual-n'; break;
1607 case COMPLETION_COMPLETE:
1608 $completionicon='manual-y'; break;
1609 }
1610 } else { // Automatic
1611 switch($completiondata->completionstate) {
1612 case COMPLETION_INCOMPLETE:
1613 $completionicon='auto-n'; break;
1614 case COMPLETION_COMPLETE:
1615 $completionicon='auto-y'; break;
1616 case COMPLETION_COMPLETE_PASS:
1617 $completionicon='auto-pass'; break;
1618 case COMPLETION_COMPLETE_FAIL:
1619 $completionicon='auto-fail'; break;
1620 }
1621 }
1622 if($completionicon) {
f17a0360 1623 static $shownhelp=false;
4e781c7b 1624 $imgsrc=$CFG->pixpath.'/i/completion-'.$completionicon.'.gif';
1625 $imgalt=get_string('completion-alt-'.$completionicon,'completion');
1626 if($completion==COMPLETION_TRACKING_MANUAL && !$isediting) {
1627 $imgtitle=get_string('completion-title-'.$completionicon,'completion');
1628 $newstate=
1629 $completiondata->completionstate==COMPLETION_COMPLETE
ca255392 1630 ? COMPLETION_INCOMPLETE
1631 : COMPLETION_COMPLETE;
a343b13f 1632 // In manual mode the icon is a toggle form...
1633
1634 // If this completion state is used by the
1635 // conditional activities system, we need to turn
1636 // off the JS.
1637 if (!empty($CFG->enableavailability) &&
1638 condition_info::completion_value_used_as_condition(
1639 $course, $mod)) {
1640 $extraclass = ' preventjs';
1641 } else {
1642 $extraclass = '';
1643 }
4e781c7b 1644 echo "
a343b13f 1645<form class='togglecompletion$extraclass' method='post' action='togglecompletion.php'><div>";
5c168a03 1646 if(!$shownhelp && !$isediting) {
f17a0360 1647 helpbutton('completionicons',get_string('completionicons','completion'),'completion');
1648 $shownhelp=true;
1649 }
1650 echo "
4e781c7b 1651<input type='hidden' name='id' value='{$mod->id}' />
1652<input type='hidden' name='completionstate' value='$newstate' />
1653<input type='image' src='$imgsrc' alt='$imgalt' title='$imgtitle' />
1654</div></form>";
1655 } else {
1656 // In auto mode, or when editing, the icon is just an image
f17a0360 1657 echo "<span class='autocompletion'>";
5c168a03 1658 if(!$shownhelp && !$isediting) {
f17a0360 1659 helpbutton('completionicons',get_string('completionicons','completion'),'completion');
1660 $shownhelp=true;
1661 }
1662 echo "<img src='$imgsrc' alt='$imgalt' title='$imgalt' /></span>";
4e781c7b 1663 }
1664 }
1665 }
1666
82bd6a5e 1667 // Show availability information (for someone who isn't allowed to
1668 // see the activity itself, or for staff)
1669 if(!$mod->uservisible) {
1670 echo '<div class="availabilityinfo">'.$mod->availableinfo.'</div>';
1671 } else if($isediting && !empty($CFG->enableavailability)) {
1672 $ci = new condition_info($mod);
1673 $fullinfo=$ci->get_full_information();
1674 if($fullinfo) {
1675 echo '<div class="availabilityinfo">'.get_string($mod->showavailability
1676 ? 'userrestriction_visible'
1677 : 'userrestriction_hidden','condition',
1678 $fullinfo).'</div>';
1679 }
1680 }
1681
dd97c328 1682 echo "</li>\n";
94361e02 1683 }
dd97c328 1684
f2d660dc 1685 } elseif ($ismoving) {
1686 echo "<ul class=\"section\">\n";
264867fd 1687 }
dd97c328 1688
7977cffd 1689 if ($ismoving) {
64fdc686 1690 echo '<li><a title="'.$strmovefull.'"'.
d4a1fcaf 1691 ' href="'.$CFG->wwwroot.'/course/mod.php?movetosection='.$section->id.'&amp;sesskey='.sesskey().'">'.
446390fb 1692 '<img class="movetarget" src="'.$CFG->pixpath.'/movehere.gif" '.
c6a55371 1693 ' alt="'.$strmovehere.'" /></a></li>
1c919752 1694 ';
7977cffd 1695 }
c6a55371 1696 if (!empty($section->sequence) || $ismoving) {
1697 echo "</ul><!--class='section'-->\n\n";
1698 }
a7ad3ea6 1699}
1700
89bfeee0 1701/**
1702 * Prints the menus to add activities and resources.
1703 */
cb57e6f4 1704function print_section_add_menus($course, $section, $modnames, $vertical=false, $return=false) {
89bfeee0 1705 global $CFG;
e0161bff 1706
217a8ee9 1707 // check to see if user can add menus
1708 if (!has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $course->id))) {
e2cd3ed0 1709 return false;
217a8ee9 1710 }
1711
89bfeee0 1712 static $resources = false;
1713 static $activities = false;
e0161bff 1714
238c0dd9 1715 if ($resources === false) {
89bfeee0 1716 $resources = array();
1717 $activities = array();
6da4b261 1718
89bfeee0 1719 foreach($modnames as $modname=>$modnamestr) {
1720 if (!course_allowed_module($course, $modname)) {
1721 continue;
1722 }
6da4b261 1723
ffd58dd6 1724 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1725 if (!file_exists($libfile)) {
1726 continue;
1727 }
1728 include_once($libfile);
89bfeee0 1729 $gettypesfunc = $modname.'_get_types';
1730 if (function_exists($gettypesfunc)) {
1731 $types = $gettypesfunc();
1732 foreach($types as $type) {
65bcf17b 1733 if (!isset($type->modclass) or !isset($type->typestr)) {
ddb0a19f 1734 debugging('Incorrect activity type in '.$modname);
65bcf17b 1735 continue;
1736 }
89bfeee0 1737 if ($type->modclass == MOD_CLASS_RESOURCE) {
1738 $resources[$type->type] = $type->typestr;
1739 } else {
1740 $activities[$type->type] = $type->typestr;
1741 }
1742 }
1743 } else {
1744 // all mods without type are considered activity
1745 $activities[$modname] = $modnamestr;
1746 }
0705ff84 1747 }
e0161bff 1748 }
1749
89bfeee0 1750 $straddactivity = get_string('addactivity');
1751 $straddresource = get_string('addresource');
1752
4f24b3e3 1753 $output = '<div class="section_add_menus">';
1754
1755 if (!$vertical) {
1756 $output .= '<div class="horizontal">';
1757 }
89bfeee0 1758
1759 if (!empty($resources)) {
1760 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&amp;section=$section&amp;sesskey=".sesskey()."&amp;add=",
0705ff84 1761 $resources, "ressection$section", "", $straddresource, 'resource/types', $straddresource, true);
1762 }
cb57e6f4 1763
89bfeee0 1764 if (!empty($activities)) {
1765 $output .= ' ';
1766 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&amp;section=$section&amp;sesskey=".sesskey()."&amp;add=",
1767 $activities, "section$section", "", $straddactivity, 'mods', $straddactivity, true);
0705ff84 1768 }
1769
4f24b3e3 1770 if (!$vertical) {
d33d0cda 1771 $output .= '</div>';
1772 }
1773
cb57e6f4 1774 $output .= '</div>';
1775
1776 if ($return) {
1777 return $output;
1778 } else {
1779 echo $output;
1780 }
e0161bff 1781}
1782
8ed5dd63 1783/**
1784 * Return the course category context for the category with id $categoryid, except
1785 * that if $categoryid is 0, return the system context.
1786 *
1787 * @param integer $categoryid a category id or 0.
1788 * @return object the corresponding context
1789 */
1790function get_category_or_system_context($categoryid) {
1791 if ($categoryid) {
1792 return get_context_instance(CONTEXT_COURSECAT, $categoryid);
1793 } else {
1794 return get_context_instance(CONTEXT_SYSTEM);
1795 }
1796}
1797
f36cbf1d 1798/**
1799 * Rebuilds the cached list of course activities stored in the database
1800 * @param int $courseid - id of course to rebuil, empty means all
1801 * @param boolean $clearonly - only clear the modinfo fields, gets rebuild automatically on the fly
1802 */
1803function rebuild_course_cache($courseid=0, $clearonly=false) {
f33e1ed4 1804 global $COURSE, $DB;
f36cbf1d 1805
1806 if ($clearonly) {
1c69b885 1807 if (empty($courseid)) {
1808 $courseselect = array();
1809 } else {
1810 $courseselect = array('id'=>$courseid);
1811 }
1812 $DB->set_field('course', 'modinfo', null, $courseselect);
f36cbf1d 1813 // update cached global COURSE too ;-)
1814 if ($courseid == $COURSE->id) {
238c0dd9 1815 $COURSE->modinfo = null;
f36cbf1d 1816 }
1817 // reset the fast modinfo cache
1818 $reset = 'reset';
1819 get_fast_modinfo($reset);
1820 return;
1821 }
5867bfb5 1822
1823 if ($courseid) {
cb6fec1f 1824 $select = array('id'=>$courseid);
5867bfb5 1825 } else {
cb6fec1f 1826 $select = array();
6cf890e3 1827 @set_time_limit(0); // this could take a while! MDL-10954
5867bfb5 1828 }
1829
cb6fec1f 1830 if ($rs = $DB->get_recordset("course", $select,'','id,fullname')) {
1831 foreach ($rs as $course) {
5867bfb5 1832 $modinfo = serialize(get_array_of_activities($course->id));
cb6fec1f 1833 if (!$DB->set_field("course", "modinfo", $modinfo, array("id"=>$course->id))) {
6ba65fa0 1834 notify("Could not cache module information for course '" . format_string($course->fullname) . "'!");
5867bfb5 1835 }
dd97c328 1836 // update cached global COURSE too ;-)
1837 if ($course->id == $COURSE->id) {
238c0dd9 1838 $COURSE->modinfo = $modinfo;
dd97c328 1839 }
5867bfb5 1840 }
cb6fec1f 1841 $rs->close();
5867bfb5 1842 }
dd97c328 1843 // reset the fast modinfo cache
65a00c97 1844 $reset = 'reset';
1845 get_fast_modinfo($reset);
5867bfb5 1846}
1847
cb6fec1f 1848/**
8ed5dd63 1849 * Gets the child categories of a given coures category. Uses a static cache
1850 * to make repeat calls efficient.
1851 *
1852 * @param unknown_type $parentid the id of a course category.
1853 * @return array all the child course categories.
cb6fec1f 1854 */
8ed5dd63 1855function get_child_categories($parentid) {
9bb19e58 1856 static $allcategories = null;
1857
1858 // only fill in this variable the first time
1859 if (null == $allcategories) {
1860 $allcategories = array();
1861
1862 $categories = get_categories();
1863 foreach ($categories as $category) {
1864 if (empty($allcategories[$category->parent])) {
1865 $allcategories[$category->parent] = array();
1866 }
1867 $allcategories[$category->parent][] = $category;
1868 }
1869 }
1870
8ed5dd63 1871 if (empty($allcategories[$parentid])) {
9bb19e58 1872 return array();
1873 } else {
8ed5dd63 1874 return $allcategories[$parentid];
9bb19e58 1875 }
1876}
1877
cb6fec1f 1878/**
8ed5dd63 1879 * This function recursively travels the categories, building up a nice list
1880 * for display. It also makes an array that list all the parents for each
1881 * category.
1882 *
1883 * For example, if you have a tree of categories like:
1884 * Miscellaneous (id = 1)
1885 * Subcategory (id = 2)
1886 * Sub-subcategory (id = 4)
1887 * Other category (id = 3)
1888 * Then after calling this function you will have
1889 * $list = array(1 => 'Miscellaneous', 2 => 'Miscellaneous / Subcategory',
1890 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
1891 * 3 => 'Other category');
1892 * $parents = array(2 => array(1), 4 => array(1, 2));
1893 *
1894 * If you specify $requiredcapability, then only categories where the current
1895 * user has that capability will be added to $list, although all categories
1896 * will still be added to $parents, and if you only have $requiredcapability
1897 * in a child category, not the parent, then the child catgegory will still be
1898 * included.
1899 *
1900 * If you specify the option $excluded, then that category, and all its children,
1901 * are omitted from the tree. This is useful when you are doing something like
1902 * moving categories, where you do not want to allow people to move a category
1903 * to be the child of itself.
1904 *
1905 * @param array $list For output, accumulates an array categoryid => full category path name
1906 * @param array $parents For output, accumulates an array categoryid => list of parent category ids.
8a1b1c32 1907 * @param string/array $requiredcapability if given, only categories where the current
1908 * user has this capability will be added to $list. Can also be an array of capabilities,
1909 * in which case they are all required.
8ed5dd63 1910 * @param integer $excludeid Omit this category and its children from the lists built.
1911 * @param object $category Build the tree starting at this category - otherwise starts at the top level.
1912 * @param string $path For internal use, as part of recursive calls.
cb6fec1f 1913 */
8ed5dd63 1914function make_categories_list(&$list, &$parents, $requiredcapability = '',
1915 $excludeid = 0, $category = NULL, $path = "") {
1916
9d866ae0 1917 // initialize the arrays if needed
1918 if (!is_array($list)) {
264867fd 1919 $list = array();
9d866ae0 1920 }
1921 if (!is_array($parents)) {
264867fd 1922 $parents = array();
9d866ae0 1923 }
1924
8ed5dd63 1925 if (empty($category)) {
1926 // Start at the top level.
1927 $category = new stdClass;
1928 $category->id = 0;
1929 } else {
1930 // This is the excluded category, don't include it.
1931 if ($excludeid > 0 && $excludeid == $category->id) {
1932 return;
1933 }
1934
1935 // Update $path.
c2cb4545 1936 if ($path) {
6ba65fa0 1937 $path = $path.' / '.format_string($category->name);
c2cb4545 1938 } else {
6ba65fa0 1939 $path = format_string($category->name);
c2cb4545 1940 }
8ed5dd63 1941
1942 // Add this category to $list, if the permissions check out.
3ce50127 1943 if (empty($requiredcapability)) {
8ed5dd63 1944 $list[$category->id] = $path;
3ce50127 1945
1946 } else {
1947 ensure_context_subobj_present($category, CONTEXT_COURSECAT);
1948 $requiredcapability = (array)$requiredcapability;
1949 if (has_all_capabilities($requiredcapability, $category->context)) {
1950 $list[$category->id] = $path;
1951 }
8ed5dd63 1952 }
c2cb4545 1953 }
1954
8ed5dd63 1955 // Add all the children recursively, while updating the parents array.
1956 if ($categories = get_child_categories($category->id)) {
c2cb4545 1957 foreach ($categories as $cat) {
1958 if (!empty($category->id)) {
3bd4de22 1959 if (isset($parents[$category->id])) {
2832badf 1960 $parents[$cat->id] = $parents[$category->id];
1961 }
c2cb4545 1962 $parents[$cat->id][] = $category->id;
1963 }
8ed5dd63 1964 make_categories_list($list, $parents, $requiredcapability, $excludeid, $cat, $path);
c2cb4545 1965 }
1966 }
1967}
1968
1969
cb6fec1f 1970/**
1971 * Recursive function to print out all the categories in a nice format
1972 * with or without courses included
1973 */
8ed5dd63 1974function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true) {
9ff5310a 1975 global $CFG;
e05bcf2f 1976
beeee4d2 1977 // maxcategorydepth == 0 meant no limit
1978 if (!empty($CFG->maxcategorydepth) && $depth >= $CFG->maxcategorydepth) {
e05bcf2f 1979 return;
9ff5310a 1980 }
c2cb4545 1981
1982 if (!$displaylist) {
e92fe848 1983 make_categories_list($displaylist, $parentslist);
c2cb4545 1984 }
1985
1986 if ($category) {
8ed5dd63 1987 if ($category->visible or has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_SYSTEM))) {
1988 print_category_info($category, $depth, $showcourses);
c2cb4545 1989 } else {
1990 return; // Don't bother printing children of invisible categories
1991 }
89adb174 1992
c2cb4545 1993 } else {
c2cb4545 1994 $category->id = "0";
1995 }
1996
9bb19e58 1997 if ($categories = get_child_categories($category->id)) { // Print all the children recursively
c2cb4545 1998 $countcats = count($categories);
1999 $count = 0;
2000 $first = true;
2001 $last = false;
2002 foreach ($categories as $cat) {
2003 $count++;
2004 if ($count == $countcats) {
2005 $last = true;
2006 }
2007 $up = $first ? false : true;
2008 $down = $last ? false : true;
2009 $first = false;
2010
8ed5dd63 2011 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1, $showcourses);
c2cb4545 2012 }
2013 }
c2cb4545 2014}
2015
cb6fec1f 2016/**
2017 * This function will return $options array for choose_from_menu, with whitespace to denote nesting.
2018 */
0705ff84 2019function make_categories_options() {
2020 make_categories_list($cats,$parents);
2021 foreach ($cats as $key => $value) {
2022 if (array_key_exists($key,$parents)) {
2023 if ($indent = count($parents[$key])) {
2024 for ($i = 0; $i < $indent; $i++) {
2025 $cats[$key] = '&nbsp;'.$cats[$key];
2026 }
2027 }
2028 }
2029 }
2030 return $cats;
2031}
c2cb4545 2032
cb6fec1f 2033/**
2034 * Prints the category info in indented fashion
2035 * This function is only used by print_whole_category_list() above
2036 */
8ed5dd63 2037function print_category_info($category, $depth, $showcourses = false) {
cb6fec1f 2038 global $CFG, $DB;
b48f834c 2039 static $strallowguests, $strrequireskey, $strsummary;
c2cb4545 2040
b48f834c 2041 if (empty($strsummary)) {
e05bcf2f 2042 $strallowguests = get_string('allowguests');
2043 $strrequireskey = get_string('requireskey');
2044 $strsummary = get_string('summary');
b48f834c 2045 }
ba2e5d73 2046
e05bcf2f 2047 $catlinkcss = $category->visible ? '' : ' class="dimmed" ';
d5f26b07 2048
cb6fec1f 2049 $coursecount = $DB->count_records('course') <= FRONTPAGECOURSELIMIT;
8ed5dd63 2050 if ($showcourses and $coursecount) {
fcf9577a 2051 $catimage = '<img src="'.$CFG->pixpath.'/i/course.gif" alt="" />';
b48f834c 2052 } else {
7b0b5c14 2053 $catimage = "&nbsp;";
8ef9cb56 2054 }
b48f834c 2055
fcf9577a 2056 echo "\n\n".'<table class="categorylist">';
d2b6ba70 2057
7ffcbfe1 2058 $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 2059 if ($showcourses and $coursecount) {
b48f834c 2060
978abb42 2061 echo '<tr>';
b48f834c 2062
2063 if ($depth) {
2064 $indent = $depth*30;
2065 $rows = count($courses) + 1;
a682f0c2 2066 echo '<td class="category indentation" rowspan="'.$rows.'" valign="top">';
b48f834c 2067 print_spacer(10, $indent);
e05bcf2f 2068 echo '</td>';
b48f834c 2069 }
89adb174 2070
9deaeaa1 2071 echo '<td valign="top" class="category image">'.$catimage.'</td>';
fcf9577a 2072 echo '<td valign="top" class="category name">';
6ba65fa0 2073 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot.'/course/category.php?id='.$category->id.'">'. format_string($category->name).'</a>';
e05bcf2f 2074 echo '</td>';
290130b3 2075 echo '<td class="category info">&nbsp;</td>';
e05bcf2f 2076 echo '</tr>';
b48f834c 2077
beeee4d2 2078 // does the depth exceed maxcategorydepth
2079 // maxcategorydepth == 0 or unset meant no limit
2080
2081 $limit = !(isset($CFG->maxcategorydepth) && ($depth >= $CFG->maxcategorydepth-1));
2082
2083 if ($courses && ($limit || $CFG->maxcategorydepth == 0)) {
c2cb4545 2084 foreach ($courses as $course) {
e05bcf2f 2085 $linkcss = $course->visible ? '' : ' class="dimmed" ';
fcf9577a 2086 echo '<tr><td valign="top">&nbsp;';
2087 echo '</td><td valign="top" class="course name">';
6ba65fa0 2088 echo '<a '.$linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'. format_string($course->fullname).'</a>';
fcf9577a 2089 echo '</td><td align="right" valign="top" class="course info">';
c2cb4545 2090 if ($course->guest ) {
e05bcf2f 2091 echo '<a title="'.$strallowguests.'" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">';
fcf9577a 2092 echo '<img alt="'.$strallowguests.'" src="'.$CFG->pixpath.'/i/guest.gif" /></a>';
ebe8ddc1 2093 } else {
fcf9577a 2094 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath.'/spacer.gif" />';
0c656181 2095 }
c2cb4545 2096 if ($course->password) {
e05bcf2f 2097 echo '<a title="'.$strrequireskey.'" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">';
fcf9577a 2098 echo '<img alt="'.$strrequireskey.'" src="'.$CFG->pixpath.'/i/key.gif" /></a>';
ebe8ddc1 2099 } else {
fcf9577a 2100 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath.'/spacer.gif" />';
b48f834c 2101 }
2102 if ($course->summary) {
e05bcf2f 2103 link_to_popup_window ('/course/info.php?id='.$course->id, 'courseinfo',
fcf9577a 2104 '<img alt="'.$strsummary.'" src="'.$CFG->pixpath.'/i/info.gif" />',
b48f834c 2105 400, 500, $strsummary);
ebe8ddc1 2106 } else {
fcf9577a 2107 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath.'/spacer.gif" />';
0c656181 2108 }
e05bcf2f 2109 echo '</td></tr>';
0c656181 2110 }
ba2e5d73 2111 }
d2b6ba70 2112 } else {
b48f834c 2113
e0140f24 2114 echo '<tr>';
2115
b48f834c 2116 if ($depth) {
2117 $indent = $depth*20;
a682f0c2 2118 echo '<td class="category indentation" valign="top">';
b48f834c 2119 print_spacer(10, $indent);
e05bcf2f 2120 echo '</td>';
d2b6ba70 2121 }
89adb174 2122
fcf9577a 2123 echo '<td valign="top" class="category name">';
6ba65fa0 2124 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot.'/course/category.php?id='.$category->id.'">'. format_string($category->name).'</a>';
e05bcf2f 2125 echo '</td>';
290130b3 2126 echo '<td valign="top" class="category number">';
7ffcbfe1 2127 if (count($courses)) {
2128 echo count($courses);
e05bcf2f 2129 }
2130 echo '</td></tr>';
c2cb4545 2131 }
e05bcf2f 2132 echo '</table>';
c2cb4545 2133}
2134
77eddcd5 2135/**
2136 * Print the buttons relating to course requests.
2137 *
2138 * @param object $systemcontext the system context.
2139 */
2140function print_course_request_buttons($systemcontext) {
2141 global $CFG, $DB;
2142 if (empty($CFG->enablecourserequests)) {
2143 return;
2144 }
e452210a 2145 if (isloggedin() && !isguestuser() && !has_capability('moodle/course:create', $systemcontext) && has_capability('moodle/course:request', $systemcontext)) {
77eddcd5 2146 /// Print a button to request a new course
2147 print_single_button('request.php', NULL, get_string('requestcourse'), 'get');
2148 }
2149 /// Print a button to manage pending requests
2150 if (has_capability('moodle/site:approvecourse', $systemcontext)) {
2151 print_single_button('pending.php', NULL, get_string('coursespending'), 'get', '_self', false, '', !$DB->record_exists('course_request', array()));
2152 }
2153}
2154
8ed5dd63 2155/**
2156 * Prints the turn editing on/off button on course/index.php or course/category.php.
2157 *
2158 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2159 * @return string HTML of the editing button, or empty string, if this user is not allowed
2160 * to see it.
2161 */
2162function update_category_button($categoryid = 0) {
2163 global $CFG, $USER;
2164
2165 // Check permissions.
2166 $context = get_category_or_system_context($categoryid);
2167 if (!has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context)) {
2168 return '';
2169 }
2170
2171 // Work out the appropriate action.
2172 if (!empty($USER->categoryediting)) {
2173 $label = get_string('turneditingoff');
2174 $edit = 'off';
2175 } else {
2176 $label = get_string('turneditingon');
2177 $edit = 'on';
2178 }
c2cb4545 2179
8ed5dd63 2180 // Generate the button HTML.
2181 $options = array('categoryedit' => $edit, 'sesskey' => sesskey());
2182 if ($categoryid) {
2183 $options['id'] = $categoryid;
2184 $page = 'category.php';
2185 } else {
2186 $page = 'index.php';
2187 }
2188 return print_single_button($CFG->wwwroot . '/course/' . $page, $options,
2189 $label, 'get', '', true);
2190}
e0b033d5 2191
cb6fec1f 2192/**
2193 * Category is 0 (for all courses) or an object
2194 */
6c54240a 2195function print_courses($category) {
810393c8 2196 global $CFG;
c2cb4545 2197
4dde1463 2198 if (!is_object($category) && $category==0) {
9bb19e58 2199 $categories = get_child_categories(0); // Parent = 0 ie top-level categories only
4dde1463 2200 if (is_array($categories) && count($categories) == 1) {
90c2ca2e 2201 $category = array_shift($categories);
238c0dd9 2202 $courses = get_courses_wmanagers($category->id,
2203 'c.sortorder ASC',
4dde1463 2204 array('password','summary','currency'));
90c2ca2e 2205 } else {
238c0dd9 2206 $courses = get_courses_wmanagers('all',
2207 'c.sortorder ASC',
4dde1463 2208 array('password','summary','currency'));
90c2ca2e 2209 }
2210 unset($categories);
607809b3 2211 } else {
238c0dd9 2212 $courses = get_courses_wmanagers($category->id,
2213 'c.sortorder ASC',
4dde1463 2214 array('password','summary','currency'));
c2cb4545 2215 }
2216
49cd4d79 2217 if ($courses) {
8fee6c60 2218 echo '<ul class="unlist">';
c2cb4545 2219 foreach ($courses as $course) {
4dde1463 2220 if ($course->visible == 1
003bbcc8 2221 || has_capability('moodle/course:viewhiddencourses',$course->context)) {
8fee6c60 2222 echo '<li>';
4dde1463 2223 print_course($course);
8fee6c60 2224 echo "</li>\n";
4dde1463 2225 }
c2cb4545 2226 }
8fee6c60 2227 echo "</ul>\n";
c2cb4545 2228 } else {
f9667a5a 2229 print_heading(get_string("nocoursesyet"));
8e480396 2230 $context = get_context_instance(CONTEXT_SYSTEM);
0468976c 2231 if (has_capability('moodle/course:create', $context)) {
255d1033 2232 $options = array();
2233 $options['category'] = $category->id;
6b7425d2 2234 echo '<div class="addcoursebutton">';
255d1033 2235 print_single_button($CFG->wwwroot.'/course/edit.php', $options, get_string("addnewcourse"));
2236 echo '</div>';
2237 }
c2cb4545 2238 }
c2cb4545 2239}
2240
04c53106 2241/**
2242 * Print a description of a course, suitable for browsing in a list.
2243 *
2244 * @param object $course the course object.
2245 * @param string $highlightterms (optional) some search terms that should be highlighted in the display.
2246 */
2247function print_course($course, $highlightterms = '') {
cb6fec1f 2248 global $CFG, $USER, $DB;
c2cb4545 2249
4dde1463 2250 if (isset($course->context)) {
2251 $context = $course->context;
2252 } else {
2253 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2254 }
146bbb8f 2255
88768091 2256 $linkcss = $course->visible ? '' : ' class="dimmed" ';
22288704 2257
7cd266e9 2258 echo '<div class="coursebox clearfix">';
afba7be1 2259 echo '<div class="info">';
7f9c4fb9 2260 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
e5e81e78 2261 $linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.
04c53106 2262 highlight($highlightterms, format_string($course->fullname)).'</a></div>';
238c0dd9 2263
d42c64ba 2264 /// first find all roles that are supposed to be displayed
238c0dd9 2265
6b4d8c4d 2266 if (!empty($CFG->coursemanager)) {
2267 $managerroles = split(',', $CFG->coursemanager);
3bf13d05 2268 $canseehidden = has_capability('moodle/role:viewhiddenassigns', $context);
4dde1463 2269 $namesarray = array();
2270 if (isset($course->managers)) {
2271 if (count($course->managers)) {
2272 $rusers = $course->managers;
2273 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
238c0dd9 2274
b682cee9 2275 /// Rename some of the role names if needed
2276 if (isset($context)) {
cb6fec1f 2277 $aliasnames = $DB->get_records('role_names', array('contextid'=>$context->id), '', 'roleid,contextid,name');
b682cee9 2278 }
2279
9d5a4b23 2280 // keep a note of users displayed to eliminate duplicates
2281 $usersshown = array();
4dde1463 2282 foreach ($rusers as $ra) {
9d5a4b23 2283
2284 // if we've already displayed user don't again
2285 if (in_array($ra->user->id,$usersshown)) {
2286 continue;
2287 }
2288 $usersshown[] = $ra->user->id;
2289
4dde1463 2290 if ($ra->hidden == 0 || $canseehidden) {
238c0dd9 2291 $fullname = fullname($ra->user, $canviewfullnames);
e6924a01 2292 if ($ra->hidden == 1) {
b9837ddf 2293 $status = " <img src=\"{$CFG->pixpath}/t/show.gif\" title=\"".get_string('userhashiddenassignments', 'role')."\" alt=\"".get_string('hiddenassign')."\" class=\"hide-show-image\"/>";
e6924a01 2294 } else {
2295 $status = '';
1780d87b 2296 }
b682cee9 2297
2298 if (isset($aliasnames[$ra->roleid])) {
87486420 2299 $ra->rolename = $aliasnames[$ra->roleid]->name;
b682cee9 2300 }
2301
238c0dd9 2302 $namesarray[] = format_string($ra->rolename)
4dde1463 2303 . ': <a href="'.$CFG->wwwroot.'/user/view.php?id='.$ra->user->id.'&amp;course='.SITEID.'">'
238c0dd9 2304 . $fullname . '</a>' . $status;
4dde1463 2305 }
2306 }
2307 }
2308 } else {
238c0dd9 2309 $rusers = get_role_users($managerroles, $context,
4dde1463 2310 true, '', 'r.sortorder ASC, u.lastname ASC', $canseehidden);
2311 if (is_array($rusers) && count($rusers)) {
2312 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
165d25cc 2313
2314 /// Rename some of the role names if needed
2315 if (isset($context)) {
2316 $aliasnames = $DB->get_records('role_names', array('contextid'=>$context->id), '', 'roleid,contextid,name');
2317 }
2318
4dde1463 2319 foreach ($rusers as $teacher) {
238c0dd9 2320 $fullname = fullname($teacher, $canviewfullnames);
165d25cc 2321
2322 /// Apply role names
2323 if (isset($aliasnames[$teacher->roleid])) {
2324 $teacher->rolename = $aliasnames[$teacher->roleid]->name;
2325 }
2326
238c0dd9 2327 $namesarray[] = format_string($teacher->rolename)
4dde1463 2328 . ': <a href="'.$CFG->wwwroot.'/user/view.php?id='.$teacher->id.'&amp;course='.SITEID.'">'
238c0dd9 2329 . $fullname . '</a>';
4dde1463 2330 }
431cad0d 2331 }
c2cb4545 2332 }
431cad0d 2333
d42c64ba 2334 if (!empty($namesarray)) {
88768091 2335 echo "<ul class=\"teachers\">\n<li>";
2336 echo implode('</li><li>', $namesarray);
2337 echo "</li></ul>";
2338 }
c2cb4545 2339 }
238c0dd9 2340
88768091 2341 require_once("$CFG->dirroot/enrol/enrol.class.php");
2342 $enrol = enrolment_factory::factory($course->enrol);
146bbb8f 2343 echo $enrol->get_access_icons($course);
c2cb4545 2344
afba7be1 2345 echo '</div><div class="summary">';
9f39c190 2346 $options = NULL;
2347 $options->noclean = true;
34b5847a 2348 $options->para = false;
04c53106 2349 echo highlight($highlightterms, format_text($course->summary, FORMAT_MOODLE, $options, $course->id));
afba7be1 2350 echo '</div>';
2351 echo '</div>';
c2cb4545 2352}
2353
cb6fec1f 2354/**
2355 * Prints custom user information on the home page.
2356 * Over time this can include all sorts of information
2357 */
c2cb4545 2358function print_my_moodle() {
cb6fec1f 2359 global $USER, $CFG, $DB;
c2cb4545 2360
86a1ba04 2361 if (empty($USER->id)) {
ba6018a9 2362 print_error('nopermissions', '', '', 'See My Moodle');
c2cb4545 2363 }
2364
5b9e50ca 2365 $courses = get_my_courses($USER->id, 'visible DESC,sortorder ASC', array('summary'));
86dd62a7 2366 $rhosts = array();
2367 $rcourses = array();
36e6379e 2368 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
86dd62a7 2369 $rcourses = get_my_remotecourses($USER->id);
643b67b8 2370 $rhosts = get_my_remotehosts();
86dd62a7 2371 }
2372
2373 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
2374
2375 if (!empty($courses)) {
8fee6c60 2376 echo '<ul class="unlist">';
86dd62a7 2377 foreach ($courses as $course) {
2378 if ($course->id == SITEID) {
2379 continue;
2380 }
8fee6c60 2381 echo '<li>';
04c53106 2382 print_course($course);
8fee6c60 2383 echo "</li>\n";
86dd62a7 2384 }
8fee6c60 2385 echo "</ul>\n";
86dd62a7 2386 }
2387
2388 // MNET
238c0dd9 2389 if (!empty($rcourses)) {
86dd62a7 2390 // at the IDP, we know of all the remote courses
2391 foreach ($rcourses as $course) {
2392 print_remote_course($course, "100%");
2393 }
2394 } elseif (!empty($rhosts)) {
2395 // non-IDP, we know of all the remote servers, but not courses
2396 foreach ($rhosts as $host) {
643b67b8 2397 print_remote_host($host, "100%");
c81696e5 2398 }
c2cb4545 2399 }
86dd62a7 2400 unset($course);
2401 unset($host);
38a10939 2402
cb6fec1f 2403 if ($DB->count_records("course") > (count($courses) + 1) ) { // Some courses not being displayed
7f989948 2404 echo "<table width=\"100%\"><tr><td align=\"center\">";
2405 print_course_search("", false, "short");
2406 echo "</td><td align=\"center\">";
2407 print_single_button("$CFG->wwwroot/course/index.php", NULL, get_string("fulllistofcourses"), "get");
2408 echo "</td></tr></table>\n";
2409 }
86dd62a7 2410
26330001 2411 } else {
cb6fec1f 2412 if ($DB->count_records("course_categories") > 1) {
cb29b020 2413 print_simple_box_start("center", "100%", "#FFFFFF", 5, "categorybox");
26330001 2414 print_whole_category_list();
2415 print_simple_box_end();
2416 } else {
35d0244a 2417 print_courses(0);
26330001 2418 }
607809b3 2419 }
2b8cef80 2420}
2421
11b0c469 2422
a8b56716 2423function print_course_search($value="", $return=false, $format="plain") {
38a10939 2424 global $CFG;
1e0fb105 2425 static $count = 0;
2426
2427 $count++;
2428
2429 $id = 'coursesearch';
2430
2431 if ($count > 1) {
2432 $id .= $count;
2433 }
38a10939 2434
2435 $strsearchcourses= get_string("searchcourses");
2436
1c919752 2437 if ($format == 'plain') {
1e0fb105 2438 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
fcf9577a 2439 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
e42f4d92 2440 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
cb6fec1f 2441 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" value="'.s($value).'" />';
e42f4d92 2442 $output .= '<input type="submit" value="'.get_string('go').'" />';
fcf9577a 2443 $output .= '</fieldset></form>';
1c919752 2444 } else if ($format == 'short') {
1e0fb105 2445 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
fcf9577a 2446 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
b1f97418 2447 $output .= '<label for="shortsearchbox">'.$strsearchcourses.': </label>';
cb6fec1f 2448 $output .= '<input type="text" id="shortsearchbox" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
e42f4d92 2449 $output .= '<input type="submit" value="'.get_string('go').'" />';
fcf9577a 2450 $output .= '</fieldset></form>';
1c919752 2451 } else if ($format == 'navbar') {
fcf9577a 2452 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2453 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
b1f97418 2454 $output .= '<label for="navsearchbox">'.$strsearchcourses.': </label>';
cb6fec1f 2455 $output .= '<input type="text" id="navsearchbox" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
e42f4d92 2456 $output .= '<input type="submit" value="'.get_string('go').'" />';
fcf9577a 2457 $output .= '</fieldset></form>';
a8b56716 2458 }
2459
2460 if ($return) {
2461 return $output;
2462 }
2463 echo $output;
38a10939 2464}
11b0c469 2465
86dd62a7 2466function print_remote_course($course, $width="100%") {
86dd62a7 2467 global $CFG, $USER;
2468
2469 $linkcss = '';
2470
2471 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&amp;wantsurl=/course/view.php?id={$course->remoteid}";
2472
7cd266e9 2473 echo '<div class="coursebox remotecoursebox clearfix">';
86dd62a7 2474 echo '<div class="info">';
2475 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2476 $linkcss.' href="'.$url.'">'
6ba65fa0 2477 . format_string($course->fullname) .'</a><br />'
2478 . format_string($course->hostname) . ' : '
238c0dd9 2479 . format_string($course->cat_name) . ' : '
2480 . format_string($course->shortname). '</div>';
86dd62a7 2481 echo '</div><div class="summary">';
2482 $options = NULL;
2483 $options->noclean = true;
2484 $options->para = false;
2485 echo format_text($course->summary, FORMAT_MOODLE, $options);
2486 echo '</div>';
2487 echo '</div>';
86dd62a7 2488}
2489
643b67b8 2490function print_remote_host($host, $width="100%") {
643b67b8 2491 global $CFG, $USER;
2492
2493 $linkcss = '';
2494
7cd266e9 2495 echo '<div class="coursebox clearfix">';
643b67b8 2496 echo '<div class="info">';
2497 echo '<div class="name">';
2498 echo '<img src="'.$CFG->pixpath.'/i/mnethost.gif" class="icon" alt="'.get_string('course').'" />';
2499 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2500 . s($host['name']).'</a> - ';
1fd80ad3 2501 echo $host['count'] . ' ' . get_string('courses');
643b67b8 2502 echo '</div>';
2503 echo '</div>';
caa90d56 2504 echo '</div>';
643b67b8 2505}
2506
86dd62a7 2507
11b0c469 2508/// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2509
2510function add_course_module($mod) {
cb6fec1f 2511 global $DB;
11b0c469 2512
e5dfd0f3 2513 $mod->added = time();
53f4ad2c 2514 unset($mod->id);
11b0c469 2515
cb6fec1f 2516 return $DB->insert_record("course_modules", $mod);
11b0c469 2517}
2518
97928ddf 2519/**
2520 * Returns course section - creates new if does not exist yet.
2521 * @param int $relative section number
2522 * @param int $courseid
2523 * @return object $course_section object
2524 */
2525function get_course_section($section, $courseid) {
cb6fec1f 2526 global $DB;
2527
2528 if ($cw = $DB->get_record("course_sections", array("section"=>$section, "course"=>$courseid))) {
97928ddf 2529 return $cw;
2530 }
2531 $cw = new object();
cb6fec1f 2532 $cw->course = $courseid;
2533 $cw->section = $section;
2534 $cw->summary = "";
97928ddf 2535 $cw->sequence = "";
cb6fec1f 2536 $id = $DB->insert_record("course_sections", $cw);
dc5af91a 2537 return $DB->get_record("course_sections", array("id"=>$id));
97928ddf 2538}
ece966f0 2539/**
2540 * Given a full mod object with section and course already defined, adds this module to that section.
2541 *
2542 * @param object $mod
2543 * @param int $beforemod An existing ID which we will insert the new module before
2544 * @return int The course_sections ID where the mod is inserted
2545 */
7977cffd 2546function add_mod_to_section($mod, $beforemod=NULL) {
cb6fec1f 2547 global $DB;
11b0c469 2548
cb6fec1f 2549 if ($section = $DB->get_record("course_sections", array("course"=>$mod->course, "section"=>$mod->section))) {
7977cffd 2550
2551 $section->sequence = trim($section->sequence);
2552
2553 if (empty($section->sequence)) {
11b0c469 2554 $newsequence = "$mod->coursemodule";
7977cffd 2555
2556 } else if ($beforemod) {
2557 $modarray = explode(",", $section->sequence);
2558
d857e8b6 2559 if ($key = array_keys($modarray, $beforemod->id)) {
7977cffd 2560 $insertarray = array($mod->id, $beforemod->id);
2561 array_splice($modarray, $key[0], 1, $insertarray);
2562 $newsequence = implode(",", $modarray);
2563
2564 } else { // Just tack it on the end anyway
2565 $newsequence = "$section->sequence,$mod->coursemodule";
2566 }
2567
2568 } else {
2569 $newsequence = "$section->sequence,$mod->coursemodule";
11b0c469 2570 }
89adb174 2571
cb6fec1f 2572 if ($DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id))) {
e5dfd0f3 2573 return $section->id; // Return course_sections ID that was used.
11b0c469 2574 } else {
e5dfd0f3 2575 return 0;
11b0c469 2576 }
89adb174 2577
11b0c469 2578 } else { // Insert a new record
cb6fec1f 2579 $section->course = $mod->course;
2580 $section->section = $mod->section;
2581 $section->summary = "";
e5dfd0f3 2582 $section->sequence = $mod->coursemodule;
cb6fec1f 2583 return $DB->insert_record("course_sections", $section);
11b0c469 2584 }
2585}
2586
48e535bc 2587function set_coursemodule_groupmode($id, $groupmode) {
cb6fec1f 2588 global $DB;
a5d424df 2589 return $DB->set_field("course_modules", "groupmode", $groupmode, array("id"=>$id));
3d575e6f 2590}
2591
177d4abf 2592function set_coursemodule_idnumber($id, $idnumber) {
cb6fec1f 2593 global $DB;
238c0dd9 2594 return $DB->set_field("course_modules", "idnumber", $idnumber, array("id"=>$id));
177d4abf 2595}
4e781c7b 2596
02f66c42 2597/**
2598* $prevstateoverrides = true will set the visibility of the course module
2599* to what is defined in visibleold. This enables us to remember the current
2600* visibility when making a whole section hidden, so that when we toggle
2601* that section back to visible, we are able to return the visibility of
2602* the course module back to what it was originally.
2603*/
2604function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
cb6fec1f 2605 global $DB;
2606 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
978abb42 2607 return false;
2608 }
cb6fec1f 2609 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
978abb42 2610 return false;
2611 }
cb6fec1f 2612 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
dcd338ff 2613 foreach($events as $event) {
48e535bc 2614 if ($visible) {
2615 show_event($event);
2616 } else {
2617 hide_event($event);
2618 }
dcd338ff 2619 }
2620 }
02f66c42 2621 if ($prevstateoverrides) {
2622 if ($visible == '0') {
2623 // Remember the current visible state so we can toggle this back.
cb6fec1f 2624 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id'=>$id));
02f66c42 2625 } else {
2626 // Get the previous saved visible states.
cb6fec1f 2627 return $DB->set_field('course_modules', 'visible', $cm->visibleold, array('id'=>$id));
02f66c42 2628 }
2629 }
cb6fec1f 2630 return $DB->set_field("course_modules", "visible", $visible, array("id"=>$id));
1acfbce5 2631}
2632
cb6fec1f 2633/**
290130b3 2634 * Delete a course module and any associated data at the course level (events)
264867fd 2635 * Until 1.5 this function simply marked a deleted flag ... now it
290130b3 2636 * deletes it completely.
2637 *
2638 */
48e535bc 2639function delete_course_module($id) {
cb6fec1f 2640 global $CFG, $DB;
f615fbab 2641 require_once($CFG->libdir.'/gradelib.php');
2642
cb6fec1f 2643 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
290130b3 2644 return true;
2645 }
cb6fec1f 2646 $modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module));
f615fbab 2647 //delete events from calendar
cb6fec1f 2648 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
dcd338ff 2649 foreach($events as $event) {
0ea03696 2650 delete_event($event->id);
dcd338ff 2651 }
2652 }
f615fbab 2653 //delete grade items, outcome items and grades attached to modules
2654 if ($grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2655 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course))) {
2656 foreach ($grade_items as $grade_item) {
2657 $grade_item->delete('moddelete');
2658 }
f615fbab 2659 }
06b3a6b2 2660
2661 delete_context(CONTEXT_MODULE, $cm->id);
cb6fec1f 2662 return $DB->delete_records('course_modules', array('id'=>$cm->id));
11b0c469 2663}
2664
2665function delete_mod_from_section($mod, $section) {
cb6fec1f 2666 global $DB;
11b0c469 2667
cb6fec1f 2668 if ($section = $DB->get_record("course_sections", array("id"=>$section)) ) {
11b0c469 2669
e5dfd0f3 2670 $modarray = explode(",", $section->sequence);
11b0c469 2671
2672 if ($key = array_keys ($modarray, $mod)) {
2673 array_splice($modarray, $key[0], 1);
2674 $newsequence = implode(",", $modarray);
cb6fec1f 2675 return $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
11b0c469 2676 } else {
2677 return false;
2678 }
89adb174 2679
11b0c469 2680 }
7977cffd 2681 return false;
11b0c469 2682}
2683
3440ec12 2684/**
2685 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
2686 *
2687 * @param object $course
2688 * @param int $section
2689 * @param int $move (-1 or 1)
2690 */
12905134 2691function move_section($course, $section, $move) {
2692/// Moves a whole course section up and down within the course
cb6fec1f 2693 global $USER, $DB;
12905134 2694
2695 if (!$move) {
2696 return true;
2697 }
2698
2699 $sectiondest = $section + $move;
2700
2701 if ($sectiondest > $course->numsections or $sectiondest < 1) {
2702 return false;
2703 }
2704
cb6fec1f 2705 if (!$sectionrecord = $DB->get_record("course_sections", array("course"=>$course->id, "section"=>$section))) {
12905134 2706 return false;
2707 }
2708
cb6fec1f 2709 if (!$sectiondestrecord = $DB->get_record("course_sections", array("course"=>$course->id, "section"=>$sectiondest))) {
12905134 2710 return false;
2711 }
2712
cb6fec1f 2713 if (!$DB->set_field("course_sections", "section", $sectiondest, array("id"=>$sectionrecord->id))) {
12905134 2714 return false;
2715 }
cb6fec1f 2716 if (!$DB->set_field("course_sections", "section", $section, array("id"=>$sectiondestrecord->id))) {
12905134 2717 return false;
2718 }
798b70a1 2719 // if the focus is on the section that is being moved, then move the focus along
2720 if (isset($USER->display[$course->id]) and ($USER->display[$course->id] == $section)) {
2721 course_set_display($course->id, $sectiondest);
2722 }
5390cbb7 2723
a987106d 2724 // Check for duplicates and fix order if needed.
5390cbb7 2725 // There is a very rare case that some sections in the same course have the same section id.
cb6fec1f 2726 $sections = $DB->get_records('course_sections', array('course'=>$course->id), 'section ASC');
a987106d 2727 $n = 0;
2728 foreach ($sections as $section) {
2729 if ($section->section != $n) {
cb6fec1f 2730 if (!$DB->set_field('course_sections', 'section', $n, array('id'=>$section->id))) {
5390cbb7 2731 return false;
2732 }
5390cbb7 2733 }
a987106d 2734 $n++;
5390cbb7 2735 }
12905134 2736 return true;
2737}
2738
3440ec12 2739/**
2740 * Moves a section within a course, from a position to another.
2741 * Be very careful: $section and $destination refer to section number,
2742 * not id!.
2743 *
2744 * @param object $course
2745 * @param int $section Section number (not id!!!)
2746 * @param int $destination
2747 * @return boolean Result
2748 */
2749function move_section_to($course, $section, $destination) {
2750/// Moves a whole course section up and down within the course
2751 global $USER, $DB;
2752
ca255392 2753 if (!$destination && $destination != 0) {
3440ec12 2754 return true;
2755 }
2756
ca255392 2757 if ($destination > $course->numsections) {
3440ec12 2758 return false;
2759 }
2760
2761 // Get all sections for this course and re-order them (2 of them should now share the same section number)
2762 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
2763 'section ASC, id ASC', 'id, section')) {
2764 return false;
2765 }
2766
2767 $sections = reorder_sections($sections, $section, $destination);
2768
2769 // Update all sections
2770 foreach ($sections as $id => $position) {
2771 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
2772 }
2773
2774 // if the focus is on the section that is being moved, then move the focus along
2775 if (isset($USER->display[$course->id]) and ($USER->display[$course->id] == $section)) {
2776 course_set_display($course->id, $destination);
2777 }
2778 return true;
2779}
2780
2781/**
2782 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
2783 * an original position number and a target position number, rebuilds the array so that the
2784 * move is made without any duplication of section positions.
2785 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
2786 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
2787 *
2788 * @param array $sections
2789 * @param int $origin_position
2790 * @param int $target_position
2791 * @return array
2792 */
2793function reorder_sections($sections, $origin_position, $target_position) {
2794 if (!is_array($sections)) {
2795 return false;
2796 }
2797
2798 // We can't move section position 0
2799 if ($origin_position < 1) {
2800 echo "We can't move section position 0";
2801 return false;
2802 }
2803
2804 // Locate origin section in sections array
2805 if (!$origin_key = array_search($origin_position, $sections)) {
2806 echo "searched position not in sections array";
2807 return false; // searched position not in sections array
2808 }
2809
2810 // Extract origin section
2811 $origin_section = $sections[$origin_key];
2812 unset($sections[$origin_key]);
2813
2814 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
2815 $found = false;
2816 $append_array = array();
2817 foreach ($sections as $id => $position) {
2818 if ($found) {
2819 $append_array[$id] = $position;
2820 unset($sections[$id]);
2821 }
2822 if ($position == $target_position) {
2823 $found = true;
2824 }
2825 }
2826
2827 // Append moved section
2828 $sections[$origin_key] = $origin_section;
2829
2830 // Append rest of array (if applicable)
2831 if (!empty($append_array)) {
2832 foreach ($append_array as $id => $position) {
2833 $sections[$id] = $position;
2834 }
2835 }
2836
2837 // Renumber positions
2838 $position = 0;
2839 foreach ($sections as $id => $p) {
2840 $sections[$id] = $position;
2841 $position++;
2842 }
2843
2844 return $sections;
2845
2846}
2847
cb6fec1f 2848/**
2849 * Move the module object $mod to the specified $section
2850 * If $beforemod exists then that is the module
2851 * before which $modid should be inserted
2852 * All parameters are objects
2853 */
7977cffd 2854function moveto_module($mod, $section, $beforemod=NULL) {
cb6fec1f 2855 global $DB;
7977cffd 2856
2857/// Remove original module from original section
7977cffd 2858 if (! delete_mod_from_section($mod->id, $mod->section)) {
2859 notify("Could not delete module from existing section");
2860 }
2861
2862/// Update module itself if necessary
2863
2864 if ($mod->section != $section->id) {
89adb174 2865 $mod->section = $section->id;
cb6fec1f 2866 if (!$DB->update_record("course_modules", $mod)) {
7977cffd 2867 return false;
2868 }
48e535bc 2869 // if moving to a hidden section then hide module
2870 if (!$section->visible) {
2871 set_coursemodule_visible($mod->id, 0);
2872 }
7977cffd 2873 }
2874
2875/// Add the module into the new section
2876
2877 $mod->course = $section->course;
2878 $mod->section = $section->section; // need relative reference
2879 $mod->coursemodule = $mod->id;
2880
2881 if (! add_mod_to_section($mod, $beforemod)) {
2882 return false;
2883 }
2884
2885 return true;
7977cffd 2886}
2887
24e1eae4 2888function make_editing_buttons($mod, $absolute=false, $moveselect=true, $indent=-1, $section=-1) {
cb6fec1f 2889 global $CFG, $USER, $DB;
94361e02 2890
3d575e6f 2891 static $str;
37a88449 2892 static $sesskey;
3d575e6f 2893
217a8ee9 2894 $modcontext = get_context_instance(CONTEXT_MODULE, $mod->id);
2895 // no permission to edit
2896 if (!has_capability('moodle/course:manageactivities', $modcontext)) {
e2cd3ed0 2897 return false;
217a8ee9 2898 }
2899
3d575e6f 2900 if (!isset($str)) {
9534a8cb 2901 $str->assign = get_string("assignroles", 'role');
90ebdf65 2902 $str->delete = get_string("delete");
2903 $str->move = get_string("move");
2904 $str->moveup = get_string("moveup");
2905 $str->movedown = get_string("movedown");
2906 $str->moveright = get_string("moveright");
2907 $str->moveleft = get_string("moveleft");
2908 $str->update = get_string("update");
2909 $str->duplicate = get_string("duplicate");
2910 $str->hide = get_string("hide");
2911 $str->show = get_string("show");
3d575e6f 2912 $str->clicktochange = get_string("clicktochange");
32d03b7b 2913 $str->forcedmode = get_string("forcedmode");
3d575e6f 2914 $str->groupsnone = get_string("groupsnone");
2915 $str->groupsseparate = get_string("groupsseparate");
2916 $str->groupsvisible = get_string("groupsvisible");
37a88449 2917 $sesskey = sesskey();
1acfbce5 2918 }
94361e02 2919
24e1eae4 2920 if ($section >= 0) {
75f087b6 2921 $section = '&amp;sr='.$section; // Section return
24e1eae4 2922 } else {
2923 $section = '';
2924 }
2925
94361e02 2926 if ($absolute) {
37a88449 2927 $path = $CFG->wwwroot.'/course';
dc0dc7d5 2928 } else {
37a88449 2929 $path = '.';
dc0dc7d5 2930 }
217a8ee9 2931 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
2932 if ($mod->visible) {
2933 $hideshow = '<a class="editing_hide" title="'.$str->hide.'" href="'.$path.'/mod.php?hide='.$mod->id.
2934 '&amp;sesskey='.$sesskey.$section.'"><img'.
2935 ' src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" '.
2936 ' alt="'.$str->hide.'" /></a>'."\n";
2937 } else {
2938 $hideshow = '<a class="editing_show" title="'.$str->show.'" href="'.$path.'/mod.php?show='.$mod->id.
2939 '&amp;sesskey='.$sesskey.$section.'"><img'.
2940 ' src="'.$CFG->pixpath.'/t/show.gif" class="iconsmall" '.
2941 ' alt="'.$str->show.'" /></a>'."\n";
2942 }
530db4cd 2943 } else {
2944 $hideshow = '';
7977cffd 2945 }
530db4cd 2946
3d575e6f 2947 if ($mod->groupmode !== false) {
2948 if ($mod->groupmode == SEPARATEGROUPS) {
32d03b7b 2949 $grouptitle = $str->groupsseparate;
cddbd5d5 2950 $groupclass = 'editing_groupsseparate';
37a88449 2951 $groupimage = $CFG->pixpath.'/t/groups.gif';
2952 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=0&amp;sesskey='.$sesskey;
3d575e6f 2953 } else if ($mod->groupmode == VISIBLEGROUPS) {
32d03b7b 2954 $grouptitle = $str->groupsvisible;
cddbd5d5 2955 $groupclass = 'editing_groupsvisible';
37a88449 2956 $groupimage = $CFG->pixpath.'/t/groupv.gif';
2957 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=1&amp;sesskey='.$sesskey;
32d03b7b 2958 } else {
2959 $grouptitle = $str->groupsnone;
90ebdf65 2960 $groupclass = 'editing_groupsnone';
37a88449 2961 $groupimage = $CFG->pixpath.'/t/groupn.gif';
2962 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=2&amp;sesskey='.$sesskey;
32d03b7b 2963 }
2964 if ($mod->groupmodelink) {
90ebdf65 2965 $groupmode = '<a class="'.$groupclass.'" title="'.$grouptitle.' ('.$str->clicktochange.')" href="'.$grouplink.'">'.
0d905d9f 2966 '<img src="'.$groupimage.'" class="iconsmall" '.
2967 'alt="'.$grouptitle.'" /></a>';
3d575e6f 2968 } else {
37a88449 2969 $groupmode = '<img title="'.$grouptitle.' ('.$str->forcedmode.')" '.
0d905d9f 2970 ' src="'.$groupimage.'" class="iconsmall" '.
2971 'alt="'.$grouptitle.'" />';
3d575e6f 2972 }
2973 } else {
2974 $groupmode = "";
2975 }
e2cd3ed0 2976
217a8ee9 2977 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $mod->course))) {
2978 if ($moveselect) {
2979 $move = '<a class="editing_move" title="'.$str->move.'" href="'.$path.'/mod.php?copy='.$mod->id.
2980 '&amp;sesskey='.$sesskey.$section.'"><img'.
2981 ' src="'.$CFG->pixpath.'/t/move.gif" class="iconsmall" '.
2982 ' alt="'.$str->move.'" /></a>'."\n";
2983 } else {
2984 $move = '<a class="editing_moveup" title="'.$str->moveup.'" href="'.$path.'/mod.php?id='.$mod->id.
2985 '&amp;move=-1&amp;sesskey='.$sesskey.$section.'"><img'.
2986 ' src="'.$CFG->pixpath.'/t/up.gif" class="iconsmall" '.
2987 ' alt="'.$str->moveup.'" /></a>'."\n".
2988 '<a class="editing_movedown" title="'.$str->movedown.'" href="'.$path.'/mod.php?id='.$mod->id.
2989 '&amp;move=1&amp;sesskey='.$sesskey.$section.'"><img'.
2990 ' src="'.$CFG->pixpath.'/t/down.gif" class="iconsmall" '.
2991 ' alt="'.$str->movedown.'" /></a>'."\n";
2992 }
7b44777e 2993 } else {
238c0dd9 2994 $move = '';
7977cffd 2995 }
2996
932be046 2997 $leftright = '';
217a8ee9 2998 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $mod->course))) {
932be046 2999
8047ab1d 3000 if (right_to_left()) { // Exchange arrows on RTL
932be046 3001 $rightarrow = 'left.gif';
3002 $leftarrow = 'right.gif';
3003 } else {
3004 $rightarrow = 'right.gif';
3005 $leftarrow = 'left.gif';
3006 }
238c0dd9 3007
217a8ee9 3008 if ($indent > 0) {
3009 $leftright .= '<a class="editing_moveleft" title="'.$str->moveleft.'" href="'.$path.'/mod.php?id='.$mod->id.
3010 '&amp;indent=-1&amp;sesskey='.$sesskey.$section.'"><img'.
932be046 3011 ' src="'.$CFG->pixpath.'/t/'.$leftarrow.'" class="iconsmall" '.
217a8ee9 3012 ' alt="'.$str->moveleft.'" /></a>'."\n";
3013 }
3014 if ($indent >= 0) {
3015 $leftright .= '<a class="editing_moveright" title="'.$str->moveright.'" href="'.$path.'/mod.php?id='.$mod->id.
3016 '&amp;indent=1&amp;sesskey='.$sesskey.$section.'"><img'.
932be046 3017 ' src="'.$CFG->pixpath.'/t/'.$rightarrow.'" class="iconsmall" '.
217a8ee9 3018 ' alt="'.$str->moveright.'" /></a>'."\n";
3019 }
37a88449 3020 }
9534a8cb 3021 if (has_capability('moodle/course:managegroups', $modcontext)){
3022 $context = get_context_instance(CONTEXT_MODULE, $mod->id);
d1aa1e48 3023 $assign = '<a class="editing_assign" title="'.$str->assign.'" href="'.$CFG->wwwroot.'/'.$CFG->admin.'/roles/assign.php?contextid='.
9534a8cb 3024 $context->id.'"><img src="'.$CFG->pixpath.'/i/roles.gif" alt="'.$str->assign.'" class="iconsmall"/></a>';
8634e001 3025 } else {
3026 $assign = '';
9534a8cb 3027 }
8634e001 3028
90ebdf65 3029 return '<span class="commands">'."\n".$leftright.$move.
3030 '<a class="editing_update" title="'.$str->update.'" href="'.$path.'/mod.php?update='.$mod->id.
37a88449 3031 '&amp;sesskey='.$sesskey.$section.'"><img'.
0d905d9f 3032 ' src="'.$CFG->pixpath.'/t/edit.gif" class="iconsmall" '.
90ebdf65 3033 ' alt="'.$str->update.'" /></a>'."\n".
3034 '<a class="editing_delete" title="'.$str->delete.'" href="'.$path.'/mod.php?delete='.$mod->id.
37a88449 3035 '&amp;sesskey='.$sesskey.$section.'"><img'.
0d905d9f 3036 ' src="'.$CFG->pixpath.'/t/delete.gif" class="iconsmall" '.
9534a8cb 3037 ' alt="'.$str->delete.'" /></a>'."\n".$hideshow.$groupmode."\n".$assign.'</span>';
90845098 3038}
3039
b61efafb 3040/**
264867fd 3041 * given a course object with shortname & fullname, this function will
b61efafb 3042 * truncate the the number of chars allowed and add ... if it was too long
3043 */
3044function course_format_name ($course,$max=100) {
264867fd 3045
6ba65fa0 3046 $str = $course->shortname.': '. $course->fullname;
b61efafb 3047 if (strlen($str) <= $max) {
3048 return $str;
3049 }
3050 else {
3051 return substr($str,0,$max-3).'...';
3052 }
3053}
3054
3055/**
3056 * This function will return true if the given course is a child course at all
3057 */
3058function course_in_meta ($course) {
cb6fec1f 3059 global $DB;
3060 return $DB->record_exists("course_meta", array("child_course"=>$course->id));
b61efafb 3061}
3062
48e535bc 3063
3064/**
7cac0c4b 3065 * Print standard form elements on module setup forms in mod/.../mod_form.php
48e535bc 3066 */
263017bb 3067function print_standard_coursemodule_settings($form, $features=null) {
cb6fec1f 3068 global $DB;
3069 if (!$course = $DB->get_record('course', array('id'=>$form->course))) {
ba6018a9 3070 print_error("invalidcourseid");
da2224f8 3071 }
3072 print_groupmode_setting($form, $course);
263017bb 3073 if (!empty($features->groupings)) {
3074 print_grouping_settings($form, $course);
3075 }
da2224f8 3076 print_visible_setting($form, $course);
48e535bc 3077}
3078
3079/**
7cac0c4b 3080 * Print groupmode form element on module setup forms in mod/.../mod_form.php
48e535bc 3081 */
5ebb746b 3082function print_groupmode_setting($form, $course=NULL) {
cb6fec1f 3083 global $DB;
48e535bc 3084
5ebb746b 3085 if (empty($course)) {
cb6fec1f 3086 if (!$course = $DB->get_record('course', array('id'=>$form->course))) {
ba6018a9 3087 print_error("invalidcourseid");
5ebb746b 3088 }
3089 }
48e535bc 3090 if ($form->coursemodule) {
cb6fec1f 3091 if (!$cm = $DB->get_record('course_modules', array('id'=>$form->coursemodule))) {
d857e8b6 3092 print_error('invalidcoursemodule');
48e535bc 3093 }
ffc536af 3094 $groupmode = groups_get_activity_groupmode($cm);
48e535bc 3095 } else {
3096 $cm = null;
ffc536af 3097 $groupmode = groups_get_course_groupmode($course);
48e535bc 3098 }
48e535bc 3099 if ($course->groupmode or (!$course->groupmodeforce)) {
3100 echo '<tr valign="top">';
3101 echo '<td align="right"><b>'.get_string('groupmode').':</b></td>';
7bbe08a2 3102 echo '<td align="left">';
ffc536af 3103 $choices = array();
48e535bc 3104 $choices[NOGROUPS] = get_string('groupsnone');
3105 $choices[SEPARATEGROUPS] = get_string('groupsseparate');
3106 $choices[VISIBLEGROUPS] = get_string('groupsvisible');
3107 choose_from_menu($choices, 'groupmode', $groupmode, '', '', 0, false, $course->groupmodeforce);
3108 helpbutton('groupmode', get_string('groupmode'));
3109 echo '</td></tr>';
3110 }
3111}
3112
263017bb 3113/**
7cac0c4b 3114 * Print groupmode form element on module setup forms in mod/.../mod_form.php
263017bb 3115 */
3116function print_grouping_settings($form, $course=NULL) {
f33e1ed4 3117 global $DB;
263017bb 3118
3119 if (empty($course)) {
cb6fec1f 3120 if (! $course = $DB->get_record('course', array('id'=>$form->course))) {
ba6018a9 3121 print_error("invalidcourseid");
263017bb 3122 }
3123 }
3124 if ($form->coursemodule) {
cb6fec1f 3125 if (!$cm = $DB->get_record('course_modules', array('id'=>$form->coursemodule))) {
d857e8b6 3126 print_error('invalidcoursemodule');
263017bb 3127 }
3128 } else {
3129 $cm = null;
3130 }
3131
f33e1ed4 3132 $groupings = $DB->get_records_menu('groupings', array('courseid'=>$course->id), 'name', 'id, name');
263017bb 3133 if (!empty($groupings)) {
3134 echo '<tr valign="top">';
3135 echo '<td align="right"><b>'.get_string('grouping', 'group').':</b></td>';
3136 echo '<td align="left">';
238c0dd9 3137
263017bb 3138 $groupingid = isset($cm->groupingid) ? $cm->groupingid : 0;
238c0dd9 3139
263017bb 3140 choose_from_menu($groupings, 'groupingid', $groupingid, get_string('none'), '', 0, false);
3141 echo '</td></tr>';
238c0dd9 3142
263017bb 3143 $checked = empty($cm->groupmembersonly) ? '':'checked="checked"';
3144 echo '<tr valign="top">';
3145 echo '<td align="right"><b>'.get_string('groupmembersonly', 'group').':</b></td>';
3146 echo '<td align="left">';
3147 echo "<input type=\"checkbox\" name=\"groupmembersonly\" value=\"1\" $checked />";
3148 echo '</td></tr>';
3149
3150 }
3151}
3152
48e535bc 3153/**
7cac0c4b 3154 * Print visibility setting form element on module setup forms in mod/.../mod_form.php
48e535bc 3155 */
5ebb746b 3156function print_visible_setting($form, $course=NULL) {
cb6fec1f 3157 global $DB;
1ee55c41 3158 if (empty($course)) {
cb6fec1f 3159 if (!$course = $DB->get_record('course', array('id'=>$form->course))) {
ba6018a9 3160 print_error("invalidcourseid");
1ee55c41 3161 }
3162 }
48e535bc 3163 if ($form->coursemodule) {
cb6fec1f 3164 $visible = $DB->get_field('course_modules', 'visible', array('id'=>$form->coursemodule));