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