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