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