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