MDL-29199 dml: fix query logging on Oracle
[moodle.git] / course / lib.php
blob2a1f01a2d43330e9279ac3d21cf14fe368a90ced
1 <?php
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.
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/>.
18 /**
19 * Library of useful functions
21 * @copyright 1999 Martin Dougiamas http://dougiamas.com
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 * @package core
24 * @subpackage course
27 defined('MOODLE_INTERNAL') || die;
29 require_once($CFG->libdir.'/completionlib.php');
30 require_once($CFG->libdir.'/filelib.php');
32 define('COURSE_MAX_LOGS_PER_PAGE', 1000); // records
33 define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds
34 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10); // courses
35 define('COURSE_MAX_COURSES_PER_DROPDOWN',1000); // max courses in log dropdown before switching to optional
36 define('COURSE_MAX_USERS_PER_DROPDOWN',1000); // max users in log dropdown before switching to optional
37 define('FRONTPAGENEWS', '0');
38 define('FRONTPAGECOURSELIST', '1');
39 define('FRONTPAGECATEGORYNAMES', '2');
40 define('FRONTPAGETOPICONLY', '3');
41 define('FRONTPAGECATEGORYCOMBO', '4');
42 define('FRONTPAGECOURSELIMIT', 200); // maximum number of courses displayed on the frontpage
43 define('EXCELROWS', 65535);
44 define('FIRSTUSEDEXCELROW', 3);
46 define('MOD_CLASS_ACTIVITY', 0);
47 define('MOD_CLASS_RESOURCE', 1);
49 function make_log_url($module, $url) {
50 switch ($module) {
51 case 'course':
52 if (strpos($url, 'report/') === 0) {
53 // there is only one report type, course reports are deprecated
54 $url = "/$url";
55 break;
57 case 'file':
58 case 'login':
59 case 'lib':
60 case 'admin':
61 case 'calendar':
62 case 'mnet course':
63 if (strpos($url, '../') === 0) {
64 $url = ltrim($url, '.');
65 } else {
66 $url = "/course/$url";
68 break;
69 case 'user':
70 case 'blog':
71 $url = "/$module/$url";
72 break;
73 case 'upload':
74 $url = $url;
75 break;
76 case 'coursetags':
77 $url = '/'.$url;
78 break;
79 case 'library':
80 case '':
81 $url = '/';
82 break;
83 case 'message':
84 $url = "/message/$url";
85 break;
86 case 'notes':
87 $url = "/notes/$url";
88 break;
89 case 'tag':
90 $url = "/tag/$url";
91 break;
92 case 'role':
93 $url = '/'.$url;
94 break;
95 default:
96 $url = "/mod/$module/$url";
97 break;
100 //now let's sanitise urls - there might be some ugly nasties:-(
101 $parts = explode('?', $url);
102 $script = array_shift($parts);
103 if (strpos($script, 'http') === 0) {
104 $script = clean_param($script, PARAM_URL);
105 } else {
106 $script = clean_param($script, PARAM_PATH);
109 $query = '';
110 if ($parts) {
111 $query = implode('', $parts);
112 $query = str_replace('&amp;', '&', $query); // both & and &amp; are stored in db :-|
113 $parts = explode('&', $query);
114 $eq = urlencode('=');
115 foreach ($parts as $key=>$part) {
116 $part = urlencode(urldecode($part));
117 $part = str_replace($eq, '=', $part);
118 $parts[$key] = $part;
120 $query = '?'.implode('&amp;', $parts);
123 return $script.$query;
127 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
128 $modname="", $modid=0, $modaction="", $groupid=0) {
129 global $CFG, $DB;
131 // It is assumed that $date is the GMT time of midnight for that day,
132 // and so the next 86400 seconds worth of logs are printed.
134 /// Setup for group handling.
136 // TODO: I don't understand group/context/etc. enough to be able to do
137 // something interesting with it here
138 // What is the context of a remote course?
140 /// If the group mode is separate, and this user does not have editing privileges,
141 /// then only the user's group can be viewed.
142 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
143 // $groupid = get_current_group($course->id);
145 /// If this course doesn't have groups, no groupid can be specified.
146 //else if (!$course->groupmode) {
147 // $groupid = 0;
150 $groupid = 0;
152 $joins = array();
153 $where = '';
155 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
156 FROM {mnet_log} l
157 LEFT JOIN {user} u ON l.userid = u.id
158 WHERE ";
159 $params = array();
161 $where .= "l.hostid = :hostid";
162 $params['hostid'] = $hostid;
164 // TODO: Is 1 really a magic number referring to the sitename?
165 if ($course != SITEID || $modid != 0) {
166 $where .= " AND l.course=:courseid";
167 $params['courseid'] = $course;
170 if ($modname) {
171 $where .= " AND l.module = :modname";
172 $params['modname'] = $modname;
175 if ('site_errors' === $modid) {
176 $where .= " AND ( l.action='error' OR l.action='infected' )";
177 } else if ($modid) {
178 //TODO: This assumes that modids are the same across sites... probably
179 //not true
180 $where .= " AND l.cmid = :modid";
181 $params['modid'] = $modid;
184 if ($modaction) {
185 $firstletter = substr($modaction, 0, 1);
186 if ($firstletter == '-') {
187 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
188 $params['modaction'] = '%'.substr($modaction, 1).'%';
189 } else {
190 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
191 $params['modaction'] = '%'.$modaction.'%';
195 if ($user) {
196 $where .= " AND l.userid = :user";
197 $params['user'] = $user;
200 if ($date) {
201 $enddate = $date + 86400;
202 $where .= " AND l.time > :date AND l.time < :enddate";
203 $params['date'] = $date;
204 $params['enddate'] = $enddate;
207 $result = array();
208 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
209 if(!empty($result['totalcount'])) {
210 $where .= " ORDER BY $order";
211 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
212 } else {
213 $result['logs'] = array();
215 return $result;
218 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
219 $modname="", $modid=0, $modaction="", $groupid=0) {
220 global $DB, $SESSION, $USER;
221 // It is assumed that $date is the GMT time of midnight for that day,
222 // and so the next 86400 seconds worth of logs are printed.
224 /// Setup for group handling.
226 /// If the group mode is separate, and this user does not have editing privileges,
227 /// then only the user's group can be viewed.
228 if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
229 if (isset($SESSION->currentgroup[$course->id])) {
230 $groupid = $SESSION->currentgroup[$course->id];
231 } else {
232 $groupid = groups_get_all_groups($course->id, $USER->id);
233 if (is_array($groupid)) {
234 $groupid = array_shift(array_keys($groupid));
235 $SESSION->currentgroup[$course->id] = $groupid;
236 } else {
237 $groupid = 0;
241 /// If this course doesn't have groups, no groupid can be specified.
242 else if (!$course->groupmode) {
243 $groupid = 0;
246 $joins = array();
247 $params = array();
249 if ($course->id != SITEID || $modid != 0) {
250 $joins[] = "l.course = :courseid";
251 $params['courseid'] = $course->id;
254 if ($modname) {
255 $joins[] = "l.module = :modname";
256 $params['modname'] = $modname;
259 if ('site_errors' === $modid) {
260 $joins[] = "( l.action='error' OR l.action='infected' )";
261 } else if ($modid) {
262 $joins[] = "l.cmid = :modid";
263 $params['modid'] = $modid;
266 if ($modaction) {
267 $firstletter = substr($modaction, 0, 1);
268 if ($firstletter == '-') {
269 $joins[] = $DB->sql_like('l.action', ':modaction', false, true, true);
270 $params['modaction'] = '%'.substr($modaction, 1).'%';
271 } else {
272 $joins[] = $DB->sql_like('l.action', ':modaction', false);
273 $params['modaction'] = '%'.$modaction.'%';
278 /// Getting all members of a group.
279 if ($groupid and !$user) {
280 if ($gusers = groups_get_members($groupid)) {
281 $gusers = array_keys($gusers);
282 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
283 } else {
284 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
287 else if ($user) {
288 $joins[] = "l.userid = :userid";
289 $params['userid'] = $user;
292 if ($date) {
293 $enddate = $date + 86400;
294 $joins[] = "l.time > :date AND l.time < :enddate";
295 $params['date'] = $date;
296 $params['enddate'] = $enddate;
299 $selector = implode(' AND ', $joins);
301 $totalcount = 0; // Initialise
302 $result = array();
303 $result['logs'] = get_logs($selector, $params, $order, $limitfrom, $limitnum, $totalcount);
304 $result['totalcount'] = $totalcount;
305 return $result;
309 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
310 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
312 global $CFG, $DB, $OUTPUT;
314 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
315 $modname, $modid, $modaction, $groupid)) {
316 echo $OUTPUT->notification("No logs found!");
317 echo $OUTPUT->footer();
318 exit;
321 $courses = array();
323 if ($course->id == SITEID) {
324 $courses[0] = '';
325 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
326 foreach ($ccc as $cc) {
327 $courses[$cc->id] = $cc->shortname;
330 } else {
331 $courses[$course->id] = $course->shortname;
334 $totalcount = $logs['totalcount'];
335 $count=0;
336 $ldcache = array();
337 $tt = getdate(time());
338 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
340 $strftimedatetime = get_string("strftimedatetime");
342 echo "<div class=\"info\">\n";
343 print_string("displayingrecords", "", $totalcount);
344 echo "</div>\n";
346 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
348 $table = new html_table();
349 $table->classes = array('logtable','generalbox');
350 $table->align = array('right', 'left', 'left');
351 $table->head = array(
352 get_string('time'),
353 get_string('ip_address'),
354 get_string('fullnameuser'),
355 get_string('action'),
356 get_string('info')
358 $table->data = array();
360 if ($course->id == SITEID) {
361 array_unshift($table->align, 'left');
362 array_unshift($table->head, get_string('course'));
365 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
366 if (empty($logs['logs'])) {
367 $logs['logs'] = array();
370 foreach ($logs['logs'] as $log) {
372 if (isset($ldcache[$log->module][$log->action])) {
373 $ld = $ldcache[$log->module][$log->action];
374 } else {
375 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
376 $ldcache[$log->module][$log->action] = $ld;
378 if ($ld && is_numeric($log->info)) {
379 // ugly hack to make sure fullname is shown correctly
380 if ($ld->mtable == 'user' && $ld->field == $DB->sql_concat('firstname', "' '" , 'lastname')) {
381 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
382 } else {
383 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
387 //Filter log->info
388 $log->info = format_string($log->info);
390 // If $log->url has been trimmed short by the db size restriction
391 // code in add_to_log, keep a note so we don't add a link to a broken url
392 $tl=textlib_get_instance();
393 $brokenurl=($tl->strlen($log->url)==100 && $tl->substr($log->url,97)=='...');
395 $row = array();
396 if ($course->id == SITEID) {
397 if (empty($log->course)) {
398 $row[] = get_string('site');
399 } else {
400 $row[] = "<a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course])."</a>";
404 $row[] = userdate($log->time, '%a').' '.userdate($log->time, $strftimedatetime);
406 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
407 $row[] = $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 440, 'width' => 700)));
409 $row[] = html_writer::link(new moodle_url("/user/view.php?id={$log->userid}&course={$log->course}"), fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id))));
411 $displayaction="$log->module $log->action";
412 if ($brokenurl) {
413 $row[] = $displayaction;
414 } else {
415 $link = make_log_url($log->module,$log->url);
416 $row[] = $OUTPUT->action_link($link, $displayaction, new popup_action('click', $link, 'fromloglive'), array('height' => 440, 'width' => 700));
418 $row[] = $log->info;
419 $table->data[] = $row;
422 echo html_writer::table($table);
423 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
427 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
428 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
430 global $CFG, $DB, $OUTPUT;
432 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
433 $modname, $modid, $modaction, $groupid)) {
434 echo $OUTPUT->notification("No logs found!");
435 echo $OUTPUT->footer();
436 exit;
439 if ($course->id == SITEID) {
440 $courses[0] = '';
441 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
442 foreach ($ccc as $cc) {
443 $courses[$cc->id] = $cc->shortname;
448 $totalcount = $logs['totalcount'];
449 $count=0;
450 $ldcache = array();
451 $tt = getdate(time());
452 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
454 $strftimedatetime = get_string("strftimedatetime");
456 echo "<div class=\"info\">\n";
457 print_string("displayingrecords", "", $totalcount);
458 echo "</div>\n";
460 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
462 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
463 echo "<tr>";
464 if ($course->id == SITEID) {
465 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
467 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
468 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
469 echo "<th class=\"c3 header\">".get_string('fullnameuser')."</th>\n";
470 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
471 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
472 echo "</tr>\n";
474 if (empty($logs['logs'])) {
475 echo "</table>\n";
476 return;
479 $row = 1;
480 foreach ($logs['logs'] as $log) {
482 $log->info = $log->coursename;
483 $row = ($row + 1) % 2;
485 if (isset($ldcache[$log->module][$log->action])) {
486 $ld = $ldcache[$log->module][$log->action];
487 } else {
488 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
489 $ldcache[$log->module][$log->action] = $ld;
491 if (0 && $ld && !empty($log->info)) {
492 // ugly hack to make sure fullname is shown correctly
493 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
494 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
495 } else {
496 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
500 //Filter log->info
501 $log->info = format_string($log->info);
503 echo '<tr class="r'.$row.'">';
504 if ($course->id == SITEID) {
505 $courseshortname = format_string($courses[$log->course], true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
506 echo "<td class=\"r$row c0\" >\n";
507 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courseshortname."</a>\n";
508 echo "</td>\n";
510 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time, '%a').
511 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
512 echo "<td class=\"r$row c2\" >\n";
513 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
514 echo $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 400, 'width' => 700)));
515 echo "</td>\n";
516 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
517 echo "<td class=\"r$row c3\" >\n";
518 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
519 echo "</td>\n";
520 echo "<td class=\"r$row c4\">\n";
521 echo $log->action .': '.$log->module;
522 echo "</td>\n";;
523 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
524 echo "</tr>\n";
526 echo "</table>\n";
528 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
532 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
533 $modid, $modaction, $groupid) {
534 global $DB;
536 $text = get_string('course')."\t".get_string('time')."\t".get_string('ip_address')."\t".
537 get_string('fullnameuser')."\t".get_string('action')."\t".get_string('info');
539 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
540 $modname, $modid, $modaction, $groupid)) {
541 return false;
544 $courses = array();
546 if ($course->id == SITEID) {
547 $courses[0] = '';
548 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
549 foreach ($ccc as $cc) {
550 $courses[$cc->id] = $cc->shortname;
553 } else {
554 $courses[$course->id] = $course->shortname;
557 $count=0;
558 $ldcache = array();
559 $tt = getdate(time());
560 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
562 $strftimedatetime = get_string("strftimedatetime");
564 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
565 $filename .= '.txt';
566 header("Content-Type: application/download\n");
567 header("Content-Disposition: attachment; filename=$filename");
568 header("Expires: 0");
569 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
570 header("Pragma: public");
572 echo get_string('savedat').userdate(time(), $strftimedatetime)."\n";
573 echo $text."\n";
575 if (empty($logs['logs'])) {
576 return true;
579 foreach ($logs['logs'] as $log) {
580 if (isset($ldcache[$log->module][$log->action])) {
581 $ld = $ldcache[$log->module][$log->action];
582 } else {
583 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
584 $ldcache[$log->module][$log->action] = $ld;
586 if ($ld && !empty($log->info)) {
587 // ugly hack to make sure fullname is shown correctly
588 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
589 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
590 } else {
591 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
595 //Filter log->info
596 $log->info = format_string($log->info);
597 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
599 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
600 $firstField = format_string($courses[$log->course], true, array('context' => $coursecontext));
601 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
602 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action, $log->info);
603 $text = implode("\t", $row);
604 echo $text." \n";
606 return true;
610 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
611 $modid, $modaction, $groupid) {
613 global $CFG, $DB;
615 require_once("$CFG->libdir/excellib.class.php");
617 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
618 $modname, $modid, $modaction, $groupid)) {
619 return false;
622 $courses = array();
624 if ($course->id == SITEID) {
625 $courses[0] = '';
626 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
627 foreach ($ccc as $cc) {
628 $courses[$cc->id] = $cc->shortname;
631 } else {
632 $courses[$course->id] = $course->shortname;
635 $count=0;
636 $ldcache = array();
637 $tt = getdate(time());
638 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
640 $strftimedatetime = get_string("strftimedatetime");
642 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
643 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
644 $filename .= '.xls';
646 $workbook = new MoodleExcelWorkbook('-');
647 $workbook->send($filename);
649 $worksheet = array();
650 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
651 get_string('fullnameuser'), get_string('action'), get_string('info'));
653 // Creating worksheets
654 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
655 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
656 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
657 $worksheet[$wsnumber]->set_column(1, 1, 30);
658 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
659 userdate(time(), $strftimedatetime));
660 $col = 0;
661 foreach ($headers as $item) {
662 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
663 $col++;
667 if (empty($logs['logs'])) {
668 $workbook->close();
669 return true;
672 $formatDate =& $workbook->add_format();
673 $formatDate->set_num_format(get_string('log_excel_date_format'));
675 $row = FIRSTUSEDEXCELROW;
676 $wsnumber = 1;
677 $myxls =& $worksheet[$wsnumber];
678 foreach ($logs['logs'] as $log) {
679 if (isset($ldcache[$log->module][$log->action])) {
680 $ld = $ldcache[$log->module][$log->action];
681 } else {
682 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
683 $ldcache[$log->module][$log->action] = $ld;
685 if ($ld && !empty($log->info)) {
686 // ugly hack to make sure fullname is shown correctly
687 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
688 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
689 } else {
690 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
694 // Filter log->info
695 $log->info = format_string($log->info);
696 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
698 if ($nroPages>1) {
699 if ($row > EXCELROWS) {
700 $wsnumber++;
701 $myxls =& $worksheet[$wsnumber];
702 $row = FIRSTUSEDEXCELROW;
706 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
708 $myxls->write($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)), '');
709 $myxls->write_date($row, 1, $log->time, $formatDate); // write_date() does conversion/timezone support. MDL-14934
710 $myxls->write($row, 2, $log->ip, '');
711 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
712 $myxls->write($row, 3, $fullname, '');
713 $myxls->write($row, 4, $log->module.' '.$log->action, '');
714 $myxls->write($row, 5, $log->info, '');
716 $row++;
719 $workbook->close();
720 return true;
723 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
724 $modid, $modaction, $groupid) {
726 global $CFG, $DB;
728 require_once("$CFG->libdir/odslib.class.php");
730 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
731 $modname, $modid, $modaction, $groupid)) {
732 return false;
735 $courses = array();
737 if ($course->id == SITEID) {
738 $courses[0] = '';
739 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
740 foreach ($ccc as $cc) {
741 $courses[$cc->id] = $cc->shortname;
744 } else {
745 $courses[$course->id] = $course->shortname;
748 $count=0;
749 $ldcache = array();
750 $tt = getdate(time());
751 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
753 $strftimedatetime = get_string("strftimedatetime");
755 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
756 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
757 $filename .= '.ods';
759 $workbook = new MoodleODSWorkbook('-');
760 $workbook->send($filename);
762 $worksheet = array();
763 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
764 get_string('fullnameuser'), get_string('action'), get_string('info'));
766 // Creating worksheets
767 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
768 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
769 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
770 $worksheet[$wsnumber]->set_column(1, 1, 30);
771 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
772 userdate(time(), $strftimedatetime));
773 $col = 0;
774 foreach ($headers as $item) {
775 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
776 $col++;
780 if (empty($logs['logs'])) {
781 $workbook->close();
782 return true;
785 $formatDate =& $workbook->add_format();
786 $formatDate->set_num_format(get_string('log_excel_date_format'));
788 $row = FIRSTUSEDEXCELROW;
789 $wsnumber = 1;
790 $myxls =& $worksheet[$wsnumber];
791 foreach ($logs['logs'] as $log) {
792 if (isset($ldcache[$log->module][$log->action])) {
793 $ld = $ldcache[$log->module][$log->action];
794 } else {
795 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
796 $ldcache[$log->module][$log->action] = $ld;
798 if ($ld && !empty($log->info)) {
799 // ugly hack to make sure fullname is shown correctly
800 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
801 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
802 } else {
803 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
807 // Filter log->info
808 $log->info = format_string($log->info);
809 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
811 if ($nroPages>1) {
812 if ($row > EXCELROWS) {
813 $wsnumber++;
814 $myxls =& $worksheet[$wsnumber];
815 $row = FIRSTUSEDEXCELROW;
819 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
821 $myxls->write_string($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)));
822 $myxls->write_date($row, 1, $log->time);
823 $myxls->write_string($row, 2, $log->ip);
824 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
825 $myxls->write_string($row, 3, $fullname);
826 $myxls->write_string($row, 4, $log->module.' '.$log->action);
827 $myxls->write_string($row, 5, $log->info);
829 $row++;
832 $workbook->close();
833 return true;
837 function print_overview($courses, array $remote_courses=array()) {
838 global $CFG, $USER, $DB, $OUTPUT;
840 $htmlarray = array();
841 if ($modules = $DB->get_records('modules')) {
842 foreach ($modules as $mod) {
843 if (file_exists(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php')) {
844 include_once(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php');
845 $fname = $mod->name.'_print_overview';
846 if (function_exists($fname)) {
847 $fname($courses,$htmlarray);
852 foreach ($courses as $course) {
853 $fullname = format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
854 echo $OUTPUT->box_start('coursebox');
855 $attributes = array('title' => s($fullname));
856 if (empty($course->visible)) {
857 $attributes['class'] = 'dimmed';
859 echo $OUTPUT->heading(html_writer::link(
860 new moodle_url('/course/view.php', array('id' => $course->id)), $fullname, $attributes), 3);
861 if (array_key_exists($course->id,$htmlarray)) {
862 foreach ($htmlarray[$course->id] as $modname => $html) {
863 echo $html;
866 echo $OUTPUT->box_end();
869 if (!empty($remote_courses)) {
870 echo $OUTPUT->heading(get_string('remotecourses', 'mnet'));
872 foreach ($remote_courses as $course) {
873 echo $OUTPUT->box_start('coursebox');
874 $attributes = array('title' => s($course->fullname));
875 echo $OUTPUT->heading(html_writer::link(
876 new moodle_url('/auth/mnet/jump.php', array('hostid' => $course->hostid, 'wantsurl' => '/course/view.php?id='.$course->remoteid)),
877 format_string($course->shortname),
878 $attributes) . ' (' . format_string($course->hostname) . ')', 3);
879 echo $OUTPUT->box_end();
885 * This function trawls through the logs looking for
886 * anything new since the user's last login
888 function print_recent_activity($course) {
889 // $course is an object
890 global $CFG, $USER, $SESSION, $DB, $OUTPUT;
892 $context = get_context_instance(CONTEXT_COURSE, $course->id);
894 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
896 $timestart = round(time() - COURSE_MAX_RECENT_PERIOD, -2); // better db caching for guests - 100 seconds
898 if (!isguestuser()) {
899 if (!empty($USER->lastcourseaccess[$course->id])) {
900 if ($USER->lastcourseaccess[$course->id] > $timestart) {
901 $timestart = $USER->lastcourseaccess[$course->id];
906 echo '<div class="activitydate">';
907 echo get_string('activitysince', '', userdate($timestart));
908 echo '</div>';
909 echo '<div class="activityhead">';
911 echo '<a href="'.$CFG->wwwroot.'/course/recent.php?id='.$course->id.'">'.get_string('recentactivityreport').'</a>';
913 echo "</div>\n";
915 $content = false;
917 /// Firstly, have there been any new enrolments?
919 $users = get_recent_enrolments($course->id, $timestart);
921 //Accessibility: new users now appear in an <OL> list.
922 if ($users) {
923 echo '<div class="newusers">';
924 echo $OUTPUT->heading(get_string("newusers").':', 3);
925 $content = true;
926 echo "<ol class=\"list\">\n";
927 foreach ($users as $user) {
928 $fullname = fullname($user, $viewfullnames);
929 echo '<li class="name"><a href="'."$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a></li>\n";
931 echo "</ol>\n</div>\n";
934 /// Next, have there been any modifications to the course structure?
936 $modinfo =& get_fast_modinfo($course);
938 $changelist = array();
940 $logs = $DB->get_records_select('log', "time > ? AND course = ? AND
941 module = 'course' AND
942 (action = 'add mod' OR action = 'update mod' OR action = 'delete mod')",
943 array($timestart, $course->id), "id ASC");
945 if ($logs) {
946 $actions = array('add mod', 'update mod', 'delete mod');
947 $newgones = array(); // added and later deleted items
948 foreach ($logs as $key => $log) {
949 if (!in_array($log->action, $actions)) {
950 continue;
952 $info = explode(' ', $log->info);
954 // note: in most cases I replaced hardcoding of label with use of
955 // $cm->has_view() but it was not possible to do this here because
956 // we don't necessarily have the $cm for it
957 if ($info[0] == 'label') { // Labels are ignored in recent activity
958 continue;
961 if (count($info) != 2) {
962 debugging("Incorrect log entry info: id = ".$log->id, DEBUG_DEVELOPER);
963 continue;
966 $modname = $info[0];
967 $instanceid = $info[1];
969 if ($log->action == 'delete mod') {
970 // unfortunately we do not know if the mod was visible
971 if (!array_key_exists($log->info, $newgones)) {
972 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $modname));
973 $changelist[$log->info] = array ('operation' => 'delete', 'text' => $strdeleted);
975 } else {
976 if (!isset($modinfo->instances[$modname][$instanceid])) {
977 if ($log->action == 'add mod') {
978 // do not display added and later deleted activities
979 $newgones[$log->info] = true;
981 continue;
983 $cm = $modinfo->instances[$modname][$instanceid];
984 if (!$cm->uservisible) {
985 continue;
988 if ($log->action == 'add mod') {
989 $stradded = get_string('added', 'moodle', get_string('modulename', $modname));
990 $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>");
992 } else if ($log->action == 'update mod' and empty($changelist[$log->info])) {
993 $strupdated = get_string('updated', 'moodle', get_string('modulename', $modname));
994 $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>");
1000 if (!empty($changelist)) {
1001 echo $OUTPUT->heading(get_string("courseupdates").':', 3);
1002 $content = true;
1003 foreach ($changelist as $changeinfo => $change) {
1004 echo '<p class="activity">'.$change['text'].'</p>';
1008 /// Now display new things from each module
1010 $usedmodules = array();
1011 foreach($modinfo->cms as $cm) {
1012 if (isset($usedmodules[$cm->modname])) {
1013 continue;
1015 if (!$cm->uservisible) {
1016 continue;
1018 $usedmodules[$cm->modname] = $cm->modname;
1021 foreach ($usedmodules as $modname) { // Each module gets it's own logs and prints them
1022 if (file_exists($CFG->dirroot.'/mod/'.$modname.'/lib.php')) {
1023 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
1024 $print_recent_activity = $modname.'_print_recent_activity';
1025 if (function_exists($print_recent_activity)) {
1026 // NOTE: original $isteacher (second parameter below) was replaced with $viewfullnames!
1027 $content = $print_recent_activity($course, $viewfullnames, $timestart) || $content;
1029 } else {
1030 debugging("Missing lib.php in lib/{$modname} - please reinstall files or uninstall the module");
1034 if (! $content) {
1035 echo '<p class="message">'.get_string('nothingnew').'</p>';
1040 * For a given course, returns an array of course activity objects
1041 * Each item in the array contains he following properties:
1043 function get_array_of_activities($courseid) {
1044 // cm - course module id
1045 // mod - name of the module (eg forum)
1046 // section - the number of the section (eg week or topic)
1047 // name - the name of the instance
1048 // visible - is the instance visible or not
1049 // groupingid - grouping id
1050 // groupmembersonly - is this instance visible to group members only
1051 // extra - contains extra string to include in any link
1052 global $CFG, $DB;
1053 if(!empty($CFG->enableavailability)) {
1054 require_once($CFG->libdir.'/conditionlib.php');
1057 $course = $DB->get_record('course', array('id'=>$courseid));
1059 if (empty($course)) {
1060 throw new moodle_exception('courseidnotfound');
1063 $mod = array();
1065 $rawmods = get_course_mods($courseid);
1066 if (empty($rawmods)) {
1067 return $mod; // always return array
1070 if ($sections = $DB->get_records("course_sections", array("course"=>$courseid), "section ASC")) {
1071 foreach ($sections as $section) {
1072 if (!empty($section->sequence)) {
1073 $sequence = explode(",", $section->sequence);
1074 foreach ($sequence as $seq) {
1075 if (empty($rawmods[$seq])) {
1076 continue;
1078 $mod[$seq] = new stdClass();
1079 $mod[$seq]->id = $rawmods[$seq]->instance;
1080 $mod[$seq]->cm = $rawmods[$seq]->id;
1081 $mod[$seq]->mod = $rawmods[$seq]->modname;
1083 // Oh dear. Inconsistent names left here for backward compatibility.
1084 $mod[$seq]->section = $section->section;
1085 $mod[$seq]->sectionid = $rawmods[$seq]->section;
1087 $mod[$seq]->module = $rawmods[$seq]->module;
1088 $mod[$seq]->added = $rawmods[$seq]->added;
1089 $mod[$seq]->score = $rawmods[$seq]->score;
1090 $mod[$seq]->idnumber = $rawmods[$seq]->idnumber;
1091 $mod[$seq]->visible = $rawmods[$seq]->visible;
1092 $mod[$seq]->visibleold = $rawmods[$seq]->visibleold;
1093 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
1094 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
1095 $mod[$seq]->groupmembersonly = $rawmods[$seq]->groupmembersonly;
1096 $mod[$seq]->indent = $rawmods[$seq]->indent;
1097 $mod[$seq]->completion = $rawmods[$seq]->completion;
1098 $mod[$seq]->extra = "";
1099 $mod[$seq]->completiongradeitemnumber =
1100 $rawmods[$seq]->completiongradeitemnumber;
1101 $mod[$seq]->completionview = $rawmods[$seq]->completionview;
1102 $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected;
1103 $mod[$seq]->availablefrom = $rawmods[$seq]->availablefrom;
1104 $mod[$seq]->availableuntil = $rawmods[$seq]->availableuntil;
1105 $mod[$seq]->showavailability = $rawmods[$seq]->showavailability;
1106 $mod[$seq]->showdescription = $rawmods[$seq]->showdescription;
1107 if (!empty($CFG->enableavailability)) {
1108 condition_info::fill_availability_conditions($rawmods[$seq]);
1109 $mod[$seq]->conditionscompletion = $rawmods[$seq]->conditionscompletion;
1110 $mod[$seq]->conditionsgrade = $rawmods[$seq]->conditionsgrade;
1113 $modname = $mod[$seq]->mod;
1114 $functionname = $modname."_get_coursemodule_info";
1116 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
1117 continue;
1120 include_once("$CFG->dirroot/mod/$modname/lib.php");
1122 if ($hasfunction = function_exists($functionname)) {
1123 if ($info = $functionname($rawmods[$seq])) {
1124 if (!empty($info->icon)) {
1125 $mod[$seq]->icon = $info->icon;
1127 if (!empty($info->iconcomponent)) {
1128 $mod[$seq]->iconcomponent = $info->iconcomponent;
1130 if (!empty($info->name)) {
1131 $mod[$seq]->name = $info->name;
1133 if ($info instanceof cached_cm_info) {
1134 // When using cached_cm_info you can include three new fields
1135 // that aren't available for legacy code
1136 if (!empty($info->content)) {
1137 $mod[$seq]->content = $info->content;
1139 if (!empty($info->extraclasses)) {
1140 $mod[$seq]->extraclasses = $info->extraclasses;
1142 if (!empty($info->iconurl)) {
1143 $mod[$seq]->iconurl = $info->iconurl;
1145 if (!empty($info->onclick)) {
1146 $mod[$seq]->onclick = $info->onclick;
1148 if (!empty($info->customdata)) {
1149 $mod[$seq]->customdata = $info->customdata;
1151 } else {
1152 // When using a stdclass, the (horrible) deprecated ->extra field
1153 // is available for BC
1154 if (!empty($info->extra)) {
1155 $mod[$seq]->extra = $info->extra;
1160 // When there is no modname_get_coursemodule_info function,
1161 // but showdescriptions is enabled, then we use the 'intro'
1162 // and 'introformat' fields in the module table
1163 if (!$hasfunction && $rawmods[$seq]->showdescription) {
1164 if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
1165 array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
1166 // Set content from intro and introformat. Filters are disabled
1167 // because we filter it with format_text at display time
1168 $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
1169 $modvalues, $rawmods[$seq]->id, false);
1171 // To save making another query just below, put name in here
1172 $mod[$seq]->name = $modvalues->name;
1175 if (!isset($mod[$seq]->name)) {
1176 $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
1179 // Minimise the database size by unsetting default options when they are
1180 // 'empty'. This list corresponds to code in the cm_info constructor.
1181 foreach (array('idnumber', 'groupmode', 'groupingid', 'groupmembersonly',
1182 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
1183 'icon', 'iconcomponent', 'customdata', 'showavailability', 'availablefrom',
1184 'availableuntil', 'conditionscompletion', 'conditionsgrade',
1185 'completionview', 'completionexpected', 'score', 'showdescription')
1186 as $property) {
1187 if (property_exists($mod[$seq], $property) &&
1188 empty($mod[$seq]->{$property})) {
1189 unset($mod[$seq]->{$property});
1192 // Special case: this value is usually set to null, but may be 0
1193 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
1194 is_null($mod[$seq]->completiongradeitemnumber)) {
1195 unset($mod[$seq]->completiongradeitemnumber);
1201 return $mod;
1206 * Returns a number of useful structures for course displays
1208 function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
1209 global $CFG, $DB, $COURSE;
1211 $mods = array(); // course modules indexed by id
1212 $modnames = array(); // all course module names (except resource!)
1213 $modnamesplural= array(); // all course module names (plural form)
1214 $modnamesused = array(); // course module names used
1216 if ($allmods = $DB->get_records("modules")) {
1217 foreach ($allmods as $mod) {
1218 if (!file_exists("$CFG->dirroot/mod/$mod->name/lib.php")) {
1219 continue;
1221 if ($mod->visible) {
1222 $modnames[$mod->name] = get_string("modulename", "$mod->name");
1223 $modnamesplural[$mod->name] = get_string("modulenameplural", "$mod->name");
1226 collatorlib::asort($modnames);
1227 } else {
1228 print_error("nomodules", 'debug');
1231 $course = ($courseid==$COURSE->id) ? $COURSE : $DB->get_record('course',array('id'=>$courseid));
1232 $modinfo = get_fast_modinfo($course);
1234 if ($rawmods=$modinfo->cms) {
1235 foreach($rawmods as $mod) { // Index the mods
1236 if (empty($modnames[$mod->modname])) {
1237 continue;
1239 $mods[$mod->id] = $mod;
1240 $mods[$mod->id]->modfullname = $modnames[$mod->modname];
1241 if (!$mod->visible and !has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_COURSE, $courseid))) {
1242 continue;
1244 // Check groupings
1245 if (!groups_course_module_visible($mod)) {
1246 continue;
1248 $modnamesused[$mod->modname] = $modnames[$mod->modname];
1250 if ($modnamesused) {
1251 collatorlib::asort($modnamesused);
1257 * Returns an array of sections for the requested course id
1259 * This function stores the sections against the course id within a staticvar encase
1260 * of subsequent requests. This is used all over + in some standard libs and course
1261 * format callbacks so subsequent requests are a reality.
1263 * @staticvar array $coursesections
1264 * @param int $courseid
1265 * @return array Array of sections
1267 function get_all_sections($courseid) {
1268 global $DB;
1269 static $coursesections = array();
1270 if (!array_key_exists($courseid, $coursesections)) {
1271 $coursesections[$courseid] = $DB->get_records("course_sections", array("course"=>"$courseid"), "section",
1272 "section, id, course, name, summary, summaryformat, sequence, visible");
1274 return $coursesections[$courseid];
1278 * Returns the course section to display or 0 meaning show all sections. Returns 0 for guests.
1279 * It also sets the $USER->display cache to array($courseid=>return value)
1281 * @param int $courseid The course id
1282 * @return int Course section to display, 0 means all
1284 function course_get_display($courseid) {
1285 global $USER, $DB;
1287 if (!isloggedin() or isguestuser()) {
1288 //do not get settings in db for guests
1289 return 0; //return the implicit setting
1292 if (!isset($USER->display[$courseid])) {
1293 if (!$display = $DB->get_field('course_display', 'display', array('userid' => $USER->id, 'course'=>$courseid))) {
1294 $display = 0; // all sections option is not stored in DB, this makes the table much smaller
1296 //use display cache for one course only - we need to keep session small
1297 $USER->display = array($courseid => $display);
1300 return $USER->display[$courseid];
1304 * Show one section only or all sections.
1306 * @param int $courseid The course id
1307 * @param mixed $display show only this section, 0 or 'all' means show all sections
1308 * @return int Course section to display, 0 means all
1310 function course_set_display($courseid, $display) {
1311 global $USER, $DB;
1313 if ($display === 'all' or empty($display)) {
1314 $display = 0;
1317 if (!isloggedin() or isguestuser()) {
1318 //do not store settings in db for guests
1319 return 0;
1322 if ($display == 0) {
1323 //show all, do not store anything in database
1324 $DB->delete_records('course_display', array('userid' => $USER->id, 'course' => $courseid));
1326 } else {
1327 if ($DB->record_exists('course_display', array('userid' => $USER->id, 'course' => $courseid))) {
1328 $DB->set_field('course_display', 'display', $display, array('userid' => $USER->id, 'course' => $courseid));
1329 } else {
1330 $record = new stdClass();
1331 $record->userid = $USER->id;
1332 $record->course = $courseid;
1333 $record->display = $display;
1334 $DB->insert_record('course_display', $record);
1338 //use display cache for one course only - we need to keep session small
1339 $USER->display = array($courseid => $display);
1341 return $display;
1345 * For a given course section, marks it visible or hidden,
1346 * and does the same for every activity in that section
1348 function set_section_visible($courseid, $sectionnumber, $visibility) {
1349 global $DB;
1351 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
1352 $DB->set_field("course_sections", "visible", "$visibility", array("id"=>$section->id));
1353 if (!empty($section->sequence)) {
1354 $modules = explode(",", $section->sequence);
1355 foreach ($modules as $moduleid) {
1356 set_coursemodule_visible($moduleid, $visibility, true);
1359 rebuild_course_cache($courseid);
1364 * Obtains shared data that is used in print_section when displaying a
1365 * course-module entry.
1367 * Calls format_text or format_string as appropriate, and obtains the correct icon.
1369 * This data is also used in other areas of the code.
1370 * @param cm_info $cm Course-module data (must come from get_fast_modinfo)
1371 * @param object $course Moodle course object
1372 * @return array An array with the following values in this order:
1373 * $content (optional extra content for after link),
1374 * $instancename (text of link)
1376 function get_print_section_cm_text(cm_info $cm, $course) {
1377 global $OUTPUT;
1379 // Get content from modinfo if specified. Content displays either
1380 // in addition to the standard link (below), or replaces it if
1381 // the link is turned off by setting ->url to null.
1382 if (($content = $cm->get_content()) !== '') {
1383 // Improve filter performance by preloading filter setttings for all
1384 // activities on the course (this does nothing if called multiple
1385 // times)
1386 filter_preload_activities($cm->get_modinfo());
1388 // Get module context
1389 $modulecontext = get_context_instance(CONTEXT_MODULE, $cm->id);
1390 $labelformatoptions = new stdClass();
1391 $labelformatoptions->noclean = true;
1392 $labelformatoptions->overflowdiv = true;
1393 $labelformatoptions->context = $modulecontext;
1394 $content = format_text($content, FORMAT_HTML, $labelformatoptions);
1395 } else {
1396 $content = '';
1399 // Get course context
1400 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
1401 $stringoptions = new stdClass;
1402 $stringoptions->context = $coursecontext;
1403 $instancename = format_string($cm->name, true, $stringoptions);
1404 return array($content, $instancename);
1408 * Prints a section full of activity modules
1410 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%", $hidecompletion=false) {
1411 global $CFG, $USER, $DB, $PAGE, $OUTPUT;
1413 static $initialised;
1415 static $groupbuttons;
1416 static $groupbuttonslink;
1417 static $isediting;
1418 static $ismoving;
1419 static $strmovehere;
1420 static $strmovefull;
1421 static $strunreadpostsone;
1422 static $groupings;
1423 static $modulenames;
1425 if (!isset($initialised)) {
1426 $groupbuttons = ($course->groupmode or (!$course->groupmodeforce));
1427 $groupbuttonslink = (!$course->groupmodeforce);
1428 $isediting = $PAGE->user_is_editing();
1429 $ismoving = $isediting && ismoving($course->id);
1430 if ($ismoving) {
1431 $strmovehere = get_string("movehere");
1432 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1434 $modulenames = array();
1435 $initialised = true;
1438 $tl = textlib_get_instance();
1440 $modinfo = get_fast_modinfo($course);
1441 $completioninfo = new completion_info($course);
1443 //Accessibility: replace table with list <ul>, but don't output empty list.
1444 if (!empty($section->sequence)) {
1446 // Fix bug #5027, don't want style=\"width:$width\".
1447 echo "<ul class=\"section img-text\">\n";
1448 $sectionmods = explode(",", $section->sequence);
1450 foreach ($sectionmods as $modnumber) {
1451 if (empty($mods[$modnumber])) {
1452 continue;
1456 * @var cm_info
1458 $mod = $mods[$modnumber];
1460 if ($ismoving and $mod->id == $USER->activitycopy) {
1461 // do not display moving mod
1462 continue;
1465 if (isset($modinfo->cms[$modnumber])) {
1466 // We can continue (because it will not be displayed at all)
1467 // if:
1468 // 1) The activity is not visible to users
1469 // and
1470 // 2a) The 'showavailability' option is not set (if that is set,
1471 // we need to display the activity so we can show
1472 // availability info)
1473 // or
1474 // 2b) The 'availableinfo' is empty, i.e. the activity was
1475 // hidden in a way that leaves no info, such as using the
1476 // eye icon.
1477 if (!$modinfo->cms[$modnumber]->uservisible &&
1478 (empty($modinfo->cms[$modnumber]->showavailability) ||
1479 empty($modinfo->cms[$modnumber]->availableinfo))) {
1480 // visibility shortcut
1481 continue;
1483 } else {
1484 if (!file_exists("$CFG->dirroot/mod/$mod->modname/lib.php")) {
1485 // module not installed
1486 continue;
1488 if (!coursemodule_visible_for_user($mod) &&
1489 empty($mod->showavailability)) {
1490 // full visibility check
1491 continue;
1495 if (!isset($modulenames[$mod->modname])) {
1496 $modulenames[$mod->modname] = get_string('modulename', $mod->modname);
1498 $modulename = $modulenames[$mod->modname];
1500 // In some cases the activity is visible to user, but it is
1501 // dimmed. This is done if viewhiddenactivities is true and if:
1502 // 1. the activity is not visible, or
1503 // 2. the activity has dates set which do not include current, or
1504 // 3. the activity has any other conditions set (regardless of whether
1505 // current user meets them)
1506 $canviewhidden = has_capability(
1507 'moodle/course:viewhiddenactivities',
1508 get_context_instance(CONTEXT_MODULE, $mod->id));
1509 $accessiblebutdim = false;
1510 if ($canviewhidden) {
1511 $accessiblebutdim = !$mod->visible;
1512 if (!empty($CFG->enableavailability)) {
1513 $accessiblebutdim = $accessiblebutdim ||
1514 $mod->availablefrom > time() ||
1515 ($mod->availableuntil && $mod->availableuntil < time()) ||
1516 count($mod->conditionsgrade) > 0 ||
1517 count($mod->conditionscompletion) > 0;
1521 $liclasses = array();
1522 $liclasses[] = 'activity';
1523 $liclasses[] = $mod->modname;
1524 $liclasses[] = 'modtype_'.$mod->modname;
1525 $extraclasses = $mod->get_extra_classes();
1526 if ($extraclasses) {
1527 $liclasses = array_merge($liclasses, explode(' ', $extraclasses));
1529 echo html_writer::start_tag('li', array('class'=>join(' ', $liclasses), 'id'=>'module-'.$modnumber));
1530 if ($ismoving) {
1531 echo '<a title="'.$strmovefull.'"'.
1532 ' href="'.$CFG->wwwroot.'/course/mod.php?moveto='.$mod->id.'&amp;sesskey='.sesskey().'">'.
1533 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1534 ' alt="'.$strmovehere.'" /></a><br />
1538 $classes = array('mod-indent');
1539 if (!empty($mod->indent)) {
1540 $classes[] = 'mod-indent-'.$mod->indent;
1541 if ($mod->indent > 15) {
1542 $classes[] = 'mod-indent-huge';
1545 echo html_writer::start_tag('div', array('class'=>join(' ', $classes)));
1547 // Get data about this course-module
1548 list($content, $instancename) =
1549 get_print_section_cm_text($modinfo->cms[$modnumber], $course);
1551 //Accessibility: for files get description via icon, this is very ugly hack!
1552 $altname = '';
1553 $altname = $mod->modfullname;
1554 if (!empty($customicon)) {
1555 $archetype = plugin_supports('mod', $mod->modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1556 if ($archetype == MOD_ARCHETYPE_RESOURCE) {
1557 $mimetype = mimeinfo_from_icon('type', $customicon);
1558 $altname = get_mimetype_description($mimetype);
1561 // Avoid unnecessary duplication: if e.g. a forum name already
1562 // includes the word forum (or Forum, etc) then it is unhelpful
1563 // to include that in the accessible description that is added.
1564 if (false !== strpos($tl->strtolower($instancename),
1565 $tl->strtolower($altname))) {
1566 $altname = '';
1568 // File type after name, for alphabetic lists (screen reader).
1569 if ($altname) {
1570 $altname = get_accesshide(' '.$altname);
1573 // We may be displaying this just in order to show information
1574 // about visibility, without the actual link
1575 $contentpart = '';
1576 if ($mod->uservisible) {
1577 // Nope - in this case the link is fully working for user
1578 $linkclasses = '';
1579 $textclasses = '';
1580 if ($accessiblebutdim) {
1581 $linkclasses .= ' dimmed';
1582 $textclasses .= ' dimmed_text';
1583 $accesstext = '<span class="accesshide">'.
1584 get_string('hiddenfromstudents').': </span>';
1585 } else {
1586 $accesstext = '';
1588 if ($linkclasses) {
1589 $linkcss = 'class="' . trim($linkclasses) . '" ';
1590 } else {
1591 $linkcss = '';
1593 if ($textclasses) {
1594 $textcss = 'class="' . trim($textclasses) . '" ';
1595 } else {
1596 $textcss = '';
1599 // Get on-click attribute value if specified
1600 $onclick = $mod->get_on_click();
1601 if ($onclick) {
1602 $onclick = ' onclick="' . $onclick . '"';
1605 if ($url = $mod->get_url()) {
1606 // Display link itself
1607 echo '<a ' . $linkcss . $mod->extra . $onclick .
1608 ' href="' . $url . '"><img src="' . $mod->get_icon_url() .
1609 '" class="activityicon" alt="' .
1610 $modulename . '" /> ' .
1611 $accesstext . '<span class="instancename">' .
1612 $instancename . $altname . '</span></a>';
1614 // If specified, display extra content after link
1615 if ($content) {
1616 $contentpart = '<div class="' . trim('contentafterlink' . $textclasses) .
1617 '">' . $content . '</div>';
1619 } else {
1620 // No link, so display only content
1621 $contentpart = '<div ' . $textcss . $mod->extra . '>' .
1622 $accesstext . $content . '</div>';
1625 if (!empty($mod->groupingid) && has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
1626 if (!isset($groupings)) {
1627 $groupings = groups_get_all_groupings($course->id);
1629 echo " <span class=\"groupinglabel\">(".format_string($groupings[$mod->groupingid]->name).')</span>';
1631 } else {
1632 $textclasses = $extraclasses;
1633 $textclasses .= ' dimmed_text';
1634 if ($textclasses) {
1635 $textcss = 'class="' . trim($textclasses) . '" ';
1636 } else {
1637 $textcss = '';
1639 $accesstext = '<span class="accesshide">' .
1640 get_string('notavailableyet', 'condition') .
1641 ': </span>';
1643 if ($url = $mod->get_url()) {
1644 // Display greyed-out text of link
1645 echo '<div ' . $textcss . $mod->extra .
1646 ' >' . '<img src="' . $mod->get_icon_url() .
1647 '" class="activityicon" alt="' .
1648 $modulename .
1649 '" /> <span>'. $instancename . $altname .
1650 '</span></div>';
1652 // Do not display content after link when it is greyed out like this.
1653 } else {
1654 // No link, so display only content (also greyed)
1655 $contentpart = '<div ' . $textcss . $mod->extra . '>' .
1656 $accesstext . $content . '</div>';
1660 // Module can put text after the link (e.g. forum unread)
1661 echo $mod->get_after_link();
1663 // If there is content but NO link (eg label), then display the
1664 // content here (BEFORE any icons). In this case cons must be
1665 // displayed after the content so that it makes more sense visually
1666 // and for accessibility reasons, e.g. if you have a one-line label
1667 // it should work similarly (at least in terms of ordering) to an
1668 // activity.
1669 if (empty($url)) {
1670 echo $contentpart;
1673 if ($isediting) {
1674 if ($groupbuttons and plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
1675 if (! $mod->groupmodelink = $groupbuttonslink) {
1676 $mod->groupmode = $course->groupmode;
1679 } else {
1680 $mod->groupmode = false;
1682 echo '&nbsp;&nbsp;';
1683 echo make_editing_buttons($mod, $absolute, true, $mod->indent, $section->section);
1684 echo $mod->get_after_edit_icons();
1687 // Completion
1688 $completion = $hidecompletion
1689 ? COMPLETION_TRACKING_NONE
1690 : $completioninfo->is_enabled($mod);
1691 if ($completion!=COMPLETION_TRACKING_NONE && isloggedin() &&
1692 !isguestuser() && $mod->uservisible) {
1693 $completiondata = $completioninfo->get_data($mod,true);
1694 $completionicon = '';
1695 if ($isediting) {
1696 switch ($completion) {
1697 case COMPLETION_TRACKING_MANUAL :
1698 $completionicon = 'manual-enabled'; break;
1699 case COMPLETION_TRACKING_AUTOMATIC :
1700 $completionicon = 'auto-enabled'; break;
1701 default: // wtf
1703 } else if ($completion==COMPLETION_TRACKING_MANUAL) {
1704 switch($completiondata->completionstate) {
1705 case COMPLETION_INCOMPLETE:
1706 $completionicon = 'manual-n'; break;
1707 case COMPLETION_COMPLETE:
1708 $completionicon = 'manual-y'; break;
1710 } else { // Automatic
1711 switch($completiondata->completionstate) {
1712 case COMPLETION_INCOMPLETE:
1713 $completionicon = 'auto-n'; break;
1714 case COMPLETION_COMPLETE:
1715 $completionicon = 'auto-y'; break;
1716 case COMPLETION_COMPLETE_PASS:
1717 $completionicon = 'auto-pass'; break;
1718 case COMPLETION_COMPLETE_FAIL:
1719 $completionicon = 'auto-fail'; break;
1722 if ($completionicon) {
1723 $imgsrc = $OUTPUT->pix_url('i/completion-'.$completionicon);
1724 $imgalt = s(get_string('completion-alt-'.$completionicon, 'completion'));
1725 if ($completion == COMPLETION_TRACKING_MANUAL && !$isediting) {
1726 $imgtitle = s(get_string('completion-title-'.$completionicon, 'completion'));
1727 $newstate =
1728 $completiondata->completionstate==COMPLETION_COMPLETE
1729 ? COMPLETION_INCOMPLETE
1730 : COMPLETION_COMPLETE;
1731 // In manual mode the icon is a toggle form...
1733 // If this completion state is used by the
1734 // conditional activities system, we need to turn
1735 // off the JS.
1736 if (!empty($CFG->enableavailability) &&
1737 condition_info::completion_value_used_as_condition($course, $mod)) {
1738 $extraclass = ' preventjs';
1739 } else {
1740 $extraclass = '';
1742 echo "
1743 <form class='togglecompletion$extraclass' method='post' action='".$CFG->wwwroot."/course/togglecompletion.php'><div>
1744 <input type='hidden' name='id' value='{$mod->id}' />
1745 <input type='hidden' name='sesskey' value='".sesskey()."' />
1746 <input type='hidden' name='completionstate' value='$newstate' />
1747 <input type='image' src='$imgsrc' alt='$imgalt' title='$imgtitle' />
1748 </div></form>";
1749 } else {
1750 // In auto mode, or when editing, the icon is just an image
1751 echo "<span class='autocompletion'>";
1752 echo "<img src='$imgsrc' alt='$imgalt' title='$imgalt' /></span>";
1757 // If there is content AND a link, then display the content here
1758 // (AFTER any icons). Otherwise it was displayed before
1759 if (!empty($url)) {
1760 echo $contentpart;
1763 // Show availability information (for someone who isn't allowed to
1764 // see the activity itself, or for staff)
1765 if (!$mod->uservisible) {
1766 echo '<div class="availabilityinfo">'.$mod->availableinfo.'</div>';
1767 } else if ($canviewhidden && !empty($CFG->enableavailability)) {
1768 $ci = new condition_info($mod);
1769 $fullinfo = $ci->get_full_information();
1770 if($fullinfo) {
1771 echo '<div class="availabilityinfo">'.get_string($mod->showavailability
1772 ? 'userrestriction_visible'
1773 : 'userrestriction_hidden','condition',
1774 $fullinfo).'</div>';
1778 echo html_writer::end_tag('div');
1779 echo html_writer::end_tag('li')."\n";
1782 } elseif ($ismoving) {
1783 echo "<ul class=\"section\">\n";
1786 if ($ismoving) {
1787 echo '<li><a title="'.$strmovefull.'"'.
1788 ' href="'.$CFG->wwwroot.'/course/mod.php?movetosection='.$section->id.'&amp;sesskey='.sesskey().'">'.
1789 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1790 ' alt="'.$strmovehere.'" /></a></li>
1793 if (!empty($section->sequence) || $ismoving) {
1794 echo "</ul><!--class='section'-->\n\n";
1799 * Prints the menus to add activities and resources.
1801 function print_section_add_menus($course, $section, $modnames, $vertical=false, $return=false) {
1802 global $CFG, $OUTPUT;
1804 // check to see if user can add menus
1805 if (!has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $course->id))) {
1806 return false;
1809 $urlbase = "/course/mod.php?id=$course->id&section=$section&sesskey=".sesskey().'&add=';
1811 $resources = array();
1812 $activities = array();
1814 foreach($modnames as $modname=>$modnamestr) {
1815 if (!course_allowed_module($course, $modname)) {
1816 continue;
1819 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1820 if (!file_exists($libfile)) {
1821 continue;
1823 include_once($libfile);
1824 $gettypesfunc = $modname.'_get_types';
1825 if (function_exists($gettypesfunc)) {
1826 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1827 if ($types = $gettypesfunc()) {
1828 $menu = array();
1829 $atype = null;
1830 $groupname = null;
1831 foreach($types as $type) {
1832 if ($type->typestr === '--') {
1833 continue;
1835 if (strpos($type->typestr, '--') === 0) {
1836 $groupname = str_replace('--', '', $type->typestr);
1837 continue;
1839 $type->type = str_replace('&amp;', '&', $type->type);
1840 if ($type->modclass == MOD_CLASS_RESOURCE) {
1841 $atype = MOD_CLASS_RESOURCE;
1843 $menu[$urlbase.$type->type] = $type->typestr;
1845 if (!is_null($groupname)) {
1846 if ($atype == MOD_CLASS_RESOURCE) {
1847 $resources[] = array($groupname=>$menu);
1848 } else {
1849 $activities[] = array($groupname=>$menu);
1851 } else {
1852 if ($atype == MOD_CLASS_RESOURCE) {
1853 $resources = array_merge($resources, $menu);
1854 } else {
1855 $activities = array_merge($activities, $menu);
1859 } else {
1860 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1861 if ($archetype == MOD_ARCHETYPE_RESOURCE) {
1862 $resources[$urlbase.$modname] = $modnamestr;
1863 } else {
1864 // all other archetypes are considered activity
1865 $activities[$urlbase.$modname] = $modnamestr;
1870 $straddactivity = get_string('addactivity');
1871 $straddresource = get_string('addresource');
1873 $output = '<div class="section_add_menus">';
1875 if (!$vertical) {
1876 $output .= '<div class="horizontal">';
1879 if (!empty($resources)) {
1880 $select = new url_select($resources, '', array(''=>$straddresource), "ressection$section");
1881 $select->set_help_icon('resources');
1882 $output .= $OUTPUT->render($select);
1885 if (!empty($activities)) {
1886 $select = new url_select($activities, '', array(''=>$straddactivity), "section$section");
1887 $select->set_help_icon('activities');
1888 $output .= $OUTPUT->render($select);
1891 if (!$vertical) {
1892 $output .= '</div>';
1895 $output .= '</div>';
1897 if ($return) {
1898 return $output;
1899 } else {
1900 echo $output;
1905 * Return the course category context for the category with id $categoryid, except
1906 * that if $categoryid is 0, return the system context.
1908 * @param integer $categoryid a category id or 0.
1909 * @return object the corresponding context
1911 function get_category_or_system_context($categoryid) {
1912 if ($categoryid) {
1913 return get_context_instance(CONTEXT_COURSECAT, $categoryid);
1914 } else {
1915 return get_context_instance(CONTEXT_SYSTEM);
1920 * Gets the child categories of a given courses category. Uses a static cache
1921 * to make repeat calls efficient.
1923 * @param int $parentid the id of a course category.
1924 * @return array all the child course categories.
1926 function get_child_categories($parentid) {
1927 static $allcategories = null;
1929 // only fill in this variable the first time
1930 if (null == $allcategories) {
1931 $allcategories = array();
1933 $categories = get_categories();
1934 foreach ($categories as $category) {
1935 if (empty($allcategories[$category->parent])) {
1936 $allcategories[$category->parent] = array();
1938 $allcategories[$category->parent][] = $category;
1942 if (empty($allcategories[$parentid])) {
1943 return array();
1944 } else {
1945 return $allcategories[$parentid];
1950 * This function recursively travels the categories, building up a nice list
1951 * for display. It also makes an array that list all the parents for each
1952 * category.
1954 * For example, if you have a tree of categories like:
1955 * Miscellaneous (id = 1)
1956 * Subcategory (id = 2)
1957 * Sub-subcategory (id = 4)
1958 * Other category (id = 3)
1959 * Then after calling this function you will have
1960 * $list = array(1 => 'Miscellaneous', 2 => 'Miscellaneous / Subcategory',
1961 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
1962 * 3 => 'Other category');
1963 * $parents = array(2 => array(1), 4 => array(1, 2));
1965 * If you specify $requiredcapability, then only categories where the current
1966 * user has that capability will be added to $list, although all categories
1967 * will still be added to $parents, and if you only have $requiredcapability
1968 * in a child category, not the parent, then the child catgegory will still be
1969 * included.
1971 * If you specify the option $excluded, then that category, and all its children,
1972 * are omitted from the tree. This is useful when you are doing something like
1973 * moving categories, where you do not want to allow people to move a category
1974 * to be the child of itself.
1976 * @param array $list For output, accumulates an array categoryid => full category path name
1977 * @param array $parents For output, accumulates an array categoryid => list of parent category ids.
1978 * @param string/array $requiredcapability if given, only categories where the current
1979 * user has this capability will be added to $list. Can also be an array of capabilities,
1980 * in which case they are all required.
1981 * @param integer $excludeid Omit this category and its children from the lists built.
1982 * @param object $category Build the tree starting at this category - otherwise starts at the top level.
1983 * @param string $path For internal use, as part of recursive calls.
1985 function make_categories_list(&$list, &$parents, $requiredcapability = '',
1986 $excludeid = 0, $category = NULL, $path = "") {
1988 // initialize the arrays if needed
1989 if (!is_array($list)) {
1990 $list = array();
1992 if (!is_array($parents)) {
1993 $parents = array();
1996 if (empty($category)) {
1997 // Start at the top level.
1998 $category = new stdClass;
1999 $category->id = 0;
2000 } else {
2001 // This is the excluded category, don't include it.
2002 if ($excludeid > 0 && $excludeid == $category->id) {
2003 return;
2006 $context = get_context_instance(CONTEXT_COURSECAT, $category->id);
2007 $categoryname = format_string($category->name, true, array('context' => $context));
2009 // Update $path.
2010 if ($path) {
2011 $path = $path.' / '.$categoryname;
2012 } else {
2013 $path = $categoryname;
2016 // Add this category to $list, if the permissions check out.
2017 if (empty($requiredcapability)) {
2018 $list[$category->id] = $path;
2020 } else {
2021 $requiredcapability = (array)$requiredcapability;
2022 if (has_all_capabilities($requiredcapability, $context)) {
2023 $list[$category->id] = $path;
2028 // Add all the children recursively, while updating the parents array.
2029 if ($categories = get_child_categories($category->id)) {
2030 foreach ($categories as $cat) {
2031 if (!empty($category->id)) {
2032 if (isset($parents[$category->id])) {
2033 $parents[$cat->id] = $parents[$category->id];
2035 $parents[$cat->id][] = $category->id;
2037 make_categories_list($list, $parents, $requiredcapability, $excludeid, $cat, $path);
2043 * This function generates a structured array of courses and categories.
2045 * The depth of categories is limited by $CFG->maxcategorydepth however there
2046 * is no limit on the number of courses!
2048 * Suitable for use with the course renderers course_category_tree method:
2049 * $renderer = $PAGE->get_renderer('core','course');
2050 * echo $renderer->course_category_tree(get_course_category_tree());
2052 * @global moodle_database $DB
2053 * @param int $id
2054 * @param int $depth
2056 function get_course_category_tree($id = 0, $depth = 0) {
2057 global $DB, $CFG;
2058 $viewhiddencats = has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_SYSTEM));
2059 $categories = get_child_categories($id);
2060 $categoryids = array();
2061 foreach ($categories as $key => &$category) {
2062 if (!$category->visible && !$viewhiddencats) {
2063 unset($categories[$key]);
2064 continue;
2066 $categoryids[$category->id] = $category;
2067 if (empty($CFG->maxcategorydepth) || $depth <= $CFG->maxcategorydepth) {
2068 list($category->categories, $subcategories) = get_course_category_tree($category->id, $depth+1);
2069 foreach ($subcategories as $subid=>$subcat) {
2070 $categoryids[$subid] = $subcat;
2072 $category->courses = array();
2076 if ($depth > 0) {
2077 // This is a recursive call so return the required array
2078 return array($categories, $categoryids);
2081 // The depth is 0 this function has just been called so we can finish it off
2083 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
2084 list($catsql, $catparams) = $DB->get_in_or_equal(array_keys($categoryids));
2085 $sql = "SELECT
2086 c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary,c.category
2087 $ccselect
2088 FROM {course} c
2089 $ccjoin
2090 WHERE c.category $catsql ORDER BY c.sortorder ASC";
2091 if ($courses = $DB->get_records_sql($sql, $catparams)) {
2092 // loop throught them
2093 foreach ($courses as $course) {
2094 if ($course->id == SITEID) {
2095 continue;
2097 context_instance_preload($course);
2098 if (!empty($course->visible) || has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id))) {
2099 $categoryids[$course->category]->courses[$course->id] = $course;
2103 return $categories;
2107 * Recursive function to print out all the categories in a nice format
2108 * with or without courses included
2110 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true) {
2111 global $CFG;
2113 // maxcategorydepth == 0 meant no limit
2114 if (!empty($CFG->maxcategorydepth) && $depth >= $CFG->maxcategorydepth) {
2115 return;
2118 if (!$displaylist) {
2119 make_categories_list($displaylist, $parentslist);
2122 if ($category) {
2123 if ($category->visible or has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_SYSTEM))) {
2124 print_category_info($category, $depth, $showcourses);
2125 } else {
2126 return; // Don't bother printing children of invisible categories
2129 } else {
2130 $category = new stdClass();
2131 $category->id = "0";
2134 if ($categories = get_child_categories($category->id)) { // Print all the children recursively
2135 $countcats = count($categories);
2136 $count = 0;
2137 $first = true;
2138 $last = false;
2139 foreach ($categories as $cat) {
2140 $count++;
2141 if ($count == $countcats) {
2142 $last = true;
2144 $up = $first ? false : true;
2145 $down = $last ? false : true;
2146 $first = false;
2148 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1, $showcourses);
2154 * This function will return $options array for html_writer::select(), with whitespace to denote nesting.
2156 function make_categories_options() {
2157 make_categories_list($cats,$parents);
2158 foreach ($cats as $key => $value) {
2159 if (array_key_exists($key,$parents)) {
2160 if ($indent = count($parents[$key])) {
2161 for ($i = 0; $i < $indent; $i++) {
2162 $cats[$key] = '&nbsp;'.$cats[$key];
2167 return $cats;
2171 * Gets the name of a course to be displayed when showing a list of courses.
2172 * By default this is just $course->fullname but user can configure it. The
2173 * result of this function should be passed through print_string.
2174 * @param object $course Moodle course object
2175 * @return string Display name of course (either fullname or short + fullname)
2177 function get_course_display_name_for_list($course) {
2178 global $CFG;
2179 if (!empty($CFG->courselistshortnames)) {
2180 return $course->shortname . ' ' .$course->fullname;
2181 } else {
2182 return $course->fullname;
2187 * Prints the category info in indented fashion
2188 * This function is only used by print_whole_category_list() above
2190 function print_category_info($category, $depth=0, $showcourses = false) {
2191 global $CFG, $DB, $OUTPUT;
2193 $strsummary = get_string('summary');
2195 $catlinkcss = null;
2196 if (!$category->visible) {
2197 $catlinkcss = array('class'=>'dimmed');
2199 static $coursecount = null;
2200 if (null === $coursecount) {
2201 // only need to check this once
2202 $coursecount = $DB->count_records('course') <= FRONTPAGECOURSELIMIT;
2205 if ($showcourses and $coursecount) {
2206 $catimage = '<img src="'.$OUTPUT->pix_url('i/course') . '" alt="" />';
2207 } else {
2208 $catimage = "&nbsp;";
2211 $courses = get_courses($category->id, 'c.sortorder ASC', 'c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary');
2212 $context = get_context_instance(CONTEXT_COURSECAT, $category->id);
2213 $fullname = format_string($category->name, true, array('context' => $context));
2215 if ($showcourses and $coursecount) {
2216 echo '<div class="categorylist clearfix">';
2217 $cat = '';
2218 $cat .= html_writer::tag('div', $catimage, array('class'=>'image'));
2219 $catlink = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
2220 $cat .= html_writer::tag('div', $catlink, array('class'=>'name'));
2222 $html = '';
2223 if ($depth > 0) {
2224 for ($i=0; $i< $depth; $i++) {
2225 $html = html_writer::tag('div', $html . $cat, array('class'=>'indentation'));
2226 $cat = '';
2228 } else {
2229 $html = $cat;
2231 echo html_writer::tag('div', $html, array('class'=>'category'));
2232 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
2234 // does the depth exceed maxcategorydepth
2235 // maxcategorydepth == 0 or unset meant no limit
2236 $limit = !(isset($CFG->maxcategorydepth) && ($depth >= $CFG->maxcategorydepth-1));
2237 if ($courses && ($limit || $CFG->maxcategorydepth == 0)) {
2238 foreach ($courses as $course) {
2239 $linkcss = null;
2240 if (!$course->visible) {
2241 $linkcss = array('class'=>'dimmed');
2244 $coursename = get_course_display_name_for_list($course);
2245 $courselink = html_writer::link(new moodle_url('/course/view.php', array('id'=>$course->id)), format_string($coursename), $linkcss);
2247 // print enrol info
2248 $courseicon = '';
2249 if ($icons = enrol_get_course_info_icons($course)) {
2250 foreach ($icons as $pix_icon) {
2251 $courseicon = $OUTPUT->render($pix_icon).' ';
2255 $coursecontent = html_writer::tag('div', $courseicon.$courselink, array('class'=>'name'));
2257 if ($course->summary) {
2258 $link = new moodle_url('/course/info.php?id='.$course->id);
2259 $actionlink = $OUTPUT->action_link($link, '<img alt="'.$strsummary.'" src="'.$OUTPUT->pix_url('i/info') . '" />',
2260 new popup_action('click', $link, 'courseinfo', array('height' => 400, 'width' => 500)),
2261 array('title'=>$strsummary));
2263 $coursecontent .= html_writer::tag('div', $actionlink, array('class'=>'info'));
2266 $html = '';
2267 for ($i=0; $i <= $depth; $i++) {
2268 $html = html_writer::tag('div', $html . $coursecontent , array('class'=>'indentation'));
2269 $coursecontent = '';
2271 echo html_writer::tag('div', $html, array('class'=>'course clearfloat'));
2274 echo '</div>';
2275 } else {
2276 echo '<div class="categorylist">';
2277 $html = '';
2278 $cat = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
2279 if (count($courses) > 0) {
2280 $cat .= html_writer::tag('span', ' ('.count($courses).')', array('title'=>get_string('numberofcourses'), 'class'=>'numberofcourse'));
2283 if ($depth > 0) {
2284 for ($i=0; $i< $depth; $i++) {
2285 $html = html_writer::tag('div', $html .$cat, array('class'=>'indentation'));
2286 $cat = '';
2288 } else {
2289 $html = $cat;
2292 echo html_writer::tag('div', $html, array('class'=>'category'));
2293 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
2294 echo '</div>';
2299 * Print the buttons relating to course requests.
2301 * @param object $systemcontext the system context.
2303 function print_course_request_buttons($systemcontext) {
2304 global $CFG, $DB, $OUTPUT;
2305 if (empty($CFG->enablecourserequests)) {
2306 return;
2308 if (!has_capability('moodle/course:create', $systemcontext) && has_capability('moodle/course:request', $systemcontext)) {
2309 /// Print a button to request a new course
2310 echo $OUTPUT->single_button('request.php', get_string('requestcourse'), 'get');
2312 /// Print a button to manage pending requests
2313 if (has_capability('moodle/site:approvecourse', $systemcontext)) {
2314 $disabled = !$DB->record_exists('course_request', array());
2315 echo $OUTPUT->single_button('pending.php', get_string('coursespending'), 'get', array('disabled'=>$disabled));
2320 * Does the user have permission to edit things in this category?
2322 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2323 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
2325 function can_edit_in_category($categoryid = 0) {
2326 $context = get_category_or_system_context($categoryid);
2327 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
2331 * Prints the turn editing on/off button on course/index.php or course/category.php.
2333 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2334 * @return string HTML of the editing button, or empty string, if this user is not allowed
2335 * to see it.
2337 function update_category_button($categoryid = 0) {
2338 global $CFG, $PAGE, $OUTPUT;
2340 // Check permissions.
2341 if (!can_edit_in_category($categoryid)) {
2342 return '';
2345 // Work out the appropriate action.
2346 if ($PAGE->user_is_editing()) {
2347 $label = get_string('turneditingoff');
2348 $edit = 'off';
2349 } else {
2350 $label = get_string('turneditingon');
2351 $edit = 'on';
2354 // Generate the button HTML.
2355 $options = array('categoryedit' => $edit, 'sesskey' => sesskey());
2356 if ($categoryid) {
2357 $options['id'] = $categoryid;
2358 $page = 'category.php';
2359 } else {
2360 $page = 'index.php';
2362 return $OUTPUT->single_button(new moodle_url('/course/' . $page, $options), $label, 'get');
2366 * Category is 0 (for all courses) or an object
2368 function print_courses($category) {
2369 global $CFG, $OUTPUT;
2371 if (!is_object($category) && $category==0) {
2372 $categories = get_child_categories(0); // Parent = 0 ie top-level categories only
2373 if (is_array($categories) && count($categories) == 1) {
2374 $category = array_shift($categories);
2375 $courses = get_courses_wmanagers($category->id,
2376 'c.sortorder ASC',
2377 array('summary','summaryformat'));
2378 } else {
2379 $courses = get_courses_wmanagers('all',
2380 'c.sortorder ASC',
2381 array('summary','summaryformat'));
2383 unset($categories);
2384 } else {
2385 $courses = get_courses_wmanagers($category->id,
2386 'c.sortorder ASC',
2387 array('summary','summaryformat'));
2390 if ($courses) {
2391 echo html_writer::start_tag('ul', array('class'=>'unlist'));
2392 foreach ($courses as $course) {
2393 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
2394 if ($course->visible == 1 || has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2395 echo html_writer::start_tag('li');
2396 print_course($course);
2397 echo html_writer::end_tag('li');
2400 echo html_writer::end_tag('ul');
2401 } else {
2402 echo $OUTPUT->heading(get_string("nocoursesyet"));
2403 $context = get_context_instance(CONTEXT_SYSTEM);
2404 if (has_capability('moodle/course:create', $context)) {
2405 $options = array();
2406 if (!empty($category->id)) {
2407 $options['category'] = $category->id;
2408 } else {
2409 $options['category'] = $CFG->defaultrequestcategory;
2411 echo html_writer::start_tag('div', array('class'=>'addcoursebutton'));
2412 echo $OUTPUT->single_button(new moodle_url('/course/edit.php', $options), get_string("addnewcourse"));
2413 echo html_writer::end_tag('div');
2419 * Print a description of a course, suitable for browsing in a list.
2421 * @param object $course the course object.
2422 * @param string $highlightterms (optional) some search terms that should be highlighted in the display.
2424 function print_course($course, $highlightterms = '') {
2425 global $CFG, $USER, $DB, $OUTPUT;
2427 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2429 // Rewrite file URLs so that they are correct
2430 $course->summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', NULL);
2432 echo html_writer::start_tag('div', array('class'=>'coursebox clearfix'));
2433 echo html_writer::start_tag('div', array('class'=>'info'));
2434 echo html_writer::start_tag('h3', array('class'=>'name'));
2436 $linkhref = new moodle_url('/course/view.php', array('id'=>$course->id));
2438 $coursename = get_course_display_name_for_list($course);
2439 $linktext = highlight($highlightterms, format_string($coursename));
2440 $linkparams = array('title'=>get_string('entercourse'));
2441 if (empty($course->visible)) {
2442 $linkparams['class'] = 'dimmed';
2444 echo html_writer::link($linkhref, $linktext, $linkparams);
2445 echo html_writer::end_tag('h3');
2447 /// first find all roles that are supposed to be displayed
2448 if (!empty($CFG->coursecontact)) {
2449 $managerroles = explode(',', $CFG->coursecontact);
2450 $namesarray = array();
2451 $rusers = array();
2453 if (!isset($course->managers)) {
2454 $rusers = get_role_users($managerroles, $context, true,
2455 'ra.id AS raid, u.id, u.username, u.firstname, u.lastname,
2456 r.name AS rolename, r.sortorder, r.id AS roleid',
2457 'r.sortorder ASC, u.lastname ASC');
2458 } else {
2459 // use the managers array if we have it for perf reasosn
2460 // populate the datastructure like output of get_role_users();
2461 foreach ($course->managers as $manager) {
2462 $u = new stdClass();
2463 $u = $manager->user;
2464 $u->roleid = $manager->roleid;
2465 $u->rolename = $manager->rolename;
2467 $rusers[] = $u;
2471 /// Rename some of the role names if needed
2472 if (isset($context)) {
2473 $aliasnames = $DB->get_records('role_names', array('contextid'=>$context->id), '', 'roleid,contextid,name');
2476 $namesarray = array();
2477 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2478 foreach ($rusers as $ra) {
2479 if (isset($namesarray[$ra->id])) {
2480 // only display a user once with the higest sortorder role
2481 continue;
2484 if (isset($aliasnames[$ra->roleid])) {
2485 $ra->rolename = $aliasnames[$ra->roleid]->name;
2488 $fullname = fullname($ra, $canviewfullnames);
2489 $namesarray[$ra->id] = format_string($ra->rolename).': '.
2490 html_writer::link(new moodle_url('/user/view.php', array('id'=>$ra->id, 'course'=>SITEID)), $fullname);
2493 if (!empty($namesarray)) {
2494 echo html_writer::start_tag('ul', array('class'=>'teachers'));
2495 foreach ($namesarray as $name) {
2496 echo html_writer::tag('li', $name);
2498 echo html_writer::end_tag('ul');
2501 echo html_writer::end_tag('div'); // End of info div
2503 echo html_writer::start_tag('div', array('class'=>'summary'));
2504 $options = new stdClass();
2505 $options->noclean = true;
2506 $options->para = false;
2507 $options->overflowdiv = true;
2508 if (!isset($course->summaryformat)) {
2509 $course->summaryformat = FORMAT_MOODLE;
2511 echo highlight($highlightterms, format_text($course->summary, $course->summaryformat, $options, $course->id));
2512 if ($icons = enrol_get_course_info_icons($course)) {
2513 echo html_writer::start_tag('div', array('class'=>'enrolmenticons'));
2514 foreach ($icons as $icon) {
2515 echo $OUTPUT->render($icon);
2517 echo html_writer::end_tag('div'); // End of enrolmenticons div
2519 echo html_writer::end_tag('div'); // End of summary div
2520 echo html_writer::end_tag('div'); // End of coursebox div
2524 * Prints custom user information on the home page.
2525 * Over time this can include all sorts of information
2527 function print_my_moodle() {
2528 global $USER, $CFG, $DB, $OUTPUT;
2530 if (!isloggedin() or isguestuser()) {
2531 print_error('nopermissions', '', '', 'See My Moodle');
2534 $courses = enrol_get_my_courses('summary', 'visible DESC,sortorder ASC');
2535 $rhosts = array();
2536 $rcourses = array();
2537 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
2538 $rcourses = get_my_remotecourses($USER->id);
2539 $rhosts = get_my_remotehosts();
2542 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
2544 if (!empty($courses)) {
2545 echo '<ul class="unlist">';
2546 foreach ($courses as $course) {
2547 if ($course->id == SITEID) {
2548 continue;
2550 echo '<li>';
2551 print_course($course);
2552 echo "</li>\n";
2554 echo "</ul>\n";
2557 // MNET
2558 if (!empty($rcourses)) {
2559 // at the IDP, we know of all the remote courses
2560 foreach ($rcourses as $course) {
2561 print_remote_course($course, "100%");
2563 } elseif (!empty($rhosts)) {
2564 // non-IDP, we know of all the remote servers, but not courses
2565 foreach ($rhosts as $host) {
2566 print_remote_host($host, "100%");
2569 unset($course);
2570 unset($host);
2572 if ($DB->count_records("course") > (count($courses) + 1) ) { // Some courses not being displayed
2573 echo "<table width=\"100%\"><tr><td align=\"center\">";
2574 print_course_search("", false, "short");
2575 echo "</td><td align=\"center\">";
2576 echo $OUTPUT->single_button("$CFG->wwwroot/course/index.php", get_string("fulllistofcourses"), "get");
2577 echo "</td></tr></table>\n";
2580 } else {
2581 if ($DB->count_records("course_categories") > 1) {
2582 echo $OUTPUT->box_start("categorybox");
2583 print_whole_category_list();
2584 echo $OUTPUT->box_end();
2585 } else {
2586 print_courses(0);
2592 function print_course_search($value="", $return=false, $format="plain") {
2593 global $CFG;
2594 static $count = 0;
2596 $count++;
2598 $id = 'coursesearch';
2600 if ($count > 1) {
2601 $id .= $count;
2604 $strsearchcourses= get_string("searchcourses");
2606 if ($format == 'plain') {
2607 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2608 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2609 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
2610 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" value="'.s($value).'" />';
2611 $output .= '<input type="submit" value="'.get_string('go').'" />';
2612 $output .= '</fieldset></form>';
2613 } else if ($format == 'short') {
2614 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2615 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2616 $output .= '<label for="shortsearchbox">'.$strsearchcourses.': </label>';
2617 $output .= '<input type="text" id="shortsearchbox" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2618 $output .= '<input type="submit" value="'.get_string('go').'" />';
2619 $output .= '</fieldset></form>';
2620 } else if ($format == 'navbar') {
2621 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2622 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2623 $output .= '<label for="navsearchbox">'.$strsearchcourses.': </label>';
2624 $output .= '<input type="text" id="navsearchbox" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2625 $output .= '<input type="submit" value="'.get_string('go').'" />';
2626 $output .= '</fieldset></form>';
2629 if ($return) {
2630 return $output;
2632 echo $output;
2635 function print_remote_course($course, $width="100%") {
2636 global $CFG, $USER;
2638 $linkcss = '';
2640 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&amp;wantsurl=/course/view.php?id={$course->remoteid}";
2642 echo '<div class="coursebox remotecoursebox clearfix">';
2643 echo '<div class="info">';
2644 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2645 $linkcss.' href="'.$url.'">'
2646 . format_string($course->fullname) .'</a><br />'
2647 . format_string($course->hostname) . ' : '
2648 . format_string($course->cat_name) . ' : '
2649 . format_string($course->shortname). '</div>';
2650 echo '</div><div class="summary">';
2651 $options = new stdClass();
2652 $options->noclean = true;
2653 $options->para = false;
2654 $options->overflowdiv = true;
2655 echo format_text($course->summary, $course->summaryformat, $options);
2656 echo '</div>';
2657 echo '</div>';
2660 function print_remote_host($host, $width="100%") {
2661 global $OUTPUT;
2663 $linkcss = '';
2665 echo '<div class="coursebox clearfix">';
2666 echo '<div class="info">';
2667 echo '<div class="name">';
2668 echo '<img src="'.$OUTPUT->pix_url('i/mnethost') . '" class="icon" alt="'.get_string('course').'" />';
2669 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2670 . s($host['name']).'</a> - ';
2671 echo $host['count'] . ' ' . get_string('courses');
2672 echo '</div>';
2673 echo '</div>';
2674 echo '</div>';
2678 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2680 function add_course_module($mod) {
2681 global $DB;
2683 $mod->added = time();
2684 unset($mod->id);
2686 return $DB->insert_record("course_modules", $mod);
2690 * Returns course section - creates new if does not exist yet.
2691 * @param int $relative section number
2692 * @param int $courseid
2693 * @return object $course_section object
2695 function get_course_section($section, $courseid) {
2696 global $DB;
2698 if ($cw = $DB->get_record("course_sections", array("section"=>$section, "course"=>$courseid))) {
2699 return $cw;
2701 $cw = new stdClass();
2702 $cw->course = $courseid;
2703 $cw->section = $section;
2704 $cw->summary = "";
2705 $cw->summaryformat = FORMAT_HTML;
2706 $cw->sequence = "";
2707 $id = $DB->insert_record("course_sections", $cw);
2708 return $DB->get_record("course_sections", array("id"=>$id));
2711 * Given a full mod object with section and course already defined, adds this module to that section.
2713 * @param object $mod
2714 * @param int $beforemod An existing ID which we will insert the new module before
2715 * @return int The course_sections ID where the mod is inserted
2717 function add_mod_to_section($mod, $beforemod=NULL) {
2718 global $DB;
2720 if ($section = $DB->get_record("course_sections", array("course"=>$mod->course, "section"=>$mod->section))) {
2722 $section->sequence = trim($section->sequence);
2724 if (empty($section->sequence)) {
2725 $newsequence = "$mod->coursemodule";
2727 } else if ($beforemod) {
2728 $modarray = explode(",", $section->sequence);
2730 if ($key = array_keys($modarray, $beforemod->id)) {
2731 $insertarray = array($mod->id, $beforemod->id);
2732 array_splice($modarray, $key[0], 1, $insertarray);
2733 $newsequence = implode(",", $modarray);
2735 } else { // Just tack it on the end anyway
2736 $newsequence = "$section->sequence,$mod->coursemodule";
2739 } else {
2740 $newsequence = "$section->sequence,$mod->coursemodule";
2743 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
2744 return $section->id; // Return course_sections ID that was used.
2746 } else { // Insert a new record
2747 $section->course = $mod->course;
2748 $section->section = $mod->section;
2749 $section->summary = "";
2750 $section->summaryformat = FORMAT_HTML;
2751 $section->sequence = $mod->coursemodule;
2752 return $DB->insert_record("course_sections", $section);
2756 function set_coursemodule_groupmode($id, $groupmode) {
2757 global $DB;
2758 return $DB->set_field("course_modules", "groupmode", $groupmode, array("id"=>$id));
2761 function set_coursemodule_idnumber($id, $idnumber) {
2762 global $DB;
2763 return $DB->set_field("course_modules", "idnumber", $idnumber, array("id"=>$id));
2767 * $prevstateoverrides = true will set the visibility of the course module
2768 * to what is defined in visibleold. This enables us to remember the current
2769 * visibility when making a whole section hidden, so that when we toggle
2770 * that section back to visible, we are able to return the visibility of
2771 * the course module back to what it was originally.
2773 function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
2774 global $DB, $CFG;
2775 require_once($CFG->libdir.'/gradelib.php');
2777 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2778 return false;
2780 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
2781 return false;
2783 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2784 foreach($events as $event) {
2785 if ($visible) {
2786 show_event($event);
2787 } else {
2788 hide_event($event);
2793 // hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there
2794 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
2795 if ($grade_items) {
2796 foreach ($grade_items as $grade_item) {
2797 $grade_item->set_hidden(!$visible);
2801 if ($prevstateoverrides) {
2802 if ($visible == '0') {
2803 // Remember the current visible state so we can toggle this back.
2804 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id'=>$id));
2805 } else {
2806 // Get the previous saved visible states.
2807 return $DB->set_field('course_modules', 'visible', $cm->visibleold, array('id'=>$id));
2810 return $DB->set_field("course_modules", "visible", $visible, array("id"=>$id));
2814 * Delete a course module and any associated data at the course level (events)
2815 * Until 1.5 this function simply marked a deleted flag ... now it
2816 * deletes it completely.
2819 function delete_course_module($id) {
2820 global $CFG, $DB;
2821 require_once($CFG->libdir.'/gradelib.php');
2822 require_once($CFG->dirroot.'/blog/lib.php');
2824 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2825 return true;
2827 $modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module));
2828 //delete events from calendar
2829 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2830 foreach($events as $event) {
2831 delete_event($event->id);
2834 //delete grade items, outcome items and grades attached to modules
2835 if ($grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2836 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course))) {
2837 foreach ($grade_items as $grade_item) {
2838 $grade_item->delete('moddelete');
2841 // Delete completion and availability data; it is better to do this even if the
2842 // features are not turned on, in case they were turned on previously (these will be
2843 // very quick on an empty table)
2844 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
2845 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id));
2847 delete_context(CONTEXT_MODULE, $cm->id);
2848 return $DB->delete_records('course_modules', array('id'=>$cm->id));
2851 function delete_mod_from_section($mod, $section) {
2852 global $DB;
2854 if ($section = $DB->get_record("course_sections", array("id"=>$section)) ) {
2856 $modarray = explode(",", $section->sequence);
2858 if ($key = array_keys ($modarray, $mod)) {
2859 array_splice($modarray, $key[0], 1);
2860 $newsequence = implode(",", $modarray);
2861 return $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
2862 } else {
2863 return false;
2867 return false;
2871 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
2873 * @param object $course
2874 * @param int $section
2875 * @param int $move (-1 or 1)
2877 function move_section($course, $section, $move) {
2878 /// Moves a whole course section up and down within the course
2879 global $USER, $DB;
2881 if (!$move) {
2882 return true;
2885 $sectiondest = $section + $move;
2887 if ($sectiondest > $course->numsections or $sectiondest < 1) {
2888 return false;
2891 if (!$sectionrecord = $DB->get_record("course_sections", array("course"=>$course->id, "section"=>$section))) {
2892 return false;
2895 if (!$sectiondestrecord = $DB->get_record("course_sections", array("course"=>$course->id, "section"=>$sectiondest))) {
2896 return false;
2899 $DB->set_field("course_sections", "section", $sectiondest, array("id"=>$sectionrecord->id));
2900 $DB->set_field("course_sections", "section", $section, array("id"=>$sectiondestrecord->id));
2902 // if the focus is on the section that is being moved, then move the focus along
2903 if (course_get_display($course->id) == $section) {
2904 course_set_display($course->id, $sectiondest);
2907 // Check for duplicates and fix order if needed.
2908 // There is a very rare case that some sections in the same course have the same section id.
2909 $sections = $DB->get_records('course_sections', array('course'=>$course->id), 'section ASC');
2910 $n = 0;
2911 foreach ($sections as $section) {
2912 if ($section->section != $n) {
2913 $DB->set_field('course_sections', 'section', $n, array('id'=>$section->id));
2915 $n++;
2917 return true;
2921 * Moves a section within a course, from a position to another.
2922 * Be very careful: $section and $destination refer to section number,
2923 * not id!.
2925 * @param object $course
2926 * @param int $section Section number (not id!!!)
2927 * @param int $destination
2928 * @return boolean Result
2930 function move_section_to($course, $section, $destination) {
2931 /// Moves a whole course section up and down within the course
2932 global $USER, $DB;
2934 if (!$destination && $destination != 0) {
2935 return true;
2938 if ($destination > $course->numsections) {
2939 return false;
2942 // Get all sections for this course and re-order them (2 of them should now share the same section number)
2943 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
2944 'section ASC, id ASC', 'id, section')) {
2945 return false;
2948 $sections = reorder_sections($sections, $section, $destination);
2950 // Update all sections
2951 foreach ($sections as $id => $position) {
2952 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
2955 // if the focus is on the section that is being moved, then move the focus along
2956 if (course_get_display($course->id) == $section) {
2957 course_set_display($course->id, $destination);
2959 return true;
2963 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
2964 * an original position number and a target position number, rebuilds the array so that the
2965 * move is made without any duplication of section positions.
2966 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
2967 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
2969 * @param array $sections
2970 * @param int $origin_position
2971 * @param int $target_position
2972 * @return array
2974 function reorder_sections($sections, $origin_position, $target_position) {
2975 if (!is_array($sections)) {
2976 return false;
2979 // We can't move section position 0
2980 if ($origin_position < 1) {
2981 echo "We can't move section position 0";
2982 return false;
2985 // Locate origin section in sections array
2986 if (!$origin_key = array_search($origin_position, $sections)) {
2987 echo "searched position not in sections array";
2988 return false; // searched position not in sections array
2991 // Extract origin section
2992 $origin_section = $sections[$origin_key];
2993 unset($sections[$origin_key]);
2995 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
2996 $found = false;
2997 $append_array = array();
2998 foreach ($sections as $id => $position) {
2999 if ($found) {
3000 $append_array[$id] = $position;
3001 unset($sections[$id]);
3003 if ($position == $target_position) {
3004 $found = true;
3008 // Append moved section
3009 $sections[$origin_key] = $origin_section;
3011 // Append rest of array (if applicable)
3012 if (!empty($append_array)) {
3013 foreach ($append_array as $id => $position) {
3014 $sections[$id] = $position;
3018 // Renumber positions
3019 $position = 0;
3020 foreach ($sections as $id => $p) {
3021 $sections[$id] = $position;
3022 $position++;
3025 return $sections;
3030 * Move the module object $mod to the specified $section
3031 * If $beforemod exists then that is the module
3032 * before which $modid should be inserted
3033 * All parameters are objects
3035 function moveto_module($mod, $section, $beforemod=NULL) {
3036 global $DB, $OUTPUT;
3038 /// Remove original module from original section
3039 if (! delete_mod_from_section($mod->id, $mod->section)) {
3040 echo $OUTPUT->notification("Could not delete module from existing section");
3043 /// Update module itself if necessary
3045 if ($mod->section != $section->id) {
3046 $mod->section = $section->id;
3047 $DB->update_record("course_modules", $mod);
3048 // if moving to a hidden section then hide module
3049 if (!$section->visible) {
3050 set_coursemodule_visible($mod->id, 0);
3054 /// Add the module into the new section
3056 $mod->course = $section->course;
3057 $mod->section = $section->section; // need relative reference
3058 $mod->coursemodule = $mod->id;
3060 if (! add_mod_to_section($mod, $beforemod)) {
3061 return false;
3064 return true;
3068 * Produces the editing buttons for a module
3070 * @global core_renderer $OUTPUT
3071 * @staticvar type $str
3072 * @param stdClass $mod The module to produce editing buttons for
3073 * @param bool $absolute_ignored ignored - all links are absolute
3074 * @param bool $moveselect If true a move seleciton process is used (default true)
3075 * @param int $indent The current indenting
3076 * @param int $section The section to link back to
3077 * @return string XHTML for the editing buttons
3079 function make_editing_buttons(stdClass $mod, $absolute_ignored = true, $moveselect = true, $indent=-1, $section=-1) {
3080 global $CFG, $OUTPUT;
3082 static $str;
3084 $coursecontext = get_context_instance(CONTEXT_COURSE, $mod->course);
3085 $modcontext = get_context_instance(CONTEXT_MODULE, $mod->id);
3087 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
3088 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
3090 // no permission to edit anything
3091 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
3092 return false;
3095 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
3097 if (!isset($str)) {
3098 $str = new stdClass;
3099 $str->assign = get_string("assignroles", 'role');
3100 $str->delete = get_string("delete");
3101 $str->move = get_string("move");
3102 $str->moveup = get_string("moveup");
3103 $str->movedown = get_string("movedown");
3104 $str->moveright = get_string("moveright");
3105 $str->moveleft = get_string("moveleft");
3106 $str->update = get_string("update");
3107 $str->duplicate = get_string("duplicate");
3108 $str->hide = get_string("hide");
3109 $str->show = get_string("show");
3110 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
3111 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
3112 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
3113 $str->forcedgroupsnone = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsnone"));
3114 $str->forcedgroupsseparate = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsseparate"));
3115 $str->forcedgroupsvisible = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsvisible"));
3118 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
3120 if ($section >= 0) {
3121 $baseurl->param('sr', $section);
3123 $actions = array();
3125 // leftright
3126 if ($hasmanageactivities) {
3127 if (right_to_left()) { // Exchange arrows on RTL
3128 $rightarrow = 't/left';
3129 $leftarrow = 't/right';
3130 } else {
3131 $rightarrow = 't/right';
3132 $leftarrow = 't/left';
3135 if ($indent > 0) {
3136 $actions[] = new action_link(
3137 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
3138 new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall')),
3139 null,
3140 array('class' => 'editing_moveleft', 'title' => $str->moveleft)
3143 if ($indent >= 0) {
3144 $actions[] = new action_link(
3145 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
3146 new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall')),
3147 null,
3148 array('class' => 'editing_moveright', 'title' => $str->moveright)
3153 // move
3154 if ($hasmanageactivities) {
3155 if ($moveselect) {
3156 $actions[] = new action_link(
3157 new moodle_url($baseurl, array('copy' => $mod->id)),
3158 new pix_icon('t/move', $str->move, 'moodle', array('class' => 'iconsmall')),
3159 null,
3160 array('class' => 'editing_move', 'title' => $str->move)
3162 } else {
3163 $actions[] = new action_link(
3164 new moodle_url($baseurl, array('id' => $mod->id, 'move' => '-1')),
3165 new pix_icon('t/up', $str->moveup, 'moodle', array('class' => 'iconsmall')),
3166 null,
3167 array('class' => 'editing_moveup', 'title' => $str->moveup)
3169 $actions[] = new action_link(
3170 new moodle_url($baseurl, array('id' => $mod->id, 'move' => '1')),
3171 new pix_icon('t/down', $str->movedown, 'moodle', array('class' => 'iconsmall')),
3172 null,
3173 array('class' => 'editing_movedown', 'title' => $str->movedown)
3178 // Update
3179 if ($hasmanageactivities) {
3180 $actions[] = new action_link(
3181 new moodle_url($baseurl, array('update' => $mod->id)),
3182 new pix_icon('t/edit', $str->update, 'moodle', array('class' => 'iconsmall')),
3183 null,
3184 array('class' => 'editing_update', 'title' => $str->update)
3188 // Duplicate (require both target import caps to be able to duplicate, see modduplicate.php)
3189 if (has_all_capabilities($dupecaps, $coursecontext)) {
3190 $actions[] = new action_link(
3191 new moodle_url($baseurl, array('duplicate' => $mod->id)),
3192 new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall')),
3193 null,
3194 array('class' => 'editing_duplicate', 'title' => $str->duplicate)
3198 // Delete
3199 if ($hasmanageactivities) {
3200 $actions[] = new action_link(
3201 new moodle_url($baseurl, array('delete' => $mod->id)),
3202 new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall')),
3203 null,
3204 array('class' => 'editing_delete', 'title' => $str->delete)
3208 // hideshow
3209 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
3210 if ($mod->visible) {
3211 $actions[] = new action_link(
3212 new moodle_url($baseurl, array('hide' => $mod->id)),
3213 new pix_icon('t/hide', $str->hide, 'moodle', array('class' => 'iconsmall')),
3214 null,
3215 array('class' => 'editing_hide', 'title' => $str->hide)
3217 } else {
3218 $actions[] = new action_link(
3219 new moodle_url($baseurl, array('show' => $mod->id)),
3220 new pix_icon('t/show', $str->show, 'moodle', array('class' => 'iconsmall')),
3221 null,
3222 array('class' => 'editing_show', 'title' => $str->show)
3227 // groupmode
3228 if ($hasmanageactivities and $mod->groupmode !== false) {
3229 if ($mod->groupmode == SEPARATEGROUPS) {
3230 $groupmode = 0;
3231 $grouptitle = $str->groupsseparate;
3232 $forcedgrouptitle = $str->forcedgroupsseparate;
3233 $groupclass = 'editing_groupsseparate';
3234 $groupimage = 't/groups';
3235 } else if ($mod->groupmode == VISIBLEGROUPS) {
3236 $groupmode = 1;
3237 $grouptitle = $str->groupsvisible;
3238 $forcedgrouptitle = $str->forcedgroupsvisible;
3239 $groupclass = 'editing_groupsvisible';
3240 $groupimage = 't/groupv';
3241 } else {
3242 $groupmode = 2;
3243 $grouptitle = $str->groupsnone;
3244 $forcedgrouptitle = $str->forcedgroupsnone;
3245 $groupclass = 'editing_groupsnone';
3246 $groupimage = 't/groupn';
3248 if ($mod->groupmodelink) {
3249 $actions[] = new action_link(
3250 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $groupmode)),
3251 new pix_icon($groupimage, $grouptitle, 'moodle', array('class' => 'iconsmall')),
3252 null,
3253 array('class' => $groupclass, 'title' => $grouptitle)
3255 } else {
3256 $actions[] = new pix_icon($groupimage, $forcedgrouptitle, 'moodle', array('title' => $forcedgrouptitle, 'class' => 'iconsmall'));
3260 // Assign
3261 if (has_capability('moodle/role:assign', $modcontext)){
3262 $actions[] = new action_link(
3263 new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $modcontext->id)),
3264 new pix_icon('i/roles', $str->assign, 'moodle', array('class' => 'iconsmall')),
3265 null,
3266 array('class' => 'editing_assign', 'title' => $str->assign)
3270 $output = html_writer::start_tag('span', array('class' => 'commands'));
3271 foreach ($actions as $action) {
3272 if ($action instanceof renderable) {
3273 $output .= $OUTPUT->render($action);
3274 } else {
3275 $output .= $action;
3278 $output .= html_writer::end_tag('span');
3279 return $output;
3283 * given a course object with shortname & fullname, this function will
3284 * truncate the the number of chars allowed and add ... if it was too long
3286 function course_format_name ($course,$max=100) {
3288 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3289 $shortname = format_string($course->shortname, true, array('context' => $context));
3290 $fullname = format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
3291 $str = $shortname.': '. $fullname;
3292 if (textlib::strlen($str) <= $max) {
3293 return $str;
3295 else {
3296 return textlib::substr($str,0,$max-3).'...';
3300 function update_restricted_mods($course, $mods) {
3301 global $DB;
3303 /// Delete all the current restricted list
3304 $DB->delete_records('course_allowed_modules', array('course'=>$course->id));
3306 if (empty($course->restrictmodules)) {
3307 return; // We're done
3310 /// Insert the new list of restricted mods
3311 foreach ($mods as $mod) {
3312 if ($mod == 0) {
3313 continue; // this is the 'allow none' option
3315 $am = new stdClass();
3316 $am->course = $course->id;
3317 $am->module = $mod;
3318 $DB->insert_record('course_allowed_modules',$am);
3323 * This function will take an int (module id) or a string (module name)
3324 * and return true or false, whether it's allowed in the given course (object)
3325 * $mod is not allowed to be an object, as the field for the module id is inconsistent
3326 * depending on where in the code it's called from (sometimes $mod->id, sometimes $mod->module)
3329 function course_allowed_module($course,$mod) {
3330 global $DB;
3332 if (empty($course->restrictmodules)) {
3333 return true;
3336 // Admins and admin-like people who can edit everything can also add anything.
3337 // Originally there was a course:update test only, but it did not match the test in course edit form
3338 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
3339 return true;
3342 if (is_numeric($mod)) {
3343 $modid = $mod;
3344 } else if (is_string($mod)) {
3345 $modid = $DB->get_field('modules', 'id', array('name'=>$mod));
3347 if (empty($modid)) {
3348 return false;
3351 return $DB->record_exists('course_allowed_modules', array('course'=>$course->id, 'module'=>$modid));
3355 * Recursively delete category including all subcategories and courses.
3356 * @param stdClass $category
3357 * @param boolean $showfeedback display some notices
3358 * @return array return deleted courses
3360 function category_delete_full($category, $showfeedback=true) {
3361 global $CFG, $DB;
3362 require_once($CFG->libdir.'/gradelib.php');
3363 require_once($CFG->libdir.'/questionlib.php');
3364 require_once($CFG->dirroot.'/cohort/lib.php');
3366 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3367 foreach ($children as $childcat) {
3368 category_delete_full($childcat, $showfeedback);
3372 $deletedcourses = array();
3373 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC')) {
3374 foreach ($courses as $course) {
3375 if (!delete_course($course, false)) {
3376 throw new moodle_exception('cannotdeletecategorycourse','','',$course->shortname);
3378 $deletedcourses[] = $course;
3382 // move or delete cohorts in this context
3383 cohort_delete_category($category);
3385 // now delete anything that may depend on course category context
3386 grade_course_category_delete($category->id, 0, $showfeedback);
3387 if (!question_delete_course_category($category, 0, $showfeedback)) {
3388 throw new moodle_exception('cannotdeletecategoryquestions','','',$category->name);
3391 // finally delete the category and it's context
3392 $DB->delete_records('course_categories', array('id'=>$category->id));
3393 delete_context(CONTEXT_COURSECAT, $category->id);
3395 events_trigger('course_category_deleted', $category);
3397 return $deletedcourses;
3401 * Delete category, but move contents to another category.
3402 * @param object $ccategory
3403 * @param int $newparentid category id
3404 * @return bool status
3406 function category_delete_move($category, $newparentid, $showfeedback=true) {
3407 global $CFG, $DB, $OUTPUT;
3408 require_once($CFG->libdir.'/gradelib.php');
3409 require_once($CFG->libdir.'/questionlib.php');
3410 require_once($CFG->dirroot.'/cohort/lib.php');
3412 if (!$newparentcat = $DB->get_record('course_categories', array('id'=>$newparentid))) {
3413 return false;
3416 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3417 foreach ($children as $childcat) {
3418 move_category($childcat, $newparentcat);
3422 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC', 'id')) {
3423 if (!move_courses(array_keys($courses), $newparentid)) {
3424 echo $OUTPUT->notification("Error moving courses");
3425 return false;
3427 echo $OUTPUT->notification(get_string('coursesmovedout', '', format_string($category->name)), 'notifysuccess');
3430 // move or delete cohorts in this context
3431 cohort_delete_category($category);
3433 // now delete anything that may depend on course category context
3434 grade_course_category_delete($category->id, $newparentid, $showfeedback);
3435 if (!question_delete_course_category($category, $newparentcat, $showfeedback)) {
3436 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $category), 'notifysuccess');
3437 return false;
3440 // finally delete the category and it's context
3441 $DB->delete_records('course_categories', array('id'=>$category->id));
3442 delete_context(CONTEXT_COURSECAT, $category->id);
3444 events_trigger('course_category_deleted', $category);
3446 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', format_string($category->name)), 'notifysuccess');
3448 return true;
3452 * Efficiently moves many courses around while maintaining
3453 * sortorder in order.
3455 * @param array $courseids is an array of course ids
3456 * @param int $categoryid
3457 * @return bool success
3459 function move_courses($courseids, $categoryid) {
3460 global $CFG, $DB, $OUTPUT;
3462 if (empty($courseids)) {
3463 // nothing to do
3464 return;
3467 if (!$category = $DB->get_record('course_categories', array('id'=>$categoryid))) {
3468 return false;
3471 $courseids = array_reverse($courseids);
3472 $newparent = get_context_instance(CONTEXT_COURSECAT, $category->id);
3473 $i = 1;
3475 foreach ($courseids as $courseid) {
3476 if ($course = $DB->get_record('course', array('id'=>$courseid), 'id, category')) {
3477 $course = new stdClass();
3478 $course->id = $courseid;
3479 $course->category = $category->id;
3480 $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
3481 if ($category->visible == 0) {
3482 // hide the course when moving into hidden category,
3483 // do not update the visibleold flag - we want to get to previous state if somebody unhides the category
3484 $course->visible = 0;
3487 $DB->update_record('course', $course);
3489 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3490 context_moved($context, $newparent);
3493 fix_course_sortorder();
3495 return true;
3499 * Hide course category and child course and subcategories
3500 * @param stdClass $category
3501 * @return void
3503 function course_category_hide($category) {
3504 global $DB;
3506 $category->visible = 0;
3507 $DB->set_field('course_categories', 'visible', 0, array('id'=>$category->id));
3508 $DB->set_field('course_categories', 'visibleold', 0, array('id'=>$category->id));
3509 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($category->id)); // store visible flag so that we can return to it if we immediately unhide
3510 $DB->set_field('course', 'visible', 0, array('category' => $category->id));
3511 // get all child categories and hide too
3512 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
3513 foreach ($subcats as $cat) {
3514 $DB->set_field('course_categories', 'visibleold', $cat->visible, array('id'=>$cat->id));
3515 $DB->set_field('course_categories', 'visible', 0, array('id'=>$cat->id));
3516 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id));
3517 $DB->set_field('course', 'visible', 0, array('category' => $cat->id));
3523 * Show course category and child course and subcategories
3524 * @param stdClass $category
3525 * @return void
3527 function course_category_show($category) {
3528 global $DB;
3530 $category->visible = 1;
3531 $DB->set_field('course_categories', 'visible', 1, array('id'=>$category->id));
3532 $DB->set_field('course_categories', 'visibleold', 1, array('id'=>$category->id));
3533 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($category->id));
3534 // get all child categories and unhide too
3535 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
3536 foreach ($subcats as $cat) {
3537 if ($cat->visibleold) {
3538 $DB->set_field('course_categories', 'visible', 1, array('id'=>$cat->id));
3540 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id));
3546 * Efficiently moves a category - NOTE that this can have
3547 * a huge impact access-control-wise...
3549 function move_category($category, $newparentcat) {
3550 global $CFG, $DB;
3552 $context = get_context_instance(CONTEXT_COURSECAT, $category->id);
3554 $hidecat = false;
3555 if (empty($newparentcat->id)) {
3556 $DB->set_field('course_categories', 'parent', 0, array('id'=>$category->id));
3558 $newparent = get_context_instance(CONTEXT_SYSTEM);
3560 } else {
3561 $DB->set_field('course_categories', 'parent', $newparentcat->id, array('id'=>$category->id));
3562 $newparent = get_context_instance(CONTEXT_COURSECAT, $newparentcat->id);
3564 if (!$newparentcat->visible and $category->visible) {
3565 // better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children will be restored properly
3566 $hidecat = true;
3570 context_moved($context, $newparent);
3572 // now make it last in new category
3573 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('id'=>$category->id));
3575 // and fix the sortorders
3576 fix_course_sortorder();
3578 if ($hidecat) {
3579 course_category_hide($category);
3584 * Returns the display name of the given section that the course prefers.
3586 * This function utilizes a callback that can be implemented within the course
3587 * formats lib.php file to customize the display name that is used to reference
3588 * the section.
3590 * By default (if callback is not defined) the method
3591 * {@see get_numeric_section_name} is called instead.
3593 * @param stdClass $course The course to get the section name for
3594 * @param stdClass $section Section object from database
3595 * @return Display name that the course format prefers, e.g. "Week 2"
3597 * @see get_generic_section_name
3599 function get_section_name(stdClass $course, stdClass $section) {
3600 global $CFG;
3602 /// Inelegant hack for bug 3408
3603 if ($course->format == 'site') {
3604 return get_string('site');
3607 // Use course formatter callback if it exists
3608 $namingfile = $CFG->dirroot.'/course/format/'.$course->format.'/lib.php';
3609 $namingfunction = 'callback_'.$course->format.'_get_section_name';
3610 if (!function_exists($namingfunction) && file_exists($namingfile)) {
3611 require_once $namingfile;
3613 if (function_exists($namingfunction)) {
3614 return $namingfunction($course, $section);
3617 // else, default behavior:
3618 return get_generic_section_name($course->format, $section);
3622 * Gets the generic section name for a courses section.
3624 * @param string $format Course format ID e.g. 'weeks' $course->format
3625 * @param stdClass $section Section object from database
3626 * @return Display name that the course format prefers, e.g. "Week 2"
3628 function get_generic_section_name($format, stdClass $section) {
3629 return get_string('sectionname', "format_$format") . ' ' . $section->section;
3633 function course_format_uses_sections($format) {
3634 global $CFG;
3636 $featurefile = $CFG->dirroot.'/course/format/'.$format.'/lib.php';
3637 $featurefunction = 'callback_'.$format.'_uses_sections';
3638 if (!function_exists($featurefunction) && file_exists($featurefile)) {
3639 require_once $featurefile;
3641 if (function_exists($featurefunction)) {
3642 return $featurefunction();
3645 return false;
3649 * Returns the information about the ajax support in the given source format
3651 * The returned object's property (boolean)capable indicates that
3652 * the course format supports Moodle course ajax features.
3653 * The property (array)testedbrowsers can be used as a parameter for {@see ajaxenabled()}.
3655 * @param string $format
3656 * @return stdClass
3658 function course_format_ajax_support($format) {
3659 global $CFG;
3661 // set up default values
3662 $ajaxsupport = new stdClass();
3663 $ajaxsupport->capable = false;
3664 $ajaxsupport->testedbrowsers = array();
3666 // get the information from the course format library
3667 $featurefile = $CFG->dirroot.'/course/format/'.$format.'/lib.php';
3668 $featurefunction = 'callback_'.$format.'_ajax_support';
3669 if (!function_exists($featurefunction) && file_exists($featurefile)) {
3670 require_once $featurefile;
3672 if (function_exists($featurefunction)) {
3673 $formatsupport = $featurefunction();
3674 if (isset($formatsupport->capable)) {
3675 $ajaxsupport->capable = $formatsupport->capable;
3677 if (is_array($formatsupport->testedbrowsers)) {
3678 $ajaxsupport->testedbrowsers = $formatsupport->testedbrowsers;
3682 return $ajaxsupport;
3686 * Can the current user delete this course?
3687 * Course creators have exception,
3688 * 1 day after the creation they can sill delete the course.
3689 * @param int $courseid
3690 * @return boolean
3692 function can_delete_course($courseid) {
3693 global $USER, $DB;
3695 $context = get_context_instance(CONTEXT_COURSE, $courseid);
3697 if (has_capability('moodle/course:delete', $context)) {
3698 return true;
3701 // hack: now try to find out if creator created this course recently (1 day)
3702 if (!has_capability('moodle/course:create', $context)) {
3703 return false;
3706 $since = time() - 60*60*24;
3708 $params = array('userid'=>$USER->id, 'url'=>"view.php?id=$courseid", 'since'=>$since);
3709 $select = "module = 'course' AND action = 'new' AND userid = :userid AND url = :url AND time > :since";
3711 return $DB->record_exists_select('log', $select, $params);
3715 * Save the Your name for 'Some role' strings.
3717 * @param integer $courseid the id of this course.
3718 * @param array $data the data that came from the course settings form.
3720 function save_local_role_names($courseid, $data) {
3721 global $DB;
3722 $context = get_context_instance(CONTEXT_COURSE, $courseid);
3724 foreach ($data as $fieldname => $value) {
3725 if (strpos($fieldname, 'role_') !== 0) {
3726 continue;
3728 list($ignored, $roleid) = explode('_', $fieldname);
3730 // make up our mind whether we want to delete, update or insert
3731 if (!$value) {
3732 $DB->delete_records('role_names', array('contextid' => $context->id, 'roleid' => $roleid));
3734 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id, 'roleid' => $roleid))) {
3735 $rolename->name = $value;
3736 $DB->update_record('role_names', $rolename);
3738 } else {
3739 $rolename = new stdClass;
3740 $rolename->contextid = $context->id;
3741 $rolename->roleid = $roleid;
3742 $rolename->name = $value;
3743 $DB->insert_record('role_names', $rolename);
3749 * Create a course and either return a $course object
3751 * Please note this functions does not verify any access control,
3752 * the calling code is responsible for all validation (usually it is the form definition).
3754 * @param array $editoroptions course description editor options
3755 * @param object $data - all the data needed for an entry in the 'course' table
3756 * @return object new course instance
3758 function create_course($data, $editoroptions = NULL) {
3759 global $CFG, $DB;
3761 //check the categoryid - must be given for all new courses
3762 $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
3764 //check if the shortname already exist
3765 if (!empty($data->shortname)) {
3766 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
3767 throw new moodle_exception('shortnametaken');
3771 //check if the id number already exist
3772 if (!empty($data->idnumber)) {
3773 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
3774 throw new moodle_exception('idnumbertaken');
3778 $data->timecreated = time();
3779 $data->timemodified = $data->timecreated;
3781 // place at beginning of any category
3782 $data->sortorder = 0;
3784 if ($editoroptions) {
3785 // summary text is updated later, we need context to store the files first
3786 $data->summary = '';
3787 $data->summary_format = FORMAT_HTML;
3790 if (!isset($data->visible)) {
3791 // data not from form, add missing visibility info
3792 $data->visible = $category->visible;
3794 $data->visibleold = $data->visible;
3796 $newcourseid = $DB->insert_record('course', $data);
3797 $context = get_context_instance(CONTEXT_COURSE, $newcourseid, MUST_EXIST);
3799 if ($editoroptions) {
3800 // Save the files used in the summary editor and store
3801 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
3802 $DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid));
3803 $DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid));
3806 $course = $DB->get_record('course', array('id'=>$newcourseid));
3808 // Setup the blocks
3809 blocks_add_default_course_blocks($course);
3811 $section = new stdClass();
3812 $section->course = $course->id; // Create a default section.
3813 $section->section = 0;
3814 $section->summaryformat = FORMAT_HTML;
3815 $DB->insert_record('course_sections', $section);
3817 fix_course_sortorder();
3819 // update module restrictions
3820 if ($course->restrictmodules) {
3821 if (isset($data->allowedmods)) {
3822 update_restricted_mods($course, $data->allowedmods);
3823 } else {
3824 if (!empty($CFG->defaultallowedmodules)) {
3825 update_restricted_mods($course, explode(',', $CFG->defaultallowedmodules));
3830 // new context created - better mark it as dirty
3831 mark_context_dirty($context->path);
3833 // Save any custom role names.
3834 save_local_role_names($course->id, (array)$data);
3836 // set up enrolments
3837 enrol_course_updated(true, $course, $data);
3839 add_to_log(SITEID, 'course', 'new', 'view.php?id='.$course->id, $data->fullname.' (ID '.$course->id.')');
3841 // Trigger events
3842 events_trigger('course_created', $course);
3844 return $course;
3848 * Update a course.
3850 * Please note this functions does not verify any access control,
3851 * the calling code is responsible for all validation (usually it is the form definition).
3853 * @param object $data - all the data needed for an entry in the 'course' table
3854 * @param array $editoroptions course description editor options
3855 * @return void
3857 function update_course($data, $editoroptions = NULL) {
3858 global $CFG, $DB;
3860 $data->timemodified = time();
3862 $oldcourse = $DB->get_record('course', array('id'=>$data->id), '*', MUST_EXIST);
3863 $context = get_context_instance(CONTEXT_COURSE, $oldcourse->id);
3865 if ($editoroptions) {
3866 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
3869 if (!isset($data->category) or empty($data->category)) {
3870 // prevent nulls and 0 in category field
3871 unset($data->category);
3873 $movecat = (isset($data->category) and $oldcourse->category != $data->category);
3875 if (!isset($data->visible)) {
3876 // data not from form, add missing visibility info
3877 $data->visible = $oldcourse->visible;
3880 if ($data->visible != $oldcourse->visible) {
3881 // reset the visibleold flag when manually hiding/unhiding course
3882 $data->visibleold = $data->visible;
3883 } else {
3884 if ($movecat) {
3885 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category));
3886 if (empty($newcategory->visible)) {
3887 // make sure when moving into hidden category the course is hidden automatically
3888 $data->visible = 0;
3893 // Update with the new data
3894 $DB->update_record('course', $data);
3896 $course = $DB->get_record('course', array('id'=>$data->id));
3898 if ($movecat) {
3899 $newparent = get_context_instance(CONTEXT_COURSECAT, $course->category);
3900 context_moved($context, $newparent);
3903 fix_course_sortorder();
3905 // Test for and remove blocks which aren't appropriate anymore
3906 blocks_remove_inappropriate($course);
3908 // update module restrictions
3909 if (isset($data->allowedmods)) {
3910 update_restricted_mods($course, $data->allowedmods);
3913 // Save any custom role names.
3914 save_local_role_names($course->id, $data);
3916 // update enrol settings
3917 enrol_course_updated(false, $course, $data);
3919 add_to_log($course->id, "course", "update", "edit.php?id=$course->id", $course->id);
3921 // Trigger events
3922 events_trigger('course_updated', $course);
3926 * Average number of participants
3927 * @return integer
3929 function average_number_of_participants() {
3930 global $DB, $SITE;
3932 //count total of enrolments for visible course (except front page)
3933 $sql = 'SELECT COUNT(*) FROM (
3934 SELECT DISTINCT ue.userid, e.courseid
3935 FROM {user_enrolments} ue, {enrol} e, {course} c
3936 WHERE ue.enrolid = e.id
3937 AND e.courseid <> :siteid
3938 AND c.id = e.courseid
3939 AND c.visible = 1) as total';
3940 $params = array('siteid' => $SITE->id);
3941 $enrolmenttotal = $DB->count_records_sql($sql, $params);
3944 //count total of visible courses (minus front page)
3945 $coursetotal = $DB->count_records('course', array('visible' => 1));
3946 $coursetotal = $coursetotal - 1 ;
3948 //average of enrolment
3949 if (empty($coursetotal)) {
3950 $participantaverage = 0;
3951 } else {
3952 $participantaverage = $enrolmenttotal / $coursetotal;
3955 return $participantaverage;
3959 * Average number of course modules
3960 * @return integer
3962 function average_number_of_courses_modules() {
3963 global $DB, $SITE;
3965 //count total of visible course module (except front page)
3966 $sql = 'SELECT COUNT(*) FROM (
3967 SELECT cm.course, cm.module
3968 FROM {course} c, {course_modules} cm
3969 WHERE c.id = cm.course
3970 AND c.id <> :siteid
3971 AND cm.visible = 1
3972 AND c.visible = 1) as total';
3973 $params = array('siteid' => $SITE->id);
3974 $moduletotal = $DB->count_records_sql($sql, $params);
3977 //count total of visible courses (minus front page)
3978 $coursetotal = $DB->count_records('course', array('visible' => 1));
3979 $coursetotal = $coursetotal - 1 ;
3981 //average of course module
3982 if (empty($coursetotal)) {
3983 $coursemoduleaverage = 0;
3984 } else {
3985 $coursemoduleaverage = $moduletotal / $coursetotal;
3988 return $coursemoduleaverage;
3992 * This class pertains to course requests and contains methods associated with
3993 * create, approving, and removing course requests.
3995 * Please note we do not allow embedded images here because there is no context
3996 * to store them with proper access control.
3998 * @copyright 2009 Sam Hemelryk
3999 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4000 * @since Moodle 2.0
4002 * @property-read int $id
4003 * @property-read string $fullname
4004 * @property-read string $shortname
4005 * @property-read string $summary
4006 * @property-read int $summaryformat
4007 * @property-read int $summarytrust
4008 * @property-read string $reason
4009 * @property-read int $requester
4011 class course_request {
4014 * This is the stdClass that stores the properties for the course request
4015 * and is externally accessed through the __get magic method
4016 * @var stdClass
4018 protected $properties;
4021 * An array of options for the summary editor used by course request forms.
4022 * This is initially set by {@link summary_editor_options()}
4023 * @var array
4024 * @static
4026 protected static $summaryeditoroptions;
4029 * Static function to prepare the summary editor for working with a course
4030 * request.
4032 * @static
4033 * @param null|stdClass $data Optional, an object containing the default values
4034 * for the form, these may be modified when preparing the
4035 * editor so this should be called before creating the form
4036 * @return stdClass An object that can be used to set the default values for
4037 * an mforms form
4039 public static function prepare($data=null) {
4040 if ($data === null) {
4041 $data = new stdClass;
4043 $data = file_prepare_standard_editor($data, 'summary', self::summary_editor_options());
4044 return $data;
4048 * Static function to create a new course request when passed an array of properties
4049 * for it.
4051 * This function also handles saving any files that may have been used in the editor
4053 * @static
4054 * @param stdClass $data
4055 * @return course_request The newly created course request
4057 public static function create($data) {
4058 global $USER, $DB, $CFG;
4059 $data->requester = $USER->id;
4061 // Summary is a required field so copy the text over
4062 $data->summary = $data->summary_editor['text'];
4063 $data->summaryformat = $data->summary_editor['format'];
4065 $data->id = $DB->insert_record('course_request', $data);
4067 // Create a new course_request object and return it
4068 $request = new course_request($data);
4070 // Notify the admin if required.
4071 if ($users = get_users_from_config($CFG->courserequestnotify, 'moodle/site:approvecourse')) {
4073 $a = new stdClass;
4074 $a->link = "$CFG->wwwroot/course/pending.php";
4075 $a->user = fullname($USER);
4076 $subject = get_string('courserequest');
4077 $message = get_string('courserequestnotifyemail', 'admin', $a);
4078 foreach ($users as $user) {
4079 $request->notify($user, $USER, 'courserequested', $subject, $message);
4083 return $request;
4087 * Returns an array of options to use with a summary editor
4089 * @uses course_request::$summaryeditoroptions
4090 * @return array An array of options to use with the editor
4092 public static function summary_editor_options() {
4093 global $CFG;
4094 if (self::$summaryeditoroptions === null) {
4095 self::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
4097 return self::$summaryeditoroptions;
4101 * Loads the properties for this course request object. Id is required and if
4102 * only id is provided then we load the rest of the properties from the database
4104 * @param stdClass|int $properties Either an object containing properties
4105 * or the course_request id to load
4107 public function __construct($properties) {
4108 global $DB;
4109 if (empty($properties->id)) {
4110 if (empty($properties)) {
4111 throw new coding_exception('You must provide a course request id when creating a course_request object');
4113 $id = $properties;
4114 $properties = new stdClass;
4115 $properties->id = (int)$id;
4116 unset($id);
4118 if (empty($properties->requester)) {
4119 if (!($this->properties = $DB->get_record('course_request', array('id' => $properties->id)))) {
4120 print_error('unknowncourserequest');
4122 } else {
4123 $this->properties = $properties;
4125 $this->properties->collision = null;
4129 * Returns the requested property
4131 * @param string $key
4132 * @return mixed
4134 public function __get($key) {
4135 return $this->properties->$key;
4139 * Override this to ensure empty($request->blah) calls return a reliable answer...
4141 * This is required because we define the __get method
4143 * @param mixed $key
4144 * @return bool True is it not empty, false otherwise
4146 public function __isset($key) {
4147 return (!empty($this->properties->$key));
4151 * Returns the user who requested this course
4153 * Uses a static var to cache the results and cut down the number of db queries
4155 * @staticvar array $requesters An array of cached users
4156 * @return stdClass The user who requested the course
4158 public function get_requester() {
4159 global $DB;
4160 static $requesters= array();
4161 if (!array_key_exists($this->properties->requester, $requesters)) {
4162 $requesters[$this->properties->requester] = $DB->get_record('user', array('id'=>$this->properties->requester));
4164 return $requesters[$this->properties->requester];
4168 * Checks that the shortname used by the course does not conflict with any other
4169 * courses that exist
4171 * @param string|null $shortnamemark The string to append to the requests shortname
4172 * should a conflict be found
4173 * @return bool true is there is a conflict, false otherwise
4175 public function check_shortname_collision($shortnamemark = '[*]') {
4176 global $DB;
4178 if ($this->properties->collision !== null) {
4179 return $this->properties->collision;
4182 if (empty($this->properties->shortname)) {
4183 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER);
4184 $this->properties->collision = false;
4185 } else if ($DB->record_exists('course', array('shortname' => $this->properties->shortname))) {
4186 if (!empty($shortnamemark)) {
4187 $this->properties->shortname .= ' '.$shortnamemark;
4189 $this->properties->collision = true;
4190 } else {
4191 $this->properties->collision = false;
4193 return $this->properties->collision;
4197 * This function approves the request turning it into a course
4199 * This function converts the course request into a course, at the same time
4200 * transferring any files used in the summary to the new course and then removing
4201 * the course request and the files associated with it.
4203 * @return int The id of the course that was created from this request
4205 public function approve() {
4206 global $CFG, $DB, $USER;
4208 $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted'=>0), '*', MUST_EXIST);
4210 $category = get_course_category($CFG->defaultrequestcategory);
4211 $courseconfig = get_config('moodlecourse');
4213 // Transfer appropriate settings
4214 $data = clone($this->properties);
4215 unset($data->id);
4216 unset($data->reason);
4217 unset($data->requester);
4219 // Set category
4220 $data->category = $category->id;
4221 $data->sortorder = $category->sortorder; // place as the first in category
4223 // Set misc settings
4224 $data->requested = 1;
4225 if (!empty($CFG->restrictmodulesfor) && $CFG->restrictmodulesfor != 'none' && !empty($CFG->restrictbydefault)) {
4226 $data->restrictmodules = 1;
4229 // Apply course default settings
4230 $data->format = $courseconfig->format;
4231 $data->numsections = $courseconfig->numsections;
4232 $data->hiddensections = $courseconfig->hiddensections;
4233 $data->newsitems = $courseconfig->newsitems;
4234 $data->showgrades = $courseconfig->showgrades;
4235 $data->showreports = $courseconfig->showreports;
4236 $data->maxbytes = $courseconfig->maxbytes;
4237 $data->groupmode = $courseconfig->groupmode;
4238 $data->groupmodeforce = $courseconfig->groupmodeforce;
4239 $data->visible = $courseconfig->visible;
4240 $data->visibleold = $data->visible;
4241 $data->lang = $courseconfig->lang;
4243 $course = create_course($data);
4244 $context = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST);
4246 // add enrol instances
4247 if (!$DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
4248 if ($manual = enrol_get_plugin('manual')) {
4249 $manual->add_default_instance($course);
4253 // enrol the requester as teacher if necessary
4254 if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
4255 enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid);
4258 $this->delete();
4260 $a = new stdClass();
4261 $a->name = format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
4262 $a->url = $CFG->wwwroot.'/course/view.php?id=' . $course->id;
4263 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a));
4265 return $course->id;
4269 * Reject a course request
4271 * This function rejects a course request, emailing the requesting user the
4272 * provided notice and then removing the request from the database
4274 * @param string $notice The message to display to the user
4276 public function reject($notice) {
4277 global $USER, $DB;
4278 $user = $DB->get_record('user', array('id' => $this->properties->requester), '*', MUST_EXIST);
4279 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
4280 $this->delete();
4284 * Deletes the course request and any associated files
4286 public function delete() {
4287 global $DB;
4288 $DB->delete_records('course_request', array('id' => $this->properties->id));
4292 * Send a message from one user to another using events_trigger
4294 * @param object $touser
4295 * @param object $fromuser
4296 * @param string $name
4297 * @param string $subject
4298 * @param string $message
4300 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message) {
4301 $eventdata = new stdClass();
4302 $eventdata->component = 'moodle';
4303 $eventdata->name = $name;
4304 $eventdata->userfrom = $fromuser;
4305 $eventdata->userto = $touser;
4306 $eventdata->subject = $subject;
4307 $eventdata->fullmessage = $message;
4308 $eventdata->fullmessageformat = FORMAT_PLAIN;
4309 $eventdata->fullmessagehtml = '';
4310 $eventdata->smallmessage = '';
4311 $eventdata->notification = 1;
4312 message_send($eventdata);
4317 * Return a list of page types
4318 * @param string $pagetype current page type
4319 * @param stdClass $parentcontext Block's parent context
4320 * @param stdClass $currentcontext Current context of block
4322 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
4323 // if above course context ,display all course fomats
4324 list($currentcontext, $course, $cm) = get_context_info_array($currentcontext->id);
4325 if ($course->id == SITEID) {
4326 return array('*'=>get_string('page-x', 'pagetype'));
4327 } else {
4328 return array('*'=>get_string('page-x', 'pagetype'),
4329 'course-*'=>get_string('page-course-x', 'pagetype'),
4330 'course-view-*'=>get_string('page-course-view-x', 'pagetype')