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