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