MDL-37085 Substitute function print_section_add_menus() with core_course_renderer...
[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
92890025 850
45e87759 851function print_overview($courses, array $remote_courses=array()) {
7c5286cd 852 global $CFG, $USER, $DB, $OUTPUT;
0d6b9d4f 853
185cfb09 854 $htmlarray = array();
6bb08163 855 if ($modules = $DB->get_records('modules')) {
f8716988 856 foreach ($modules as $mod) {
857 if (file_exists(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php')) {
f461e8ec 858 include_once(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php');
f8716988 859 $fname = $mod->name.'_print_overview';
0d6b9d4f 860 if (function_exists($fname)) {
185cfb09 861 $fname($courses,$htmlarray);
0d6b9d4f 862 }
863 }
864 }
865 }
185cfb09 866 foreach ($courses as $course) {
9a5e297b 867 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
45e87759 868 echo $OUTPUT->box_start('coursebox');
91d284c1 869 $attributes = array('title' => s($fullname));
185cfb09 870 if (empty($course->visible)) {
45e87759 871 $attributes['class'] = 'dimmed';
185cfb09 872 }
45e87759 873 echo $OUTPUT->heading(html_writer::link(
91d284c1 874 new moodle_url('/course/view.php', array('id' => $course->id)), $fullname, $attributes), 3);
185cfb09 875 if (array_key_exists($course->id,$htmlarray)) {
876 foreach ($htmlarray[$course->id] as $modname => $html) {
877 echo $html;
878 }
879 }
e6db3026 880 echo $OUTPUT->box_end();
185cfb09 881 }
45e87759
DM
882
883 if (!empty($remote_courses)) {
884 echo $OUTPUT->heading(get_string('remotecourses', 'mnet'));
885 }
886 foreach ($remote_courses as $course) {
887 echo $OUTPUT->box_start('coursebox');
888 $attributes = array('title' => s($course->fullname));
889 echo $OUTPUT->heading(html_writer::link(
890 new moodle_url('/auth/mnet/jump.php', array('hostid' => $course->hostid, 'wantsurl' => '/course/view.php?id='.$course->remoteid)),
891 format_string($course->shortname),
892 $attributes) . ' (' . format_string($course->hostname) . ')', 3);
893 echo $OUTPUT->box_end();
894 }
0d6b9d4f 895}
896
897
cb6fec1f 898/**
899 * This function trawls through the logs looking for
900 * anything new since the user's last login
901 */
600149be 902function print_recent_activity($course) {
903 // $course is an object
008350b5 904 global $CFG, $USER, $SESSION, $DB, $OUTPUT;
600149be 905
9a5e297b 906 $context = context_course::instance($course->id);
2ac64806 907
dd97c328 908 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
909
910 $timestart = round(time() - COURSE_MAX_RECENT_PERIOD, -2); // better db caching for guests - 100 seconds
0f87cb1d 911
4f0c2d00 912 if (!isguestuser()) {
e2a3a0e7 913 if (!empty($USER->lastcourseaccess[$course->id])) {
914 if ($USER->lastcourseaccess[$course->id] > $timestart) {
915 $timestart = $USER->lastcourseaccess[$course->id];
916 }
9e51847a 917 }
3d891989 918 }
0f87cb1d 919
de785682 920 echo '<div class="activitydate">';
27bf9e20 921 echo get_string('activitysince', '', userdate($timestart));
de785682 922 echo '</div>';
923 echo '<div class="activityhead">';
0f87cb1d 924
de785682 925 echo '<a href="'.$CFG->wwwroot.'/course/recent.php?id='.$course->id.'">'.get_string('recentactivityreport').'</a>';
0f87cb1d 926
5fc835a5 927 echo "</div>\n";
0f87cb1d 928
600149be 929 $content = false;
1b5910c4 930
dd97c328 931/// Firstly, have there been any new enrolments?
932
6c38b7e0 933 $users = get_recent_enrolments($course->id, $timestart);
1b5910c4 934
5fc835a5 935 //Accessibility: new users now appear in an <OL> list.
6c38b7e0 936 if ($users) {
27bf9e20 937 echo '<div class="newusers">';
008350b5 938 echo $OUTPUT->heading(get_string("newusers").':', 3);
dd97c328 939 $content = true;
5fc835a5 940 echo "<ol class=\"list\">\n";
6c38b7e0 941 foreach ($users as $user) {
dd97c328 942 $fullname = fullname($user, $viewfullnames);
943 echo '<li class="name"><a href="'."$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a></li>\n";
600149be 944 }
5fc835a5 945 echo "</ol>\n</div>\n";
600149be 946 }
947
dd97c328 948/// Next, have there been any modifications to the course structure?
949
f20edd52 950 $modinfo = get_fast_modinfo($course);
dd97c328 951
952 $changelist = array();
1b5910c4 953
cb6fec1f 954 $logs = $DB->get_records_select('log', "time > ? AND course = ? AND
955 module = 'course' AND
956 (action = 'add mod' OR action = 'update mod' OR action = 'delete mod')",
957 array($timestart, $course->id), "id ASC");
1b5910c4 958
959 if ($logs) {
dd97c328 960 $actions = array('add mod', 'update mod', 'delete mod');
961 $newgones = array(); // added and later deleted items
1b5910c4 962 foreach ($logs as $key => $log) {
dd97c328 963 if (!in_array($log->action, $actions)) {
964 continue;
965 }
c71f3265 966 $info = explode(' ', $log->info);
c9f6251e 967
0d8b6a69 968 // note: in most cases I replaced hardcoding of label with use of
969 // $cm->has_view() but it was not possible to do this here because
970 // we don't necessarily have the $cm for it
dd97c328 971 if ($info[0] == 'label') { // Labels are ignored in recent activity
c9f6251e 972 continue;
973 }
974
dd97c328 975 if (count($info) != 2) {
976 debugging("Incorrect log entry info: id = ".$log->id, DEBUG_DEVELOPER);
977 continue;
978 }
979
980 $modname = $info[0];
981 $instanceid = $info[1];
982
983 if ($log->action == 'delete mod') {
984 // unfortunately we do not know if the mod was visible
985 if (!array_key_exists($log->info, $newgones)) {
986 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $modname));
987 $changelist[$log->info] = array ('operation' => 'delete', 'text' => $strdeleted);
988 }
989 } else {
990 if (!isset($modinfo->instances[$modname][$instanceid])) {
991 if ($log->action == 'add mod') {
992 // do not display added and later deleted activities
993 $newgones[$log->info] = true;
994 }
995 continue;
996 }
997 $cm = $modinfo->instances[$modname][$instanceid];
998 if (!$cm->uservisible) {
ff96219d 999 continue;
dd97c328 1000 }
1001
1002 if ($log->action == 'add mod') {
1003 $stradded = get_string('added', 'moodle', get_string('modulename', $modname));
1004 $changelist[$log->info] = array('operation' => 'add', 'text' => "$stradded:<br /><a href=\"$CFG->wwwroot/mod/$cm->modname/view.php?id={$cm->id}\">".format_string($cm->name, true)."</a>");
1005
1006 } else if ($log->action == 'update mod' and empty($changelist[$log->info])) {
1007 $strupdated = get_string('updated', 'moodle', get_string('modulename', $modname));
1008 $changelist[$log->info] = array('operation' => 'update', 'text' => "$strupdated:<br /><a href=\"$CFG->wwwroot/mod/$cm->modname/view.php?id={$cm->id}\">".format_string($cm->name, true)."</a>");
600149be 1009 }
ef25340c 1010 }
1011 }
1012 }
1013
9c9f7d77 1014 if (!empty($changelist)) {
008350b5 1015 echo $OUTPUT->heading(get_string("courseupdates").':', 3);
dd97c328 1016 $content = true;
ef25340c 1017 foreach ($changelist as $changeinfo => $change) {
dd97c328 1018 echo '<p class="activity">'.$change['text'].'</p>';
600149be 1019 }
89adb174 1020 }
bf40f9c1 1021
dd97c328 1022/// Now display new things from each module
0fd7da81 1023
dd97c328 1024 $usedmodules = array();
1025 foreach($modinfo->cms as $cm) {
1026 if (isset($usedmodules[$cm->modname])) {
1027 continue;
1028 }
1029 if (!$cm->uservisible) {
1030 continue;
1031 }
1032 $usedmodules[$cm->modname] = $cm->modname;
1033 }
e2a3a0e7 1034
dd97c328 1035 foreach ($usedmodules as $modname) { // Each module gets it's own logs and prints them
1036 if (file_exists($CFG->dirroot.'/mod/'.$modname.'/lib.php')) {
1037 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
1038 $print_recent_activity = $modname.'_print_recent_activity';
296c6ac2 1039 if (function_exists($print_recent_activity)) {
dd97c328 1040 // NOTE: original $isteacher (second parameter below) was replaced with $viewfullnames!
1041 $content = $print_recent_activity($course, $viewfullnames, $timestart) || $content;
600149be 1042 }
296c6ac2 1043 } else {
238c0dd9 1044 debugging("Missing lib.php in lib/{$modname} - please reinstall files or uninstall the module");
600149be 1045 }
1046 }
1047
1048 if (! $content) {
27bf9e20 1049 echo '<p class="message">'.get_string('nothingnew').'</p>';
600149be 1050 }
600149be 1051}
1052
cb6fec1f 1053/**
1054 * For a given course, returns an array of course activity objects
1055 * Each item in the array contains he following properties:
1056 */
d897cae4 1057function get_array_of_activities($courseid) {
d897cae4 1058// cm - course module id
1059// mod - name of the module (eg forum)
1060// section - the number of the section (eg week or topic)
1061// name - the name of the instance
5867bfb5 1062// visible - is the instance visible or not
13534ef7
ML
1063// groupingid - grouping id
1064// groupmembersonly - is this instance visible to group members only
86aa7ccf 1065// extra - contains extra string to include in any link
cb6fec1f 1066 global $CFG, $DB;
82bd6a5e 1067 if(!empty($CFG->enableavailability)) {
1068 require_once($CFG->libdir.'/conditionlib.php');
1069 }
8dddba42 1070
a0c30e1b 1071 $course = $DB->get_record('course', array('id'=>$courseid));
1072
1073 if (empty($course)) {
1074 throw new moodle_exception('courseidnotfound');
1075 }
1076
d897cae4 1077 $mod = array();
1078
a0c30e1b 1079 $rawmods = get_course_mods($courseid);
1080 if (empty($rawmods)) {
dd97c328 1081 return $mod; // always return array
d897cae4 1082 }
1083
5744ea36 1084 if ($sections = $DB->get_records("course_sections", array("course"=>$courseid), "section ASC")) {
d897cae4 1085 foreach ($sections as $section) {
74666583 1086 if (!empty($section->sequence)) {
d897cae4 1087 $sequence = explode(",", $section->sequence);
1088 foreach ($sequence as $seq) {
7af6281f 1089 if (empty($rawmods[$seq])) {
1090 continue;
1091 }
b85b25eb 1092 $mod[$seq] = new stdClass();
dd97c328 1093 $mod[$seq]->id = $rawmods[$seq]->instance;
1094 $mod[$seq]->cm = $rawmods[$seq]->id;
1095 $mod[$seq]->mod = $rawmods[$seq]->modname;
adaeccb6 1096
1097 // Oh dear. Inconsistent names left here for backward compatibility.
dd97c328 1098 $mod[$seq]->section = $section->section;
adaeccb6 1099 $mod[$seq]->sectionid = $rawmods[$seq]->section;
1100
1101 $mod[$seq]->module = $rawmods[$seq]->module;
1102 $mod[$seq]->added = $rawmods[$seq]->added;
1103 $mod[$seq]->score = $rawmods[$seq]->score;
66b250fd 1104 $mod[$seq]->idnumber = $rawmods[$seq]->idnumber;
dd97c328 1105 $mod[$seq]->visible = $rawmods[$seq]->visible;
adaeccb6 1106 $mod[$seq]->visibleold = $rawmods[$seq]->visibleold;
dd97c328 1107 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
1108 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
13534ef7 1109 $mod[$seq]->groupmembersonly = $rawmods[$seq]->groupmembersonly;
82bd6a5e 1110 $mod[$seq]->indent = $rawmods[$seq]->indent;
1111 $mod[$seq]->completion = $rawmods[$seq]->completion;
dd97c328 1112 $mod[$seq]->extra = "";
adaeccb6 1113 $mod[$seq]->completiongradeitemnumber =
1114 $rawmods[$seq]->completiongradeitemnumber;
1115 $mod[$seq]->completionview = $rawmods[$seq]->completionview;
1116 $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected;
1117 $mod[$seq]->availablefrom = $rawmods[$seq]->availablefrom;
1118 $mod[$seq]->availableuntil = $rawmods[$seq]->availableuntil;
1119 $mod[$seq]->showavailability = $rawmods[$seq]->showavailability;
8c40662e 1120 $mod[$seq]->showdescription = $rawmods[$seq]->showdescription;
adaeccb6 1121 if (!empty($CFG->enableavailability)) {
82bd6a5e 1122 condition_info::fill_availability_conditions($rawmods[$seq]);
82bd6a5e 1123 $mod[$seq]->conditionscompletion = $rawmods[$seq]->conditionscompletion;
1124 $mod[$seq]->conditionsgrade = $rawmods[$seq]->conditionsgrade;
76af15bb 1125 $mod[$seq]->conditionsfield = $rawmods[$seq]->conditionsfield;
82bd6a5e 1126 }
8dddba42 1127
1128 $modname = $mod[$seq]->mod;
1129 $functionname = $modname."_get_coursemodule_info";
1130
3a37b3f8 1131 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
1132 continue;
1133 }
1134
8dddba42 1135 include_once("$CFG->dirroot/mod/$modname/lib.php");
1136
b3a89232 1137 if ($hasfunction = function_exists($functionname)) {
9d361034 1138 if ($info = $functionname($rawmods[$seq])) {
9d361034 1139 if (!empty($info->icon)) {
1140 $mod[$seq]->icon = $info->icon;
1141 }
9a9012dc
PS
1142 if (!empty($info->iconcomponent)) {
1143 $mod[$seq]->iconcomponent = $info->iconcomponent;
1144 }
1ea543df 1145 if (!empty($info->name)) {
9a9012dc 1146 $mod[$seq]->name = $info->name;
1ea543df 1147 }
0d8b6a69 1148 if ($info instanceof cached_cm_info) {
1149 // When using cached_cm_info you can include three new fields
1150 // that aren't available for legacy code
1151 if (!empty($info->content)) {
1152 $mod[$seq]->content = $info->content;
1153 }
1154 if (!empty($info->extraclasses)) {
1155 $mod[$seq]->extraclasses = $info->extraclasses;
1156 }
c443a1cd
EL
1157 if (!empty($info->iconurl)) {
1158 $mod[$seq]->iconurl = $info->iconurl;
1159 }
0d8b6a69 1160 if (!empty($info->onclick)) {
1161 $mod[$seq]->onclick = $info->onclick;
1162 }
1163 if (!empty($info->customdata)) {
1164 $mod[$seq]->customdata = $info->customdata;
1165 }
1166 } else {
1167 // When using a stdclass, the (horrible) deprecated ->extra field
1168 // is available for BC
1169 if (!empty($info->extra)) {
1170 $mod[$seq]->extra = $info->extra;
1171 }
1172 }
c9f6251e 1173 }
1174 }
b3a89232 1175 // When there is no modname_get_coursemodule_info function,
1176 // but showdescriptions is enabled, then we use the 'intro'
1177 // and 'introformat' fields in the module table
1178 if (!$hasfunction && $rawmods[$seq]->showdescription) {
1179 if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
1180 array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
1181 // Set content from intro and introformat. Filters are disabled
1182 // because we filter it with format_text at display time
1183 $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
1184 $modvalues, $rawmods[$seq]->id, false);
1185
1186 // To save making another query just below, put name in here
1187 $mod[$seq]->name = $modvalues->name;
1188 }
1189 }
1ea543df 1190 if (!isset($mod[$seq]->name)) {
9a9012dc 1191 $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
1ea543df 1192 }
0d8b6a69 1193
1194 // Minimise the database size by unsetting default options when they are
1195 // 'empty'. This list corresponds to code in the cm_info constructor.
8c40662e 1196 foreach (array('idnumber', 'groupmode', 'groupingid', 'groupmembersonly',
c443a1cd 1197 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
adaeccb6 1198 'icon', 'iconcomponent', 'customdata', 'showavailability', 'availablefrom',
1199 'availableuntil', 'conditionscompletion', 'conditionsgrade',
8c40662e 1200 'completionview', 'completionexpected', 'score', 'showdescription')
1201 as $property) {
0d8b6a69 1202 if (property_exists($mod[$seq], $property) &&
1203 empty($mod[$seq]->{$property})) {
1204 unset($mod[$seq]->{$property});
1205 }
1206 }
adaeccb6 1207 // Special case: this value is usually set to null, but may be 0
1208 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
1209 is_null($mod[$seq]->completiongradeitemnumber)) {
1210 unset($mod[$seq]->completiongradeitemnumber);
1211 }
d897cae4 1212 }
1213 }
1214 }
1215 }
1216 return $mod;
1217}
1218
cb6fec1f 1219/**
d57aa283
MG
1220 * Returns the localised human-readable names of all used modules
1221 *
1222 * @param bool $plural if true returns the plural forms of the names
1223 * @return array where key is the module name (component name without 'mod_') and
1224 * the value is the human-readable string. Array sorted alphabetically by value
cb6fec1f 1225 */
d57aa283
MG
1226function get_module_types_names($plural = false) {
1227 static $modnames = null;
1228 global $DB, $CFG;
1229 if ($modnames === null) {
1230 $modnames = array(0 => array(), 1 => array());
1231 if ($allmods = $DB->get_records("modules")) {
1232 foreach ($allmods as $mod) {
1233 if (file_exists("$CFG->dirroot/mod/$mod->name/lib.php") && $mod->visible) {
1234 $modnames[0][$mod->name] = get_string("modulename", "$mod->name");
1235 $modnames[1][$mod->name] = get_string("modulenameplural", "$mod->name");
1236 }
13534ef7 1237 }
d57aa283
MG
1238 collatorlib::asort($modnames[0]);
1239 collatorlib::asort($modnames[1]);
c7da6f7a 1240 }
7468bf01 1241 }
d57aa283 1242 return $modnames[(int)$plural];
7468bf01 1243}
1244
93d46f48
RK
1245/**
1246 * Set highlighted section. Only one section can be highlighted at the time.
1247 *
1248 * @param int $courseid course id
1249 * @param int $marker highlight section with this number, 0 means remove higlightin
1250 * @return void
1251 */
1252function course_set_marker($courseid, $marker) {
1253 global $DB;
1254 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
a062c97c 1255 format_base::reset_course_cache($courseid);
93d46f48
RK
1256}
1257
cb6fec1f 1258/**
7e85563d 1259 * For a given course section, marks it visible or hidden,
cb6fec1f 1260 * and does the same for every activity in that section
ebaa29d1
ARN
1261 *
1262 * @param int $courseid course id
1263 * @param int $sectionnumber The section number to adjust
1264 * @param int $visibility The new visibility
1265 * @return array A list of resources which were hidden in the section
cb6fec1f 1266 */
7d99d695 1267function set_section_visible($courseid, $sectionnumber, $visibility) {
cb6fec1f 1268 global $DB;
7d99d695 1269
ebaa29d1 1270 $resourcestotoggle = array();
cb6fec1f 1271 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
1272 $DB->set_field("course_sections", "visible", "$visibility", array("id"=>$section->id));
7d99d695 1273 if (!empty($section->sequence)) {
1274 $modules = explode(",", $section->sequence);
1275 foreach ($modules as $moduleid) {
00a34234
FM
1276 if ($cm = $DB->get_record('course_modules', array('id' => $moduleid), 'visible, visibleold')) {
1277 if ($visibility) {
1278 // As we unhide the section, we use the previously saved visibility stored in visibleold.
1279 set_coursemodule_visible($moduleid, $cm->visibleold);
1280 } else {
1281 // We hide the section, so we hide the module but we store the original state in visibleold.
1282 set_coursemodule_visible($moduleid, 0);
1283 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id' => $moduleid));
1284 }
1285 }
7d99d695 1286 }
1287 }
38b19bbc 1288 rebuild_course_cache($courseid, true);
ebaa29d1
ARN
1289
1290 // Determine which modules are visible for AJAX update
1291 if (!empty($modules)) {
1292 list($insql, $params) = $DB->get_in_or_equal($modules);
1293 $select = 'id ' . $insql . ' AND visible = ?';
1294 array_push($params, $visibility);
1295 if (!$visibility) {
1296 $select .= ' AND visibleold = 1';
1297 }
1298 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
1299 }
7d99d695 1300 }
ebaa29d1 1301 return $resourcestotoggle;
7d99d695 1302}
ba2e5d73 1303
0d8b6a69 1304/**
1305 * Obtains shared data that is used in print_section when displaying a
1306 * course-module entry.
1307 *
1308 * Calls format_text or format_string as appropriate, and obtains the correct icon.
1309 *
f89c53f6
MG
1310 * @deprecated since 2.5
1311 *
0d8b6a69 1312 * This data is also used in other areas of the code.
1313 * @param cm_info $cm Course-module data (must come from get_fast_modinfo)
f89c53f6 1314 * @param object $course (argument not used)
0d8b6a69 1315 * @return array An array with the following values in this order:
1316 * $content (optional extra content for after link),
1317 * $instancename (text of link)
1318 */
1319function get_print_section_cm_text(cm_info $cm, $course) {
f89c53f6
MG
1320 return array($cm->get_formatted_content(array('overflowdiv' => true, 'noclean' => true)),
1321 $cm->get_formatted_name());
0d8b6a69 1322}
1323
cb6fec1f 1324/**
1325 * Prints a section full of activity modules
5946d376
FM
1326 *
1327 * @param stdClass $course The course
eda43c7d
MG
1328 * @param stdClass|section_info $section The section object containing properties id and section
1329 * @param array $mods (argument not used)
1330 * @param array $modnamesused (argument not used)
5946d376 1331 * @param bool $absolute All links are absolute
49aa038b 1332 * @param string $width (argument not used)
5946d376 1333 * @param bool $hidecompletion Hide completion status
b8514b6a 1334 * @param int $sectionreturn The section to return to
5946d376 1335 * @return void
cb6fec1f 1336 */
923451c5 1337function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%", $hidecompletion=false, $sectionreturn=null) {
e63f88c9 1338 global $CFG, $USER, $DB, $PAGE, $OUTPUT;
7977cffd 1339
dd97c328 1340 static $initialised;
1341
3d575e6f 1342 static $groupbuttons;
32d03b7b 1343 static $groupbuttonslink;
52dcc2f9 1344 static $isediting;
7977cffd 1345 static $ismoving;
49aa038b 1346 static $movingpix;
7977cffd 1347 static $strmovefull;
54669989 1348 static $strunreadpostsone;
110a32e2 1349
dd97c328 1350 if (!isset($initialised)) {
9fd9c29b 1351 $groupbuttons = ($course->groupmode or (!$course->groupmodeforce));
32d03b7b 1352 $groupbuttonslink = (!$course->groupmodeforce);
830dd6e9 1353 $isediting = $PAGE->user_is_editing();
dd97c328 1354 $ismoving = $isediting && ismoving($course->id);
3d575e6f 1355 if ($ismoving) {
49aa038b 1356 $movingpix = new pix_icon('movehere', get_string('movehere'), 'moodle', array('class' => 'movetarget'));
dd97c328 1357 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
3d575e6f 1358 }
dd97c328 1359 $initialised = true;
7977cffd 1360 }
dd97c328 1361
dd97c328 1362 $modinfo = get_fast_modinfo($course);
984baa77 1363 $completioninfo = new completion_info($course);
f558b291 1364 $courserenderer = $PAGE->get_renderer('core', 'course');
94361e02 1365
49aa038b
MG
1366 // Get the list of modules visible to user (excluding the module being moved if there is one)
1367 $moduleslist = array();
eda43c7d 1368 if (!empty($modinfo->sections[$section->section])) {
eda43c7d
MG
1369 foreach ($modinfo->sections[$section->section] as $modnumber) {
1370 $mod = $modinfo->cms[$modnumber];
c9f6251e 1371
dd97c328 1372 if ($ismoving and $mod->id == $USER->activitycopy) {
1373 // do not display moving mod
1374 continue;
1375 }
eda43c7d
MG
1376 // We can continue (because it will not be displayed at all)
1377 // if:
1378 // 1) The activity is not visible to users
1379 // and
1380 // 2a) The 'showavailability' option is not set (if that is set,
1381 // we need to display the activity so we can show
1382 // availability info)
1383 // or
1384 // 2b) The 'availableinfo' is empty, i.e. the activity was
1385 // hidden in a way that leaves no info, such as using the
1386 // eye icon.
1387 if (!$mod->uservisible &&
1388 (empty($mod->showavailability) ||
1389 empty($mod->availableinfo))) {
1390 // visibility shortcut
1391 continue;
0d8b6a69 1392 }
0d8b6a69 1393
49aa038b
MG
1394 $moduleslist[$modnumber] = $mod;
1395 }
1396 }
1397
1398 if (!empty($moduleslist) || $ismoving) {
1399
1400 echo html_writer::start_tag('ul', array('class' => 'section img-text'));
1401
1402 foreach ($moduleslist as $modnumber => $mod) {
1403
2f48819b 1404 // In some cases the activity is visible to user, but it is
e8e50986 1405 // dimmed. This is done if viewhiddenactivities is true and if:
1406 // 1. the activity is not visible, or
1407 // 2. the activity has dates set which do not include current, or
1408 // 3. the activity has any other conditions set (regardless of whether
1409 // current user meets them)
110f73ad 1410 $modcontext = context_module::instance($mod->id);
1411 $canviewhidden = has_capability('moodle/course:viewhiddenactivities', $modcontext);
49aa038b 1412 $accessiblebutdim = !$mod->uservisible;
64020473 1413 $conditionalhidden = false;
49aa038b 1414 if (!$accessiblebutdim && $canviewhidden) {
e8e50986 1415 $accessiblebutdim = !$mod->visible;
1416 if (!empty($CFG->enableavailability)) {
64020473 1417 $conditionalhidden = $mod->availablefrom > time() ||
e8e50986 1418 ($mod->availableuntil && $mod->availableuntil < time()) ||
2f48819b 1419 count($mod->conditionsgrade) > 0 ||
e8e50986 1420 count($mod->conditionscompletion) > 0;
1421 }
64020473 1422 $accessiblebutdim = $conditionalhidden || $accessiblebutdim;
e8e50986 1423 }
1424
49aa038b 1425 $modclasses = 'activity '. $mod->modname. 'modtype_'.$mod->modname. ' '. $mod->get_extra_classes();
dd97c328 1426 if ($ismoving) {
49aa038b
MG
1427 $movingurl = new moodle_url('/course/mod.php', array('moveto' => $mod->id, 'sesskey' => sesskey()));
1428 echo html_writer::tag('li', html_writer::link($movingurl, $OUTPUT->render($movingpix)), array('class' => 'movehere'));
dd97c328 1429 }
9d361034 1430
49aa038b
MG
1431 echo html_writer::start_tag('li', array('class' => $modclasses, 'id' => 'module-'. $modnumber));
1432 $indentclasses = 'mod-indent';
060cd0c8 1433 if (!empty($mod->indent)) {
49aa038b 1434 $indentclasses .= ' mod-indent-'.$mod->indent;
060cd0c8 1435 if ($mod->indent > 15) {
49aa038b 1436 $indentclasses .= ' mod-indent-huge';
060cd0c8 1437 }
dd97c328 1438 }
49aa038b 1439 echo html_writer::start_tag('div', array('class' => $indentclasses));
dd97c328 1440
0d8b6a69 1441 // Get data about this course-module
f89c53f6
MG
1442 $content = $mod->get_formatted_content(array('overflowdiv' => true, 'noclean' => true));
1443 $instancename = $mod->get_formatted_name();
0d8b6a69 1444
1445 //Accessibility: for files get description via icon, this is very ugly hack!
1446 $altname = '';
1447 $altname = $mod->modfullname;
0d8b6a69 1448 // Avoid unnecessary duplication: if e.g. a forum name already
1449 // includes the word forum (or Forum, etc) then it is unhelpful
1450 // to include that in the accessible description that is added.
f8311def
PS
1451 if (false !== strpos(textlib::strtolower($instancename),
1452 textlib::strtolower($altname))) {
0d8b6a69 1453 $altname = '';
1454 }
1455 // File type after name, for alphabetic lists (screen reader).
1456 if ($altname) {
1457 $altname = get_accesshide(' '.$altname);
554606c7 1458 }
dd97c328 1459
e40bd746
FM
1460 // Start the div for the activity title, excluding the edit icons.
1461 echo html_writer::start_tag('div', array('class' => 'activityinstance'));
1462
0d8b6a69 1463 // We may be displaying this just in order to show information
49aa038b 1464 // about visibility, without the actual link ($mod->uservisible)
0d8b6a69 1465 $contentpart = '';
0d8b6a69 1466 $linkclasses = '';
1467 $textclasses = '';
49aa038b 1468 $accesstext = '';
0d8b6a69 1469 if ($accessiblebutdim) {
64020473
RT
1470 $linkclasses .= ' dimmed';
1471 $textclasses .= ' dimmed_text';
1472 if ($conditionalhidden) {
1473 $linkclasses .= ' conditionalhidden';
1474 $textclasses .= ' conditionalhidden';
1475 }
49aa038b
MG
1476 if ($mod->uservisible) {
1477 // show accessibility note only if user can access the module himself
1478 $accesstext = get_accesshide(get_string('hiddenfromstudents').': ');
1479 }
c4d989a1 1480 }
aac94fd0 1481
e5ad278a
RT
1482 // Get on-click attribute value if specified and decode the onclick - it
1483 // has already been encoded for display (puke).
1484 $onclick = htmlspecialchars_decode($mod->get_on_click(), ENT_QUOTES);
e40bd746
FM
1485
1486 $groupinglabel = '';
1487 if (!empty($mod->groupingid) && has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
1488 $groupings = groups_get_all_groupings($course->id);
1489 $groupinglabel = html_writer::tag('span', '('.format_string($groupings[$mod->groupingid]->name).')',
49aa038b 1490 array('class' => 'groupinglabel '.$textclasses));
0d8b6a69 1491 }
c9f6251e 1492
0d8b6a69 1493 if ($url = $mod->get_url()) {
e40bd746
FM
1494 // Display link itself.
1495 $activitylink = html_writer::empty_tag('img', array('src' => $mod->get_icon_url(),
1496 'class' => 'iconlarge activityicon', 'alt' => $mod->modfullname)) . $accesstext .
1497 html_writer::tag('span', $instancename . $altname, array('class' => 'instancename'));
49aa038b
MG
1498 if ($mod->uservisible) {
1499 echo html_writer::link($url, $activitylink, array('class' => $linkclasses, 'onclick' => $onclick)) .
1500 $groupinglabel;
1501 } else {
1502 echo html_writer::tag('div', $activitylink, array('class' => $textclasses)) .
1503 $groupinglabel;
1504 }
e40bd746
FM
1505
1506 // If specified, display extra content after link.
0d8b6a69 1507 if ($content) {
e40bd746
FM
1508 $contentpart = html_writer::tag('div', $content, array('class' =>
1509 trim('contentafterlink ' . $textclasses)));
c93dae38 1510 }
dd97c328 1511 } else {
e40bd746 1512 // No link, so display only content.
49aa038b 1513 $contentpart = html_writer::tag('div', $accesstext . $content, array('class' => $textclasses));
f37da850 1514 }
1515
0d8b6a69 1516 // Module can put text after the link (e.g. forum unread)
1517 echo $mod->get_after_link();
1518
e40bd746
FM
1519 // Closing the tag which contains everything but edit icons. $contentpart should not be part of this.
1520 echo html_writer::end_tag('div');
1521
611684a8 1522 // If there is content but NO link (eg label), then display the
1523 // content here (BEFORE any icons). In this case cons must be
1524 // displayed after the content so that it makes more sense visually
1525 // and for accessibility reasons, e.g. if you have a one-line label
1526 // it should work similarly (at least in terms of ordering) to an
1527 // activity.
1528 if (empty($url)) {
1529 echo $contentpart;
1530 }
1531
dd97c328 1532 if ($isediting) {
525e16ce 1533 if ($groupbuttons and plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
dd97c328 1534 if (! $mod->groupmodelink = $groupbuttonslink) {
1535 $mod->groupmode = $course->groupmode;
3d575e6f 1536 }
dd97c328 1537
1538 } else {
1539 $mod->groupmode = false;
c9f6251e 1540 }
b8514b6a 1541 echo make_editing_buttons($mod, $absolute, true, $mod->indent, $sectionreturn);
0d8b6a69 1542 echo $mod->get_after_edit_icons();
94361e02 1543 }
4e781c7b 1544
1545 // Completion
3982f0f8 1546 $completion = $hidecompletion
4e781c7b 1547 ? COMPLETION_TRACKING_NONE
1548 : $completioninfo->is_enabled($mod);
2f48819b 1549 if ($completion!=COMPLETION_TRACKING_NONE && isloggedin() &&
82bd6a5e 1550 !isguestuser() && $mod->uservisible) {
3982f0f8 1551 $completiondata = $completioninfo->get_data($mod,true);
1552 $completionicon = '';
1553 if ($isediting) {
1554 switch ($completion) {
ca255392 1555 case COMPLETION_TRACKING_MANUAL :
3982f0f8 1556 $completionicon = 'manual-enabled'; break;
ca255392 1557 case COMPLETION_TRACKING_AUTOMATIC :
3982f0f8 1558 $completionicon = 'auto-enabled'; break;
4e781c7b 1559 default: // wtf
1560 }
3982f0f8 1561 } else if ($completion==COMPLETION_TRACKING_MANUAL) {
4e781c7b 1562 switch($completiondata->completionstate) {
1563 case COMPLETION_INCOMPLETE:
3982f0f8 1564 $completionicon = 'manual-n'; break;
4e781c7b 1565 case COMPLETION_COMPLETE:
3982f0f8 1566 $completionicon = 'manual-y'; break;
4e781c7b 1567 }
1568 } else { // Automatic
1569 switch($completiondata->completionstate) {
1570 case COMPLETION_INCOMPLETE:
3982f0f8 1571 $completionicon = 'auto-n'; break;
4e781c7b 1572 case COMPLETION_COMPLETE:
3982f0f8 1573 $completionicon = 'auto-y'; break;
4e781c7b 1574 case COMPLETION_COMPLETE_PASS:
3982f0f8 1575 $completionicon = 'auto-pass'; break;
4e781c7b 1576 case COMPLETION_COMPLETE_FAIL:
3982f0f8 1577 $completionicon = 'auto-fail'; break;
4e781c7b 1578 }
1579 }
3982f0f8 1580 if ($completionicon) {
b5d0cafc 1581 $imgsrc = $OUTPUT->pix_url('i/completion-'.$completionicon);
110f73ad 1582 $formattedname = format_string($mod->name, true, array('context' => $modcontext));
1583 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $formattedname);
76c0123b 1584 if ($completion == COMPLETION_TRACKING_MANUAL && !$isediting) {
110f73ad 1585 $imgtitle = get_string('completion-title-' . $completionicon, 'completion', $formattedname);
3982f0f8 1586 $newstate =
4e781c7b 1587 $completiondata->completionstate==COMPLETION_COMPLETE
ca255392 1588 ? COMPLETION_INCOMPLETE
1589 : COMPLETION_COMPLETE;
a343b13f 1590 // In manual mode the icon is a toggle form...
1591
1592 // If this completion state is used by the
1593 // conditional activities system, we need to turn
1594 // off the JS.
2f48819b 1595 if (!empty($CFG->enableavailability) &&
76c0123b 1596 condition_info::completion_value_used_as_condition($course, $mod)) {
a343b13f 1597 $extraclass = ' preventjs';
1598 } else {
1599 $extraclass = '';
1600 }
da6076f1 1601 echo html_writer::start_tag('form', array(
1602 'class' => 'togglecompletion' . $extraclass,
1603 'method' => 'post',
1604 'action' => $CFG->wwwroot . '/course/togglecompletion.php'));
1605 echo html_writer::start_tag('div');
1606 echo html_writer::empty_tag('input', array(
1607 'type' => 'hidden', 'name' => 'id', 'value' => $mod->id));
1608 echo html_writer::empty_tag('input', array(
1609 'type' => 'hidden', 'name' => 'modulename',
1610 'value' => $mod->name));
1611 echo html_writer::empty_tag('input', array(
1612 'type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey()));
1613 echo html_writer::empty_tag('input', array(
1614 'type' => 'hidden', 'name' => 'completionstate',
1615 'value' => $newstate));
1616 echo html_writer::empty_tag('input', array(
1617 'type' => 'image', 'src' => $imgsrc, 'alt' => $imgalt, 'title' => $imgtitle));
1618 echo html_writer::end_tag('div');
1619 echo html_writer::end_tag('form');
4e781c7b 1620 } else {
1621 // In auto mode, or when editing, the icon is just an image
f17a0360 1622 echo "<span class='autocompletion'>";
f17a0360 1623 echo "<img src='$imgsrc' alt='$imgalt' title='$imgalt' /></span>";
4e781c7b 1624 }
1625 }
1626 }
1627
611684a8 1628 // If there is content AND a link, then display the content here
1629 // (AFTER any icons). Otherwise it was displayed before
1630 if (!empty($url)) {
1631 echo $contentpart;
1632 }
0d8b6a69 1633
2f48819b 1634 // Show availability information (for someone who isn't allowed to
82bd6a5e 1635 // see the activity itself, or for staff)
3982f0f8 1636 if (!$mod->uservisible) {
82bd6a5e 1637 echo '<div class="availabilityinfo">'.$mod->availableinfo.'</div>';
57bda785 1638 } else if ($canviewhidden && !empty($CFG->enableavailability)) {
588b94ac
RT
1639 // Don't add availability information if user is not editing and activity is hidden.
1640 if ($mod->visible || $PAGE->user_is_editing()) {
1641 $hidinfoclass = '';
1642 if (!$mod->visible) {
1643 $hidinfoclass = 'hide';
1644 }
1645 $ci = new condition_info($mod);
1646 $fullinfo = $ci->get_full_information();
1647 if($fullinfo) {
1648 echo '<div class="availabilityinfo '.$hidinfoclass.'">'.get_string($mod->showavailability
1649 ? 'userrestriction_visible'
1650 : 'userrestriction_hidden','condition',
1651 $fullinfo).'</div>';
1652 }
82bd6a5e 1653 }
1654 }
1655
060cd0c8
SH
1656 echo html_writer::end_tag('div');
1657 echo html_writer::end_tag('li')."\n";
94361e02 1658 }
dd97c328 1659
49aa038b
MG
1660 if ($ismoving) {
1661 $movingurl = new moodle_url('/course/mod.php', array('movetosection' => $section->id, 'sesskey' => sesskey()));
1662 echo html_writer::tag('li', html_writer::link($movingurl, $OUTPUT->render($movingpix)), array('class' => 'movehere'));
1663 }
dd97c328 1664
49aa038b 1665 echo html_writer::end_tag('ul'); // .section
c6a55371 1666 }
a7ad3ea6 1667}
1668
89bfeee0 1669/**
1670 * Prints the menus to add activities and resources.
5946d376 1671 *
9a6aa5c1
MG
1672 * @deprecated since 2.5
1673 *
1674 * @param stdClass $course course object, must be the same as set on the page
923451c5 1675 * @param int $section relative section number (field course_sections.section)
9a6aa5c1 1676 * @param null|array $modnames (argument ignored) get_module_types_names() is used instead of argument
5946d376
FM
1677 * @param bool $vertical Vertical orientation
1678 * @param bool $return Return the menus or send them to output
b8514b6a 1679 * @param int $sectionreturn The section to link back to
5946d376 1680 * @return void|string depending on $return
89bfeee0 1681 */
d57aa283 1682function print_section_add_menus($course, $section, $modnames = null, $vertical=false, $return=false, $sectionreturn=null) {
9a6aa5c1
MG
1683 global $PAGE;
1684 $output = '';
1685 $courserenderer = $PAGE->get_renderer('core', 'course');
1686 $output = $courserenderer->course_section_add_cm_control($course, $section, $sectionreturn,
1687 array('inblock' => $vertical));
cb57e6f4 1688 if ($return) {
1689 return $output;
1690 } else {
1691 echo $output;
9a6aa5c1 1692 return !empty($output);
cb57e6f4 1693 }
e0161bff 1694}
1695
59155a3f
ARN
1696/**
1697 * Retrieve all metadata for the requested modules
1698 *
1699 * @param object $course The Course
1700 * @param array $modnames An array containing the list of modules and their
1701 * names
a41b1d96 1702 * @param int $sectionreturn The section to return to
59155a3f
ARN
1703 * @return array A list of stdClass objects containing metadata about each
1704 * module
1705 */
923451c5 1706function get_module_metadata($course, $modnames, $sectionreturn = null) {
59155a3f
ARN
1707 global $CFG, $OUTPUT;
1708
1709 // get_module_metadata will be called once per section on the page and courses may show
1710 // different modules to one another
1711 static $modlist = array();
1712 if (!isset($modlist[$course->id])) {
1713 $modlist[$course->id] = array();
1714 }
1715
1716 $return = array();
17079335
MG
1717 $urlbase = new moodle_url('/course/mod.php', array('id' => $course->id, 'sesskey' => sesskey()));
1718 if ($sectionreturn !== null) {
1719 $urlbase->param('sr', $sectionreturn);
1720 }
59155a3f
ARN
1721 foreach($modnames as $modname => $modnamestr) {
1722 if (!course_allowed_module($course, $modname)) {
1723 continue;
1724 }
ad47d025 1725 if (isset($modlist[$course->id][$modname])) {
59155a3f
ARN
1726 // This module is already cached
1727 $return[$modname] = $modlist[$course->id][$modname];
1728 continue;
1729 }
1730
1731 // Include the module lib
1732 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1733 if (!file_exists($libfile)) {
1734 continue;
1735 }
1736 include_once($libfile);
1737
1738 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1739 $gettypesfunc = $modname.'_get_types';
1740 if (function_exists($gettypesfunc)) {
1741 if ($types = $gettypesfunc()) {
1742 $group = new stdClass();
1743 $group->name = $modname;
1744 $group->icon = $OUTPUT->pix_icon('icon', '', $modname, array('class' => 'icon'));
1745 foreach($types as $type) {
1746 if ($type->typestr === '--') {
1747 continue;
1748 }
1749 if (strpos($type->typestr, '--') === 0) {
1750 $group->title = str_replace('--', '', $type->typestr);
1751 continue;
1752 }
1753 // Set the Sub Type metadata
1754 $subtype = new stdClass();
1755 $subtype->title = $type->typestr;
1756 $subtype->type = str_replace('&amp;', '&', $type->type);
1757 $subtype->name = preg_replace('/.*type=/', '', $subtype->type);
1758 $subtype->archetype = $type->modclass;
1759
1760 // The group archetype should match the subtype archetypes and all subtypes
1761 // should have the same archetype
1762 $group->archetype = $subtype->archetype;
1763
1764 if (get_string_manager()->string_exists('help' . $subtype->name, $modname)) {
1765 $subtype->help = get_string('help' . $subtype->name, $modname);
1766 }
17079335 1767 $subtype->link = new moodle_url($urlbase, array('add' => $subtype->type));
59155a3f
ARN
1768 $group->types[] = $subtype;
1769 }
1770 $modlist[$course->id][$modname] = $group;
1771 }
1772 } else {
1773 $module = new stdClass();
17079335 1774 $module->title = $modnamestr;
59155a3f 1775 $module->name = $modname;
17079335 1776 $module->link = new moodle_url($urlbase, array('add' => $modname));
59155a3f 1777 $module->icon = $OUTPUT->pix_icon('icon', '', $module->name, array('class' => 'icon'));
01e0e704
ARN
1778 $sm = get_string_manager();
1779 if ($sm->string_exists('modulename_help', $modname)) {
59155a3f 1780 $module->help = get_string('modulename_help', $modname);
01e0e704
ARN
1781 if ($sm->string_exists('modulename_link', $modname)) { // Link to further info in Moodle docs
1782 $link = get_string('modulename_link', $modname);
1783 $linktext = get_string('morehelp');
afe3566c 1784 $module->help .= html_writer::tag('div', $OUTPUT->doc_link($link, $linktext, true), array('class' => 'helpdoclink'));
01e0e704 1785 }
59155a3f
ARN
1786 }
1787 $module->archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1788 $modlist[$course->id][$modname] = $module;
1789 }
1790 $return[$modname] = $modlist[$course->id][$modname];
1791 }
1792
1793 return $return;
1794}
1795
8ed5dd63 1796/**
1797 * Return the course category context for the category with id $categoryid, except
1798 * that if $categoryid is 0, return the system context.
1799 *
1800 * @param integer $categoryid a category id or 0.
1801 * @return object the corresponding context
1802 */
1803function get_category_or_system_context($categoryid) {
1804 if ($categoryid) {
4658aec5 1805 return context_coursecat::instance($categoryid, IGNORE_MISSING);
8ed5dd63 1806 } else {
9a5e297b 1807 return context_system::instance();
8ed5dd63 1808 }
1809}
1810
cb6fec1f 1811/**
7e85563d 1812 * Gets the child categories of a given courses category. Uses a static cache
8ed5dd63 1813 * to make repeat calls efficient.
1814 *
e92c39ca 1815 * @param int $parentid the id of a course category.
8ed5dd63 1816 * @return array all the child course categories.
cb6fec1f 1817 */
8ed5dd63 1818function get_child_categories($parentid) {
9bb19e58 1819 static $allcategories = null;
1820
1821 // only fill in this variable the first time
1822 if (null == $allcategories) {
1823 $allcategories = array();
1824
1825 $categories = get_categories();
1826 foreach ($categories as $category) {
1827 if (empty($allcategories[$category->parent])) {
1828 $allcategories[$category->parent] = array();
1829 }
1830 $allcategories[$category->parent][] = $category;
1831 }
1832 }
1833
8ed5dd63 1834 if (empty($allcategories[$parentid])) {
9bb19e58 1835 return array();
1836 } else {
8ed5dd63 1837 return $allcategories[$parentid];
9bb19e58 1838 }
1839}
1840
cb6fec1f 1841/**
8ed5dd63 1842 * This function recursively travels the categories, building up a nice list
1843 * for display. It also makes an array that list all the parents for each
1844 * category.
1845 *
1846 * For example, if you have a tree of categories like:
1847 * Miscellaneous (id = 1)
1848 * Subcategory (id = 2)
1849 * Sub-subcategory (id = 4)
1850 * Other category (id = 3)
1851 * Then after calling this function you will have
1852 * $list = array(1 => 'Miscellaneous', 2 => 'Miscellaneous / Subcategory',
1853 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
1854 * 3 => 'Other category');
1855 * $parents = array(2 => array(1), 4 => array(1, 2));
1856 *
1857 * If you specify $requiredcapability, then only categories where the current
1858 * user has that capability will be added to $list, although all categories
1859 * will still be added to $parents, and if you only have $requiredcapability
1860 * in a child category, not the parent, then the child catgegory will still be
1861 * included.
1862 *
1863 * If you specify the option $excluded, then that category, and all its children,
1864 * are omitted from the tree. This is useful when you are doing something like
1865 * moving categories, where you do not want to allow people to move a category
1866 * to be the child of itself.
1867 *
1868 * @param array $list For output, accumulates an array categoryid => full category path name
1869 * @param array $parents For output, accumulates an array categoryid => list of parent category ids.
8a1b1c32 1870 * @param string/array $requiredcapability if given, only categories where the current
1871 * user has this capability will be added to $list. Can also be an array of capabilities,
1872 * in which case they are all required.
8ed5dd63 1873 * @param integer $excludeid Omit this category and its children from the lists built.
1874 * @param object $category Build the tree starting at this category - otherwise starts at the top level.
1875 * @param string $path For internal use, as part of recursive calls.
cb6fec1f 1876 */
8ed5dd63 1877function make_categories_list(&$list, &$parents, $requiredcapability = '',
1878 $excludeid = 0, $category = NULL, $path = "") {
1879
9d866ae0 1880 // initialize the arrays if needed
1881 if (!is_array($list)) {
264867fd 1882 $list = array();
9d866ae0 1883 }
1884 if (!is_array($parents)) {
264867fd 1885 $parents = array();
9d866ae0 1886 }
1887
8ed5dd63 1888 if (empty($category)) {
1889 // Start at the top level.
1890 $category = new stdClass;
1891 $category->id = 0;
1892 } else {
1893 // This is the excluded category, don't include it.
1894 if ($excludeid > 0 && $excludeid == $category->id) {
1895 return;
1896 }
1897
9a5e297b 1898 $context = context_coursecat::instance($category->id);
63390481
SH
1899 $categoryname = format_string($category->name, true, array('context' => $context));
1900
8ed5dd63 1901 // Update $path.
c2cb4545 1902 if ($path) {
63390481 1903 $path = $path.' / '.$categoryname;
c2cb4545 1904 } else {
63390481 1905 $path = $categoryname;
c2cb4545 1906 }
8ed5dd63 1907
1908 // Add this category to $list, if the permissions check out.
3ce50127 1909 if (empty($requiredcapability)) {
8ed5dd63 1910 $list[$category->id] = $path;
3ce50127 1911
1912 } else {
3ce50127 1913 $requiredcapability = (array)$requiredcapability;
63390481 1914 if (has_all_capabilities($requiredcapability, $context)) {
3ce50127 1915 $list[$category->id] = $path;
1916 }
8ed5dd63 1917 }
c2cb4545 1918 }
1919
8ed5dd63 1920 // Add all the children recursively, while updating the parents array.
1921 if ($categories = get_child_categories($category->id)) {
c2cb4545 1922 foreach ($categories as $cat) {
1923 if (!empty($category->id)) {
3bd4de22 1924 if (isset($parents[$category->id])) {
2832badf 1925 $parents[$cat->id] = $parents[$category->id];
1926 }
c2cb4545 1927 $parents[$cat->id][] = $category->id;
1928 }
8ed5dd63 1929 make_categories_list($list, $parents, $requiredcapability, $excludeid, $cat, $path);
c2cb4545 1930 }
1931 }
1932}
1933
24e27ac0
SH
1934/**
1935 * This function generates a structured array of courses and categories.
1936 *
1937 * The depth of categories is limited by $CFG->maxcategorydepth however there
1938 * is no limit on the number of courses!
1939 *
1940 * Suitable for use with the course renderers course_category_tree method:
1941 * $renderer = $PAGE->get_renderer('core','course');
1942 * echo $renderer->course_category_tree(get_course_category_tree());
1943 *
1944 * @global moodle_database $DB
1945 * @param int $id
1946 * @param int $depth
1947 */
1948function get_course_category_tree($id = 0, $depth = 0) {
cf41dc37 1949 global $DB, $CFG;
9a5e297b 1950 $viewhiddencats = has_capability('moodle/category:viewhiddencategories', context_system::instance());
24e27ac0
SH
1951 $categories = get_child_categories($id);
1952 $categoryids = array();
1953 foreach ($categories as $key => &$category) {
1954 if (!$category->visible && !$viewhiddencats) {
1955 unset($categories[$key]);
1956 continue;
1957 }
1958 $categoryids[$category->id] = $category;
1959 if (empty($CFG->maxcategorydepth) || $depth <= $CFG->maxcategorydepth) {
1960 list($category->categories, $subcategories) = get_course_category_tree($category->id, $depth+1);
3ebc548f
SH
1961 foreach ($subcategories as $subid=>$subcat) {
1962 $categoryids[$subid] = $subcat;
1963 }
24e27ac0
SH
1964 $category->courses = array();
1965 }
1966 }
1967
1968 if ($depth > 0) {
1969 // This is a recursive call so return the required array
1970 return array($categories, $categoryids);
1971 }
1972
7f88c426
DP
1973 if (empty($categoryids)) {
1974 // No categories available (probably all hidden).
1975 return array();
1976 }
1977
24e27ac0
SH
1978 // The depth is 0 this function has just been called so we can finish it off
1979
1980 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
1981 list($catsql, $catparams) = $DB->get_in_or_equal(array_keys($categoryids));
1982 $sql = "SELECT
df997f84 1983 c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary,c.category
24e27ac0
SH
1984 $ccselect
1985 FROM {course} c
1986 $ccjoin
1987 WHERE c.category $catsql ORDER BY c.sortorder ASC";
1988 if ($courses = $DB->get_records_sql($sql, $catparams)) {
1989 // loop throught them
1990 foreach ($courses as $course) {
1991 if ($course->id == SITEID) {
1992 continue;
1993 }
1994 context_instance_preload($course);
9a5e297b 1995 if (!empty($course->visible) || has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
24e27ac0
SH
1996 $categoryids[$course->category]->courses[$course->id] = $course;
1997 }
1998 }
1999 }
2000 return $categories;
2001}
c2cb4545 2002
cb6fec1f 2003/**
2004 * Recursive function to print out all the categories in a nice format
2005 * with or without courses included
2006 */
8ed5dd63 2007function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true) {
9ff5310a 2008 global $CFG;
e05bcf2f 2009
beeee4d2 2010 // maxcategorydepth == 0 meant no limit
2011 if (!empty($CFG->maxcategorydepth) && $depth >= $CFG->maxcategorydepth) {
e05bcf2f 2012 return;
9ff5310a 2013 }
c2cb4545 2014
2015 if (!$displaylist) {
e92fe848 2016 make_categories_list($displaylist, $parentslist);
c2cb4545 2017 }
2018
2019 if ($category) {
9a5e297b 2020 if ($category->visible or has_capability('moodle/category:viewhiddencategories', context_system::instance())) {
8ed5dd63 2021 print_category_info($category, $depth, $showcourses);
c2cb4545 2022 } else {
2023 return; // Don't bother printing children of invisible categories
2024 }
89adb174 2025
c2cb4545 2026 } else {
b85b25eb 2027 $category = new stdClass();
c2cb4545 2028 $category->id = "0";
2029 }
2030
9bb19e58 2031 if ($categories = get_child_categories($category->id)) { // Print all the children recursively
c2cb4545 2032 $countcats = count($categories);
2033 $count = 0;
2034 $first = true;
2035 $last = false;
2036 foreach ($categories as $cat) {
2037 $count++;
2038 if ($count == $countcats) {
2039 $last = true;
2040 }
2041 $up = $first ? false : true;
2042 $down = $last ? false : true;
2043 $first = false;
2044
8ed5dd63 2045 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1, $showcourses);
c2cb4545 2046 }
2047 }
c2cb4545 2048}
2049
cb6fec1f 2050/**
af90698b 2051 * This function will return $options array for html_writer::select(), with whitespace to denote nesting.
cb6fec1f 2052 */
0705ff84 2053function make_categories_options() {
2054 make_categories_list($cats,$parents);
2055 foreach ($cats as $key => $value) {
2056 if (array_key_exists($key,$parents)) {
2057 if ($indent = count($parents[$key])) {
2058 for ($i = 0; $i < $indent; $i++) {
2059 $cats[$key] = '&nbsp;'.$cats[$key];
2060 }
2061 }
2062 }
2063 }
2064 return $cats;
2065}
c2cb4545 2066
cb6fec1f 2067/**
2068 * Prints the category info in indented fashion
2069 * This function is only used by print_whole_category_list() above
2070 */
f3e5bf86 2071function print_category_info($category, $depth=0, $showcourses = false) {
6b608f8f 2072 global $CFG, $DB, $OUTPUT;
c2cb4545 2073
df997f84 2074 $strsummary = get_string('summary');
ba2e5d73 2075
ea831ceb
RW
2076 $catlinkcss = null;
2077 if (!$category->visible) {
2078 $catlinkcss = array('class'=>'dimmed');
2079 }
dc247e52 2080 static $coursecount = null;
2081 if (null === $coursecount) {
2082 // only need to check this once
2083 $coursecount = $DB->count_records('course') <= FRONTPAGECOURSELIMIT;
2084 }
2085
8ed5dd63 2086 if ($showcourses and $coursecount) {
b5d0cafc 2087 $catimage = '<img src="'.$OUTPUT->pix_url('i/course') . '" alt="" />';
b48f834c 2088 } else {
7b0b5c14 2089 $catimage = "&nbsp;";
8ef9cb56 2090 }
2afcfc44 2091
df997f84 2092 $courses = get_courses($category->id, 'c.sortorder ASC', 'c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary');
9a5e297b 2093 $context = context_coursecat::instance($category->id);
63390481
SH
2094 $fullname = format_string($category->name, true, array('context' => $context));
2095
8ed5dd63 2096 if ($showcourses and $coursecount) {
2a63b636 2097 echo '<div class="categorylist clearfix">';
2afcfc44 2098 $cat = '';
2a63b636 2099 $cat .= html_writer::tag('div', $catimage, array('class'=>'image'));
63390481 2100 $catlink = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
2afcfc44
RW
2101 $cat .= html_writer::tag('div', $catlink, array('class'=>'name'));
2102
ea831ceb 2103 $html = '';
2afcfc44
RW
2104 if ($depth > 0) {
2105 for ($i=0; $i< $depth; $i++) {
ea831ceb 2106 $html = html_writer::tag('div', $html . $cat, array('class'=>'indentation'));
2afcfc44 2107 $cat = '';
cb184beb 2108 }
2afcfc44 2109 } else {
ea831ceb 2110 $html = $cat;
2afcfc44 2111 }
2a63b636 2112 echo html_writer::tag('div', $html, array('class'=>'category'));
2afcfc44 2113 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
b48f834c 2114
beeee4d2 2115 // does the depth exceed maxcategorydepth
2afcfc44 2116 // maxcategorydepth == 0 or unset meant no limit
beeee4d2 2117 $limit = !(isset($CFG->maxcategorydepth) && ($depth >= $CFG->maxcategorydepth-1));
beeee4d2 2118 if ($courses && ($limit || $CFG->maxcategorydepth == 0)) {
c2cb4545 2119 foreach ($courses as $course) {
ea831ceb
RW
2120 $linkcss = null;
2121 if (!$course->visible) {
2122 $linkcss = array('class'=>'dimmed');
2123 }
2a63b636 2124
7fb46992 2125 $coursename = get_course_display_name_for_list($course);
2126 $courselink = html_writer::link(new moodle_url('/course/view.php', array('id'=>$course->id)), format_string($coursename), $linkcss);
2afcfc44 2127
bf423bb1 2128 // print enrol info
f3e5bf86 2129 $courseicon = '';
bf423bb1
PS
2130 if ($icons = enrol_get_course_info_icons($course)) {
2131 foreach ($icons as $pix_icon) {
65edd8ad 2132 $courseicon = $OUTPUT->render($pix_icon);
bf423bb1
PS
2133 }
2134 }
2135
f3e5bf86
SH
2136 $coursecontent = html_writer::tag('div', $courseicon.$courselink, array('class'=>'name'));
2137
b48f834c 2138 if ($course->summary) {
75015e5f 2139 $link = new moodle_url('/course/info.php?id='.$course->id);
2afcfc44 2140 $actionlink = $OUTPUT->action_link($link, '<img alt="'.$strsummary.'" src="'.$OUTPUT->pix_url('i/info') . '" />',
75015e5f
PS
2141 new popup_action('click', $link, 'courseinfo', array('height' => 400, 'width' => 500)),
2142 array('title'=>$strsummary));
2afcfc44
RW
2143
2144 $coursecontent .= html_writer::tag('div', $actionlink, array('class'=>'info'));
2145 }
2146
ea831ceb 2147 $html = '';
f3e5bf86 2148 for ($i=0; $i <= $depth; $i++) {
ea831ceb 2149 $html = html_writer::tag('div', $html . $coursecontent , array('class'=>'indentation'));
2afcfc44 2150 $coursecontent = '';
0c656181 2151 }
ea831ceb 2152 echo html_writer::tag('div', $html, array('class'=>'course clearfloat'));
2afcfc44 2153 }
ba2e5d73 2154 }
2afcfc44
RW
2155 echo '</div>';
2156 } else {
2a63b636 2157 echo '<div class="categorylist">';
ea831ceb 2158 $html = '';
63390481 2159 $cat = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
eea78ebc
DP
2160 if (count($courses) > 0) {
2161 $cat .= html_writer::tag('span', ' ('.count($courses).')', array('title'=>get_string('numberofcourses'), 'class'=>'numberofcourse'));
2162 }
2a63b636 2163
ea831ceb
RW
2164 if ($depth > 0) {
2165 for ($i=0; $i< $depth; $i++) {
2166 $html = html_writer::tag('div', $html .$cat, array('class'=>'indentation'));
2167 $cat = '';
2168 }
2169 } else {
2170 $html = $cat;
2171 }
2a63b636
PS
2172
2173 echo html_writer::tag('div', $html, array('class'=>'category'));
ea831ceb 2174 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
cb184beb 2175 echo '</div>';
2afcfc44 2176 }
c2cb4545 2177}
2178
77eddcd5 2179/**
2180 * Print the buttons relating to course requests.
2181 *
2182 * @param object $systemcontext the system context.
2183 */
2184function print_course_request_buttons($systemcontext) {
b4531207 2185 global $CFG, $DB, $OUTPUT;
77eddcd5 2186 if (empty($CFG->enablecourserequests)) {
2187 return;
2188 }
4f0c2d00 2189 if (!has_capability('moodle/course:create', $systemcontext) && has_capability('moodle/course:request', $systemcontext)) {
77eddcd5 2190 /// Print a button to request a new course
5c2ed7e2 2191 echo $OUTPUT->single_button('request.php', get_string('requestcourse'), 'get');
77eddcd5 2192 }
2193 /// Print a button to manage pending requests
2194 if (has_capability('moodle/site:approvecourse', $systemcontext)) {
5c2ed7e2
PS
2195 $disabled = !$DB->record_exists('course_request', array());
2196 echo $OUTPUT->single_button('pending.php', get_string('coursespending'), 'get', array('disabled'=>$disabled));
77eddcd5 2197 }
2198}
2199
5048e034 2200/**
2201 * Does the user have permission to edit things in this category?
2202 *
2203 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2204 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
2205 */
2206function can_edit_in_category($categoryid = 0) {
2207 $context = get_category_or_system_context($categoryid);
2208 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
2209}
2210
8ed5dd63 2211/**
2212 * Prints the turn editing on/off button on course/index.php or course/category.php.
2213 *
2214 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2215 * @return string HTML of the editing button, or empty string, if this user is not allowed
2216 * to see it.
2217 */
2218function update_category_button($categoryid = 0) {
b4531207 2219 global $CFG, $PAGE, $OUTPUT;
8ed5dd63 2220
2221 // Check permissions.
5048e034 2222 if (!can_edit_in_category($categoryid)) {
8ed5dd63 2223 return '';
2224 }
2225
2226 // Work out the appropriate action.
830dd6e9 2227 if ($PAGE->user_is_editing()) {
8ed5dd63 2228 $label = get_string('turneditingoff');
2229 $edit = 'off';
2230 } else {
2231 $label = get_string('turneditingon');
2232 $edit = 'on';
2233 }
c2cb4545 2234
8ed5dd63 2235 // Generate the button HTML.
2236 $options = array('categoryedit' => $edit, 'sesskey' => sesskey());
2237 if ($categoryid) {
2238 $options['id'] = $categoryid;
2239 $page = 'category.php';
2240 } else {
2241 $page = 'index.php';
2242 }
a6855934 2243 return $OUTPUT->single_button(new moodle_url('/course/' . $page, $options), $label, 'get');
8ed5dd63 2244}
e0b033d5 2245
cb6fec1f 2246/**
2247 * Category is 0 (for all courses) or an object
2248 */
6c54240a 2249function print_courses($category) {
2f48819b 2250 global $CFG, $OUTPUT;
c2cb4545 2251
4dde1463 2252 if (!is_object($category) && $category==0) {
9bb19e58 2253 $categories = get_child_categories(0); // Parent = 0 ie top-level categories only
4dde1463 2254 if (is_array($categories) && count($categories) == 1) {
90c2ca2e 2255 $category = array_shift($categories);
238c0dd9 2256 $courses = get_courses_wmanagers($category->id,
2257 'c.sortorder ASC',
df997f84 2258 array('summary','summaryformat'));
90c2ca2e 2259 } else {
238c0dd9 2260 $courses = get_courses_wmanagers('all',
2261 'c.sortorder ASC',
df997f84 2262 array('summary','summaryformat'));
90c2ca2e 2263 }
2264 unset($categories);
607809b3 2265 } else {
238c0dd9 2266 $courses = get_courses_wmanagers($category->id,
2267 'c.sortorder ASC',
df997f84 2268 array('summary','summaryformat'));
c2cb4545 2269 }
2270
49cd4d79 2271 if ($courses) {
002fc5ba 2272 echo html_writer::start_tag('ul', array('class'=>'unlist'));
c2cb4545 2273 foreach ($courses as $course) {
9a5e297b 2274 $coursecontext = context_course::instance($course->id);
4f0c2d00 2275 if ($course->visible == 1 || has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
002fc5ba 2276 echo html_writer::start_tag('li');
4dde1463 2277 print_course($course);
002fc5ba 2278 echo html_writer::end_tag('li');
4dde1463 2279 }
c2cb4545 2280 }
002fc5ba 2281 echo html_writer::end_tag('ul');
c2cb4545 2282 } else {
7c5286cd 2283 echo $OUTPUT->heading(get_string("nocoursesyet"));
9a5e297b 2284 $context = context_system::instance();
0468976c 2285 if (has_capability('moodle/course:create', $context)) {
255d1033 2286 $options = array();
4868e95f
DM
2287 if (!empty($category->id)) {
2288 $options['category'] = $category->id;
2289 } else {
2290 $options['category'] = $CFG->defaultrequestcategory;
2291 }
002fc5ba 2292 echo html_writer::start_tag('div', array('class'=>'addcoursebutton'));
a6855934 2293 echo $OUTPUT->single_button(new moodle_url('/course/edit.php', $options), get_string("addnewcourse"));
002fc5ba 2294 echo html_writer::end_tag('div');
255d1033 2295 }
c2cb4545 2296 }
c2cb4545 2297}
2298
04c53106 2299/**
2300 * Print a description of a course, suitable for browsing in a list.
2301 *
2302 * @param object $course the course object.
2303 * @param string $highlightterms (optional) some search terms that should be highlighted in the display.
2304 */
2305function print_course($course, $highlightterms = '') {
666e8458 2306 global $CFG, $USER, $DB, $OUTPUT;
c2cb4545 2307
9a5e297b 2308 $context = context_course::instance($course->id);
146bbb8f 2309
8bdc9cac 2310 // Rewrite file URLs so that they are correct
64f93798 2311 $course->summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', NULL);
8bdc9cac 2312
002fc5ba
SH
2313 echo html_writer::start_tag('div', array('class'=>'coursebox clearfix'));
2314 echo html_writer::start_tag('div', array('class'=>'info'));
2315 echo html_writer::start_tag('h3', array('class'=>'name'));
22288704 2316
002fc5ba 2317 $linkhref = new moodle_url('/course/view.php', array('id'=>$course->id));
7fb46992 2318
2319 $coursename = get_course_display_name_for_list($course);
2320 $linktext = highlight($highlightterms, format_string($coursename));
002fc5ba
SH
2321 $linkparams = array('title'=>get_string('entercourse'));
2322 if (empty($course->visible)) {
2323 $linkparams['class'] = 'dimmed';
2324 }
2325 echo html_writer::link($linkhref, $linktext, $linkparams);
2326 echo html_writer::end_tag('h3');
238c0dd9 2327
d42c64ba 2328 /// first find all roles that are supposed to be displayed
df997f84 2329 if (!empty($CFG->coursecontact)) {
c71f3265 2330 $managerroles = explode(',', $CFG->coursecontact);
e52a8ebd 2331 $rusers = array();
9d5a4b23 2332
e52a8ebd 2333 if (!isset($course->managers)) {
9695ff81 2334 list($sort, $sortparams) = users_order_by_sql('u');
e52a8ebd 2335 $rusers = get_role_users($managerroles, $context, true,
c52551dc
PS
2336 'ra.id AS raid, u.id, u.username, u.firstname, u.lastname, rn.name AS rolecoursealias,
2337 r.name AS rolename, r.sortorder, r.id AS roleid, r.shortname AS roleshortname',
9695ff81 2338 'r.sortorder ASC, ' . $sort, null, '', '', '', '', $sortparams);
e52a8ebd
DP
2339 } else {
2340 // use the managers array if we have it for perf reasosn
2341 // populate the datastructure like output of get_role_users();
2342 foreach ($course->managers as $manager) {
c52551dc
PS
2343 $user = clone($manager->user);
2344 $user->roleid = $manager->roleid;
2345 $user->rolename = $manager->rolename;
2346 $user->roleshortname = $manager->roleshortname;
2347 $user->rolecoursealias = $manager->rolecoursealias;
2348 $rusers[$user->id] = $user;
4dde1463 2349 }
e52a8ebd 2350 }
165d25cc 2351
e52a8ebd
DP
2352 $namesarray = array();
2353 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2354 foreach ($rusers as $ra) {
2355 if (isset($namesarray[$ra->id])) {
2356 // only display a user once with the higest sortorder role
2357 continue;
2358 }
165d25cc 2359
c52551dc
PS
2360 $role = new stdClass();
2361 $role->id = $ra->roleid;
2362 $role->name = $ra->rolename;
2363 $role->shortname = $ra->roleshortname;
2364 $role->coursealias = $ra->rolecoursealias;
2365 $rolename = role_get_name($role, $context, ROLENAME_ALIAS);
e52a8ebd
DP
2366
2367 $fullname = fullname($ra, $canviewfullnames);
c52551dc 2368 $namesarray[$ra->id] = $rolename.': '.
e52a8ebd 2369 html_writer::link(new moodle_url('/user/view.php', array('id'=>$ra->id, 'course'=>SITEID)), $fullname);
c2cb4545 2370 }
431cad0d 2371
d42c64ba 2372 if (!empty($namesarray)) {
002fc5ba
SH
2373 echo html_writer::start_tag('ul', array('class'=>'teachers'));
2374 foreach ($namesarray as $name) {
2375 echo html_writer::tag('li', $name);
2376 }
2377 echo html_writer::end_tag('ul');
88768091 2378 }
c2cb4545 2379 }
002fc5ba 2380 echo html_writer::end_tag('div'); // End of info div
238c0dd9 2381
002fc5ba 2382 echo html_writer::start_tag('div', array('class'=>'summary'));
b85b25eb 2383 $options = new stdClass();
9f39c190 2384 $options->noclean = true;
34b5847a 2385 $options->para = false;
367a75fa 2386 $options->overflowdiv = true;
8bdc9cac
SH
2387 if (!isset($course->summaryformat)) {
2388 $course->summaryformat = FORMAT_MOODLE;
2389 }
2390 echo highlight($highlightterms, format_text($course->summary, $course->summaryformat, $options, $course->id));
e877160d 2391 if ($icons = enrol_get_course_info_icons($course)) {
002fc5ba
SH
2392 echo html_writer::start_tag('div', array('class'=>'enrolmenticons'));
2393 foreach ($icons as $icon) {
2394 echo $OUTPUT->render($icon);
2395 }
2396 echo html_writer::end_tag('div'); // End of enrolmenticons div
2397 }
2398 echo html_writer::end_tag('div'); // End of summary div
2399 echo html_writer::end_tag('div'); // End of coursebox div
c2cb4545 2400}
2401
cb6fec1f 2402/**
2403 * Prints custom user information on the home page.
2404 * Over time this can include all sorts of information
2405 */
c2cb4545 2406function print_my_moodle() {
e6db3026 2407 global $USER, $CFG, $DB, $OUTPUT;
c2cb4545 2408
4f0c2d00 2409 if (!isloggedin() or isguestuser()) {
ba6018a9 2410 print_error('nopermissions', '', '', 'See My Moodle');
c2cb4545 2411 }
2412
df997f84 2413 $courses = enrol_get_my_courses('summary', 'visible DESC,sortorder ASC');
0a127169 2414 $rhosts = array();
2415 $rcourses = array();
2416 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
2417 $rcourses = get_my_remotecourses($USER->id);
2418 $rhosts = get_my_remotehosts();
2419 }
2420
2421 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
2422
2423 if (!empty($courses)) {
2424 echo '<ul class="unlist">';
2425 foreach ($courses as $course) {
2426 if ($course->id == SITEID) {
2427 continue;
2428 }
2429 echo '<li>';
2430 print_course($course);
2431 echo "</li>\n";
86dd62a7 2432 }
0a127169 2433 echo "</ul>\n";
86dd62a7 2434 }
2435
0a127169 2436 // MNET
2437 if (!empty($rcourses)) {
2438 // at the IDP, we know of all the remote courses
2439 foreach ($rcourses as $course) {
2440 print_remote_course($course, "100%");
2441 }
2442 } elseif (!empty($rhosts)) {
2443 // non-IDP, we know of all the remote servers, but not courses
2444 foreach ($rhosts as $host) {
2445 print_remote_host($host, "100%");
2446 }
2447 }
86dd62a7 2448 unset($course);
0a127169 2449 unset($host);
38a10939 2450
cb6fec1f 2451 if ($DB->count_records("course") > (count($courses) + 1) ) { // Some courses not being displayed
7f989948 2452 echo "<table width=\"100%\"><tr><td align=\"center\">";
2453 print_course_search("", false, "short");
2454 echo "</td><td align=\"center\">";
5c2ed7e2 2455 echo $OUTPUT->single_button("$CFG->wwwroot/course/index.php", get_string("fulllistofcourses"), "get");
7f989948 2456 echo "</td></tr></table>\n";
2457 }
86dd62a7 2458
26330001 2459 } else {
cb6fec1f 2460 if ($DB->count_records("course_categories") > 1) {
e6db3026 2461 echo $OUTPUT->box_start("categorybox");
26330001 2462 print_whole_category_list();
e6db3026 2463 echo $OUTPUT->box_end();
26330001 2464 } else {
35d0244a 2465 print_courses(0);
26330001 2466 }
607809b3 2467 }
2b8cef80 2468}
2469
11b0c469 2470
a8b56716 2471function print_course_search($value="", $return=false, $format="plain") {
38a10939 2472 global $CFG;
1e0fb105 2473 static $count = 0;
2474
2475 $count++;
2476
2477 $id = 'coursesearch';
2478
2479 if ($count > 1) {
2480 $id .= $count;
2481 }
38a10939 2482
2483 $strsearchcourses= get_string("searchcourses");
2484
1c919752 2485 if ($format == 'plain') {
1e0fb105 2486 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
fcf9577a 2487 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
e42f4d92 2488 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
cb6fec1f 2489 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" value="'.s($value).'" />';
e42f4d92 2490 $output .= '<input type="submit" value="'.get_string('go').'" />';
fcf9577a 2491 $output .= '</fieldset></form>';
1c919752 2492 } else if ($format == 'short') {
1e0fb105 2493 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
fcf9577a 2494 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
b1f97418 2495 $output .= '<label for="shortsearchbox">'.$strsearchcourses.': </label>';
cb6fec1f 2496 $output .= '<input type="text" id="shortsearchbox" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
e42f4d92 2497 $output .= '<input type="submit" value="'.get_string('go').'" />';
fcf9577a 2498 $output .= '</fieldset></form>';
1c919752 2499 } else if ($format == 'navbar') {
fcf9577a 2500 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2501 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
b1f97418 2502 $output .= '<label for="navsearchbox">'.$strsearchcourses.': </label>';
cb6fec1f 2503 $output .= '<input type="text" id="navsearchbox" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
e42f4d92 2504 $output .= '<input type="submit" value="'.get_string('go').'" />';
fcf9577a 2505 $output .= '</fieldset></form>';
a8b56716 2506 }
2507
2508 if ($return) {
2509 return $output;
2510 }
2511 echo $output;
38a10939 2512}
11b0c469 2513
86dd62a7 2514function print_remote_course($course, $width="100%") {
86dd62a7 2515 global $CFG, $USER;
2516
2517 $linkcss = '';
2518
2519 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&amp;wantsurl=/course/view.php?id={$course->remoteid}";
2520
7cd266e9 2521 echo '<div class="coursebox remotecoursebox clearfix">';
86dd62a7 2522 echo '<div class="info">';
2523 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2524 $linkcss.' href="'.$url.'">'
6ba65fa0 2525 . format_string($course->fullname) .'</a><br />'
2526 . format_string($course->hostname) . ' : '
238c0dd9 2527 . format_string($course->cat_name) . ' : '
2528 . format_string($course->shortname). '</div>';
86dd62a7 2529 echo '</div><div class="summary">';
b85b25eb 2530 $options = new stdClass();
86dd62a7 2531 $options->noclean = true;
2532 $options->para = false;
367a75fa 2533 $options->overflowdiv = true;
152a2273 2534 echo format_text($course->summary, $course->summaryformat, $options);
86dd62a7 2535 echo '</div>';
2536 echo '</div>';
86dd62a7 2537}
2538
643b67b8 2539function print_remote_host($host, $width="100%") {
6b608f8f 2540 global $OUTPUT;
643b67b8 2541
2542 $linkcss = '';
2543
7cd266e9 2544 echo '<div class="coursebox clearfix">';
643b67b8 2545 echo '<div class="info">';
2546 echo '<div class="name">';
b5d0cafc 2547 echo '<img src="'.$OUTPUT->pix_url('i/mnethost') . '" class="icon" alt="'.get_string('course').'" />';
643b67b8 2548 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2549 . s($host['name']).'</a> - ';
1fd80ad3 2550 echo $host['count'] . ' ' . get_string('courses');
643b67b8 2551 echo '</div>';
2552 echo '</div>';
caa90d56 2553 echo '</div>';
643b67b8 2554}
2555
86dd62a7 2556
11b0c469 2557/// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2558
2559function add_course_module($mod) {
cb6fec1f 2560 global $DB;
11b0c469 2561
e5dfd0f3 2562 $mod->added = time();
53f4ad2c 2563 unset($mod->id);
11b0c469 2564
38b19bbc
MG
2565 $cmid = $DB->insert_record("course_modules", $mod);
2566 rebuild_course_cache($mod->course, true);
2567 return $cmid;
11b0c469 2568}
2569
97928ddf 2570/**
4ede27b2 2571 * Creates missing course section(s) and rebuilds course cache
99e9f9a6 2572 *
b46be6ad 2573 * @param int|stdClass $courseorid course id or course object
4ede27b2
MG
2574 * @param int|array $sections list of relative section numbers to create
2575 * @return bool if there were any sections created
97928ddf 2576 */
b46be6ad 2577function course_create_sections_if_missing($courseorid, $sections) {
cb6fec1f 2578 global $DB;
4ede27b2
MG
2579 if (!is_array($sections)) {
2580 $sections = array($sections);
2581 }
b46be6ad
MG
2582 $existing = array_keys(get_fast_modinfo($courseorid)->get_section_info_all());
2583 if (is_object($courseorid)) {
2584 $courseorid = $courseorid->id;
2585 }
4ede27b2
MG
2586 $coursechanged = false;
2587 foreach ($sections as $sectionnum) {
2588 if (!in_array($sectionnum, $existing)) {
2589 $cw = new stdClass();
b46be6ad 2590 $cw->course = $courseorid;
4ede27b2
MG
2591 $cw->section = $sectionnum;
2592 $cw->summary = '';
2593 $cw->summaryformat = FORMAT_HTML;
2594 $cw->sequence = '';
2595 $id = $DB->insert_record("course_sections", $cw);
2596 $coursechanged = true;
2597 }
2598 }
2599 if ($coursechanged) {
b46be6ad 2600 rebuild_course_cache($courseorid, true);
4ede27b2
MG
2601 }
2602 return $coursechanged;
97928ddf 2603}
52f14061 2604
ece966f0 2605/**
722e6ba9 2606 * Adds an existing module to the section
ece966f0 2607 *
722e6ba9
MG
2608 * Updates both tables {course_sections} and {course_modules}
2609 *
2610 * @param int|stdClass $courseorid course id or course object
46453565 2611 * @param int $cmid id of the module already existing in course_modules table
722e6ba9
MG
2612 * @param int $sectionnum relative number of the section (field course_sections.section)
2613 * If section does not exist it will be created
2614 * @param int|stdClass $beforemod id or object with field id corresponding to the module
2615 * before which the module needs to be included. Null for inserting in the
2616 * end of the section
2617 * @return int The course_sections ID where the module is inserted
ece966f0 2618 */
46453565 2619function course_add_cm_to_section($courseorid, $cmid, $sectionnum, $beforemod = null) {
722e6ba9
MG
2620 global $DB, $COURSE;
2621 if (is_object($beforemod)) {
2622 $beforemod = $beforemod->id;
2623 }
46453565
PS
2624 if (is_object($courseorid)) {
2625 $courseid = $courseorid->id;
2626 } else {
2627 $courseid = $courseorid;
2628 }
b46be6ad 2629 course_create_sections_if_missing($courseorid, $sectionnum);
46453565
PS
2630 // Do not try to use modinfo here, there is no guarantee it is valid!
2631 $section = $DB->get_record('course_sections', array('course'=>$courseid, 'section'=>$sectionnum), '*', MUST_EXIST);
722e6ba9 2632 $modarray = explode(",", trim($section->sequence));
281d730e 2633 if (empty($section->sequence)) {
46453565 2634 $newsequence = "$cmid";
722e6ba9 2635 } else if ($beforemod && ($key = array_keys($modarray, $beforemod))) {
46453565 2636 $insertarray = array($cmid, $beforemod);
722e6ba9
MG
2637 array_splice($modarray, $key[0], 1, $insertarray);
2638 $newsequence = implode(",", $modarray);
2639 } else {
46453565 2640 $newsequence = "$section->sequence,$cmid";
722e6ba9
MG
2641 }
2642 $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id));
46453565 2643 $DB->set_field('course_modules', 'section', $section->id, array('id' => $cmid));
b46be6ad
MG
2644 if (is_object($courseorid)) {
2645 rebuild_course_cache($courseorid->id, true);
2646 } else {
2647 rebuild_course_cache($courseorid, true);
2648 }
722e6ba9 2649 return $section->id; // Return course_sections ID that was used.
11b0c469 2650}
2651
48e535bc 2652function set_coursemodule_groupmode($id, $groupmode) {
cb6fec1f 2653 global $DB;
38b19bbc
MG
2654 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST);
2655 if ($cm->groupmode != $groupmode) {
2656 $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id));
2657 rebuild_course_cache($cm->course, true);
2658 }
2659 return ($cm->groupmode != $groupmode);
3d575e6f 2660}
2661
177d4abf 2662function set_coursemodule_idnumber($id, $idnumber) {
cb6fec1f 2663 global $DB;
38b19bbc
MG
2664 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST);
2665 if ($cm->idnumber != $idnumber) {
2666 $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id));
2667 rebuild_course_cache($cm->course, true);
2668 }
2669 return ($cm->idnumber != $idnumber);
177d4abf 2670}
4e781c7b 2671
02f66c42 2672/**
00a34234
FM
2673 * Set the visibility of a module and inherent properties.
2674 *
2675 * From 2.4 the parameter $prevstateoverrides has been removed, the logic it triggered
2676 * has been moved to {@link set_section_visible()} which was the only place from which
2677 * the parameter was used.
2678 *
2679 * @param int $id of the module
2680 * @param int $visible state of the module
2681 * @return bool false when the module was not found, true otherwise
2682 */
2683function set_coursemodule_visible($id, $visible) {
f5e2602a 2684 global $DB, $CFG;
0f078024
DM
2685 require_once($CFG->libdir.'/gradelib.php');
2686
00a34234
FM
2687 // Trigger developer's attention when using the previously removed argument.
2688 if (func_num_args() > 2) {
2689 debugging('Wrong number of arguments passed to set_coursemodule_visible(), $prevstateoverrides
2690 has been removed.', DEBUG_DEVELOPER);
2691 }
2692
cb6fec1f 2693 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
978abb42 2694 return false;
2695 }
cb6fec1f 2696 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
978abb42 2697 return false;
2698 }
cb6fec1f 2699 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
dcd338ff 2700 foreach($events as $event) {
48e535bc 2701 if ($visible) {
2702 show_event($event);
2703 } else {
2704 hide_event($event);
2705 }
dcd338ff 2706 }
2707 }
f5e2602a 2708
0f078024
DM
2709 // hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there
2710 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
2711 if ($grade_items) {
2712 foreach ($grade_items as $grade_item) {
2713 $grade_item->set_hidden(!$visible);
2714 }
f5e2602a 2715 }
f685e830 2716
00a34234
FM
2717 // Updating visible and visibleold to keep them in sync. Only changing a section visibility will
2718 // affect visibleold to allow for an original visibility restore. See set_section_visible().
2719 $cminfo = new stdClass();
2720 $cminfo->id = $id;
2721 $cminfo->visible = $visible;
2722 $cminfo->visibleold = $visible;
2723 $DB->update_record('course_modules', $cminfo);
2724
38b19bbc
MG
2725 rebuild_course_cache($cm->course, true);
2726 return true;
1acfbce5 2727}
2728
cb6fec1f 2729/**
290130b3 2730 * Delete a course module and any associated data at the course level (events)
264867fd 2731 * Until 1.5 this function simply marked a deleted flag ... now it
290130b3 2732 * deletes it completely.
2733 *
2734 */
48e535bc 2735function delete_course_module($id) {
cb6fec1f 2736 global $CFG, $DB;
f615fbab 2737 require_once($CFG->libdir.'/gradelib.php');
cae83708 2738 require_once($CFG->dirroot.'/blog/lib.php');
f615fbab 2739
cb6fec1f 2740 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
290130b3 2741 return true;
2742 }
cb6fec1f 2743 $modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module));
f615fbab 2744 //delete events from calendar
cb6fec1f 2745 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
dcd338ff 2746 foreach($events as $event) {
0ea03696 2747 delete_event($event->id);
dcd338ff 2748 }
2749 }
f615fbab 2750 //delete grade items, outcome items and grades attached to modules
2751 if ($grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2752 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course))) {
2753 foreach ($grade_items as $grade_item) {
2754 $grade_item->delete('moddelete');
2755 }
f615fbab 2756 }
46e12372
SM
2757 // Delete completion and availability data; it is better to do this even if the
2758 // features are not turned on, in case they were turned on previously (these will be
2759 // very quick on an empty table)
2760 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
2761 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id));
a8f84c28 2762 $DB->delete_records('course_modules_avail_fields', array('coursemoduleid' => $cm->id));
ede323e2
ARN
2763 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
2764 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
06b3a6b2 2765
2766 delete_context(CONTEXT_MODULE, $cm->id);
38b19bbc
MG
2767 $DB->delete_records('course_modules', array('id'=>$cm->id));
2768 rebuild_course_cache($cm->course, true);
2769 return true;
11b0c469 2770}
2771
722e6ba9 2772function delete_mod_from_section($modid, $sectionid) {
cb6fec1f 2773 global $DB;
11b0c469 2774
722e6ba9 2775 if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
11b0c469 2776
e5dfd0f3 2777 $modarray = explode(",", $section->sequence);
11b0c469 2778
722e6ba9 2779 if ($key = array_keys ($modarray, $modid)) {
11b0c469 2780 array_splice($modarray, $key[0], 1);
2781 $newsequence = implode(",", $modarray);
38b19bbc
MG
2782 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
2783 rebuild_course_cache($section->course, true);
2784 return true;
11b0c469 2785 } else {
2786 return false;
2787 }
89adb174 2788
11b0c469 2789 }
7977cffd 2790 return false;
11b0c469 2791}
2792
3440ec12 2793/**
2794 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
2795 *
93d46f48
RK
2796 * @param object $course course object
2797 * @param int $section Section number (not id!!!)
3440ec12 2798 * @param int $move (-1 or 1)
93d46f48 2799 * @return boolean true if section moved successfully
ac5f6414 2800 * @todo MDL-33379 remove this function in 2.5
3440ec12 2801 */
12905134 2802function move_section($course, $section, $move) {
ac5f6414
RT
2803 debugging('This function will be removed before 2.5 is released please use move_section_to', DEBUG_DEVELOPER);
2804
12905134 2805/// Moves a whole course section up and down within the course
38b19bbc 2806 global $USER;
12905134 2807
2808 if (!$move) {
2809 return true;
2810 }
2811
2812 $sectiondest = $section + $move;
2813
850acb35
MG
2814 // compartibility with course formats using field 'numsections'
2815 $courseformatoptions = course_get_format($course)->get_format_options();
2816 if (array_key_exists('numsections', $courseformatoptions) &&
2817 $sectiondest > $courseformatoptions['numsections'] or $sectiondest < 1) {
12905134 2818 return false;
2819 }
2820
eb01aa2c 2821 $retval = move_section_to($course, $section, $sectiondest);
eb01aa2c 2822 return $retval;
12905134 2823}
2824
3440ec12 2825/**
2826 * Moves a section within a course, from a position to another.
2827 * Be very careful: $section and $destination refer to section number,
2828 * not id!.
2829 *
2830 * @param object $course
2831 * @param int $section Section number (not id!!!)
2832 * @param int $destination
2833 * @return boolean Result
2834 */
2835function move_section_to($course, $section, $destination) {
2836/// Moves a whole course section up and down within the course
2837 global $USER, $DB;
2838
ca255392 2839 if (!$destination && $destination != 0) {
3440ec12 2840 return true;
2841 }
2842
850acb35
MG
2843 // compartibility with course formats using field 'numsections'
2844 $courseformatoptions = course_get_format($course)->get_format_options();
2845 if ((array_key_exists('numsections', $courseformatoptions) &&
2846 ($destination > $courseformatoptions['numsections'])) || ($destination < 1)) {
3440ec12 2847 return false;
2848 }
2849
2850 // Get all sections for this course and re-order them (2 of them should now share the same section number)
2851 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
2852 'section ASC, id ASC', 'id, section')) {
2853 return false;
2854 }
2855
cf76b335 2856 $movedsections = reorder_sections($sections, $section, $destination);
3440ec12 2857
cf76b335 2858 // Update all sections. Do this in 2 steps to avoid breaking database
2859 // uniqueness constraint
2860 $transaction = $DB->start_delegated_transaction();
2861 foreach ($movedsections as $id => $position) {
2862 if ($sections[$id] !== $position) {
2863 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
2864 }
2865 }
e7e0f8d2
DP
2866 foreach ($movedsections as $id => $position) {
2867 if ($sections[$id] !== $position) {
2868 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
2869 }
3440ec12 2870 }
2871
15e2552f
RK
2872 // If we move the highlighted section itself, then just highlight the destination.
2873 // Adjust the higlighted section location if we move something over it either direction.
2874 if ($section == $course->marker) {
e7b6e6b9 2875 course_set_marker($course->id, $destination);
2365213f 2876 } elseif ($section > $course->marker && $course->marker >= $destination) {
e7b6e6b9 2877 course_set_marker($course->id, $course->marker+1);
2365213f 2878 } elseif ($section < $course->marker && $course->marker <= $destination) {
e7b6e6b9 2879 course_set_marker($course->id, $course->marker-1);
15e2552f
RK
2880 }
2881
cf76b335 2882 $transaction->allow_commit();
38b19bbc 2883 rebuild_course_cache($course->id, true);
3440ec12 2884 return true;
2885}
2886
2887/**
2888 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
2889 * an original position number and a target position number, rebuilds the array so that the
2890 * move is made without any duplication of section positions.
2891 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
2892 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
2893 *
2894 * @param array $sections
2895 * @param int $origin_position
2896 * @param int $target_position
2897 * @return array
2898 */
2899function reorder_sections($sections, $origin_position, $target_position) {
2900 if (!is_array($sections)) {
2901 return false;
2902 }
2903
2904 // We can't move section position 0
2905 if ($origin_position < 1) {
2906 echo "We can't move section position 0";
2907 return false;
2908 }
2909
2910 // Locate origin section in sections array
2911 if (!$origin_key = array_search($origin_position, $sections)) {
2912 echo "searched position not in sections array";
2913 return false; // searched position not in sections array
2914 }
2915
2916 // Extract origin section
2917 $origin_section = $sections[$origin_key];
2918 unset($sections[$origin_key]);
2919
2920 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
2921 $found = false;
2922 $append_array = array();
2923 foreach ($sections as $id => $position) {
2924 if ($found) {
2925 $append_array[$id] = $position;
2926 unset($sections[$id]);
2927 }
2928 if ($position == $target_position) {
eb01aa2c
RT
2929 if ($target_position < $origin_position) {
2930 $append_array[$id] = $position;
2931 unset($sections[$id]);
2932 }
3440ec12 2933 $found = true;
2934 }
2935 }
2936
2937 // Append moved section
2938 $sections[$origin_key] = $origin_section;
2939
2940 // Append rest of array (if applicable)
2941 if (!empty($append_array)) {
2942 foreach ($append_array as $id => $position) {
2943 $sections[$id] = $position;
2944 }
2945 }
2946
2947 // Renumber positions
2948 $position = 0;
2949 foreach ($sections as $id => $p) {
2950 $sections[$id] = $position;
2951 $position++;
2952 }
2953
2954 return $sections;
2955
2956}
2957
cb6fec1f 2958/**
2959 * Move the module object $mod to the specified $section
2960 * If $beforemod exists then that is the module
2961 * before which $modid should be inserted
2962 * All parameters are objects
2963 */
7977cffd 2964function moveto_module($mod, $section, $beforemod=NULL) {
38b19bbc 2965 global $OUTPUT;
7977cffd 2966
2967/// Remove original module from original section
7977cffd 2968 if (! delete_mod_from_section($mod->id, $mod->section)) {
e6db3026 2969 echo $OUTPUT->notification("Could not delete module from existing section");
7977cffd 2970 }
2971
722e6ba9
MG
2972 // if moving to a hidden section then hide module
2973 if (!$section->visible && $mod->visible) {
2974 set_coursemodule_visible($mod->id, 0);
7977cffd 2975 }
2976
2977/// Add the module into the new section
722e6ba9 2978 course_add_cm_to_section($section->course, $mod->id, $section->section, $beforemod);
7977cffd 2979 return true;
7977cffd 2980}
2981
7749e187
SH
2982/**
2983 * Produces the editing buttons for a module
2984 *
2985 * @global core_renderer $OUTPUT
2986 * @staticvar type $str
2987 * @param stdClass $mod The module to produce editing buttons for
f558b291
MG
2988 * @param bool $absolute_ignored (argument ignored) - all links are absolute
2989 * @param bool $moveselect (argument ignored)
7749e187
SH
2990 * @param int $indent The current indenting
2991 * @param int $section The section to link back to
2992 * @return string XHTML for the editing buttons
2993 */
923451c5 2994function make_editing_buttons(stdClass $mod, $absolute_ignored = true, $moveselect = true, $indent=-1, $section=null) {
f558b291
MG
2995 global $PAGE;
2996 if (!($mod instanceof cm_info)) {
2997 $modinfo = get_fast_modinfo($mod->course);
2998 $mod = $modinfo->get_cm($mod->id);
2999 }
3000 $actions = course_get_cm_edit_actions($mod, $indent, $section);
3001
3002 $courserenderer = $PAGE->get_renderer('core', 'course');
3003 // The space added before the <span> is a ugly hack but required to set the CSS property white-space: nowrap
3004 // and having it to work without attaching the preceding text along with it. Hopefully the refactoring of
3005 // the course page HTML will allow this to be removed.
3006 return ' ' . $courserenderer->course_section_cm_edit_actions($actions);
3007}
3008
3009/**
3010 * Returns the list of all editing actions that current user can perform on the module
3011 *
3012 * @param cm_info $mod The module to produce editing buttons for
3013 * @param int $indent The current indenting (default -1 means no move left-right actions)
3014 * @param int $sr The section to link back to (used for creating the links)
3015 * @return array array of action_link or pix_icon objects
3016 */
3017function course_get_cm_edit_actions(cm_info $mod, $indent = -1, $sr = null) {
3018 global $COURSE, $SITE;
94361e02 3019
3d575e6f 3020 static $str;
3021
9a5e297b
AA
3022 $coursecontext = context_course::instance($mod->course);
3023 $modcontext = context_module::instance($mod->id);
7749e187 3024
af189935
PS
3025 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
3026 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
3027
3028 // no permission to edit anything
3029 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
f558b291 3030 return array();
217a8ee9 3031 }
3032
af189935
PS
3033 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
3034
3d575e6f 3035 if (!isset($str)) {
f558b291
MG
3036 $str = get_strings(array('delete', 'move', 'moveright', 'moveleft',
3037 'update', 'duplicate', 'hide', 'show', 'edittitle'), 'moodle');
3038 $str->assign = get_string('assignroles', 'role');
6dc5908e
ARN
3039 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
3040 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
3041 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
3042 $str->forcedgroupsnone = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsnone"));
3043 $str->forcedgroupsseparate = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsseparate"));
3044 $str->forcedgroupsvisible = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsvisible"));
1acfbce5 3045 }
94361e02 3046
af189935 3047 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
24e1eae4 3048
f558b291
MG
3049 if ($sr !== null) {
3050 $baseurl->param('sr', $sr);
7749e187
SH
3051 }
3052 $actions = array();
3053
7a9a07d2 3054 // AJAX edit title
f558b291
MG
3055 if ($mod->modname !== 'label' && $hasmanageactivities &&
3056 (($mod->course == $COURSE->id && course_ajax_enabled($COURSE)) ||
3057 ($mod->course == SITEID && course_ajax_enabled($SITE)))) {
3058 // we will not display link if we are on some other-course page (where we should not see this module anyway)
3059 $actions['title'] = new action_link(
7a9a07d2 3060 new moodle_url($baseurl, array('update' => $mod->id)),
aad982aa 3061 new pix_icon('t/editstring', $str->edittitle, 'moodle', array('class' => 'iconsmall visibleifjs', 'title' => '')),
7a9a07d2
ARN
3062 null,
3063 array('class' => 'editing_title', 'title' => $str->edittitle)
3064 );
3065 }
3066
7749e187 3067 // leftright
af189935 3068 if ($hasmanageactivities) {
7749e187
SH
3069 if (right_to_left()) { // Exchange arrows on RTL
3070 $rightarrow = 't/left';
3071 $leftarrow = 't/right';
3072 } else {
3073 $rightarrow = 't/right';
3074 $leftarrow = 't/left';
3075 }
3076
3077 if ($indent > 0) {
f558b291 3078 $actions['moveleft'] = new action_link(
7749e187 3079 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
aad982aa 3080 new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall', 'title' => '')),
7749e187
SH
3081 null,
3082 array('class' => 'editing_moveleft', 'title' => $str->moveleft)
3083 );
3084 }
3085 if ($indent >= 0) {
f558b291 3086 $actions['moveright'] = new action_link(
7749e187 3087 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
aad982aa 3088 new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall', 'title' => '')),
7749e187
SH
3089 null,
3090 array('class' => 'editing_moveright', 'title' => $str->moveright)
3091 );
3092 }
dc0dc7d5 3093 }
7749e187
SH
3094
3095 // move
af189935 3096 if ($hasmanageactivities) {
f558b291
MG
3097 $actions['move'] = new action_link(
3098 new moodle_url($baseurl, array('copy' => $mod->id)),
3099 new pix_icon('t/move', $str->move, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3100 null,
3101 array('class' => 'editing_move', 'title' => $str->move)
3102 );
7749e187
SH
3103 }
3104
3105 // Update
af189935 3106 if ($hasmanageactivities) {
f558b291 3107 $actions['update'] = new action_link(
af189935 3108 new moodle_url($baseurl, array('update' => $mod->id)),
aad982aa 3109 new pix_icon('t/edit', $str->update, 'moodle', array('class' => 'iconsmall', 'title' => '')),
af189935
PS
3110 null,
3111 array('class' => 'editing_update', 'title' => $str->update)
3112 );
3113 }
7749e187 3114
8a1a951f 3115 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
f558b291
MG
3116 // note that restoring on front page is never allowed
3117 if ($mod->course != SITEID && has_all_capabilities($dupecaps, $coursecontext) &&
3118 plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2)) {
3119 $actions['duplicate'] = new action_link(
8645a28f 3120 new moodle_url($baseurl, array('duplicate' => $mod->id)),
aad982aa 3121 new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall', 'title' => '')),
8645a28f
EL
3122 null,
3123 array('class' => 'editing_duplicate', 'title' => $str->duplicate)
3124 );
3125 }
7749e187
SH
3126
3127 // Delete
af189935 3128 if ($hasmanageactivities) {
f558b291 3129 $actions['delete'] = new action_link(
af189935 3130 new moodle_url($baseurl, array('delete' => $mod->id)),
aad982aa 3131 new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall', 'title' => '')),
af189935
PS
3132 null,
3133 array('class' => 'editing_delete', 'title' => $str->delete)