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