weekly release
[moodle.git] / course / lib.php
CommitLineData
d9cb06dc 1<?php
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
18/**
19 * Library of useful functions
20 *
21 * @copyright 1999 Martin Dougiamas http://dougiamas.com
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
df997f84
PS
23 * @package core
24 * @subpackage course
d9cb06dc 25 */
f9903ed0 26
df997f84
PS
27defined('MOODLE_INTERNAL') || die;
28
4e781c7b 29require_once($CFG->libdir.'/completionlib.php');
8bdc9cac 30require_once($CFG->libdir.'/filelib.php');
f9903ed0 31
92890025 32define('COURSE_MAX_LOG_DISPLAY', 150); // days
33define('COURSE_MAX_LOGS_PER_PAGE', 1000); // records
34define('COURSE_LIVELOG_REFRESH', 60); // Seconds
35define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds
36define('COURSE_MAX_SUMMARIES_PER_PAGE', 10); // courses
950c35a9 37define('COURSE_MAX_COURSES_PER_DROPDOWN',1000); // max courses in log dropdown before switching to optional
92890025 38define('COURSE_MAX_USERS_PER_DROPDOWN',1000); // max users in log dropdown before switching to optional
220a90c5 39define('FRONTPAGENEWS', '0');
40define('FRONTPAGECOURSELIST', '1');
41define('FRONTPAGECATEGORYNAMES', '2');
42define('FRONTPAGETOPICONLY', '3');
43define('FRONTPAGECATEGORYCOMBO', '4');
6f24e48e 44define('FRONTPAGECOURSELIMIT', 200); // maximum number of courses displayed on the frontpage
45define('EXCELROWS', 65535);
46define('FIRSTUSEDEXCELROW', 3);
60fdc714 47
89bfeee0 48define('MOD_CLASS_ACTIVITY', 0);
49define('MOD_CLASS_RESOURCE', 1);
50
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'),
29cbe431 350 get_string('fullnamecourse'),
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 1242/**
cc10c0b9
PS
1243 * Returns the course section to display or 0 meaning show all sections. Returns 0 for guests.
1244 * It also sets the $USER->display cache to array($courseid=>return value)
1245 *
13801a49 1246 * @param int $courseid The course id
cc10c0b9 1247 * @return int Course section to display, 0 means all
13801a49
AB
1248 */
1249function course_get_display($courseid) {
1250 global $USER, $DB;
1251
1252 if (!isloggedin() or isguestuser()) {
1253 //do not get settings in db for guests
1254 return 0; //return the implicit setting
1255 }
1256
1257 if (!isset($USER->display[$courseid])) {
cc10c0b9
PS
1258 if (!$display = $DB->get_field('course_display', 'display', array('userid' => $USER->id, 'course'=>$courseid))) {
1259 $display = 0; // all sections option is not stored in DB, this makes the table much smaller
13801a49 1260 }
cc10c0b9
PS
1261 //use display cache for one course only - we need to keep session small
1262 $USER->display = array($courseid => $display);
13801a49 1263 }
cc10c0b9 1264
13801a49
AB
1265 return $USER->display[$courseid];
1266}
1267
cc10c0b9
PS
1268/**
1269 * Show one section only or all sections.
1270 *
1271 * @param int $courseid The course id
1272 * @param mixed $display show only this section, 0 or 'all' means show all sections
1273 * @return int Course section to display, 0 means all
1274 */
1275function course_set_display($courseid, $display) {
cb6fec1f 1276 global $USER, $DB;
b86fc0e2 1277
cc10c0b9 1278 if ($display === 'all' or empty($display)) {
b86fc0e2 1279 $display = 0;
1280 }
1281
4f0c2d00 1282 if (!isloggedin() or isguestuser()) {
7b678e0a 1283 //do not store settings in db for guests
cc10c0b9
PS
1284 return 0;
1285 }
1286
1287 if ($display == 0) {
1288 //show all, do not store anything in database
1289 $DB->delete_records('course_display', array('userid' => $USER->id, 'course' => $courseid));
1290
b86fc0e2 1291 } else {
cc10c0b9
PS
1292 if ($DB->record_exists('course_display', array('userid' => $USER->id, 'course' => $courseid))) {
1293 $DB->set_field('course_display', 'display', $display, array('userid' => $USER->id, 'course' => $courseid));
13801a49 1294 } else {
cc10c0b9
PS
1295 $record = new stdClass();
1296 $record->userid = $USER->id;
1297 $record->course = $courseid;
1298 $record->display = $display;
1299 $DB->insert_record('course_display', $record);
13801a49 1300 }
b86fc0e2 1301 }
1302
cc10c0b9
PS
1303 //use display cache for one course only - we need to keep session small
1304 $USER->display = array($courseid => $display);
1305
1306 return $display;
b86fc0e2 1307}
1308
cb6fec1f 1309/**
7e85563d 1310 * For a given course section, marks it visible or hidden,
cb6fec1f 1311 * and does the same for every activity in that section
1312 */
7d99d695 1313function set_section_visible($courseid, $sectionnumber, $visibility) {
cb6fec1f 1314 global $DB;
7d99d695 1315
cb6fec1f 1316 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
1317 $DB->set_field("course_sections", "visible", "$visibility", array("id"=>$section->id));
7d99d695 1318 if (!empty($section->sequence)) {
1319 $modules = explode(",", $section->sequence);
1320 foreach ($modules as $moduleid) {
02f66c42 1321 set_coursemodule_visible($moduleid, $visibility, true);
7d99d695 1322 }
1323 }
5867bfb5 1324 rebuild_course_cache($courseid);
7d99d695 1325 }
1326}
ba2e5d73 1327
0d8b6a69 1328/**
1329 * Obtains shared data that is used in print_section when displaying a
1330 * course-module entry.
1331 *
1332 * Calls format_text or format_string as appropriate, and obtains the correct icon.
1333 *
1334 * This data is also used in other areas of the code.
1335 * @param cm_info $cm Course-module data (must come from get_fast_modinfo)
1336 * @param object $course Moodle course object
1337 * @return array An array with the following values in this order:
1338 * $content (optional extra content for after link),
1339 * $instancename (text of link)
1340 */
1341function get_print_section_cm_text(cm_info $cm, $course) {
1342 global $OUTPUT;
1343
1344 // Get course context
1345 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
1346
1347 // Get content from modinfo if specified. Content displays either
1348 // in addition to the standard link (below), or replaces it if
1349 // the link is turned off by setting ->url to null.
1350 if (($content = $cm->get_content()) !== '') {
1351 $labelformatoptions = new stdClass();
1352 $labelformatoptions->noclean = true;
1353 $labelformatoptions->overflowdiv = true;
1354 $labelformatoptions->context = $coursecontext;
1355 $content = format_text($content, FORMAT_HTML, $labelformatoptions);
1356 } else {
1357 $content = '';
1358 }
1359
1360 $stringoptions = new stdClass;
1361 $stringoptions->context = $coursecontext;
1362 $instancename = format_string($cm->name, true, $stringoptions);
1363 return array($content, $instancename);
1364}
1365
cb6fec1f 1366/**
1367 * Prints a section full of activity modules
1368 */
4e781c7b 1369function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%", $hidecompletion=false) {
e63f88c9 1370 global $CFG, $USER, $DB, $PAGE, $OUTPUT;
7977cffd 1371
dd97c328 1372 static $initialised;
1373
3d575e6f 1374 static $groupbuttons;
32d03b7b 1375 static $groupbuttonslink;
52dcc2f9 1376 static $isediting;
7977cffd 1377 static $ismoving;
1378 static $strmovehere;
1379 static $strmovefull;
54669989 1380 static $strunreadpostsone;
dd97c328 1381 static $groupings;
0d8b6a69 1382 static $modulenames;
110a32e2 1383
dd97c328 1384 if (!isset($initialised)) {
9fd9c29b 1385 $groupbuttons = ($course->groupmode or (!$course->groupmodeforce));
32d03b7b 1386 $groupbuttonslink = (!$course->groupmodeforce);
830dd6e9 1387 $isediting = $PAGE->user_is_editing();
dd97c328 1388 $ismoving = $isediting && ismoving($course->id);
3d575e6f 1389 if ($ismoving) {
dd97c328 1390 $strmovehere = get_string("movehere");
1391 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
3d575e6f 1392 }
0d8b6a69 1393 $modulenames = array();
dd97c328 1394 $initialised = true;
7977cffd 1395 }
dd97c328 1396
0d8b6a69 1397 $tl = textlib_get_instance();
94361e02 1398
dd97c328 1399 $modinfo = get_fast_modinfo($course);
984baa77 1400 $completioninfo = new completion_info($course);
94361e02 1401
7e85563d 1402 //Accessibility: replace table with list <ul>, but don't output empty list.
74666583 1403 if (!empty($section->sequence)) {
94361e02 1404
f2d660dc 1405 // Fix bug #5027, don't want style=\"width:$width\".
6285f8a8 1406 echo "<ul class=\"section img-text\">\n";
94361e02 1407 $sectionmods = explode(",", $section->sequence);
1408
1409 foreach ($sectionmods as $modnumber) {
9ae687af 1410 if (empty($mods[$modnumber])) {
1411 continue;
1412 }
dd97c328 1413
0d8b6a69 1414 /**
1415 * @var cm_info
1416 */
94361e02 1417 $mod = $mods[$modnumber];
c9f6251e 1418
dd97c328 1419 if ($ismoving and $mod->id == $USER->activitycopy) {
1420 // do not display moving mod
1421 continue;
1422 }
c9f6251e 1423
dd97c328 1424 if (isset($modinfo->cms[$modnumber])) {
85f55ba2 1425 // We can continue (because it will not be displayed at all)
1426 // if:
1427 // 1) The activity is not visible to users
1428 // and
1429 // 2a) The 'showavailability' option is not set (if that is set,
2f48819b 1430 // we need to display the activity so we can show
85f55ba2 1431 // availability info)
1432 // or
2f48819b 1433 // 2b) The 'availableinfo' is empty, i.e. the activity was
1434 // hidden in a way that leaves no info, such as using the
85f55ba2 1435 // eye icon.
82bd6a5e 1436 if (!$modinfo->cms[$modnumber]->uservisible &&
85f55ba2 1437 (empty($modinfo->cms[$modnumber]->showavailability) ||
1438 empty($modinfo->cms[$modnumber]->availableinfo))) {
dd97c328 1439 // visibility shortcut
1440 continue;
86aa7ccf 1441 }
dd97c328 1442 } else {
0f56c9da 1443 if (!file_exists("$CFG->dirroot/mod/$mod->modname/lib.php")) {
1444 // module not installed
1445 continue;
1446 }
82bd6a5e 1447 if (!coursemodule_visible_for_user($mod) &&
1448 empty($mod->showavailability)) {
dd97c328 1449 // full visibility check
1450 continue;
9d361034 1451 }
dd97c328 1452 }
1453
0d8b6a69 1454 if (!isset($modulenames[$mod->modname])) {
1455 $modulenames[$mod->modname] = get_string('modulename', $mod->modname);
1456 }
1457 $modulename = $modulenames[$mod->modname];
1458
2f48819b 1459 // In some cases the activity is visible to user, but it is
e8e50986 1460 // dimmed. This is done if viewhiddenactivities is true and if:
1461 // 1. the activity is not visible, or
1462 // 2. the activity has dates set which do not include current, or
1463 // 3. the activity has any other conditions set (regardless of whether
1464 // current user meets them)
1465 $canviewhidden = has_capability(
1466 'moodle/course:viewhiddenactivities',
1467 get_context_instance(CONTEXT_MODULE, $mod->id));
1468 $accessiblebutdim = false;
1469 if ($canviewhidden) {
1470 $accessiblebutdim = !$mod->visible;
1471 if (!empty($CFG->enableavailability)) {
1472 $accessiblebutdim = $accessiblebutdim ||
1473 $mod->availablefrom > time() ||
1474 ($mod->availableuntil && $mod->availableuntil < time()) ||
2f48819b 1475 count($mod->conditionsgrade) > 0 ||
e8e50986 1476 count($mod->conditionscompletion) > 0;
1477 }
1478 }
1479
060cd0c8
SH
1480 $liclasses = array();
1481 $liclasses[] = 'activity';
1482 $liclasses[] = $mod->modname;
1483 $liclasses[] = 'modtype_'.$mod->modname;
0d8b6a69 1484 $extraclasses = $mod->get_extra_classes();
1485 if ($extraclasses) {
1486 $liclasses = array_merge($liclasses, explode(' ', $extraclasses));
1487 }
060cd0c8 1488 echo html_writer::start_tag('li', array('class'=>join(' ', $liclasses), 'id'=>'module-'.$modnumber));
dd97c328 1489 if ($ismoving) {
1490 echo '<a title="'.$strmovefull.'"'.
d4a1fcaf 1491 ' href="'.$CFG->wwwroot.'/course/mod.php?moveto='.$mod->id.'&amp;sesskey='.sesskey().'">'.
b5d0cafc 1492 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
dd97c328 1493 ' alt="'.$strmovehere.'" /></a><br />
1494 ';
1495 }
9d361034 1496
060cd0c8
SH
1497 $classes = array('mod-indent');
1498 if (!empty($mod->indent)) {
1499 $classes[] = 'mod-indent-'.$mod->indent;
1500 if ($mod->indent > 15) {
1501 $classes[] = 'mod-indent-huge';
1502 }
dd97c328 1503 }
060cd0c8 1504 echo html_writer::start_tag('div', array('class'=>join(' ', $classes)));
dd97c328 1505
0d8b6a69 1506 // Get data about this course-module
1507 list($content, $instancename) =
1508 get_print_section_cm_text($modinfo->cms[$modnumber], $course);
1509
1510 //Accessibility: for files get description via icon, this is very ugly hack!
1511 $altname = '';
1512 $altname = $mod->modfullname;
1513 if (!empty($customicon)) {
1514 $archetype = plugin_supports('mod', $mod->modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1515 if ($archetype == MOD_ARCHETYPE_RESOURCE) {
1516 $mimetype = mimeinfo_from_icon('type', $customicon);
1517 $altname = get_mimetype_description($mimetype);
1518 }
1519 }
1520 // Avoid unnecessary duplication: if e.g. a forum name already
1521 // includes the word forum (or Forum, etc) then it is unhelpful
1522 // to include that in the accessible description that is added.
1523 if (false !== strpos($tl->strtolower($instancename),
1524 $tl->strtolower($altname))) {
1525 $altname = '';
1526 }
1527 // File type after name, for alphabetic lists (screen reader).
1528 if ($altname) {
1529 $altname = get_accesshide(' '.$altname);
554606c7 1530 }
dd97c328 1531
0d8b6a69 1532 // We may be displaying this just in order to show information
1533 // about visibility, without the actual link
1534 $contentpart = '';
1535 if ($mod->uservisible) {
1536 // Nope - in this case the link is fully working for user
1537 $linkclasses = '';
1538 $textclasses = '';
1539 if ($accessiblebutdim) {
1540 $linkclasses .= ' dimmed';
1541 $textclasses .= ' dimmed_text';
1542 $accesstext = '<span class="accesshide">'.
1543 get_string('hiddenfromstudents').': </span>';
722b4ce1 1544 } else {
0d8b6a69 1545 $accesstext = '';
dd97c328 1546 }
0d8b6a69 1547 if ($linkclasses) {
1548 $linkcss = 'class="' . trim($linkclasses) . '" ';
1549 } else {
1550 $linkcss = '';
1551 }
1552 if ($textclasses) {
1553 $textcss = 'class="' . trim($textclasses) . '" ';
1554 } else {
1555 $textcss = '';
c4d989a1 1556 }
aac94fd0 1557
0d8b6a69 1558 // Get on-click attribute value if specified
1559 $onclick = $mod->get_on_click();
1560 if ($onclick) {
1561 $onclick = ' onclick="' . $onclick . '"';
1562 }
c9f6251e 1563
0d8b6a69 1564 if ($url = $mod->get_url()) {
1565 // Display link itself
1566 echo '<a ' . $linkcss . $mod->extra . $onclick .
1567 ' href="' . $url . '"><img src="' . $mod->get_icon_url() .
1568 '" class="activityicon" alt="' .
1569 $modulename . '" /> ' .
1570 $accesstext . '<span class="instancename">' .
1571 $instancename . $altname . '</span></a>';
1572
1573 // If specified, display extra content after link
1574 if ($content) {
1575 $contentpart = '<div class="contentafterlink' .
1576 trim($textclasses) . '">' . $content . '</div>';
c93dae38 1577 }
dd97c328 1578 } else {
0d8b6a69 1579 // No link, so display only content
1580 $contentpart = '<div ' . $textcss . $mod->extra . '>' .
1581 $accesstext . $content . '</div>';
dd97c328 1582 }
e0b033d5 1583
0d8b6a69 1584 if (!empty($mod->groupingid) && has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
1585 if (!isset($groupings)) {
1586 $groupings = groups_get_all_groupings($course->id);
6285f8a8 1587 }
0d8b6a69 1588 echo " <span class=\"groupinglabel\">(".format_string($groupings[$mod->groupingid]->name).')</span>';
dd97c328 1589 }
0d8b6a69 1590 } else {
1591 $textclasses = $extraclasses;
1592 $textclasses .= ' dimmed_text';
1593 if ($textclasses) {
1594 $textcss = 'class="' . trim($textclasses) . '" ';
1595 } else {
1596 $textcss = '';
dd97c328 1597 }
0d8b6a69 1598 $accesstext = '<span class="accesshide">' .
1599 get_string('notavailableyet', 'condition') .
1600 ': </span>';
6285f8a8 1601
0d8b6a69 1602 if ($url = $mod->get_url()) {
82bd6a5e 1603 // Display greyed-out text of link
0d8b6a69 1604 echo '<div ' . $textcss . $mod->extra .
1605 ' >' . '<img src="' . $mod->get_icon_url() .
1606 '" class="activityicon" alt="' .
1607 $modulename .
1608 '" /> <span>'. $instancename . $altname .
1609 '</span></div>';
1610
1611 // Do not display content after link when it is greyed out like this.
1612 } else {
1613 // No link, so display only content (also greyed)
1614 $contentpart = '<div ' . $textcss . $mod->extra . '>' .
1615 $accesstext . $content . '</div>';
f37da850 1616 }
dd97c328 1617 }
f37da850 1618
0d8b6a69 1619 // Module can put text after the link (e.g. forum unread)
1620 echo $mod->get_after_link();
1621
dd97c328 1622 if ($isediting) {
525e16ce 1623 if ($groupbuttons and plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
dd97c328 1624 if (! $mod->groupmodelink = $groupbuttonslink) {
1625 $mod->groupmode = $course->groupmode;
3d575e6f 1626 }
dd97c328 1627
1628 } else {
1629 $mod->groupmode = false;
c9f6251e 1630 }
dd97c328 1631 echo '&nbsp;&nbsp;';
1632 echo make_editing_buttons($mod, $absolute, true, $mod->indent, $section->section);
0d8b6a69 1633 echo $mod->get_after_edit_icons();
94361e02 1634 }
4e781c7b 1635
1636 // Completion
3982f0f8 1637 $completion = $hidecompletion
4e781c7b 1638 ? COMPLETION_TRACKING_NONE
1639 : $completioninfo->is_enabled($mod);
2f48819b 1640 if ($completion!=COMPLETION_TRACKING_NONE && isloggedin() &&
82bd6a5e 1641 !isguestuser() && $mod->uservisible) {
3982f0f8 1642 $completiondata = $completioninfo->get_data($mod,true);
1643 $completionicon = '';
1644 if ($isediting) {
1645 switch ($completion) {
ca255392 1646 case COMPLETION_TRACKING_MANUAL :
3982f0f8 1647 $completionicon = 'manual-enabled'; break;
ca255392 1648 case COMPLETION_TRACKING_AUTOMATIC :
3982f0f8 1649 $completionicon = 'auto-enabled'; break;
4e781c7b 1650 default: // wtf
1651 }
3982f0f8 1652 } else if ($completion==COMPLETION_TRACKING_MANUAL) {
4e781c7b 1653 switch($completiondata->completionstate) {
1654 case COMPLETION_INCOMPLETE:
3982f0f8 1655 $completionicon = 'manual-n'; break;
4e781c7b 1656 case COMPLETION_COMPLETE:
3982f0f8 1657 $completionicon = 'manual-y'; break;
4e781c7b 1658 }
1659 } else { // Automatic
1660 switch($completiondata->completionstate) {
1661 case COMPLETION_INCOMPLETE:
3982f0f8 1662 $completionicon = 'auto-n'; break;
4e781c7b 1663 case COMPLETION_COMPLETE:
3982f0f8 1664 $completionicon = 'auto-y'; break;
4e781c7b 1665 case COMPLETION_COMPLETE_PASS:
3982f0f8 1666 $completionicon = 'auto-pass'; break;
4e781c7b 1667 case COMPLETION_COMPLETE_FAIL:
3982f0f8 1668 $completionicon = 'auto-fail'; break;
4e781c7b 1669 }
1670 }
3982f0f8 1671 if ($completionicon) {
b5d0cafc 1672 $imgsrc = $OUTPUT->pix_url('i/completion-'.$completionicon);
76c0123b
PS
1673 $imgalt = s(get_string('completion-alt-'.$completionicon, 'completion'));
1674 if ($completion == COMPLETION_TRACKING_MANUAL && !$isediting) {
1675 $imgtitle = s(get_string('completion-title-'.$completionicon, 'completion'));
3982f0f8 1676 $newstate =
4e781c7b 1677 $completiondata->completionstate==COMPLETION_COMPLETE
ca255392 1678 ? COMPLETION_INCOMPLETE
1679 : COMPLETION_COMPLETE;
a343b13f 1680 // In manual mode the icon is a toggle form...
1681
1682 // If this completion state is used by the
1683 // conditional activities system, we need to turn
1684 // off the JS.
2f48819b 1685 if (!empty($CFG->enableavailability) &&
76c0123b 1686 condition_info::completion_value_used_as_condition($course, $mod)) {
a343b13f 1687 $extraclass = ' preventjs';
1688 } else {
1689 $extraclass = '';
1690 }
4e781c7b 1691 echo "
76c0123b 1692<form class='togglecompletion$extraclass' method='post' action='togglecompletion.php'><div>
4e781c7b 1693<input type='hidden' name='id' value='{$mod->id}' />
8c194133 1694<input type='hidden' name='sesskey' value='".sesskey()."' />
4e781c7b 1695<input type='hidden' name='completionstate' value='$newstate' />
1696<input type='image' src='$imgsrc' alt='$imgalt' title='$imgtitle' />
1697</div></form>";
1698 } else {
1699 // In auto mode, or when editing, the icon is just an image
f17a0360 1700 echo "<span class='autocompletion'>";
f17a0360 1701 echo "<img src='$imgsrc' alt='$imgalt' title='$imgalt' /></span>";
4e781c7b 1702 }
1703 }
1704 }
1705
0d8b6a69 1706 // Display the content (if any) at this part of the html
1707 echo $contentpart;
1708
2f48819b 1709 // Show availability information (for someone who isn't allowed to
82bd6a5e 1710 // see the activity itself, or for staff)
3982f0f8 1711 if (!$mod->uservisible) {
82bd6a5e 1712 echo '<div class="availabilityinfo">'.$mod->availableinfo.'</div>';
e8e50986 1713 } else if ($canviewhidden && !empty($CFG->enableavailability)) {
82bd6a5e 1714 $ci = new condition_info($mod);
3982f0f8 1715 $fullinfo = $ci->get_full_information();
82bd6a5e 1716 if($fullinfo) {
2f48819b 1717 echo '<div class="availabilityinfo">'.get_string($mod->showavailability
82bd6a5e 1718 ? 'userrestriction_visible'
1719 : 'userrestriction_hidden','condition',
1720 $fullinfo).'</div>';
1721 }
1722 }
1723
060cd0c8
SH
1724 echo html_writer::end_tag('div');
1725 echo html_writer::end_tag('li')."\n";
94361e02 1726 }
dd97c328 1727
f2d660dc 1728 } elseif ($ismoving) {
1729 echo "<ul class=\"section\">\n";
264867fd 1730 }
dd97c328 1731
7977cffd 1732 if ($ismoving) {
64fdc686 1733 echo '<li><a title="'.$strmovefull.'"'.
d4a1fcaf 1734 ' href="'.$CFG->wwwroot.'/course/mod.php?movetosection='.$section->id.'&amp;sesskey='.sesskey().'">'.
b5d0cafc 1735 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
c6a55371 1736 ' alt="'.$strmovehere.'" /></a></li>
1c919752 1737 ';
7977cffd 1738 }
c6a55371 1739 if (!empty($section->sequence) || $ismoving) {
1740 echo "</ul><!--class='section'-->\n\n";
1741 }
a7ad3ea6 1742}
1743
89bfeee0 1744/**
1745 * Prints the menus to add activities and resources.
1746 */
cb57e6f4 1747function print_section_add_menus($course, $section, $modnames, $vertical=false, $return=false) {
64e12bb7 1748 global $CFG, $OUTPUT;
e0161bff 1749
217a8ee9 1750 // check to see if user can add menus
1751 if (!has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $course->id))) {
e2cd3ed0 1752 return false;
217a8ee9 1753 }
1754
31dadc6f
PS
1755 $urlbase = "/course/mod.php?id=$course->id&section=$section&sesskey=".sesskey().'&add=';
1756
017ab27c
DP
1757 $resources = array();
1758 $activities = array();
6da4b261 1759
017ab27c
DP
1760 foreach($modnames as $modname=>$modnamestr) {
1761 if (!course_allowed_module($course, $modname)) {
1762 continue;
1763 }
6da4b261 1764
017ab27c
DP
1765 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1766 if (!file_exists($libfile)) {
1767 continue;
1768 }
1769 include_once($libfile);
1770 $gettypesfunc = $modname.'_get_types';
1771 if (function_exists($gettypesfunc)) {
1772 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1773 if ($types = $gettypesfunc()) {
1774 $menu = array();
1775 $atype = null;
1776 $groupname = null;
1777 foreach($types as $type) {
31dadc6f 1778 if ($type->typestr === '--') {
017ab27c 1779 continue;
65bcf17b 1780 }
017ab27c
DP
1781 if (strpos($type->typestr, '--') === 0) {
1782 $groupname = str_replace('--', '', $type->typestr);
1783 continue;
89bfeee0 1784 }
017ab27c
DP
1785 $type->type = str_replace('&amp;', '&', $type->type);
1786 if ($type->modclass == MOD_CLASS_RESOURCE) {
1787 $atype = MOD_CLASS_RESOURCE;
1788 }
1789 $menu[$urlbase.$type->type] = $type->typestr;
89bfeee0 1790 }
017ab27c
DP
1791 if (!is_null($groupname)) {
1792 if ($atype == MOD_CLASS_RESOURCE) {
1793 $resources[] = array($groupname=>$menu);
1794 } else {
1795 $activities[] = array($groupname=>$menu);
1796 }
aa54ed7b 1797 } else {
017ab27c
DP
1798 if ($atype == MOD_CLASS_RESOURCE) {
1799 $resources = array_merge($resources, $menu);
1800 } else {
1801 $activities = array_merge($activities, $menu);
1802 }
aa54ed7b 1803 }
89bfeee0 1804 }
017ab27c
DP
1805 } else {
1806 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1807 if ($archetype == MOD_ARCHETYPE_RESOURCE) {
1808 $resources[$urlbase.$modname] = $modnamestr;
1809 } else {
1810 // all other archetypes are considered activity
1811 $activities[$urlbase.$modname] = $modnamestr;
1812 }
0705ff84 1813 }
e0161bff 1814 }
1815
89bfeee0 1816 $straddactivity = get_string('addactivity');
1817 $straddresource = get_string('addresource');
1818
4f24b3e3 1819 $output = '<div class="section_add_menus">';
1820
1821 if (!$vertical) {
1822 $output .= '<div class="horizontal">';
1823 }
82fcab32 1824
89bfeee0 1825 if (!empty($resources)) {
31dadc6f 1826 $select = new url_select($resources, '', array(''=>$straddresource), "ressection$section");
d2265f13 1827 $select->set_help_icon('resources');
31dadc6f 1828 $output .= $OUTPUT->render($select);
0705ff84 1829 }
cb57e6f4 1830
89bfeee0 1831 if (!empty($activities)) {
31dadc6f 1832 $select = new url_select($activities, '', array(''=>$straddactivity), "section$section");
d2265f13 1833 $select->set_help_icon('activities');
31dadc6f 1834 $output .= $OUTPUT->render($select);
0705ff84 1835 }
1836
4f24b3e3 1837 if (!$vertical) {
d33d0cda 1838 $output .= '</div>';
1839 }
1840
cb57e6f4 1841 $output .= '</div>';
1842
1843 if ($return) {
1844 return $output;
1845 } else {
1846 echo $output;
1847 }
e0161bff 1848}
1849
8ed5dd63 1850/**
1851 * Return the course category context for the category with id $categoryid, except
1852 * that if $categoryid is 0, return the system context.
1853 *
1854 * @param integer $categoryid a category id or 0.
1855 * @return object the corresponding context
1856 */
1857function get_category_or_system_context($categoryid) {
1858 if ($categoryid) {
1859 return get_context_instance(CONTEXT_COURSECAT, $categoryid);
1860 } else {
1861 return get_context_instance(CONTEXT_SYSTEM);
1862 }
1863}
1864
f36cbf1d 1865/**
1866 * Rebuilds the cached list of course activities stored in the database
7e85563d 1867 * @param int $courseid - id of course to rebuild, empty means all
f36cbf1d 1868 * @param boolean $clearonly - only clear the modinfo fields, gets rebuild automatically on the fly
1869 */
1870function rebuild_course_cache($courseid=0, $clearonly=false) {
e6db3026 1871 global $COURSE, $DB, $OUTPUT;
f36cbf1d 1872
58d89c24
SH
1873 // Destroy navigation caches
1874 navigation_cache::destroy_volatile_caches();
1875
f36cbf1d 1876 if ($clearonly) {
1c69b885 1877 if (empty($courseid)) {
1878 $courseselect = array();
1879 } else {
1880 $courseselect = array('id'=>$courseid);
1881 }
1882 $DB->set_field('course', 'modinfo', null, $courseselect);
f36cbf1d 1883 // update cached global COURSE too ;-)
f80ee891 1884 if ($courseid == $COURSE->id or empty($courseid)) {
238c0dd9 1885 $COURSE->modinfo = null;
f36cbf1d 1886 }
1887 // reset the fast modinfo cache
1888 $reset = 'reset';
1889 get_fast_modinfo($reset);
1890 return;
1891 }
5867bfb5 1892
1893 if ($courseid) {
cb6fec1f 1894 $select = array('id'=>$courseid);
5867bfb5 1895 } else {
cb6fec1f 1896 $select = array();
6cf890e3 1897 @set_time_limit(0); // this could take a while! MDL-10954
5867bfb5 1898 }
1899
a0c3fc63
EL
1900 $rs = $DB->get_recordset("course", $select,'','id,fullname');
1901 foreach ($rs as $course) {
1902 $modinfo = serialize(get_array_of_activities($course->id));
1903 $DB->set_field("course", "modinfo", $modinfo, array("id"=>$course->id));
1904 // update cached global COURSE too ;-)
1905 if ($course->id == $COURSE->id) {
1906 $COURSE->modinfo = $modinfo;
5867bfb5 1907 }
1908 }
a0c3fc63 1909 $rs->close();
dd97c328 1910 // reset the fast modinfo cache
65a00c97 1911 $reset = 'reset';
1912 get_fast_modinfo($reset);
5867bfb5 1913}
1914
cb6fec1f 1915/**
7e85563d 1916 * Gets the child categories of a given courses category. Uses a static cache
8ed5dd63 1917 * to make repeat calls efficient.
1918 *
e92c39ca 1919 * @param int $parentid the id of a course category.
8ed5dd63 1920 * @return array all the child course categories.
cb6fec1f 1921 */
8ed5dd63 1922function get_child_categories($parentid) {
9bb19e58 1923 static $allcategories = null;
1924
1925 // only fill in this variable the first time
1926 if (null == $allcategories) {
1927 $allcategories = array();
1928
1929 $categories = get_categories();
1930 foreach ($categories as $category) {
1931 if (empty($allcategories[$category->parent])) {
1932 $allcategories[$category->parent] = array();
1933 }
1934 $allcategories[$category->parent][] = $category;
1935 }
1936 }
1937
8ed5dd63 1938 if (empty($allcategories[$parentid])) {
9bb19e58 1939 return array();
1940 } else {
8ed5dd63 1941 return $allcategories[$parentid];
9bb19e58 1942 }
1943}
1944
cb6fec1f 1945/**
8ed5dd63 1946 * This function recursively travels the categories, building up a nice list
1947 * for display. It also makes an array that list all the parents for each
1948 * category.
1949 *
1950 * For example, if you have a tree of categories like:
1951 * Miscellaneous (id = 1)
1952 * Subcategory (id = 2)
1953 * Sub-subcategory (id = 4)
1954 * Other category (id = 3)
1955 * Then after calling this function you will have
1956 * $list = array(1 => 'Miscellaneous', 2 => 'Miscellaneous / Subcategory',
1957 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
1958 * 3 => 'Other category');
1959 * $parents = array(2 => array(1), 4 => array(1, 2));
1960 *
1961 * If you specify $requiredcapability, then only categories where the current
1962 * user has that capability will be added to $list, although all categories
1963 * will still be added to $parents, and if you only have $requiredcapability
1964 * in a child category, not the parent, then the child catgegory will still be
1965 * included.
1966 *
1967 * If you specify the option $excluded, then that category, and all its children,
1968 * are omitted from the tree. This is useful when you are doing something like
1969 * moving categories, where you do not want to allow people to move a category
1970 * to be the child of itself.
1971 *
1972 * @param array $list For output, accumulates an array categoryid => full category path name
1973 * @param array $parents For output, accumulates an array categoryid => list of parent category ids.
8a1b1c32 1974 * @param string/array $requiredcapability if given, only categories where the current
1975 * user has this capability will be added to $list. Can also be an array of capabilities,
1976 * in which case they are all required.
8ed5dd63 1977 * @param integer $excludeid Omit this category and its children from the lists built.
1978 * @param object $category Build the tree starting at this category - otherwise starts at the top level.
1979 * @param string $path For internal use, as part of recursive calls.
cb6fec1f 1980 */
8ed5dd63 1981function make_categories_list(&$list, &$parents, $requiredcapability = '',
1982 $excludeid = 0, $category = NULL, $path = "") {
1983
9d866ae0 1984 // initialize the arrays if needed
1985 if (!is_array($list)) {
264867fd 1986 $list = array();
9d866ae0 1987 }
1988 if (!is_array($parents)) {
264867fd 1989 $parents = array();
9d866ae0 1990 }
1991
8ed5dd63 1992 if (empty($category)) {
1993 // Start at the top level.
1994 $category = new stdClass;
1995 $category->id = 0;
1996 } else {
1997 // This is the excluded category, don't include it.
1998 if ($excludeid > 0 && $excludeid == $category->id) {
1999 return;
2000 }
2001
2002 // Update $path.
c2cb4545 2003 if ($path) {
6ba65fa0 2004 $path = $path.' / '.format_string($category->name);
c2cb4545 2005 } else {
6ba65fa0 2006 $path = format_string($category->name);
c2cb4545 2007 }
8ed5dd63 2008
2009 // Add this category to $list, if the permissions check out.
3ce50127 2010 if (empty($requiredcapability)) {
8ed5dd63 2011 $list[$category->id] = $path;
3ce50127 2012
2013 } else {
2014 ensure_context_subobj_present($category, CONTEXT_COURSECAT);
2015 $requiredcapability = (array)$requiredcapability;
2016 if (has_all_capabilities($requiredcapability, $category->context)) {
2017 $list[$category->id] = $path;
2018 }
8ed5dd63 2019 }
c2cb4545 2020 }
2021
8ed5dd63 2022 // Add all the children recursively, while updating the parents array.
2023 if ($categories = get_child_categories($category->id)) {
c2cb4545 2024 foreach ($categories as $cat) {
2025 if (!empty($category->id)) {
3bd4de22 2026 if (isset($parents[$category->id])) {
2832badf 2027 $parents[$cat->id] = $parents[$category->id];
2028 }
c2cb4545 2029 $parents[$cat->id][] = $category->id;
2030 }
8ed5dd63 2031 make_categories_list($list, $parents, $requiredcapability, $excludeid, $cat, $path);
c2cb4545 2032 }
2033 }
2034}
2035
24e27ac0
SH
2036/**
2037 * This function generates a structured array of courses and categories.
2038 *
2039 * The depth of categories is limited by $CFG->maxcategorydepth however there
2040 * is no limit on the number of courses!
2041 *
2042 * Suitable for use with the course renderers course_category_tree method:
2043 * $renderer = $PAGE->get_renderer('core','course');
2044 * echo $renderer->course_category_tree(get_course_category_tree());
2045 *
2046 * @global moodle_database $DB
2047 * @param int $id
2048 * @param int $depth
2049 */
2050function get_course_category_tree($id = 0, $depth = 0) {
cf41dc37 2051 global $DB, $CFG;
24e27ac0
SH
2052 $viewhiddencats = has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_SYSTEM));
2053 $categories = get_child_categories($id);
2054 $categoryids = array();
2055 foreach ($categories as $key => &$category) {
2056 if (!$category->visible && !$viewhiddencats) {
2057 unset($categories[$key]);
2058 continue;
2059 }
2060 $categoryids[$category->id] = $category;
2061 if (empty($CFG->maxcategorydepth) || $depth <= $CFG->maxcategorydepth) {
2062 list($category->categories, $subcategories) = get_course_category_tree($category->id, $depth+1);
3ebc548f
SH
2063 foreach ($subcategories as $subid=>$subcat) {
2064 $categoryids[$subid] = $subcat;
2065 }
24e27ac0
SH
2066 $category->courses = array();
2067 }
2068 }
2069
2070 if ($depth > 0) {
2071 // This is a recursive call so return the required array
2072 return array($categories, $categoryids);
2073 }
2074
2075 // The depth is 0 this function has just been called so we can finish it off
2076
2077 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
2078 list($catsql, $catparams) = $DB->get_in_or_equal(array_keys($categoryids));
2079 $sql = "SELECT
df997f84 2080 c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary,c.category
24e27ac0
SH
2081 $ccselect
2082 FROM {course} c
2083 $ccjoin
2084 WHERE c.category $catsql ORDER BY c.sortorder ASC";
2085 if ($courses = $DB->get_records_sql($sql, $catparams)) {
2086 // loop throught them
2087 foreach ($courses as $course) {
2088 if ($course->id == SITEID) {
2089 continue;
2090 }
2091 context_instance_preload($course);
2092 if (!empty($course->visible) || has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id))) {
2093 $categoryids[$course->category]->courses[$course->id] = $course;
2094 }
2095 }
2096 }
2097 return $categories;
2098}
c2cb4545 2099
cb6fec1f 2100/**
2101 * Recursive function to print out all the categories in a nice format
2102 * with or without courses included
2103 */
8ed5dd63 2104function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true) {
9ff5310a 2105 global $CFG;
e05bcf2f 2106
beeee4d2 2107 // maxcategorydepth == 0 meant no limit
2108 if (!empty($CFG->maxcategorydepth) && $depth >= $CFG->maxcategorydepth) {
e05bcf2f 2109 return;
9ff5310a 2110 }
c2cb4545 2111
2112 if (!$displaylist) {
e92fe848 2113 make_categories_list($displaylist, $parentslist);
c2cb4545 2114 }
2115
2116 if ($category) {
8ed5dd63 2117 if ($category->visible or has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_SYSTEM))) {
2118 print_category_info($category, $depth, $showcourses);
c2cb4545 2119 } else {
2120 return; // Don't bother printing children of invisible categories
2121 }
89adb174 2122
c2cb4545 2123 } else {
c2cb4545 2124 $category->id = "0";
2125 }
2126
9bb19e58 2127 if ($categories = get_child_categories($category->id)) { // Print all the children recursively
c2cb4545 2128 $countcats = count($categories);
2129 $count = 0;
2130 $first = true;
2131 $last = false;
2132 foreach ($categories as $cat) {
2133 $count++;
2134 if ($count == $countcats) {
2135 $last = true;
2136 }
2137 $up = $first ? false : true;
2138 $down = $last ? false : true;
2139 $first = false;
2140
8ed5dd63 2141 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1, $showcourses);
c2cb4545 2142 }
2143 }
c2cb4545 2144}
2145
cb6fec1f 2146/**
af90698b 2147 * This function will return $options array for html_writer::select(), with whitespace to denote nesting.
cb6fec1f 2148 */
0705ff84 2149function make_categories_options() {
2150 make_categories_list($cats,$parents);
2151 foreach ($cats as $key => $value) {
2152 if (array_key_exists($key,$parents)) {
2153 if ($indent = count($parents[$key])) {
2154 for ($i = 0; $i < $indent; $i++) {
2155 $cats[$key] = '&nbsp;'.$cats[$key];
2156 }
2157 }
2158 }
2159 }
2160 return $cats;
2161}
c2cb4545 2162
cb6fec1f 2163/**
2164 * Prints the category info in indented fashion
2165 * This function is only used by print_whole_category_list() above
2166 */
f3e5bf86 2167function print_category_info($category, $depth=0, $showcourses = false) {
6b608f8f 2168 global $CFG, $DB, $OUTPUT;
c2cb4545 2169
df997f84 2170 $strsummary = get_string('summary');
ba2e5d73 2171
ea831ceb
RW
2172 $catlinkcss = null;
2173 if (!$category->visible) {
2174 $catlinkcss = array('class'=>'dimmed');
2175 }
dc247e52 2176 static $coursecount = null;
2177 if (null === $coursecount) {
2178 // only need to check this once
2179 $coursecount = $DB->count_records('course') <= FRONTPAGECOURSELIMIT;
2180 }
2181
8ed5dd63 2182 if ($showcourses and $coursecount) {
b5d0cafc 2183 $catimage = '<img src="'.$OUTPUT->pix_url('i/course') . '" alt="" />';
b48f834c 2184 } else {
7b0b5c14 2185 $catimage = "&nbsp;";
8ef9cb56 2186 }
2afcfc44 2187
df997f84 2188 $courses = get_courses($category->id, 'c.sortorder ASC', 'c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary');
8ed5dd63 2189 if ($showcourses and $coursecount) {
2a63b636 2190 echo '<div class="categorylist clearfix">';
2afcfc44 2191 $cat = '';
2a63b636 2192 $cat .= html_writer::tag('div', $catimage, array('class'=>'image'));
ea831ceb 2193 $catlink = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), format_string($category->name), $catlinkcss);
2afcfc44
RW
2194 $cat .= html_writer::tag('div', $catlink, array('class'=>'name'));
2195
ea831ceb 2196 $html = '';
2afcfc44
RW
2197 if ($depth > 0) {
2198 for ($i=0; $i< $depth; $i++) {
ea831ceb 2199 $html = html_writer::tag('div', $html . $cat, array('class'=>'indentation'));
2afcfc44 2200 $cat = '';
cb184beb 2201 }
2afcfc44 2202 } else {
ea831ceb 2203 $html = $cat;
2afcfc44 2204 }
2a63b636 2205 echo html_writer::tag('div', $html, array('class'=>'category'));
2afcfc44 2206 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
b48f834c 2207
beeee4d2 2208 // does the depth exceed maxcategorydepth
2afcfc44 2209 // maxcategorydepth == 0 or unset meant no limit
beeee4d2 2210 $limit = !(isset($CFG->maxcategorydepth) && ($depth >= $CFG->maxcategorydepth-1));
beeee4d2 2211 if ($courses && ($limit || $CFG->maxcategorydepth == 0)) {
c2cb4545 2212 foreach ($courses as $course) {
ea831ceb
RW
2213 $linkcss = null;
2214 if (!$course->visible) {
2215 $linkcss = array('class'=>'dimmed');
2216 }
2a63b636 2217
ea831ceb 2218 $courselink = html_writer::link(new moodle_url('/course/view.php', array('id'=>$course->id)), format_string($course->fullname), $linkcss);
2afcfc44 2219
bf423bb1 2220 // print enrol info
f3e5bf86 2221 $courseicon = '';
bf423bb1
PS
2222 if ($icons = enrol_get_course_info_icons($course)) {
2223 foreach ($icons as $pix_icon) {
f3e5bf86 2224 $courseicon = $OUTPUT->render($pix_icon).' ';
bf423bb1
PS
2225 }
2226 }
2227
f3e5bf86
SH
2228 $coursecontent = html_writer::tag('div', $courseicon.$courselink, array('class'=>'name'));
2229
b48f834c 2230 if ($course->summary) {
75015e5f 2231 $link = new moodle_url('/course/info.php?id='.$course->id);
2afcfc44 2232 $actionlink = $OUTPUT->action_link($link, '<img alt="'.$strsummary.'" src="'.$OUTPUT->pix_url('i/info') . '" />',
75015e5f
PS
2233 new popup_action('click', $link, 'courseinfo', array('height' => 400, 'width' => 500)),
2234 array('title'=>$strsummary));
2afcfc44
RW
2235
2236 $coursecontent .= html_writer::tag('div', $actionlink, array('class'=>'info'));
2237 }
2238
ea831ceb 2239 $html = '';
f3e5bf86 2240 for ($i=0; $i <= $depth; $i++) {
ea831ceb 2241 $html = html_writer::tag('div', $html . $coursecontent , array('class'=>'indentation'));
2afcfc44 2242 $coursecontent = '';
0c656181 2243 }
ea831ceb 2244 echo html_writer::tag('div', $html, array('class'=>'course clearfloat'));
2afcfc44 2245 }
ba2e5d73 2246 }
2afcfc44
RW
2247 echo '</div>';
2248 } else {
2a63b636 2249 echo '<div class="categorylist">';
ea831ceb
RW
2250 $html = '';
2251 $cat = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), format_string($category->name), $catlinkcss);
43fa1451 2252 $cat .= html_writer::tag('span', ' ('.count($courses).')', array('title'=>get_string('numberofcourses'), 'class'=>'numberofcourse'));
2a63b636 2253
ea831ceb
RW
2254 if ($depth > 0) {
2255 for ($i=0; $i< $depth; $i++) {
2256 $html = html_writer::tag('div', $html .$cat, array('class'=>'indentation'));
2257 $cat = '';
2258 }
2259 } else {
2260 $html = $cat;
2261 }
2a63b636
PS
2262
2263 echo html_writer::tag('div', $html, array('class'=>'category'));
ea831ceb 2264 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
cb184beb 2265 echo '</div>';
2afcfc44 2266 }
c2cb4545 2267}
2268
77eddcd5 2269/**
2270 * Print the buttons relating to course requests.
2271 *
2272 * @param object $systemcontext the system context.
2273 */
2274function print_course_request_buttons($systemcontext) {
b4531207 2275 global $CFG, $DB, $OUTPUT;
77eddcd5 2276 if (empty($CFG->enablecourserequests)) {
2277 return;
2278 }
4f0c2d00 2279 if (!has_capability('moodle/course:create', $systemcontext) && has_capability('moodle/course:request', $systemcontext)) {
77eddcd5 2280 /// Print a button to request a new course
5c2ed7e2 2281 echo $OUTPUT->single_button('request.php', get_string('requestcourse'), 'get');
77eddcd5 2282 }
2283 /// Print a button to manage pending requests
2284 if (has_capability('moodle/site:approvecourse', $systemcontext)) {
5c2ed7e2
PS
2285 $disabled = !$DB->record_exists('course_request', array());
2286 echo $OUTPUT->single_button('pending.php', get_string('coursespending'), 'get', array('disabled'=>$disabled));
77eddcd5 2287 }
2288}
2289
5048e034 2290/**
2291 * Does the user have permission to edit things in this category?
2292 *
2293 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2294 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
2295 */
2296function can_edit_in_category($categoryid = 0) {
2297 $context = get_category_or_system_context($categoryid);
2298 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
2299}
2300
8ed5dd63 2301/**
2302 * Prints the turn editing on/off button on course/index.php or course/category.php.
2303 *
2304 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2305 * @return string HTML of the editing button, or empty string, if this user is not allowed
2306 * to see it.
2307 */
2308function update_category_button($categoryid = 0) {
b4531207 2309 global $CFG, $PAGE, $OUTPUT;
8ed5dd63 2310
2311 // Check permissions.
5048e034 2312 if (!can_edit_in_category($categoryid)) {
8ed5dd63 2313 return '';
2314 }
2315
2316 // Work out the appropriate action.
830dd6e9 2317 if ($PAGE->user_is_editing()) {
8ed5dd63 2318 $label = get_string('turneditingoff');
2319 $edit = 'off';
2320 } else {
2321 $label = get_string('turneditingon');
2322 $edit = 'on';
2323 }
c2cb4545 2324
8ed5dd63 2325 // Generate the button HTML.
2326 $options = array('categoryedit' => $edit, 'sesskey' => sesskey());
2327 if ($categoryid) {
2328 $options['id'] = $categoryid;
2329 $page = 'category.php';
2330 } else {
2331 $page = 'index.php';
2332 }
a6855934 2333 return $OUTPUT->single_button(new moodle_url('/course/' . $page, $options), $label, 'get');
8ed5dd63 2334}
e0b033d5 2335
cb6fec1f 2336/**
2337 * Category is 0 (for all courses) or an object
2338 */
6c54240a 2339function print_courses($category) {
2f48819b 2340 global $CFG, $OUTPUT;
c2cb4545 2341
4dde1463 2342 if (!is_object($category) && $category==0) {
9bb19e58 2343 $categories = get_child_categories(0); // Parent = 0 ie top-level categories only
4dde1463 2344 if (is_array($categories) && count($categories) == 1) {
90c2ca2e 2345 $category = array_shift($categories);
238c0dd9 2346 $courses = get_courses_wmanagers($category->id,
2347 'c.sortorder ASC',
df997f84 2348 array('summary','summaryformat'));
90c2ca2e 2349 } else {
238c0dd9 2350 $courses = get_courses_wmanagers('all',
2351 'c.sortorder ASC',
df997f84 2352 array('summary','summaryformat'));
90c2ca2e 2353 }
2354 unset($categories);
607809b3 2355 } else {
238c0dd9 2356 $courses = get_courses_wmanagers($category->id,
2357 'c.sortorder ASC',
df997f84 2358 array('summary','summaryformat'));
c2cb4545 2359 }
2360
49cd4d79 2361 if ($courses) {
002fc5ba 2362 echo html_writer::start_tag('ul', array('class'=>'unlist'));
c2cb4545 2363 foreach ($courses as $course) {
4f0c2d00
PS
2364 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
2365 if ($course->visible == 1 || has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
002fc5ba 2366 echo html_writer::start_tag('li');
4dde1463 2367 print_course($course);
002fc5ba 2368 echo html_writer::end_tag('li');
4dde1463 2369 }
c2cb4545 2370 }
002fc5ba 2371 echo html_writer::end_tag('ul');
c2cb4545 2372 } else {
7c5286cd 2373 echo $OUTPUT->heading(get_string("nocoursesyet"));
8e480396 2374 $context = get_context_instance(CONTEXT_SYSTEM);
0468976c 2375 if (has_capability('moodle/course:create', $context)) {
255d1033 2376 $options = array();
4868e95f
DM
2377 if (!empty($category->id)) {
2378 $options['category'] = $category->id;
2379 } else {
2380 $options['category'] = $CFG->defaultrequestcategory;
2381 }
002fc5ba 2382 echo html_writer::start_tag('div', array('class'=>'addcoursebutton'));
a6855934 2383 echo $OUTPUT->single_button(new moodle_url('/course/edit.php', $options), get_string("addnewcourse"));
002fc5ba 2384 echo html_writer::end_tag('div');
255d1033 2385 }
c2cb4545 2386 }
c2cb4545 2387}
2388
04c53106 2389/**
2390 * Print a description of a course, suitable for browsing in a list.
2391 *
2392 * @param object $course the course object.
2393 * @param string $highlightterms (optional) some search terms that should be highlighted in the display.
2394 */
2395function print_course($course, $highlightterms = '') {
666e8458 2396 global $CFG, $USER, $DB, $OUTPUT;
c2cb4545 2397
4f0c2d00 2398 $context = get_context_instance(CONTEXT_COURSE, $course->id);
146bbb8f 2399
8bdc9cac 2400 // Rewrite file URLs so that they are correct
64f93798 2401 $course->summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', NULL);
8bdc9cac 2402
002fc5ba
SH
2403 echo html_writer::start_tag('div', array('class'=>'coursebox clearfix'));
2404 echo html_writer::start_tag('div', array('class'=>'info'));
2405 echo html_writer::start_tag('h3', array('class'=>'name'));
22288704 2406
002fc5ba
SH
2407 $linkhref = new moodle_url('/course/view.php', array('id'=>$course->id));
2408 $linktext = highlight($highlightterms, format_string($course->fullname));
2409 $linkparams = array('title'=>get_string('entercourse'));
2410 if (empty($course->visible)) {
2411 $linkparams['class'] = 'dimmed';
2412 }
2413 echo html_writer::link($linkhref, $linktext, $linkparams);
2414 echo html_writer::end_tag('h3');
238c0dd9 2415
d42c64ba 2416 /// first find all roles that are supposed to be displayed
df997f84 2417 if (!empty($CFG->coursecontact)) {
c71f3265 2418 $managerroles = explode(',', $CFG->coursecontact);
4dde1463 2419 $namesarray = array();
2420 if (isset($course->managers)) {
2421 if (count($course->managers)) {
2422 $rusers = $course->managers;
2423 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
238c0dd9 2424
b682cee9 2425 /// Rename some of the role names if needed
2426 if (isset($context)) {
cb6fec1f 2427 $aliasnames = $DB->get_records('role_names', array('contextid'=>$context->id), '', 'roleid,contextid,name');
b682cee9 2428 }
2429
9d5a4b23 2430 // keep a note of users displayed to eliminate duplicates
2431 $usersshown = array();
4dde1463 2432 foreach ($rusers as $ra) {
9d5a4b23 2433
2434 // if we've already displayed user don't again
2435 if (in_array($ra->user->id,$usersshown)) {
2436 continue;
2437 }
2438 $usersshown[] = $ra->user->id;
2439
4f0c2d00 2440 $fullname = fullname($ra->user, $canviewfullnames);
b682cee9 2441
4f0c2d00
PS
2442 if (isset($aliasnames[$ra->roleid])) {
2443 $ra->rolename = $aliasnames[$ra->roleid]->name;
4dde1463 2444 }
4f0c2d00 2445
002fc5ba
SH
2446 $namesarray[] = format_string($ra->rolename).': '.
2447 html_writer::link(new moodle_url('/user/view.php', array('id'=>$ra->user->id, 'course'=>SITEID)), $fullname);
4dde1463 2448 }
2449 }
2450 } else {
238c0dd9 2451 $rusers = get_role_users($managerroles, $context,
4f0c2d00 2452 true, '', 'r.sortorder ASC, u.lastname ASC');
4dde1463 2453 if (is_array($rusers) && count($rusers)) {
2454 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
165d25cc 2455
2456 /// Rename some of the role names if needed
2457 if (isset($context)) {
2458 $aliasnames = $DB->get_records('role_names', array('contextid'=>$context->id), '', 'roleid,contextid,name');
2459 }
2460
4dde1463 2461 foreach ($rusers as $teacher) {
238c0dd9 2462 $fullname = fullname($teacher, $canviewfullnames);
165d25cc 2463
2464 /// Apply role names
2465 if (isset($aliasnames[$teacher->roleid])) {
2466 $teacher->rolename = $aliasnames[$teacher->roleid]->name;
2467 }
2468
002fc5ba
SH
2469 $namesarray[] = format_string($teacher->rolename).': '.
2470 html_writer::link(new moodle_url('/user/view.php', array('id'=>$teacher->id, 'course'=>SITEID)), $fullname);
4dde1463 2471 }
431cad0d 2472 }
c2cb4545 2473 }
431cad0d 2474
d42c64ba 2475 if (!empty($namesarray)) {
002fc5ba
SH
2476 echo html_writer::start_tag('ul', array('class'=>'teachers'));
2477 foreach ($namesarray as $name) {
2478 echo html_writer::tag('li', $name);
2479 }
2480 echo html_writer::end_tag('ul');
88768091 2481 }
c2cb4545 2482 }
002fc5ba 2483 echo html_writer::end_tag('div'); // End of info div
238c0dd9 2484
002fc5ba 2485 echo html_writer::start_tag('div', array('class'=>'summary'));
9f39c190 2486 $options = NULL;
2487 $options->noclean = true;
34b5847a 2488 $options->para = false;
367a75fa 2489 $options->overflowdiv = true;
8bdc9cac
SH
2490 if (!isset($course->summaryformat)) {
2491 $course->summaryformat = FORMAT_MOODLE;
2492 }
2493 echo highlight($highlightterms, format_text($course->summary, $course->summaryformat, $options, $course->id));
002fc5ba
SH
2494 if ((!isloggedin() || is_siteadmin()) && $icons = enrol_get_course_info_icons($course)) {
2495 echo html_writer::start_tag('div', array('class'=>'enrolmenticons'));
2496 foreach ($icons as $icon) {
2497 echo $OUTPUT->render($icon);
2498 }
2499 echo html_writer::end_tag('div'); // End of enrolmenticons div
2500 }
2501 echo html_writer::end_tag('div'); // End of summary div
2502 echo html_writer::end_tag('div'); // End of coursebox div
c2cb4545 2503}
2504
cb6fec1f 2505/**
2506 * Prints custom user information on the home page.
2507 * Over time this can include all sorts of information
2508 */
c2cb4545 2509function print_my_moodle() {
e6db3026 2510 global $USER, $CFG, $DB, $OUTPUT;
c2cb4545 2511
4f0c2d00 2512 if (!isloggedin() or isguestuser()) {
ba6018a9 2513 print_error('nopermissions', '', '', 'See My Moodle');
c2cb4545 2514 }
2515
df997f84 2516 $courses = enrol_get_my_courses('summary', 'visible DESC,sortorder ASC');
0a127169 2517 $rhosts = array();
2518 $rcourses = array();
2519 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
2520 $rcourses = get_my_remotecourses($USER->id);
2521 $rhosts = get_my_remotehosts();
2522 }
2523
2524 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
2525
2526 if (!empty($courses)) {
2527 echo '<ul class="unlist">';
2528 foreach ($courses as $course) {
2529 if ($course->id == SITEID) {
2530 continue;
2531 }
2532 echo '<li>';
2533 print_course($course);
2534 echo "</li>\n";
86dd62a7 2535 }
0a127169 2536 echo "</ul>\n";
86dd62a7 2537 }
2538
0a127169 2539 // MNET
2540 if (!empty($rcourses)) {
2541 // at the IDP, we know of all the remote courses
2542 foreach ($rcourses as $course) {
2543 print_remote_course($course, "100%");
2544 }
2545 } elseif (!empty($rhosts)) {
2546 // non-IDP, we know of all the remote servers, but not courses
2547 foreach ($rhosts as $host) {
2548 print_remote_host($host, "100%");
2549 }
2550 }
86dd62a7 2551 unset($course);
0a127169 2552 unset($host);
38a10939 2553
cb6fec1f 2554 if ($DB->count_records("course") > (count($courses) + 1) ) { // Some courses not being displayed
7f989948 2555 echo "<table width=\"100%\"><tr><td align=\"center\">";
2556 print_course_search("", false, "short");
2557 echo "</td><td align=\"center\">";
5c2ed7e2 2558 echo $OUTPUT->single_button("$CFG->wwwroot/course/index.php", get_string("fulllistofcourses"), "get");
7f989948 2559 echo "</td></tr></table>\n";
2560 }
86dd62a7 2561
26330001 2562 } else {
cb6fec1f 2563 if ($DB->count_records("course_categories") > 1) {
e6db3026 2564 echo $OUTPUT->box_start("categorybox");
26330001 2565 print_whole_category_list();
e6db3026 2566 echo $OUTPUT->box_end();
26330001 2567 } else {
35d0244a 2568 print_courses(0);
26330001 2569 }
607809b3 2570 }
2b8cef80 2571}
2572
11b0c469 2573
a8b56716 2574function print_course_search($value="", $return=false, $format="plain") {
38a10939 2575 global $CFG;
1e0fb105 2576 static $count = 0;
2577
2578 $count++;
2579
2580 $id = 'coursesearch';
2581
2582 if ($count > 1) {
2583 $id .= $count;
2584 }
38a10939 2585
2586 $strsearchcourses= get_string("searchcourses");
2587
1c919752 2588 if ($format == 'plain') {
1e0fb105 2589 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
fcf9577a 2590 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
e42f4d92 2591 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
cb6fec1f 2592 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" value="'.s($value).'" />';
e42f4d92 2593 $output .= '<input type="submit" value="'.get_string('go').'" />';
fcf9577a 2594 $output .= '</fieldset></form>';
1c919752 2595 } else if ($format == 'short') {
1e0fb105 2596 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
fcf9577a 2597 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
b1f97418 2598 $output .= '<label for="shortsearchbox">'.$strsearchcourses.': </label>';
cb6fec1f 2599 $output .= '<input type="text" id="shortsearchbox" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
e42f4d92 2600 $output .= '<input type="submit" value="'.get_string('go').'" />';
fcf9577a 2601 $output .= '</fieldset></form>';
1c919752 2602 } else if ($format == 'navbar') {
fcf9577a 2603 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2604 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
b1f97418 2605 $output .= '<label for="navsearchbox">'.$strsearchcourses.': </label>';
cb6fec1f 2606 $output .= '<input type="text" id="navsearchbox" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
e42f4d92 2607 $output .= '<input type="submit" value="'.get_string('go').'" />';
fcf9577a 2608 $output .= '</fieldset></form>';
a8b56716 2609 }
2610
2611 if ($return) {
2612 return $output;
2613 }
2614 echo $output;
38a10939 2615}
11b0c469 2616
86dd62a7 2617function print_remote_course($course, $width="100%") {
86dd62a7 2618 global $CFG, $USER;
2619
2620 $linkcss = '';
2621
2622 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&amp;wantsurl=/course/view.php?id={$course->remoteid}";
2623
7cd266e9 2624 echo '<div class="coursebox remotecoursebox clearfix">';
86dd62a7 2625 echo '<div class="info">';
2626 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2627 $linkcss.' href="'.$url.'">'
6ba65fa0 2628 . format_string($course->fullname) .'</a><br />'
2629 . format_string($course->hostname) . ' : '
238c0dd9 2630 . format_string($course->cat_name) . ' : '
2631 . format_string($course->shortname). '</div>';
86dd62a7 2632 echo '</div><div class="summary">';
2633 $options = NULL;
2634 $options->noclean = true;
2635 $options->para = false;
367a75fa 2636 $options->overflowdiv = true;
152a2273 2637 echo format_text($course->summary, $course->summaryformat, $options);
86dd62a7 2638 echo '</div>';
2639 echo '</div>';
86dd62a7 2640}
2641
643b67b8 2642function print_remote_host($host, $width="100%") {
6b608f8f 2643 global $OUTPUT;
643b67b8 2644
2645 $linkcss = '';
2646
7cd266e9 2647 echo '<div class="coursebox clearfix">';
643b67b8 2648 echo '<div class="info">';
2649 echo '<div class="name">';
b5d0cafc 2650 echo '<img src="'.$OUTPUT->pix_url('i/mnethost') . '" class="icon" alt="'.get_string('course').'" />';
643b67b8 2651 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2652 . s($host['name']).'</a> - ';
1fd80ad3 2653 echo $host['count'] . ' ' . get_string('courses');
643b67b8 2654 echo '</div>';
2655 echo '</div>';
caa90d56 2656 echo '</div>';
643b67b8 2657}
2658
86dd62a7 2659
11b0c469 2660/// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2661
2662function add_course_module($mod) {
cb6fec1f 2663 global $DB;
11b0c469 2664
e5dfd0f3 2665 $mod->added = time();
53f4ad2c 2666 unset($mod->id);
11b0c469 2667
cb6fec1f 2668 return $DB->insert_record("course_modules", $mod);
11b0c469 2669}
2670
97928ddf 2671/**
2672 * Returns course section - creates new if does not exist yet.
2673 * @param int $relative section number
2674 * @param int $courseid
2675 * @return object $course_section object
2676 */
2677function get_course_section($section, $courseid) {
cb6fec1f 2678 global $DB;
2679
2680 if ($cw = $DB->get_record("course_sections", array("section"=>$section, "course"=>$courseid))) {
97928ddf 2681 return $cw;
2682 }
fbaea88f 2683 $cw = new stdClass();
cb6fec1f 2684 $cw->course = $courseid;
2685 $cw->section = $section;
2686 $cw->summary = "";
09eb2151 2687 $cw->summaryformat = FORMAT_HTML;
97928ddf 2688 $cw->sequence = "";
cb6fec1f 2689 $id = $DB->insert_record("course_sections", $cw);
dc5af91a 2690 return $DB->get_record("course_sections", array("id"=>$id));
97928ddf 2691}
ece966f0 2692/**
2693 * Given a full mod object with section and course already defined, adds this module to that section.
2694 *
2695 * @param object $mod
2696 * @param int $beforemod An existing ID which we will insert the new module before
2697 * @return int The course_sections ID where the mod is inserted
2698 */
7977cffd 2699function add_mod_to_section($mod, $beforemod=NULL) {
cb6fec1f 2700 global $DB;
11b0c469 2701
cb6fec1f 2702 if ($section = $DB->get_record("course_sections", array("course"=>$mod->course, "section"=>$mod->section))) {
7977cffd 2703
2704 $section->sequence = trim($section->sequence);
2705
2706 if (empty($section->sequence)) {
11b0c469 2707 $newsequence = "$mod->coursemodule";
7977cffd 2708
2709 } else if ($beforemod) {
2710 $modarray = explode(",", $section->sequence);
2711
d857e8b6 2712 if ($key = array_keys($modarray, $beforemod->id)) {
7977cffd 2713 $insertarray = array($mod->id, $beforemod->id);
2714 array_splice($modarray, $key[0], 1, $insertarray);
2715 $newsequence = implode(",", $modarray);
2716
2717 } else { // Just tack it on the end anyway
2718 $newsequence = "$section->sequence,$mod->coursemodule";
2719 }
2720
2721 } else {
2722 $newsequence = "$section->sequence,$mod->coursemodule";
11b0c469 2723 }
89adb174 2724
f685e830
PS
2725 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
2726 return $section->id; // Return course_sections ID that was used.
89adb174 2727
11b0c469 2728 } else { // Insert a new record
cb6fec1f 2729 $section->course = $mod->course;
2730 $section->section = $mod->section;
2731 $section->summary = "";
09eb2151 2732 $section->summaryformat = FORMAT_HTML;
e5dfd0f3 2733 $section->sequence = $mod->coursemodule;
cb6fec1f 2734 return $DB->insert_record("course_sections", $section);
11b0c469 2735 }
2736}
2737
48e535bc 2738function set_coursemodule_groupmode($id, $groupmode) {
cb6fec1f 2739 global $DB;
a5d424df 2740 return $DB->set_field("course_modules", "groupmode", $groupmode, array("id"=>$id));
3d575e6f 2741}
2742
177d4abf 2743function set_coursemodule_idnumber($id, $idnumber) {
cb6fec1f 2744 global $DB;
238c0dd9 2745 return $DB->set_field("course_modules", "idnumber", $idnumber, array("id"=>$id));
177d4abf 2746}
4e781c7b 2747
02f66c42 2748/**
2749* $prevstateoverrides = true will set the visibility of the course module
2750* to what is defined in visibleold. This enables us to remember the current
2751* visibility when making a whole section hidden, so that when we toggle
2752* that section back to visible, we are able to return the visibility of
2753* the course module back to what it was originally.
2754*/
2755function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
f5e2602a 2756 global $DB, $CFG;
0f078024
DM
2757 require_once($CFG->libdir.'/gradelib.php');
2758
cb6fec1f 2759 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
978abb42 2760 return false;
2761 }
cb6fec1f 2762 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
978abb42 2763 return false;
2764 }
cb6fec1f 2765 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
dcd338ff 2766 foreach($events as $event) {
48e535bc 2767 if ($visible) {
2768 show_event($event);
2769 } else {
2770 hide_event($event);
2771 }
dcd338ff 2772 }
2773 }
f5e2602a 2774
0f078024
DM
2775 // hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there
2776 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
2777 if ($grade_items) {
2778 foreach ($grade_items as $grade_item) {
2779 $grade_item->set_hidden(!$visible);
2780 }
f5e2602a 2781 }
f685e830 2782
02f66c42 2783 if ($prevstateoverrides) {
2784 if ($visible == '0') {
2785 // Remember the current visible state so we can toggle this back.
cb6fec1f 2786 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id'=>$id));
02f66c42 2787 } else {
2788 // Get the previous saved visible states.
cb6fec1f 2789 return $DB->set_field('course_modules', 'visible', $cm->visibleold, array('id'=>$id));
02f66c42 2790 }
2791 }
cb6fec1f 2792 return $DB->set_field("course_modules", "visible", $visible, array("id"=>$id));
1acfbce5 2793}
2794
cb6fec1f 2795/**
290130b3 2796 * Delete a course module and any associated data at the course level (events)
264867fd 2797 * Until 1.5 this function simply marked a deleted flag ... now it
290130b3 2798 * deletes it completely.
2799 *
2800 */
48e535bc 2801function delete_course_module($id) {
cb6fec1f 2802 global $CFG, $DB;
f615fbab 2803 require_once($CFG->libdir.'/gradelib.php');
cae83708 2804 require_once($CFG->dirroot.'/blog/lib.php');
f615fbab 2805
cb6fec1f 2806 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
290130b3 2807 return true;
2808 }
cb6fec1f 2809 $modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module));
f615fbab 2810 //delete events from calendar
cb6fec1f 2811 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
dcd338ff 2812 foreach($events as $event) {
0ea03696 2813 delete_event($event->id);
dcd338ff 2814 }
2815 }
f615fbab 2816 //delete grade items, outcome items and grades attached to modules
2817 if ($grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2818 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course))) {
2819 foreach ($grade_items as $grade_item) {
2820 $grade_item->delete('moddelete');
2821 }
f615fbab 2822 }
46e12372
SM
2823 // Delete completion and availability data; it is better to do this even if the
2824 // features are not turned on, in case they were turned on previously (these will be
2825 // very quick on an empty table)
2826 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
2827 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id));
06b3a6b2 2828
2829 delete_context(CONTEXT_MODULE, $cm->id);
bf66a674 2830 return $DB->delete_records('course_modules', array('id'=>$cm->id));
11b0c469 2831}
2832
2833function delete_mod_from_section($mod, $section) {
cb6fec1f 2834 global $DB;
11b0c469 2835
cb6fec1f 2836 if ($section = $DB->get_record("course_sections", array("id"=>$section)) ) {
11b0c469 2837
e5dfd0f3 2838 $modarray = explode(",", $section->sequence);
11b0c469 2839
2840 if ($key = array_keys ($modarray, $mod)) {
2841 array_splice($modarray, $key[0], 1);
2842 $newsequence = implode(",", $modarray);
cb6fec1f 2843 return $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
11b0c469 2844 } else {
2845 return false;
2846 }
89adb174 2847
11b0c469 2848 }
7977cffd 2849 return false;
11b0c469 2850}
2851
3440ec12 2852/**
2853 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
2854 *
2855 * @param object $course
2856 * @param int $section
2857 * @param int $move (-1 or 1)
2858 */
12905134 2859function move_section($course, $section, $move) {
2860/// Moves a whole course section up and down within the course
cb6fec1f 2861 global $USER, $DB;
12905134 2862
2863 if (!$move) {
2864 return true;
2865 }
2866
2867 $sectiondest = $section + $move;
2868
2869 if ($sectiondest > $course->numsections or $sectiondest < 1) {
2870 return false;
2871 }
2872
cb6fec1f 2873 if (!$sectionrecord = $DB->get_record("course_sections", array("course"=>$course->id, "section"=>$section))) {
12905134 2874 return false;
2875 }
2876
cb6fec1f 2877 if (!$sectiondestrecord = $DB->get_record("course_sections", array("course"=>$course->id, "section"=>$sectiondest))) {
12905134 2878 return false;
2879 }
2880
f685e830
PS
2881 $DB->set_field("course_sections", "section", $sectiondest, array("id"=>$sectionrecord->id));
2882 $DB->set_field("course_sections", "section", $section, array("id"=>$sectiondestrecord->id));
2883
798b70a1 2884 // if the focus is on the section that is being moved, then move the focus along
13801a49 2885 if (course_get_display($course->id) == $section) {
798b70a1 2886 course_set_display($course->id, $sectiondest);
2887 }
5390cbb7 2888
a987106d 2889 // Check for duplicates and fix order if needed.
5390cbb7 2890 // There is a very rare case that some sections in the same course have the same section id.
cb6fec1f 2891 $sections = $DB->get_records('course_sections', array('course'=>$course->id), 'section ASC');
a987106d 2892 $n = 0;
2893 foreach ($sections as $section) {
2894 if ($section->section != $n) {
f685e830 2895 $DB->set_field('course_sections', 'section', $n, array('id'=>$section->id));
5390cbb7 2896 }
a987106d 2897 $n++;
5390cbb7 2898 }
12905134 2899 return true;
2900}
2901
3440ec12 2902/**
2903 * Moves a section within a course, from a position to another.
2904 * Be very careful: $section and $destination refer to section number,
2905 * not id!.
2906 *
2907 * @param object $course
2908 * @param int $section Section number (not id!!!)
2909 * @param int $destination
2910 * @return boolean Result
2911 */
2912function move_section_to($course, $section, $destination) {
2913/// Moves a whole course section up and down within the course
2914 global $USER, $DB;
2915
ca255392 2916 if (!$destination && $destination != 0) {
3440ec12 2917 return true;
2918 }
2919
ca255392 2920 if ($destination > $course->numsections) {
3440ec12 2921 return false;
2922 }
2923
2924 // Get all sections for this course and re-order them (2 of them should now share the same section number)
2925 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
2926 'section ASC, id ASC', 'id, section')) {
2927 return false;
2928 }
2929
2930 $sections = reorder_sections($sections, $section, $destination);
2931
2932 // Update all sections
2933 foreach ($sections as $id => $position) {
2934 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
2935 }
2936
2937 // if the focus is on the section that is being moved, then move the focus along
13801a49 2938 if (course_get_display($course->id) == $section) {
3440ec12 2939 course_set_display($course->id, $destination);
2940 }
2941 return true;
2942}
2943
2944/**
2945 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
2946 * an original position number and a target position number, rebuilds the array so that the
2947 * move is made without any duplication of section positions.
2948 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
2949 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
2950 *
2951 * @param array $sections
2952 * @param int $origin_position
2953 * @param int $target_position
2954 * @return array
2955 */
2956function reorder_sections($sections, $origin_position, $target_position) {
2957 if (!is_array($sections)) {
2958 return false;
2959 }
2960
2961 // We can't move section position 0
2962 if ($origin_position < 1) {
2963 echo "We can't move section position 0";
2964 return false;
2965 }
2966
2967 // Locate origin section in sections array
2968 if (!$origin_key = array_search($origin_position, $sections)) {
2969 echo "searched position not in sections array";
2970 return false; // searched position not in sections array
2971 }
2972
2973 // Extract origin section
2974 $origin_section = $sections[$origin_key];
2975 unset($sections[$origin_key]);
2976
2977 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
2978 $found = false;
2979 $append_array = array();
2980 foreach ($sections as $id => $position) {
2981 if ($found) {
2982 $append_array[$id] = $position;
2983 unset($sections[$id]);
2984 }
2985 if ($position == $target_position) {
2986 $found = true;
2987 }
2988 }
2989
2990 // Append moved section
2991 $sections[$origin_key] = $origin_section;
2992
2993 // Append rest of array (if applicable)
2994 if (!empty($append_array)) {
2995 foreach ($append_array as $id => $position) {
2996 $sections[$id] = $position;
2997 }
2998 }
2999
3000 // Renumber positions
3001 $position = 0;
3002 foreach ($sections as $id => $p) {
3003 $sections[$id] = $position;
3004 $position++;
3005 }
3006
3007 return $sections;
3008
3009}
3010
cb6fec1f 3011/**
3012 * Move the module object $mod to the specified $section
3013 * If $beforemod exists then that is the module
3014 * before which $modid should be inserted
3015 * All parameters are objects
3016 */
7977cffd 3017function moveto_module($mod, $section, $beforemod=NULL) {
e6db3026 3018 global $DB, $OUTPUT;
7977cffd 3019
3020/// Remove original module from original section
7977cffd 3021 if (! delete_mod_from_section($mod->id, $mod->section)) {
e6db3026 3022 echo $OUTPUT->notification("Could not delete module from existing section");
7977cffd 3023 }
3024
3025/// Update module itself if necessary
3026
3027 if ($mod->section != $section->id) {
89adb174 3028 $mod->section = $section->id;
bb4b6010 3029 $DB->update_record("course_modules", $mod);
48e535bc 3030 // if moving to a hidden section then hide module
3031 if (!$section->visible) {
3032 set_coursemodule_visible($mod->id, 0);
3033 }
7977cffd 3034 }
3035
3036/// Add the module into the new section
3037
3038 $mod->course = $section->course;
3039 $mod->section = $section->section; // need relative reference
3040 $mod->coursemodule = $mod->id;
3041
3042 if (! add_mod_to_section($mod, $beforemod)) {
3043 return false;
3044 }
3045
3046 return true;
7977cffd 3047}
3048
24e1eae4 3049function make_editing_buttons($mod, $absolute=false, $moveselect=true, $indent=-1, $section=-1) {
6b608f8f 3050 global $CFG, $USER, $DB, $OUTPUT;
94361e02 3051
3d575e6f 3052 static $str;
37a88449 3053 static $sesskey;
3d575e6f 3054
217a8ee9 3055 $modcontext = get_context_instance(CONTEXT_MODULE, $mod->id);
3056 // no permission to edit
3057 if (!has_capability('moodle/course:manageactivities', $modcontext)) {
e2cd3ed0 3058 return false;
217a8ee9 3059 }
3060
3d575e6f 3061 if (!isset($str)) {
9534a8cb 3062 $str->assign = get_string("assignroles", 'role');
90ebdf65 3063 $str->delete = get_string("delete");
3064 $str->move = get_string("move");
3065 $str->moveup = get_string("moveup");
3066 $str->movedown = get_string("movedown");
3067 $str->moveright = get_string("moveright");
3068 $str->moveleft = get_string("moveleft");
3069 $str->update = get_string("update");
3070 $str->duplicate = get_string("duplicate");
3071 $str->hide = get_string("hide");
3072 $str->show = get_string("show");
3d575e6f 3073 $str->clicktochange = get_string("clicktochange");
32d03b7b 3074 $str->forcedmode = get_string("forcedmode");
3d575e6f 3075 $str->groupsnone = get_string("groupsnone");
3076 $str->groupsseparate = get_string("groupsseparate");
3077 $str->groupsvisible = get_string("groupsvisible");
37a88449 3078 $sesskey = sesskey();
1acfbce5 3079 }
94361e02 3080
24e1eae4 3081 if ($section >= 0) {
75f087b6 3082 $section = '&amp;sr='.$section; // Section return
24e1eae4 3083 } else {
3084 $section = '';
3085 }
3086
94361e02 3087 if ($absolute) {
37a88449 3088 $path = $CFG->wwwroot.'/course';
dc0dc7d5 3089 } else {
37a88449 3090 $path = '.';
dc0dc7d5 3091 }
217a8ee9 3092 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
3093 if ($mod->visible) {
3094 $hideshow = '<a class="editing_hide" title="'.$str->hide.'" href="'.$path.'/mod.php?hide='.$mod->id.
3095 '&amp;sesskey='.$sesskey.$section.'"><img'.
b5d0cafc 3096 ' src="'.$OUTPUT->pix_url('t/hide') . '" class="iconsmall" '.
217a8ee9 3097 ' alt="'.$str->hide.'" /></a>'."\n";
3098 } else {
3099 $hideshow = '<a class="editing_show" title="'.$str->show.'" href="'.$path.'/mod.php?show='.$mod->id.
3100 '&amp;sesskey='.$sesskey.$section.'"><img'.
b5d0cafc 3101 ' src="'.$OUTPUT->pix_url('t/show') . '" class="iconsmall" '.
217a8ee9 3102 ' alt="'.$str->show.'" /></a>'."\n";
3103 }
530db4cd 3104 } else {
3105 $hideshow = '';
7977cffd 3106 }
530db4cd 3107
3d575e6f 3108 if ($mod->groupmode !== false) {
3109 if ($mod->groupmode == SEPARATEGROUPS) {
32d03b7b 3110 $grouptitle = $str->groupsseparate;
cddbd5d5 3111 $groupclass = 'editing_groupsseparate';
b5d0cafc 3112 $groupimage = $OUTPUT->pix_url('t/groups') . '';
37a88449 3113 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=0&amp;sesskey='.$sesskey;
3d575e6f 3114 } else if ($mod->groupmode == VISIBLEGROUPS) {
32d03b7b 3115 $grouptitle = $str->groupsvisible;
cddbd5d5 3116 $groupclass = 'editing_groupsvisible';
b5d0cafc 3117 $groupimage = $OUTPUT->pix_url('t/groupv') . '';
37a88449 3118 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=1&amp;sesskey='.$sesskey;
32d03b7b 3119 } else {
3120 $grouptitle = $str->groupsnone;
90ebdf65 3121 $groupclass = 'editing_groupsnone';
b5d0cafc 3122 $groupimage = $OUTPUT->pix_url('t/groupn') . '';
37a88449 3123 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=2&amp;sesskey='.$sesskey;
32d03b7b 3124 }
3125 if ($mod->groupmodelink) {
90ebdf65 3126 $groupmode = '<a class="'.$groupclass.'" title="'.$grouptitle.' ('.$str->clicktochange.')" href="'.$grouplink.'">'.
0d905d9f 3127 '<img src="'.$groupimage.'" class="iconsmall" '.
3128 'alt="'.$grouptitle.'" /></a>';
3d575e6f 3129 } else {
37a88449 3130 $groupmode = '<img title="'.$grouptitle.' ('.$str->forcedmode.')" '.
0d905d9f 3131 ' src="'.$groupimage.'" class="iconsmall" '.
3132 'alt="'.$grouptitle.'" />';
3d575e6f 3133 }
3134 } else {
3135 $groupmode = "";
3136 }
e2cd3ed0 3137
217a8ee9 3138 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $mod->course))) {
3139 if ($moveselect) {
3140 $move = '<a class="editing_move" title="'.$str->move.'" href="'.$path.'/mod.php?copy='.$mod->id.
3141 '&amp;sesskey='.$sesskey.$section.'"><img'.
b5d0cafc 3142 ' src="'.$OUTPUT->pix_url('t/move') . '" class="iconsmall" '.
217a8ee9 3143 ' alt="'.$str->move.'" /></a>'."\n";
3144 } else {
3145 $move = '<a class="editing_moveup" title="'.$str->moveup.'" href="'.$path.'/mod.php?id='.$mod->id.
3146 '&amp;move=-1&amp;sesskey='.$sesskey.$section.'"><img'.
b5d0cafc 3147 ' src="'.$OUTPUT->pix_url('t/up') . '" class="iconsmall" '.
217a8ee9 3148 ' alt="'.$str->moveup.'" /></a>'."\n".
3149 '<a class="editing_movedown" title="'.$str->movedown.'" href="'.$path.'/mod.php?id='.$mod->id.
3150 '&amp;move=1&amp;sesskey='.$sesskey.$section.'"><img'.
b5d0cafc 3151 ' src="'.$OUTPUT->pix_url('t/down') . '" class="iconsmall" '.
217a8ee9 3152 ' alt="'.$str->movedown.'" /></a>'."\n";
3153 }
7b44777e 3154 } else {
238c0dd9 3155 $move = '';
7977cffd 3156 }
3157
932be046 3158 $leftright = '';
217a8ee9 3159 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $mod->course))) {
932be046 3160
78946b9b
PS
3161 if (right_to_left()) { // Exchange arrows on RTL
3162 $rightarrow = 't/left';
3163 $leftarrow = 't/right';
3164 } else {
3165 $rightarrow = 't/right';
3166 $leftarrow = 't/left';
932be046 3167 }
238c0dd9 3168
217a8ee9 3169 if ($indent > 0) {