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