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