MDL-37082 core_course: create new course_delete_module function that handles the...
[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 }
cf003abc 1172 $subtype->link = new moodle_url($urlbase, array('add' => $modname, 'type' => $subtype->name));
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) {
11fbebb0 1426 $categorycourses = get_category_courses_array($category->id);
e226a86d 1427 } else {
11fbebb0 1428 $categorycourses = get_category_courses_array();
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/**
a347aee3
MN
2186 * This function will handles the whole deletion process of a module. This includes calling
2187 * the modules delete_instance function, deleting files, events, grades, conditional data,
2188 * the data in the course_module and course_sections table and adding a module deletion
2189 * event to the DB.
290130b3 2190 *
a347aee3
MN
2191 * @param int $cmid the course module id
2192 * @since 2.5
290130b3 2193 */
a347aee3
MN
2194function course_delete_module($cmid) {
2195 global $CFG, $DB, $USER;
2196
f615fbab 2197 require_once($CFG->libdir.'/gradelib.php');
cae83708 2198 require_once($CFG->dirroot.'/blog/lib.php');
f615fbab 2199
a347aee3
MN
2200 // Get the course module.
2201 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
290130b3 2202 return true;
2203 }
a347aee3
MN
2204
2205 // Get the module context.
2206 $modcontext = context_module::instance($cm->id);
2207
2208 // Get the course module name.
2209 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
2210
2211 // Get the file location of the delete_instance function for this module.
2212 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
2213
2214 // Include the file required to call the delete_instance function for this module.
2215 if (file_exists($modlib)) {
2216 require_once($modlib);
2217 } else {
2218 throw new moodle_exception("This module is missing mod/$modulename/lib.php", '', '',
2219 null, 'failedtodeletemodulemissinglibfile');
2220 }
2221
2222 $deleteinstancefunction = $modulename . "_delete_instance";
2223
2224 if (!$deleteinstancefunction($cm->instance)) {
2225 throw new moodle_exception("Could not delete the $modulename (instance)", '', '',
2226 null, 'failedtodeletemoduleinstance');
2227 }
2228
2229 // Remove all module files in case modules forget to do that.
2230 $fs = get_file_storage();
2231 $fs->delete_area_files($modcontext->id);
2232
2233 // Delete events from calendar.
2234 if ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename))) {
dcd338ff 2235 foreach($events as $event) {
0ea03696 2236 delete_event($event->id);
dcd338ff 2237 }
2238 }
a347aee3
MN
2239
2240 // Delete grade items, outcome items and grades attached to modules.
2241 if ($grade_items = grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $modulename,
2242 'iteminstance' => $cm->instance, 'courseid' => $cm->course))) {
f615fbab 2243 foreach ($grade_items as $grade_item) {
2244 $grade_item->delete('moddelete');
2245 }
f615fbab 2246 }
a347aee3 2247
46e12372
SM
2248 // Delete completion and availability data; it is better to do this even if the
2249 // features are not turned on, in case they were turned on previously (these will be
a347aee3 2250 // very quick on an empty table).
46e12372
SM
2251 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
2252 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id));
a8f84c28 2253 $DB->delete_records('course_modules_avail_fields', array('coursemoduleid' => $cm->id));
ede323e2
ARN
2254 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
2255 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
06b3a6b2 2256
a347aee3 2257 // Delete the context.
06b3a6b2 2258 delete_context(CONTEXT_MODULE, $cm->id);
a347aee3
MN
2259
2260 // Delete the module from the course_modules table.
2261 $DB->delete_records('course_modules', array('id' => $cm->id));
2262
2263 // Delete module from that section.
2264 if (!delete_mod_from_section($cm->id, $cm->section)) {
2265 throw new moodle_exception("Could not delete the $modulename from section", '', '',
2266 null, 'failedtodeletemodulefromsection');
2267 }
2268
2269 // Trigger a mod_deleted event with information about this module.
2270 $eventdata = new stdClass();
2271 $eventdata->modulename = $modulename;
2272 $eventdata->cmid = $cm->id;
2273 $eventdata->courseid = $cm->course;
2274 $eventdata->userid = $USER->id;
2275 events_trigger('mod_deleted', $eventdata);
2276
2277 add_to_log($cm->course, 'course', "delete mod",
2278 "view.php?id=$cm->course",
2279 "$modulename $cm->instance", $cm->id);
2280
38b19bbc 2281 rebuild_course_cache($cm->course, true);
11b0c469 2282}
2283
722e6ba9 2284function delete_mod_from_section($modid, $sectionid) {
cb6fec1f 2285 global $DB;
11b0c469 2286
722e6ba9 2287 if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
11b0c469 2288
e5dfd0f3 2289 $modarray = explode(",", $section->sequence);
11b0c469 2290
722e6ba9 2291 if ($key = array_keys ($modarray, $modid)) {
11b0c469 2292 array_splice($modarray, $key[0], 1);
2293 $newsequence = implode(",", $modarray);
38b19bbc
MG
2294 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
2295 rebuild_course_cache($section->course, true);
2296 return true;
11b0c469 2297 } else {
2298 return false;
2299 }
89adb174 2300
11b0c469 2301 }
7977cffd 2302 return false;
11b0c469 2303}
2304
3440ec12 2305/**
2306 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
2307 *
93d46f48
RK
2308 * @param object $course course object
2309 * @param int $section Section number (not id!!!)
3440ec12 2310 * @param int $move (-1 or 1)
93d46f48 2311 * @return boolean true if section moved successfully
ac5f6414 2312 * @todo MDL-33379 remove this function in 2.5
3440ec12 2313 */
12905134 2314function move_section($course, $section, $move) {
ac5f6414
RT
2315 debugging('This function will be removed before 2.5 is released please use move_section_to', DEBUG_DEVELOPER);
2316
12905134 2317/// Moves a whole course section up and down within the course
38b19bbc 2318 global $USER;
12905134 2319
2320 if (!$move) {
2321 return true;
2322 }
2323
2324 $sectiondest = $section + $move;
2325
850acb35
MG
2326 // compartibility with course formats using field 'numsections'
2327 $courseformatoptions = course_get_format($course)->get_format_options();
2328 if (array_key_exists('numsections', $courseformatoptions) &&
2329 $sectiondest > $courseformatoptions['numsections'] or $sectiondest < 1) {
12905134 2330 return false;
2331 }
2332
eb01aa2c 2333 $retval = move_section_to($course, $section, $sectiondest);
eb01aa2c 2334 return $retval;
12905134 2335}
2336
3440ec12 2337/**
2338 * Moves a section within a course, from a position to another.
2339 * Be very careful: $section and $destination refer to section number,
2340 * not id!.
2341 *
2342 * @param object $course
2343 * @param int $section Section number (not id!!!)
2344 * @param int $destination
2345 * @return boolean Result
2346 */
2347function move_section_to($course, $section, $destination) {
2348/// Moves a whole course section up and down within the course
2349 global $USER, $DB;
2350
ca255392 2351 if (!$destination && $destination != 0) {
3440ec12 2352 return true;
2353 }
2354
850acb35
MG
2355 // compartibility with course formats using field 'numsections'
2356 $courseformatoptions = course_get_format($course)->get_format_options();
2357 if ((array_key_exists('numsections', $courseformatoptions) &&
2358 ($destination > $courseformatoptions['numsections'])) || ($destination < 1)) {
3440ec12 2359 return false;
2360 }
2361
2362 // Get all sections for this course and re-order them (2 of them should now share the same section number)
2363 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
2364 'section ASC, id ASC', 'id, section')) {
2365 return false;
2366 }
2367
cf76b335 2368 $movedsections = reorder_sections($sections, $section, $destination);
3440ec12 2369
cf76b335 2370 // Update all sections. Do this in 2 steps to avoid breaking database
2371 // uniqueness constraint
2372 $transaction = $DB->start_delegated_transaction();
2373 foreach ($movedsections as $id => $position) {
2374 if ($sections[$id] !== $position) {
2375 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
2376 }
2377 }
e7e0f8d2
DP
2378 foreach ($movedsections as $id => $position) {
2379 if ($sections[$id] !== $position) {
2380 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
2381 }
3440ec12 2382 }
2383
15e2552f
RK
2384 // If we move the highlighted section itself, then just highlight the destination.
2385 // Adjust the higlighted section location if we move something over it either direction.
2386 if ($section == $course->marker) {
e7b6e6b9 2387 course_set_marker($course->id, $destination);
2365213f 2388 } elseif ($section > $course->marker && $course->marker >= $destination) {
e7b6e6b9 2389 course_set_marker($course->id, $course->marker+1);
2365213f 2390 } elseif ($section < $course->marker && $course->marker <= $destination) {
e7b6e6b9 2391 course_set_marker($course->id, $course->marker-1);
15e2552f
RK
2392 }
2393
cf76b335 2394 $transaction->allow_commit();
38b19bbc 2395 rebuild_course_cache($course->id, true);
3440ec12 2396 return true;
2397}
2398
2399/**
2400 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
2401 * an original position number and a target position number, rebuilds the array so that the
2402 * move is made without any duplication of section positions.
2403 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
2404 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
2405 *
2406 * @param array $sections
2407 * @param int $origin_position
2408 * @param int $target_position
2409 * @return array
2410 */
2411function reorder_sections($sections, $origin_position, $target_position) {
2412 if (!is_array($sections)) {
2413 return false;
2414 }
2415
2416 // We can't move section position 0
2417 if ($origin_position < 1) {
2418 echo "We can't move section position 0";
2419 return false;
2420 }
2421
2422 // Locate origin section in sections array
2423 if (!$origin_key = array_search($origin_position, $sections)) {
2424 echo "searched position not in sections array";
2425 return false; // searched position not in sections array
2426 }
2427
2428 // Extract origin section
2429 $origin_section = $sections[$origin_key];
2430 unset($sections[$origin_key]);
2431
2432 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
2433 $found = false;
2434 $append_array = array();
2435 foreach ($sections as $id => $position) {
2436 if ($found) {
2437 $append_array[$id] = $position;
2438 unset($sections[$id]);
2439 }
2440 if ($position == $target_position) {
eb01aa2c
RT
2441 if ($target_position < $origin_position) {
2442 $append_array[$id] = $position;
2443 unset($sections[$id]);
2444 }
3440ec12 2445 $found = true;
2446 }
2447 }
2448
2449 // Append moved section
2450 $sections[$origin_key] = $origin_section;
2451
2452 // Append rest of array (if applicable)
2453 if (!empty($append_array)) {
2454 foreach ($append_array as $id => $position) {
2455 $sections[$id] = $position;
2456 }
2457 }
2458
2459 // Renumber positions
2460 $position = 0;
2461 foreach ($sections as $id => $p) {
2462 $sections[$id] = $position;
2463 $position++;
2464 }
2465
2466 return $sections;
2467
2468}
2469
cb6fec1f 2470/**
2471 * Move the module object $mod to the specified $section
2472 * If $beforemod exists then that is the module
2473 * before which $modid should be inserted
2474 * All parameters are objects
2475 */
7977cffd 2476function moveto_module($mod, $section, $beforemod=NULL) {
38b19bbc 2477 global $OUTPUT;
7977cffd 2478
2479/// Remove original module from original section
7977cffd 2480 if (! delete_mod_from_section($mod->id, $mod->section)) {
e6db3026 2481 echo $OUTPUT->notification("Could not delete module from existing section");
7977cffd 2482 }
2483
722e6ba9
MG
2484 // if moving to a hidden section then hide module
2485 if (!$section->visible && $mod->visible) {
2486 set_coursemodule_visible($mod->id, 0);
7977cffd 2487 }
2488
2489/// Add the module into the new section
722e6ba9 2490 course_add_cm_to_section($section->course, $mod->id, $section->section, $beforemod);
7977cffd 2491 return true;
7977cffd 2492}
2493
f558b291
MG
2494/**
2495 * Returns the list of all editing actions that current user can perform on the module
2496 *
2497 * @param cm_info $mod The module to produce editing buttons for
2498 * @param int $indent The current indenting (default -1 means no move left-right actions)
2499 * @param int $sr The section to link back to (used for creating the links)
2500 * @return array array of action_link or pix_icon objects
2501 */
2502function course_get_cm_edit_actions(cm_info $mod, $indent = -1, $sr = null) {
2503 global $COURSE, $SITE;
94361e02 2504
3d575e6f 2505 static $str;
2506
9a5e297b
AA
2507 $coursecontext = context_course::instance($mod->course);
2508 $modcontext = context_module::instance($mod->id);
7749e187 2509
af189935
PS
2510 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
2511 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
2512
2513 // no permission to edit anything
2514 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
f558b291 2515 return array();
217a8ee9 2516 }
2517
af189935
PS
2518 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
2519
3d575e6f 2520 if (!isset($str)) {
f558b291
MG
2521 $str = get_strings(array('delete', 'move', 'moveright', 'moveleft',
2522 'update', 'duplicate', 'hide', 'show', 'edittitle'), 'moodle');
2523 $str->assign = get_string('assignroles', 'role');
6dc5908e
ARN
2524 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
2525 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
2526 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
2527 $str->forcedgroupsnone = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsnone"));
2528 $str->forcedgroupsseparate = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsseparate"));
2529 $str->forcedgroupsvisible = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsvisible"));
1acfbce5 2530 }
94361e02 2531
af189935 2532 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
24e1eae4 2533
f558b291
MG
2534 if ($sr !== null) {
2535 $baseurl->param('sr', $sr);
7749e187
SH
2536 }
2537 $actions = array();
2538
7a9a07d2 2539 // AJAX edit title
f558b291
MG
2540 if ($mod->modname !== 'label' && $hasmanageactivities &&
2541 (($mod->course == $COURSE->id && course_ajax_enabled($COURSE)) ||
2542 ($mod->course == SITEID && course_ajax_enabled($SITE)))) {
2543 // we will not display link if we are on some other-course page (where we should not see this module anyway)
2544 $actions['title'] = new action_link(
7a9a07d2 2545 new moodle_url($baseurl, array('update' => $mod->id)),
aad982aa 2546 new pix_icon('t/editstring', $str->edittitle, 'moodle', array('class' => 'iconsmall visibleifjs', 'title' => '')),
7a9a07d2
ARN
2547 null,
2548 array('class' => 'editing_title', 'title' => $str->edittitle)
2549 );
2550 }
2551
7749e187 2552 // leftright
af189935 2553 if ($hasmanageactivities) {
7749e187
SH
2554 if (right_to_left()) { // Exchange arrows on RTL
2555 $rightarrow = 't/left';
2556 $leftarrow = 't/right';
2557 } else {
2558 $rightarrow = 't/right';
2559 $leftarrow = 't/left';
2560 }
2561
2562 if ($indent > 0) {
f558b291 2563 $actions['moveleft'] = new action_link(
7749e187 2564 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
aad982aa 2565 new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall', 'title' => '')),
7749e187
SH
2566 null,
2567 array('class' => 'editing_moveleft', 'title' => $str->moveleft)
2568 );
2569 }
2570 if ($indent >= 0) {
f558b291 2571 $actions['moveright'] = new action_link(
7749e187 2572 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
aad982aa 2573 new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall', 'title' => '')),
7749e187
SH
2574 null,
2575 array('class' => 'editing_moveright', 'title' => $str->moveright)
2576 );
2577 }
dc0dc7d5 2578 }
7749e187
SH
2579
2580 // move
af189935 2581 if ($hasmanageactivities) {
f558b291
MG
2582 $actions['move'] = new action_link(
2583 new moodle_url($baseurl, array('copy' => $mod->id)),
2584 new pix_icon('t/move', $str->move, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2585 null,
2586 array('class' => 'editing_move', 'title' => $str->move)
2587 );
7749e187
SH
2588 }
2589
2590 // Update
af189935 2591 if ($hasmanageactivities) {
f558b291 2592 $actions['update'] = new action_link(
af189935 2593 new moodle_url($baseurl, array('update' => $mod->id)),
aad982aa 2594 new pix_icon('t/edit', $str->update, 'moodle', array('class' => 'iconsmall', 'title' => '')),
af189935
PS
2595 null,
2596 array('class' => 'editing_update', 'title' => $str->update)
2597 );
2598 }
7749e187 2599
8a1a951f 2600 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
f558b291
MG
2601 // note that restoring on front page is never allowed
2602 if ($mod->course != SITEID && has_all_capabilities($dupecaps, $coursecontext) &&
2603 plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2)) {
2604 $actions['duplicate'] = new action_link(
8645a28f 2605 new moodle_url($baseurl, array('duplicate' => $mod->id)),
aad982aa 2606 new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall', 'title' => '')),
8645a28f
EL
2607 null,
2608 array('class' => 'editing_duplicate', 'title' => $str->duplicate)
2609 );
2610 }
7749e187
SH
2611
2612 // Delete
af189935 2613 if ($hasmanageactivities) {
f558b291 2614 $actions['delete'] = new action_link(
af189935 2615 new moodle_url($baseurl, array('delete' => $mod->id)),
aad982aa 2616 new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall', 'title' => '')),
af189935
PS
2617 null,
2618 array('class' => 'editing_delete', 'title' => $str->delete)
2619 );
2620 }
7749e187
SH
2621
2622 // hideshow
217a8ee9 2623 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
2624 if ($mod->visible) {
f558b291 2625 $actions['hide'] = new action_link(
7749e187 2626 new moodle_url($baseurl, array('hide' => $mod->id)),
aad982aa 2627 new pix_icon('t/hide', $str->hide, 'moodle', array('class' => 'iconsmall', 'title' => '')),
7749e187
SH
2628 null,
2629 array('class' => 'editing_hide', 'title' => $str->hide)
2630 );
217a8ee9 2631 } else {
f558b291 2632 $actions['show'] = new action_link(
7749e187 2633 new moodle_url($baseurl, array('show' => $mod->id)),
aad982aa 2634 new pix_icon('t/show', $str->show, 'moodle', array('class' => 'iconsmall', 'title' => '')),
7749e187
SH
2635 null,
2636 array('class' => 'editing_show', 'title' => $str->show)
2637 );
217a8ee9 2638 }
7977cffd 2639 }
530db4cd 2640
7749e187 2641 // groupmode
5c016ab3
MG
2642 if ($hasmanageactivities and plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
2643 if ($mod->coursegroupmodeforce) {
2644 $modgroupmode = $mod->coursegroupmode;
2645 } else {
2646 $modgroupmode = $mod->groupmode;
2647 }
2648 if ($modgroupmode == SEPARATEGROUPS) {
f558b291 2649 $groupmode = NOGROUPS;
32d03b7b 2650 $grouptitle = $str->groupsseparate;
6dc5908e 2651 $forcedgrouptitle = $str->forcedgroupsseparate;
f558b291 2652 $actionname = 'groupsseparate';
7749e187 2653 $groupimage = 't/groups';
5c016ab3 2654 } else if ($modgroupmode == VISIBLEGROUPS) {
f558b291 2655 $groupmode = SEPARATEGROUPS;
32d03b7b 2656 $grouptitle = $str->groupsvisible;
6dc5908e 2657 $forcedgrouptitle = $str->forcedgroupsvisible;
f558b291 2658 $actionname = 'groupsvisible';
7749e187 2659 $groupimage = 't/groupv';
32d03b7b 2660 } else {
f558b291 2661 $groupmode = VISIBLEGROUPS;
32d03b7b 2662 $grouptitle = $str->groupsnone;
6dc5908e 2663 $forcedgrouptitle = $str->forcedgroupsnone;
f558b291 2664 $actionname = 'groupsnone';
7749e187 2665 $groupimage = 't/groupn';
32d03b7b 2666 }
5c016ab3 2667 if (!$mod->coursegroupmodeforce) {
f558b291 2668 $actions[$actionname] = new action_link(
7749e187 2669 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $groupmode)),
aad982aa 2670 new pix_icon($groupimage, $grouptitle, 'moodle', array('class' => 'iconsmall', 'title' => '')),
7749e187 2671 null,
f558b291 2672 array('class' => 'editing_'. $actionname, 'title' => $grouptitle)
7749e187 2673 );
3d575e6f 2674 } else {
f558b291 2675 $actions[$actionname] = new pix_icon($groupimage, $forcedgrouptitle, 'moodle', array('title' => $forcedgrouptitle, 'class' => 'iconsmall'));
3d575e6f 2676 }
7977cffd 2677 }
2678
7749e187 2679 // Assign
af189935 2680 if (has_capability('moodle/role:assign', $modcontext)){
f558b291
MG
2681 $actions['assign'] = new action_link(
2682 new moodle_url('/admin/roles/assign.php', array('contextid' => $modcontext->id)),
fbb207c5 2683 new pix_icon('t/assignroles', $str->assign, 'moodle', array('class' => 'iconsmall', 'title' => '')),
7749e187
SH
2684 null,
2685 array('class' => 'editing_assign', 'title' => $str->assign)
2686 );
2687 }
2688
f558b291 2689 return $actions;
90845098 2690}
2691
b61efafb 2692/**
264867fd 2693 * given a course object with shortname & fullname, this function will
b61efafb 2694 * truncate the the number of chars allowed and add ... if it was too long
2695 */
2696function course_format_name ($course,$max=100) {
264867fd 2697
9a5e297b 2698 $context = context_course::instance($course->id);
8ebbb06a 2699 $shortname = format_string($course->shortname, true, array('context' => $context));
9a5e297b 2700 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
d1e36240 2701 $str = $shortname.': '. $fullname;
138c7678 2702 if (textlib::strlen($str) <= $max) {
b61efafb 2703 return $str;
2704 }
2705 else {
138c7678 2706 return textlib::substr($str,0,$max-3).'...';
b61efafb 2707 }
2708}
2709
0705ff84 2710/**
9665ecd2
TH
2711 * Is the user allowed to add this type of module to this course?
2712 * @param object $course the course settings. Only $course->id is used.
2713 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
2714 * @return bool whether the current user is allowed to add this type of module to this course.
0705ff84 2715 */
9665ecd2 2716function course_allowed_module($course, $modname) {
9665ecd2
TH
2717 if (is_numeric($modname)) {
2718 throw new coding_exception('Function course_allowed_module no longer
2719 supports numeric module ids. Please update your code to pass the module name.');
0705ff84 2720 }
264867fd 2721
9665ecd2
TH
2722 $capability = 'mod/' . $modname . ':addinstance';
2723 if (!get_capability_info($capability)) {
2724 // Debug warning that the capability does not exist, but no more than once per page.
2725 static $warned = array();
2726 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
2727 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
2728 debugging('The module ' . $modname . ' does not define the standard capability ' .
2729 $capability , DEBUG_DEVELOPER);
2730 $warned[$modname] = 1;
2731 }
ddb0a19f 2732
9665ecd2
TH
2733 // If the capability does not exist, the module can always be added.
2734 return true;
0705ff84 2735 }
238c0dd9 2736
9665ecd2
TH
2737 $coursecontext = context_course::instance($course->id);
2738 return has_capability($capability, $coursecontext);
0705ff84 2739}
2740
e2b347e9 2741/**
2742 * Recursively delete category including all subcategories and courses.
e92c39ca 2743 * @param stdClass $category
a3a1708f 2744 * @param boolean $showfeedback display some notices
2745 * @return array return deleted courses
e2b347e9 2746 */
2747function category_delete_full($category, $showfeedback=true) {
cb6fec1f 2748 global $CFG, $DB;
e2b347e9 2749 require_once($CFG->libdir.'/gradelib.php');
2750 require_once($CFG->libdir.'/questionlib.php');
e60ff536 2751 require_once($CFG->dirroot.'/cohort/lib.php');
e2b347e9 2752
cb6fec1f 2753 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
e2b347e9 2754 foreach ($children as $childcat) {
a3a1708f 2755 category_delete_full($childcat, $showfeedback);
e2b347e9 2756 }
2757 }
2758
a3a1708f 2759 $deletedcourses = array();
cb6fec1f 2760 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC')) {
e2b347e9 2761 foreach ($courses as $course) {
2942a5cd 2762 if (!delete_course($course, false)) {
a3a1708f 2763 throw new moodle_exception('cannotdeletecategorycourse','','',$course->shortname);
e2b347e9 2764 }
a3a1708f 2765 $deletedcourses[] = $course;
e2b347e9 2766 }
2767 }
2768
e60ff536
PS
2769 // move or delete cohorts in this context
2770 cohort_delete_category($category);
2771
e2b347e9 2772 // now delete anything that may depend on course category context
2773 grade_course_category_delete($category->id, 0, $showfeedback);
2774 if (!question_delete_course_category($category, 0, $showfeedback)) {
a3a1708f 2775 throw new moodle_exception('cannotdeletecategoryquestions','','',$category->name);
e2b347e9 2776 }
2777
2778 // finally delete the category and it's context
cb6fec1f 2779 $DB->delete_records('course_categories', array('id'=>$category->id));
e2b347e9 2780 delete_context(CONTEXT_COURSECAT, $category->id);
2781
2942a5cd 2782 events_trigger('course_category_deleted', $category);
e2b347e9 2783
2f48819b 2784 return $deletedcourses;
e2b347e9 2785}
2786
2787/**
2788 * Delete category, but move contents to another category.
2789 * @param object $ccategory
2790 * @param int $newparentid category id
2791 * @return bool status
2792 */
2793function category_delete_move($category, $newparentid, $showfeedback=true) {
e6db3026 2794 global $CFG, $DB, $OUTPUT;
e2b347e9 2795 require_once($CFG->libdir.'/gradelib.php');
2796 require_once($CFG->libdir.'/questionlib.php');
e60ff536 2797 require_once($CFG->dirroot.'/cohort/lib.php');
e2b347e9 2798
cb6fec1f 2799 if (!$newparentcat = $DB->get_record('course_categories', array('id'=>$newparentid))) {
e2b347e9 2800 return false;
2801 }
2802
cb6fec1f 2803 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
e2b347e9 2804 foreach ($children as $childcat) {
90ee78e2 2805 move_category($childcat, $newparentcat);
e2b347e9 2806 }
2807 }
2808
cb6fec1f 2809 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC', 'id')) {
e2b347e9 2810 if (!move_courses(array_keys($courses), $newparentid)) {
2f951d86
FS
2811 if ($showfeedback) {
2812 echo $OUTPUT->notification("Error moving courses");
2813 }
e2b347e9 2814 return false;
2815 }
2f951d86
FS
2816 if ($showfeedback) {
2817 echo $OUTPUT->notification(get_string('coursesmovedout', '', format_string($category->name)), 'notifysuccess');
2818 }
e2b347e9 2819 }
2820
e60ff536
PS
2821 // move or delete cohorts in this context
2822 cohort_delete_category($category);
2823
e2b347e9 2824 // now delete anything that may depend on course category context
2825 grade_course_category_delete($category->id, $newparentid, $showfeedback);
2826 if (!question_delete_course_category($category, $newparentcat, $showfeedback)) {
2f951d86
FS
2827 if ($showfeedback) {
2828 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $category), 'notifysuccess');
2829 }
e2b347e9 2830 return false;
2831 }
2832
2833 // finally delete the category and it's context
cb6fec1f 2834 $DB->delete_records('course_categories', array('id'=>$category->id));
e2b347e9 2835 delete_context(CONTEXT_COURSECAT, $category->id);
2836
2942a5cd 2837 events_trigger('course_category_deleted', $category);
e2b347e9 2838
2f951d86
FS
2839 if ($showfeedback) {
2840 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', format_string($category->name)), 'notifysuccess');
2841 }
e2b347e9 2842 return true;
2843}
2844
cb6fec1f 2845/**
2846 * Efficiently moves many courses around while maintaining
2847 * sortorder in order.
2848 *
e92c39ca
PS
2849 * @param array $courseids is an array of course ids
2850 * @param int $categoryid
df997f84 2851 * @return bool success
cb6fec1f 2852 */
2853function move_courses($courseids, $categoryid) {
e6db3026 2854 global $CFG, $DB, $OUTPUT;
861efb19 2855
df997f84
PS
2856 if (empty($courseids)) {
2857 // nothing to do
2858 return;
2859 }
264867fd 2860
df997f84
PS
2861 if (!$category = $DB->get_record('course_categories', array('id'=>$categoryid))) {
2862 return false;
2863 }
19f601d1 2864
df997f84 2865 $courseids = array_reverse($courseids);
9a5e297b 2866 $newparent = context_coursecat::instance($category->id);
df997f84 2867 $i = 1;
0cbe8111 2868
df997f84
PS
2869 foreach ($courseids as $courseid) {
2870 if ($course = $DB->get_record('course', array('id'=>$courseid), 'id, category')) {
77bf97e3
MG
2871 $course = new stdClass();
2872 $course->id = $courseid;
df997f84
PS
2873 $course->category = $category->id;
2874 $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
2875 if ($category->visible == 0) {
2876 // hide the course when moving into hidden category,
2877 // do not update the visibleold flag - we want to get to previous state if somebody unhides the category
2878 $course->visible = 0;
861efb19 2879 }
df997f84
PS
2880
2881 $DB->update_record('course', $course);
2882
9a5e297b 2883 $context = context_course::instance($course->id);
df997f84 2884 context_moved($context, $newparent);
264867fd 2885 }
0cbe8111 2886 }
df997f84
PS
2887 fix_course_sortorder();
2888
861efb19 2889 return true;
2890}
2891
df997f84
PS
2892/**
2893 * Hide course category and child course and subcategories
e92c39ca 2894 * @param stdClass $category
df997f84
PS
2895 * @return void
2896 */
2897function course_category_hide($category) {
2898 global $DB;
2899
2900 $category->visible = 0;
2901 $DB->set_field('course_categories', 'visible', 0, array('id'=>$category->id));
2902 $DB->set_field('course_categories', 'visibleold', 0, array('id'=>$category->id));
2903 $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
2904 $DB->set_field('course', 'visible', 0, array('category' => $category->id));
2905 // get all child categories and hide too
2906 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
2907 foreach ($subcats as $cat) {
2908 $DB->set_field('course_categories', 'visibleold', $cat->visible, array('id'=>$cat->id));
2909 $DB->set_field('course_categories', 'visible', 0, array('id'=>$cat->id));
2910 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id));
2911 $DB->set_field('course', 'visible', 0, array('category' => $cat->id));
2912 }
2913 }
2914}
2915
2916/**
2917 * Show course category and child course and subcategories
e92c39ca 2918 * @param stdClass $category
df997f84
PS
2919 * @return void
2920 */
2921function course_category_show($category) {
2922 global $DB;
2923
2924 $category->visible = 1;
2925 $DB->set_field('course_categories', 'visible', 1, array('id'=>$category->id));
2926 $DB->set_field('course_categories', 'visibleold', 1, array('id'=>$category->id));
2927 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($category->id));
2928 // get all child categories and unhide too
2929 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
2930 foreach ($subcats as $cat) {
2931 if ($cat->visibleold) {
2932 $DB->set_field('course_categories', 'visible', 1, array('id'=>$cat->id));
2933 }
2934 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id));
2935 }
2936 }
2937}
2938
cb6fec1f 2939/**
2940 * Efficiently moves a category - NOTE that this can have
2941 * a huge impact access-control-wise...
2942 */
90ee78e2 2943function move_category($category, $newparentcat) {
cb6fec1f 2944 global $CFG, $DB;
19f601d1 2945
9a5e297b 2946 $context = context_coursecat::instance($category->id);
1f41940f 2947
df997f84 2948 $hidecat = false;
1f41940f 2949 if (empty($newparentcat->id)) {
90ee78e2 2950 $DB->set_field('course_categories', 'parent', 0, array('id'=>$category->id));
0cbe8111 2951
9a5e297b 2952 $newparent = context_system::instance();
0cbe8111 2953
1f41940f 2954 } else {
90ee78e2 2955 $DB->set_field('course_categories', 'parent', $newparentcat->id, array('id'=>$category->id));
9a5e297b 2956 $newparent = context_coursecat::instance($newparentcat->id);
df997f84
PS
2957
2958 if (!$newparentcat->visible and $category->visible) {
2959 // better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children will be restored properly
2960 $hidecat = true;
2961 }
19f601d1 2962 }
2963
19f601d1 2964 context_moved($context, $newparent);
2965
3440ec12 2966 // now make it last in new category
0cbe8111 2967 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('id'=>$category->id));
2968
2969 // and fix the sortorders
19f601d1 2970 fix_course_sortorder();
df997f84
PS
2971
2972 if ($hidecat) {
2973 course_category_hide($category);
2974 }
19f601d1 2975}
2976
ae628043 2977/**
ee7084e9 2978 * Returns the display name of the given section that the course prefers
7487c856 2979 *
ee7084e9
MG
2980 * Implementation of this function is provided by course format
2981 * @see format_base::get_section_name()
7487c856 2982 *
ee7084e9
MG
2983 * @param int|stdClass $courseorid The course to get the section name for (object or just course id)
2984 * @param int|stdClass $section Section object from database or just field course_sections.section
2985 * @return string Display name that the course format prefers, e.g. "Week 2"
ae628043 2986 */
ee7084e9
MG
2987function get_section_name($courseorid, $section) {
2988 return course_get_format($courseorid)->get_section_name($section);
7487c856
SH
2989}
2990
2991/**
ee7084e9 2992 * Tells if current course format uses sections
1b048629 2993 *
7487c856 2994 * @param string $format Course format ID e.g. 'weeks' $course->format
ee7084e9 2995 * @return bool
7487c856 2996 */
7487c856 2997function course_format_uses_sections($format) {
ee7084e9
MG
2998 $course = new stdClass();
2999 $course->format = $format;
3000 return course_get_format($course)->uses_sections();
ae628043 3001}
3002
c0b5d925
DM
3003/**
3004 * Returns the information about the ajax support in the given source format
3005 *
3006 * The returned object's property (boolean)capable indicates that
3007 * the course format supports Moodle course ajax features.
3008 * The property (array)testedbrowsers can be used as a parameter for {@see ajaxenabled()}.
3009 *
3010 * @param string $format
3011 * @return stdClass
3012 */
3013function course_format_ajax_support($format) {
ee7084e9
MG
3014 $course = new stdClass();
3015 $course->format = $format;
3016 return course_get_format($course)->supports_ajax();
c0b5d925
DM
3017}
3018
2585a68d 3019/**
3020 * Can the current user delete this course?
8b449a39 3021 * Course creators have exception,
3022 * 1 day after the creation they can sill delete the course.
2585a68d 3023 * @param int $courseid
3024 * @return boolean
2585a68d 3025 */
3026function can_delete_course($courseid) {
8b449a39 3027 global $USER, $DB;
2585a68d 3028
9a5e297b 3029 $context = context_course::instance($courseid);
2585a68d 3030
8b449a39 3031 if (has_capability('moodle/course:delete', $context)) {
3032 return true;
3033 }
3034
3035 // hack: now try to find out if creator created this course recently (1 day)
3036 if (!has_capability('moodle/course:create', $context)) {
3037 return false;
3038 }
3039
3040 $since = time() - 60*60*24;
3041
3042 $params = array('userid'=>$USER->id, 'url'=>"view.php?id=$courseid", 'since'=>$since);
3043 $select = "module = 'course' AND action = 'new' AND userid = :userid AND url = :url AND time > :since";
3044
3045 return $DB->record_exists_select('log', $select, $params);
2585a68d 3046}
3047
bef12c99 3048/**
3049 * Save the Your name for 'Some role' strings.
3050 *
3051 * @param integer $courseid the id of this course.
3052 * @param array $data the data that came from the course settings form.
3053 */
3054function save_local_role_names($courseid, $data) {
3055 global $DB;
9a5e297b 3056 $context = context_course::instance($courseid);
bef12c99 3057
3058 foreach ($data as $fieldname => $value) {
df997f84 3059 if (strpos($fieldname, 'role_') !== 0) {
bef12c99 3060 continue;
3061 }
3062 list($ignored, $roleid) = explode('_', $fieldname);
3063
3064 // make up our mind whether we want to delete, update or insert
3065 if (!$value) {
3066 $DB->delete_records('role_names', array('contextid' => $context->id, 'roleid' => $roleid));
3067
3068 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id, 'roleid' => $roleid))) {
3069 $rolename->name = $value;
3070 $DB->update_record('role_names', $rolename);
3071
3072 } else {
3073 $rolename = new stdClass;
3074 $rolename->contextid = $context->id;
3075 $rolename->roleid = $roleid;
3076 $rolename->name = $value;
3077 $DB->insert_record('role_names', $rolename);
3078 }
3079 }
3080}
2585a68d 3081
c3df0901 3082/**
df997f84
PS
3083 * Create a course and either return a $course object
3084 *
3085 * Please note this functions does not verify any access control,
3086 * the calling code is responsible for all validation (usually it is the form definition).
bfefa87e 3087 *
df997f84 3088 * @param array $editoroptions course description editor options
bfefa87e 3089 * @param object $data - all the data needed for an entry in the 'course' table
df997f84 3090 * @return object new course instance
bfefa87e 3091 */
df997f84
PS
3092function create_course($data, $editoroptions = NULL) {
3093 global $CFG, $DB;
bfefa87e 3094
df997f84
PS
3095 //check the categoryid - must be given for all new courses
3096 $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
71b77297 3097
3098 //check if the shortname already exist
df997f84
PS
3099 if (!empty($data->shortname)) {
3100 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
71b77297 3101 throw new moodle_exception('shortnametaken');
3102 }
3103 }
3104
3105 //check if the id number already exist
df997f84
PS
3106 if (!empty($data->idnumber)) {
3107 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
71b77297 3108 throw new moodle_exception('idnumbertaken');
3109 }
3110 }
2f48819b 3111
df997f84
PS
3112 $data->timecreated = time();
3113 $data->timemodified = $data->timecreated;
71b77297 3114
df997f84
PS
3115 // place at beginning of any category
3116 $data->sortorder = 0;
00f270bc 3117
df997f84
PS
3118 if ($editoroptions) {
3119 // summary text is updated later, we need context to store the files first
3120 $data->summary = '';
3121 $data->summary_format = FORMAT_HTML;
3122 }
3123
db1218a9
PS
3124 if (!isset($data->visible)) {
3125 // data not from form, add missing visibility info
54a01598 3126 $data->visible = $category->visible;
bfefa87e 3127 }
db1218a9 3128 $data->visibleold = $data->visible;
2585a68d 3129
df997f84 3130 $newcourseid = $DB->insert_record('course', $data);
9a5e297b 3131 $context = context_course::instance($newcourseid, MUST_EXIST);
bfefa87e 3132
df997f84
PS
3133 if ($editoroptions) {
3134 // Save the files used in the summary editor and store
64f93798 3135 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
df997f84
PS
3136 $DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid));
3137 $DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid));
3138 }
bfefa87e 3139
fc79ede5
MG
3140 // update course format options
3141 course_get_format($newcourseid)->update_course_format_options($data);
3142
3143 $course = course_get_format($newcourseid)->get_course();
bfefa87e 3144
df997f84
PS
3145 // Setup the blocks
3146 blocks_add_default_course_blocks($course);
bfefa87e 3147
4ede27b2
MG
3148 // Create a default section.
3149 course_create_sections_if_missing($course, 0);
bfefa87e 3150
df997f84 3151 fix_course_sortorder();
bfefa87e 3152
df997f84
PS
3153 // new context created - better mark it as dirty
3154 mark_context_dirty($context->path);
bfefa87e 3155
df997f84 3156 // Save any custom role names.
e92c39ca 3157 save_local_role_names($course->id, (array)$data);
bfefa87e