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