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