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