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